DRY Principle in C#: An Example of Saving a Customer

Patel Dhiren
2 min readMay 28, 2023

--

One fundamental principle that helps achieve this is the DRY (Don’t Repeat Yourself) principle. By avoiding code duplication and promoting code reuse, the DRY principle improves maintainability and reduces the chances of introducing bugs.

Let’s continue with the example of a laptop to illustrate DRY Principle in C#:

public class Customer
{
public string Name { get; set; }
public string Email { get; set; }
// other properties

// Validate method to ensure the customer object is valid
public bool Validate()
{
if (string.IsNullOrWhiteSpace(Name))
{
Console.WriteLine("Please provide a valid name.");
return false;
}

if (string.IsNullOrWhiteSpace(Email))
{
Console.WriteLine("Please provide a valid email address.");
return false;
}

// Perform additional validation checks

return true;
}
}

The Customer class consists of properties such as Name and Email, representing customer-specific attributes. Additionally, we have a Validate method that checks if the customer object is valid before saving.

public class CustomerRepository
{
public void SaveCustomer(Customer customer)
{
if (customer.Validate())
{
// Save the customer to the database or perform other necessary actions
Console.WriteLine("Customer saved successfully.");
}
}
}

we create a CustomerRepository class responsible for saving the customer to the database or performing other necessary actions. The SaveCustomer method in the CustomerRepository class leverages the Validate method to ensure the customer object is valid.

public class Program
{
public static void Main()
{
Customer customer = new Customer
{
Name = "John Doe",
Email = "johndoe@example.com",
// set other properties
};

CustomerRepository repository = new CustomerRepository();
repository.SaveCustomer(customer);
}
}

we create a Main method in the Program class, where we create a Customer object and call the SaveCustomer method on a CustomerRepository instance.

By separating the validation logic into the Validate method within the Customer class, we avoid code duplication. The validation logic can be reused in other parts of the system, promoting maintainability and adhering to the DRY principle.

Thank you! I’m glad to hear that you’re enjoying the learning process. If you have any more questions or need further assistance, feel free to ask. Happy learning to you too!

--

--