I'm trying to find out if there is a consensus on when we should create a new method in our code. For example should we only create a new method/function if we are going to be using the code again (therefore we obviously cut down on the lines used) or is it common to do it just to avoid code clutter as well. I've been programming for a long time now but I've really just gone in and decided in rather random fashion.
Are there any design patterns or books that deal with this? A related question would be if we should only set parameters in an object using getter and setter methods. This would create a lot more code obviously but would make things more manageable? Any consensus on that?
I think there are no specific design guidelines for this. But some of the design principles do talk about method creation.
DRY ( don't repeat yourself) is a guiding principle when comes to method creation. You group similar logic in a single method so that you don't duplicate them all over your code and thus make maintenance a nightmare.
Single Responsibility Principle is another. It says that your class, or method should do only one thing. This is to make the method size small.
I regard programming as an art. As such I split methods when it feels right to split them, or to write a new one.
That said, there are some thumb rules (which does not overrule my instincts).
IF you have deja vue (the code you write seems familiar) you are probably repeating yourself, which means you should us an existing function/method and not write a new one.
No more than two constructs deep
for(...) for(...) for(...) BAD
No more than one loop in a row (one after the other).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With