Single responsibility principle

When talking about SOLID principles, we will start off with the SRP. Here, we are actually saying that a class has a specific task that it needs to fulfil and it should not do anything else.

Getting ready

You will create a new class and write code to log an error to the database when an exception is thrown on adding more troops to the star ship, causing it to be over capacity.

How to do it…

  1. Create a new class called StarShip:
    public class Starship
    {
           
    }
  2. To your class, add a new method that will set the maximum troop capacity of the StarShip class:
    public void SetMaximumTroopCapacity(int capacity)
    {            
    
    }
  3. Inside this method, add a trycatch clause that will attempt to set the maximum troop capacity, but for some reason, it will fail. Upon failure, it will write the error to the log table inside the database:
    try
    {
        // Read current capacity and try to add more
    }
    catch (Exception ex)
    {
        string connectionString = "connection string goes here";
        string sql = $"INSERT INTO tblLog (error, date) VALUES ({ex.Message}, GetDate())";
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            SqlCommand cmd = new SqlCommand(sql);
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
        }
        throw ex;
    }

How it works…

If you have code that looks like the preceding one, you are in contravention of the SRP. The StarShip class is no longer responsible for just itself and things that have to do with star ships. It now has to fulfill the role of logging errors to the database too. You see the problem here is that the database-logging code does not belong in the catch clause of the SetMaximumTroopCapacity method. A better approach would be to create a separate DatabaseLogging class with methods to create connections and write exceptions to the appropriate log table. You will also find that you are going to have to write that logging code in multiple places (in every catch clause). If you are finding that you are repeating code (by copying and pasting from other areas), you probably need to put that code into a common class, and you have likely broken the SRP rule.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.137.59