This post originated from an RSS feed registered with .NET Buzz
by Raymond Lewallen.
Original Post: Good design or bad design of abstract class?
Feed Title: Raymond Lewallen
Feed URL: /error.htm?aspxerrorpath=/blogs/raymond.lewallen/rss.aspx
Feed Description: Patterns and Practices, OOP, .Net and Sql
âDO NOT define public or protected-internal constructors in abstract types.â
Then it reads:
âDO define a protected or an internal constructor on abstract types.â
Sure. Makes perfect sense. Then come the examples. It says the following code is good design:
Good design
publicabstractclass MySecondAbstract
{
protected MySecondAbstract()
{
}
}
So far so good. Everything Iâve shown and read so far is something I think weâve all known and agreed with for many, many years. Its basic abstract class design.
This next bit of code is labeled as good design/incorrect design:
Good design/incorrect design
// good design
publicabstractclass MyFirstAbstract
{
protectedint _userId;
// incorrect design
protected MyFirstAbstract(int userId)
{
if (userId <= 0)
{
thrownew ArgumentOutOfRangeException("userid");
}
_userId = userId;
}
}
Why this would be bad design, as the book states. Simple constructors are fine. Protected constructors for abstract classes are fine. Exceptions from within constructors are fine when appropriate. So whats the deal?
At first the thought was, maybe its creating a default public parameterless constructor that gets exposed. But, the compiler is smarter than that and its not. So far the only thing I can figure out is that design guidelines require that a parameterless, protected constuctor always exist for an abstract type.
What are your thoughts on this? Why would the above abstract class MyFirstAbstract be bad design?