Total Pageviews

Tuesday, September 11, 2012

Abstract Class Design

Because abstract classes should never be instantiated, it is important to correctly define their constructors. It is also important to ensure that the functionality of your abstract class is correct and easily extended. The following guidelines help ensure that your abstract classes are correctly designed and work as expected when implemented.

Do not define public or protected internal (Protected Friend in Visual Basic) constructors in abstract types.
Constructors with public or protected internal visibility are for types that can be instantiated. Abstract types can never be instantiated.

Do define a protected or an internal constructor in abstract classes.
If you define a protected constructor in an abstract class, the base class can perform initialization tasks when instances of a derived class are created. An internal constructor prevents the abstract class from being used as the base class of types that are not in the same assembly as the abstract class.

Do provide at least one concrete type that inherits from each abstract class that you ship.
This practice helps library designers locate problems or oversights in the abstract class design. It also means that for high-level scenarios where developers might not understand abstract classes and inheritance, they can use the concrete class without having to learn these concepts. For example, the .NET Framework provides the abstract classes WebRequest and WebResponse to handle sending requests to, and receiving replies from a Uniform Resource Identifier. As one of several concrete implementations for these abstract classes, the Framework includes the HttpWebRequest and HttpWebResponse classes, which are HTTP-specific implementations of the abstract classes.

No comments:

Post a Comment