_db.Add(user.Username, user.Password, user.EmailAddress) Public void SendEmail(MailMessage message) Public EmailService(SmtpClient smtpClient) Public User(string username, string password, string emailAddress) What we end with are multiple reasons to change this class: If the email service we use changes, if the database or process of storing users changes, and if the properties of a user changed.Ī quick refactor to separate these responsibilities gives us: 1 This class ends up with a number of responsibilities: Smtp.Send(new MailMessage(" ", _emailAddress)) _db.Add(_username, _password, _emailAddress) Public User(string username, string password, string emailAddress, Database db) The flow of creating a new “user” on this blogging website is to create a new user, add it into the database and send an email to the user to confirm their account. Therefore the ultimate reason to adhere to SRP is to minimise the chance of having to go back and change your code.Ī basic example to visualise the idea is a blogging system built in C#. The reason for the usage of a reason to change is that when a closely coupled class changes in some way, then the changes can break the code in unexpected ways. If a class, function or block of code has more than one job to do, then it is considered to have more than a single responsibility and “closely coupled”. Another way to approach the concept is considering the amount of jobs a part of code has. That definition seems slightly hand-wavey at first and could mean a lot of things. A class should only ever have one reason to change. The Single Responsibility Principle (SRP) defines a responsibility as “a reason to change”. Don’t attempt to apply every single one of these principles in your plan before you have written a single line of code. Some of the patterns and ideas and how they are applied have been long-term abused and should only really be used as they are needed. A large problem that OOP and “SOLID Code” suffers with is over-complexity. Robert’s books provide both anecdotal and statistical evidence of how his practices improved the delivery of software in the business’ he has worked for and the SOLID principles are a summarisation of the rules he followed.Ī forewarning to these principles is to avoid needless complexity in your code. They were designed to make code more readable, extendable and testable in any environment and any language. Martin (“Uncle Bob”), he didn’t give them the famous SOLID mnemonic, rather he just laid out his five rules that governed how he wrote clean object-oriented code. These ideas were first written by Robert C. The SOLID principles are a set of principles that guide developers in the designing of software. The Single Responsibility Principle (SRP) is the first of the SOLID principles, and makes up the S.
0 Comments
Leave a Reply. |