Explained: A class or interface should have a single purpose

Aviva C# Coding Guidelines is an awesome reference for best practices while coding in C#.

In this blog we will study a sample of how to and not to write coding conforming to the rule – A class or interface should have a single purpose.

By definition, rule AV1000 says,

A class or interface should have a single purpose within the system it participates in. In general, a class is either representing a primitive type like an email or ISBN number, an abstraction of some business concept, a plain data structure or responsible for orchestrating the interaction between other classes. It is never a combination of those. This rule is widely known as the Single Responsibility Principle, one of the SOLID principles.
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 it usage by making it immutable.

Sample of how to mix purposes in a single class

public class Shape
{
   public int GetAreaForRectangle(int length, int height)
   {
      return length * height;
   }
   public int GetAreaForCircle(int radius)
   {
      return 3.14 * (radius * radius);
    }
    public int GetAreaForSquare(int side)
   {
      return side * side;
    }
}

Sample of how to have single purpose classes for the same functionality

public interface IShape
{
      int CalculateArea();
}
public class Rectangle: IShape
{
   private int length;
   private int height;
   public Rectangle(int length, int height)
   {
      this.length = length;
      this.height = height;
   }
   public int CalculateArea()
   {
      return length * height;
   }
}
public class Circle: IShape
{
   private int pie;
   private int radius;
   public Rectangle(int radius)
   {
      this.radius = radius;
   }
   public int CalculateArea()
   {
      return pie * radius;
   }
}
public class Square: IShape
{
   private int side;
   public Rectangle(int side)
   {
      this.side = side;
   }
   public int CalculateArea()
   {
      return side * side;
   }
}
Advertisements