views:

67

answers:

5

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?

+1  A: 

Probably my own personal rule is if it is more than 2 lines long, and is referenced more than once on the same page (ASP.net), or a few times spread over a couple of pages, than I will write a function to do it.

Pyronaut
+1  A: 

I think you generally have to think of a chunk of codes have a chance of being reuse. It comes with experience to figure that out and plan ahead.

KahWee Teng
+4  A: 

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.

Justin L.
+1: Second concept is the SRP http://en.wikipedia.org/wiki/Single_responsibility_principle
Binary Worrier
A: 

I was taught that anything you do more than once should be a function. Anything similar should have a parent class, and above all else consult your source code "standards" within your organization. The latter mostly deals with formatting.

bobby
I'd be careful with advocating inheritance just to provide easy access to common functions. Composition is better. Leave inheritance to expressing `is-a` relationships.
Lauri Lehtinen
point taken Lauri
bobby
A: 

I agree with the answers that concentrate on reusability and eliminating repetition, but I also believe that readability is at least as important. So in addition to repetition, I would look for pieces of code (classes, functions, blocks, etc.) that do more than one thing.

If the name associated with the code does not describe what it does, then that is a good time to refactor that code into units which each have a single responsibility and a descriptive name. This separation of concerns will help both reusability, and readability.

Useful code can stick around for a long time, so it is important that you (or ideally someone else) can go back and easily understand code that was written months or years before.

richj