When do I put logic in a class as opposed to passing the class into a utility class?
When I have a series of processes which are similar in nature but work on slightly different types of objects, do I unify the type of work in a single utility class, or do I put the functionality directly开发者_JAVA百科 on each object that will need to utilized the functionality?
I'm not concerned about a specific case per-se, but I'm most curious about what factors go into this decision.
I think it depends on the class-ancestry of your objects, the real difference in logic between each object, and the future-possible-need to do this on some other kind of class.
It sounds to me like the utility class is a good way to go if the functionaliy you're applying to multiple classes is largely the same, and could be applied to future classes down the road.
if on the other hand the functionality is different enoguh that you'd end up with a big switch/case statement in your utility class to accomodate the differnet object types, you might want to implement it in the objects themselves.
You have two approaches to your problem: One is to use generic programming (horizontal polymorphism) or to attack it using a more traditional vertical hierarchy based implementation.
You decisions have to be based in the type of similarities that are shared among the various data types. In the case that we can define a complete and orthogonal contract that can be operated in any type then we can easily decide to use generics.
This for example is the case with List, Dictionary and all the class under the System.Collections.Generic name space that eventually replaced their corresponding non generic counterparts of the early versions of .NET.
In the other hand, again from the .NET world we can use as an example of a vertical hierarchy, the UserControl class than derives from ContainerControl and serves as the base for other controls specializing it behavior using its virtual methods...
In most of the cases though the design of your class hierarchy involves a lot of judgment calls that are not always to defined deterministically as they rely more on your experience and talent as a developer rather in a concrete model that can be applied across the board in every possible situation..
精彩评论