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
{
public void Create(some param)
{
}
}
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
{
ICustomerRepository rep;
public Customer():this(new CustomerRepository())
{
}
public customer(ICustomerRepository re)
{
rep = re;
}
public void Create(some param)
{
rep.Create(some param);
}
}
public interface ICustomerRepository
{
void Create(some param);
}
public class CustomerRepository : ICustomerRepository
{
public void Create(some param)
{
}
}
I hope this helps!.
Regards,
-Vinayak