Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should we create a new method?

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?

like image 299
Matthew Stopa Avatar asked Nov 17 '09 15:11

Matthew Stopa


2 Answers

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.

like image 144
Graviton Avatar answered Sep 23 '22 07:09

Graviton


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).

  1. If you need to scroll the screen to read one method, you need to split it
  2. 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.

  3. No more than two constructs deep

    for(...) for(...) for(...) BAD

  4. No more than one loop in a row (one after the other).

  5. If you need to return more then one type of data (a null/false version is not) then you need to split something.
  6. If you get confused when reading your method - split it
  7. A method/function should be responsible for one task.
  8. The most obvious - when writing new functionality :-)
like image 36
Itay Moav -Malimovka Avatar answered Sep 20 '22 07:09

Itay Moav -Malimovka