• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to organize and design classes?  RSS feed

 
Jonathan Haybok
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Unnar Björnsson
Ranch Hand
Posts: 164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!