Search code examples
solid-principlesdesign-principles

Identify classes and class naming strategies


I am trying to understand Single Responsibility Principle and identify possible class that can be in my system.

For now I know principles said by Uncle Bob, ie
avoid weasel words like manager,data,super or processor. We should be able to write description of class in less than 25 words without use of words like "if","and","or" and "but".

However problem arises when I try to identify if I am really following SRP right.

Eg: I had a scenario where 1. I need to send email to user. 2. The email will be verified when user clicks on link

So, my class would be like:

Scenario 1:

class EmailVerifier
{
      function sendEmail();
      function verifyEmail();
}

OR

Scenario 2:

class EmailVerifier
    {
          function verifyEmail();
    }

class MailSender
    {
          function verifyEmail();
    }

If I say scenario 1 is correct, I tried to write description of class , it would be like,

EmailVerifier class sends email to the customer and verifies the email .

If I say scenario 2 is correct, then for every verb I encounter or every function eg: verifyEmail(),sendEmail(),addEmail() , I need to create new class.

Please tell me what might be the correct way.

Also,

I have a scenario where, I have to ,

Add customer, Delete customer, Edit customer, Save customer Search customer, SelectAll customers, FindCustomer by id

For such classes can I name them like CustomerService class or any other naming strategy would be better.

Note: I have already seen other questions like these
Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?


Solution

  • Let's start with the Customer example, because that's simpler. In a standard MVC architecture, you would have a CustomerController which interacts with a CustomerDAO. I leave it as an exercise for you to google the terms MVC architecture and Data Access Object if necessary.

    In the email example, we can simplify the naming problem by applying a more Object-Oriented approach as opposed to a procedural one. In simple terms, OOP tells us that data should be combined with the logic that manipulates it. In this case, I suggest the Email object (data) should be combined with the verify function (logic) thus allowing the email to verify itself.

    class Email
    {
      function verify();
      function getMessage();
      // etc.
    }
    

    Better yet, a design pattern such as the Builder would allow verification to occur before construction of the Email object; because, after all, why create an Email object in the first place if it can't pass verification? Note that verification logic is likely to change for the same reason as the structure of the email object itself. Same reason to change == Single Responsibility.

    Finally, since sending an email is agnostic of the email message itself, the MailSender remains its own class, i.e. sending is also a Single Responsibility.