views:

67

answers:

2

I am wondering if it is good practice to call public functions also internally.

By public functions I mean all methods/functions that you created explicitly to be called from other objects, modules, etc. For example methods that you would typically put in a Java interface definition. By calling internally, I mean in the same module, class, etc.

I've always felt about this as somehow 'misusing' public methods, although I can't think of any valid technical reason not to do it.

The alternative would be to put the body of the function in a private function/method, which you can invoke internally. The body of the public method would then consist of a single call to the private function.

I image this question is highly subjective, but still... Any thoughts on this?

+2  A: 

There is no reason not to use public methods internally. Don't wrap private methods in public methods, there's no benefit to it and it makes you code slightly less clear.

RossFabricant
+1  A: 

Yes, you can do it, it is a fine practice which must however be considered strongly with respect to the situation.

Two examples:

  • Be careful not to call methods in the class constructor: during the call your class is partially initialized, so any call to methods (of the class itself or inherited) could have bad and hard to track consequences. As a rule of thumb, the constructor must be "self-satisfied" with respect to the class.

  • Since you are using methods of the class, you have free access to its implementation. Ask yourself "Do I want to access the class through its interface, or through its implementation?".

To better explain the second point, suppose you have a class A with methods foo() and bar().

Suppose that foo() calls bar() in its code. In this case you are talking with the interface of your object. This interface could not be the one you expect! For example, suppose that the class has been reimplemented (class B, derived from A) by you, but also by an user of your code, and that method bar() has been overridden. Due to the inheritance, A::foo() will call B::bar(), instead of A::bar().

By not using the bar() method call, and accessing the implementation instead, you are guaranteed that your function behaves the same, even for child classes.

Some of these issues enter in the so-called fragile base class problem. Here is a very good article about it.

Stefano Borini
Ah, good remark (about initialization), didn't consider this before.
Rabarberski
It is just due to the number of bites that you remember the teeth before it opens the mouth.
Stefano Borini