Class Design Guidelines

A class or interface should have a single reason for change (HTA1000)

Single Responsibility Principle, one of the S.O.L.I.D. principles.

Single Responsibility Principle, what does it mean? It means that a software module should have one reason to change, then that’s what I call a responsibility, a reason to change.

So the Responsibility Principle simply says, “Find one reason to change and take everything else out of the class.” So that you separate the things that change for different reasons, you group together the things to change for the same reasons. This is somewhat out of the norm for object oriented design, early object oriented design principles had as grouping together functions that operated on the same data structures so that the methods of a class would all manipulate the same variables of that class, but if those methods change for different reasons then they really belong in separate classes.

  • from SOLID Principles with Uncle Bob - Robert C. Martin

The aim of the principle is to limit the impact of change rather than to atomise classes/interfaces. A single change to the requirements/system should ideally only impact a single module. This is often confused with a class/interface should only do one thing but it is subtly different. The key change over traditional OOD is don’t gather everything relating to the ‘thing’ into a single class or interface. Consider what elements are likely to change and for what reason. Then gather all the things that will change for the same reason together into one module.

Tip: “Gather together the things that change for the same reasons. Separate those things that change for different reasons.” - Robert C. Martin

Tip: A class with the word And in it is an obvious violation of this rule.

Tip: Use Design Patterns to communicate the intent of a class. If you can’t assign a single design pattern to a class, chances are that it is doing more than one thing.

Note If you create a class representing a primitive type you can greatly simplify its use by making it immutable.

Only create a constructor that returns a useful object (HTA1001)

There should be no need to set additional properties before the object can be used for whatever purpose it was designed. However, if your constructor needs more than three parameters (which violates HTA1561), your class might have too much responsibility (and violates HTA1000).

An interface should be small and focused (HTA1003)

Interfaces should have a name that clearly explains their purpose or role in the system. Do not combine many vaguely related members on the same interface just because they were all on the same class. Separate the members based on the responsibility of those members, so that callers only need to call or implement the interface related to a particular task. This rule is more commonly known as the Interface Segregation Principle.

Use an interface rather than a base class to support multiple implementations (HTA1004)

If you want to expose an extension point from your class, expose it as an interface rather than as a base class. You don’t want to force users of that extension point to derive their implementations from a base class that might have an undesired behavior. However, for their convenience you may implement a(n abstract) default implementation that can serve as a starting point.

Use an interface to decouple classes from each other (HTA1005)

Interfaces are a very effective mechanism for decoupling classes from each other:

  • They can prevent bidirectional associations.
  • They simplify the replacement of one implementation with another.
  • They allow the replacement of an expensive external service or resource with a temporary stub for use in a non-production environment.
  • They allow the replacement of the actual implementation with a dummy implementation or a fake object in a unit test.
  • Using a dependency injection framework you can centralize the choice of which class is used whenever a specific interface is requested.

Avoid static classes (HTA1008)

With the exception of extension method containers, static classes very often lead to badly designed code. They are also very difficult, if not impossible, to test in isolation, unless you’re willing to use some very hacky tools. You can instead use DI and a container and inject the dependency in the constructor. If the scope of the DI is per application, then you have a singleton that can be moved in unit testing and the dependency is obvious.

Note: If you really need that static class, mark it as static so that the compiler can prevent instance members and instantiating your class. This relieves you of creating an explicit private constructor.

Don’t suppress compiler warnings using the new keyword (HTA1010)

Compiler warning CS0114 is issued when breaking Polymorphism, one of the most essential object-orientation principles. The warning goes away when you add the new keyword, but it keeps sub-classes difficult to understand. Consider the following two classes:

public class Book
{
	public virtual void Print()
	{
		Console.WriteLine("Printing Book");
	}
}

public class PocketBook : Book
{
	public new void Print()
	{
		Console.WriteLine("Printing PocketBook");
	}
}

This will cause behavior that you would not normally expect from class hierarchies:

PocketBook pocketBook = new PocketBook();

pocketBook.Print(); // Outputs "Printing PocketBook "

((Book)pocketBook).Print(); // Outputs "Printing Book"

It should not make a difference whether you call Print() through a reference to the base class or through the derived class.

It should be possible to treat a derived type as if it were a base type (HTA1011)

In other words, you should be able to pass an instance of a derived class wherever its base class is expected, without the callee knowing the derived class. A very notorious example of a violation of this rule is throwing a NotImplementedException when overriding methods from a base class. A less subtle example is not honoring the behavior expected by the base class.

Note: This rule is also known as the Liskov Substitution Principle, one of the S.O.L.I.D. principles.

Don’t refer to derived classes from the base class (HTA1013)

Having dependencies from a base class to its sub-classes goes against proper object-oriented design and might prevent other developers from adding new derived classes.

Avoid exposing the other objects an object depends on (HTA1014)

If you find yourself writing code like this then you might be violating the Law of Demeter.

someObject.SomeProperty.GetChild().Foo()

An object should not expose any other classes it depends on because callers may misuse that exposed property or method to access the object behind it. By doing so, you allow calling code to become coupled to the class you are using, and thereby limiting the chance that you can easily replace it in a future stage.

Note: Using a class that is designed using the Fluent Interface pattern seems to violate this rule, but it is simply returning itself so that method chaining is allowed.

Exception: Inversion of Control or Dependency Injection frameworks often require you to expose a dependency as a public property. As long as this property is not used for anything other than dependency injection I would not consider it a violation.

Avoid bidirectional dependencies (HTA1020)

This means that two classes know about each other’s public members or rely on each other’s internal behavior. Refactoring or replacing one of those classes requires changes on both parties and may involve a lot of unexpected work. The most obvious way of breaking that dependency is to introduce an interface for one of the classes and using Dependency Injection.

Exception: Domain models such as defined in Domain-Driven Design tend to occasionally involve bidirectional associations that model real-life associations. In those cases, make sure they are really necessary, and if they are, keep them in.

Classes should have state and behavior (HTA1025)

In general, if you find a lot of data-only classes in your code base, you probably also have a few (static) classes with a lot of behavior (see HTA1008). Use the principles of object-orientation explained in this section and move the logic close to the data it applies to.

Exception: The only exceptions to this rule are classes that are used to transfer data over a communication channel, also called Data Transfer Objects, or a class that wraps several parameters of a method.

Classes should protect the consistency of their internal state (HTA1026)

Validate incoming arguments from public members. For example:

public void SetAge(int years)
{
	AssertValueIsInRange(years, 0, 200, nameof(years));

	this.age = years;
}

Protect invariants on internal state. For example:

public void Render()
{
	AssertNotDisposed();

	// ...
}