I currently have a Java class called "node" which has a number of fields. Which fields in the class are used depends on a field called "type". There are close to 10 (this can grow) different types of "nodes". I was wondering if it is good to have a single class to handle all types or have different class for each type. What is the best programming practice in these cases? I would like to know (or a link to similar question/tutorials) how the performance will be affected (like memory etc.) if I use a single class?
|
|
This is a standard case for inheritance. You do not incur performance problems due to sub-classing. If you are performing any casting between sub types and super types several if statements will be executed at run time and are used to check for cast exceptions. In your single class model you would need to check your "type" field whenever a method or field is accessed to see if that particular "type" of node has those fields available. Memory should also not be a concern because you will be creating the same number of objects in either the single class model or the inheritance model. |
|||||||||||||||||||
|
|
The giveaway is in the name of your variable: Each subclass should contain the fields relevant only to it. By doing this refactoring, your code will be easier to maintain and extend. Good design generally trumps (and usually helps) performance. In this case - don't worry about it. |
|||
|
|
|
This situation is the perfect case for applying the factory pattern which basically creates the required subclass based on specific inputs. Also inheritance is not to be abused as changes to the super class trickle down to sub-classes. |
||||
|
|
It might be a decorator or state design pattern or a composition since we are talking about nodes here, composite pattern is a good candidate and since every node might possibly behave differently depending on the type, we may consider each node instance as states with different handling of a more generic behavior or we could have a base abstract class for a node and several concrete classes that are just decorators to provide additional functionality or customized behaviors. |
|||||||||||||||
|