Tuesday, July 24, 2007
class design
What are the facts need to be checked when designing a class .NET . Here are a few.
1. Can you inherit from an existing class?
2. Does this class need to be concrete, an interface , an abstract class or static class?
3. IS this class part of a pattern or a standalone?
4. Does this need to be part of a library ? What is the namespace?
5. What properties and methods it needs to expose and why?
When to use Interface ?
a. When creating a standalone project which can be changed at will, use an interface in preference to an abstract class; because, it offers more design flexibility.
b. Use interfaces to introduce polymorphic behavior without subclassing and to model multiple inheritance—allowing a specific type to support numerous behaviors.
c. Use an interface to design a polymorphic hierarchy for value types.
d. Use an interface when an immutable contract is really intended.
e. A well-designed interface defines a very specific range of functionality. Split up interfaces that contain unrelated functionality
f. Need to think about future business changes ( extensibility) if this is a business object.
When to use an abstract class ?
a. When creating a class library which will be widely distributed or reused—especially to clients, use an abstract class in preference to an interface; because, it simplifies versioning. This is the practice used by the Microsoft team which developed the base class library (com was designed around interfaces.)
b. Use an abstract class to define a common base class for a family of types.
c. Use an abstract class to provide default behavior.
d. Subclass only a base class in a hierarchy to which the class logically belongs.
6. When deciding between property and method: If the purpose is to set or retrieve a piece of data define a property. If it is to perform a general action then define a method.
Subscribe to:
Post Comments (Atom)
1 comment:
Regarding #4 - Considering extensibility is important, but extensibility can be a double-edged sword in many respects. To give a narrow example specific to .NET, if you mark a method as virtual, you necessarily cause late-binding because the CLR has to traverse the method table for your class. This can potentially constitute a serious performance penalty.
Post a Comment