ES as Exercises of Single responsibility principle

By | March 14, 2020

Single responsibility principle

Each class should have only one responsibility (one reason to change) — one purpose of existence.

How to use the SRP principle in practice? 

Combine into one code, which has the same reason to change. Separate a code that has many reasons to change.

Difficulties with SRP

There are some difficulties with the SRP principle:

  • It is not defined what a change is.
  • It is not defined what the responsibility is.
  • It requires anticipating the future.

Class, function, method, etc. should be responsible for a single business logic on one level of abstraction. (http://adam.wroclaw.pl/2014/12/zasada-pojedynczej-odpowiedzialnosci/)

Classes should be organized to minimize complexity. They should:

  • Be small enough to reduce dependencies.
  • Be large enough to maximize consistency.

By default, you should choose to group functionality for code separation. (https://sklivvz.com/posts/i-dont-love-the-single-responsibility-principle)

Example

The class book has two responsibilities.

  1. Has information about itself.
  2. Print itself.

   class Book
    {
        private string title;
        private string content;
        public Book(string title, string content)
        {
            this.title = title;
            this.content = content;
        }



        public void PrintBook()
        {
            Console.WriteLine(title);
            Console.WriteLine(content);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Book book = new Book("Interesting title", "Nice content");
            book.PrintBook();
        }
    }

In these changes, I have assigned the responsibility for the book to a separate class.


class Book
    {
        private string title;
        private string content;

        public Book(string title, string content)
        {
            this.title = title;
            this.content = content;
        }

        public string GetBookToPrint()
        {
            return $"{title}{Environment.NewLine}{content}";
        }
    }


    interface IPrinter
    {
        void Print(string content);
    }

    class BookPrinter : IPrinter
    {
        public void Print(string content)
        {
            Console.WriteLine(content);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            IPrinter printer = new BookPrinter();
            Book book = new Book("Interesting title", "Nice content");
            var bookToPrint = book.GetBookToPrint();
            printer.Print(bookToPrint);
        }
    }

    }

All posts from mini project: Learn SOLID and OOP principles:

Sources

Main image

Materials

 

Leave a Reply

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