Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Refactoring Tips - Tip 4

2.88/5 (8 votes)
1 Mar 2010CPOL 1  
Refactoring Tips - Tip 4Tip 4 Based on one of the design principle - SRP( Single Responsibility Principle) There should be only one reason to change or break a classs.Dont mixup more than one functionality in a class.Bad practice Dont have domain and persistence logic in a...
Refactoring Tips - Tip 4

Tip 4


Based on one of the design principle - SRP( Single Responsibility Principle) There should be only one reason to change or break a classs.

Dont mixup more than one functionality in a class.

Bad practice

Dont have domain and persistence logic in a single class.

Following class- 'Customer' contains both domain logic and persistent logic,hence there are two reasons to change.(domain and data related) This is against the rules described above(SRP).

public class Customer
{
  //Attributes...
  //Behaviors (CRUD Operations)

  public void Create(some param)
  {
    //Writing code as shown below...

    //Creating Data Connection...
    // Opening connection...
    //Firing a Query against the data store
    //Processing the data...
    //Closing connection...
  }

  //Some more methods.....like Update,Delete,Read etc...
}

Good practice

Have two sets of classes - one for domain and one for persistence

In the following snippet, we are having two set of classes one exclusive to the domain logic(Customer), which in turn gets the data ability through the repository class (which is exclusively to the data).

public class Customer
 {
   //Attributes...
   //Behaviors (CRUD Operations)
   ICustomerRepository rep;
   public Customer():this(new CustomerRepository())
   {
   }
   public customer(ICustomerRepository re)
   {
     rep = re;
   }
   
   public void Create(some param)
   {
     //To get the Data..
     rep.Create(some param);
   }
   //Some more methods.....like Update,Delete,Read etc...
 }
 
public interface ICustomerRepository 
{
 void Create(some param);
 //Some more methods...
}
public class CustomerRepository : ICustomerRepository 
{
 
 public void Create(some param)
 {
     //Creating Data Connection...
     // Opening connection...
     //Firing a Query against the data store
     //Processing the data...
     //Closing connection...
 }
//Some more methods ...like update,delete,read etc...
}


I hope this helps!.

Regards,
-Vinayak

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)