views:

57

answers:

5

Hi,

In class design, is it a bad habit if one method calls another method in the same class (For example, 3 methods call 1 method in the same class).

Thanks

+1  A: 

Methods are just functions and functions are abstractions useful for code reuse and design improvement. If three methods of one class need to do the same thing while running should they copy-paste the code for that or call a separate method?

Having some meaningful part of code separated into a method being called by other methods is just another example of code reuse which is good unless you really overdo it.

sharptooth
+1  A: 

No. It appears that you have found a valid use to uphold DRY principles.

spender
A: 

No. In fact it is good practice to do this. Or do you think that your three methods that do the calling should each duplicate the called code?

anon
A: 

Not at all. Infact quite the opposite. Methods are there to accomplish specific tasks, and you should use them for precisely that.

MaLio
+1  A: 

Not at all, it's expected if you've designed your classes properly. You should have a small public interface, and if the implementation is complex, you'll probably end up calling many private methods in the same class.

In fact, not doing this can be an anti-pattern. If you're constantly calling methods of another class, it's called Feature Envy and you should probably combine classes. If you're putting all the implementation into one gargantuan function, that's just unmaintainable, and probably contains a lot of code duplication.

Breaking things out into other reusable methods is a good thing. Your case of 3 methods calling the same one is perfect code reuse. It would be very bad if the code of that one function was duplicated in each of the calling functions.

Tesserex