10. Single responsibility principle

For me it is the one of the most important rules about developing software. It comes from SOLID principles by Robert C. Martin.

In short it states that

every module, class or function in a computer program should have responsibility over a single part of that program’s functionality

What are important consequences of this?

It helps to keep particular logic in one place.

Thus, when you want to modify behavior of your software you make it in one place only.

So, you test and write test for one module only and change in that module should not affect behavior of other parts of the system.

It helps to reduce code repetition. You don’t have to think if you should make that change in that place or in several others. There is less need to look for method or class usage across the system and verifying is it correct in this context or not.

In effect your system is more reliable and you are less afraid of changing it, so you can faster deliver better software and develop features.

Examples:

setting value from outside in many places vs in getter
copying code around -> refactor to function with parameters
splitting big class or function
writing test to such examples
class UrlHelper {
    static function switchToHttps(string url){
        return url.StartsWith("https") ? url : url.Replace("http", "https");
    }
}

class Website {
    public string address;
}

//file1
var bar = new Website();
bar.name = UrlHelper.switchToHttps("http://example.com");

//file2
websites.forEach(x=>x.address = UrlHelper.switchToHttps("http://example.com"));

//file3
websites.forEach(x=>x.address = "http://example.com"); //BUG
class Website {
    private string address;
    public void setAddress(string value){
        name = value.StartsWith("https") ? url : url.Replace("http", "https");
    }

    public string getAddress(){
        return address;
    }
}

//file1
var website = new Website();
website.setAddress("http://example.com");

//file2
websites.forEach(w=>w.setAddress("http://example.com"));

//file3
websites.forEach(w=>w.setAddress("http://example.com")); //bug impossible to occur

References

Leave a comment

Your email address will not be published. Required fields are marked *