Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the golden rule for when to split code up into functions?

It's good to split code up into functions and classes for modularity / decoupling, but if you do it too much, you get really fragmented code which is also not good.

What is the golden rule for when to split code up into functions?

like image 502
Chetan Avatar asked Jun 24 '10 05:06

Chetan


Video Answer


2 Answers

It really does depend on the size and scope of your project.

I tend to split things into functions every time there is something repeated, and that repetition generalized/abstracted, following the golden rule of DRY (Do not repeat yourself).

As far as splitting up classes, I tend to follow the Object Oriented Programming mantra of isolating what is the same from what is different, and split up classes if one class is implementing more an one large theoretical "idea" or entity.

But honestly if your code is too fragmented and opaque, you should try considering refactoring into a different approach/paradigm.

like image 51
Justin L. Avatar answered Sep 20 '22 17:09

Justin L.


If I can give it a good name (better than the code it replaces), it becomes a function

like image 38
Stephan Eggermont Avatar answered Sep 20 '22 17:09

Stephan Eggermont