This seems like such a simple question, but I often have trouble separating code out into different methods. For example, if I want to parse an XML file, I would most likely end up with one big block of code inside a class' constructor. I don't know when to separate out functionality in a method. Is there a simple rule to it? Can you guys give me any advice on how to better organize the information?
There are no exact rules to class and method design. But one good guideline to think about is that a class, and each method in the class, must have a single, clear purpose. If you're noticing that you're creating a class that does everything, or a method that does a number of things that are not directly connected, then think about splitting the class or method up into multiple classes or methods (this is the single responsibility principle).
As mentioned a method should have a clear purpose, it should provide a service to objects. It's a good idea to think in terms of reusability, can the method be used in other circumstances? A method that calculates the distance between two points for example has numerous uses in many applications, now letting the method also add a new point halfway between the two given points would perhaps suit this particular case but it would render it useless in almost any other.
A good sign of a bad method (but not necessarily) is if you are having trouble giving it a proper name.
Post by:autobot
What does a metric clock look like? I bet it is nothing like this tiny ad:
a bit of art, as a gift, the permaculture playing cards