A class should have only one responsibility

Responsibility is the work that has been assigned to the class. In the SOLID set of principles, the S stands for Single Responsibility Principle (SRP). When applied to a class, SRP states that the class must only work on a single aspect of the feature being implemented. The responsibility of that single aspect should be fully encapsulated within the class. Therefore, you should never apply more than one responsibility to a class.

Let's look at an example to understand why:

public class MultipleResponsibilities() 
{
public string DecryptString(string text,
SecurityAlgorithm algorithm)
{
// ...implementation...
}

public string EncryptString(string text,
SecurityAlgorithm algorithm)
{
// ...implementation...
}

public string ReadTextFromFile(string filename)
{
// ...implementation...
}

public string SaveTextToFile(string text, string filename)
{
// ...implementation...
}
}

As you can see in the preceding code, for the MultipleResponsibilities class, we have our cryptography functionalities implemented with the DecryptString and the EncryptString methods. We also have file access implemented with the ReadTextFromFile and SaveTextToFile methods. This class breaks the SRP principle.

So we need to break this class up into two classes, one for cryptography and the other for file access:

namespace FakeCompany.Core.Security
{
public class Cryptography
{
public string DecryptString(string text,
SecurityAlgorithm algorithm)
{
// ...implementation...
}

public string EncryptString(string text,
SecurityAlgorithm algorithm)
{
// ...implementation...
}
}
}

As we can nowsee from the preceding code, by moving theEncryptStringandDecryptStringmethods to their ownCryptographyclass in the core security namespace, we have made it easy to reuse the code to encrypt and decrypt strings across different products and technology groups. TheCryptographyclass also complies with SRP.

In the following code, we can see that the SecurityAlgorithm parameter of the Cryptography class is an enum and has been placed in its own source file. This helps to keep code clean, minimal, and well organized:

using System;

namespace FakeCompany.Core.Security
{
[Flags]
public enum SecurityAlgorithm
{
Aes,
AesCng,
MD5,
SHA5
}
}

Now, in the following TextFile class, we again abide by SRP and have a nice reusable class that is in the appropriate core filesystem namespace. The TextFile class is reusable across different products and technology groups:

namespace FakeCompany.Core.FileSystem
{
public class TextFile
{
public string ReadTextFromFile(string filename)
{
// ...implementation...
}

public string SaveTextToFile(string text, string filename)
{
// ...implementation...
}
}
}

We've looked at the organization and the responsibility of classes. Now let's take a look at commenting on classes for the benefit of other developers.