Mastering Solid Principles in Csharp
Mastering Solid Principles in Csharp
Vikash Singh
All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in
any form or by any means, including photocopying, recording, or other electronic or mechanical
methods, without the prior written permission of the publisher, except in the case of brief
quotations embodied in critical reviews and certain other noncommercial uses permitted by
copyright law. Although the author/co-author and publisher have made every effort to ensure
that the information in this book was correct at press time, the author/co-author and publisher do
not assume and hereby disclaim any liability to any party for any loss, damage, or disruption
caused by errors or omissions, whether such errors or omissions result from negligence,
accident, or any other cause. The resources in this book are provided for informational purposes
only and should not be used to replace the specialized training and professional judgment of a
health care or mental health care professional. Neither the author/co-author nor the publisher
can be held responsible for the use of the information provided within this book. Please always
consult a trained professional before making any decision regarding the treatment of yourself or
others.
https://www.c-sharpcorner.com/ebooks/ 2
Table of Contents:
Introduction................................................................................................................................. 4
Understanding SOLID Principles ..................................................................................................... 6
Single Responsibility Principle (SRP) ............................................................................................... 8
Open/Closed Principle (OCP) ........................................................................................................11
Liskov Substitution Principle (LSP).................................................................................................14
Interface Segregation Principle (ISP) .............................................................................................17
Dependency Inversion Principle (DIP)............................................................................................19
Applying SOLID Principles in a C# Project .......................................................................................22
https://www.c-sharpcorner.com/ebooks/ 3
1
Introduction
Overview
https://www.c-sharpcorner.com/ebooks/ 4
Introduction
Brief Introduction to Software Design Principles
Software design principles are the foundation of creating robust, maintainable, and scalable
applications. They help developers write code that is easier to understand, test, and modify.
Adopting these principles can significantly reduce the complexity of the codebase and improve
the overall quality of the software.
How This Ebook Will Help Developers Understand and Apply SOLID Principles in C#
This ebook provides a comprehensive guide to understanding and applying the SOLID
principles in C#. It includes detailed explanations, real-world examples, and code snippets to
illustrate each principle. By the end of this ebook, developers will be equipped with the
knowledge to implement SOLID principles in their projects, leading to cleaner, more
maintainable, and scalable code.
https://www.c-sharpcorner.com/ebooks/ 5
2
Understanding SOLID
Principles
Overview
https://www.c-sharpcorner.com/ebooks/ 6
Explanation of SOLID Acronym
• S: Single Responsibility Principle (SRP)
• O: Open/Closed Principle (OCP)
• L: Liskov Substitution Principle (LSP)
• I: Interface Segregation Principle (ISP)
• D: Dependency Inversion Principle (DIP)
• SRP: Think of a business card – it has a single purpose: to provide contact information.
• OCP: Consider a plug socket – it supports different devices without needing
modification.
• LSP: Imagine different types of vehicles – a car, truck, and motorcycle – each can be
driven by a driver without needing to change the driver’s understanding.
• ISP: Think of a restaurant menu – instead of one giant menu, it’s better to have separate
menus for drinks, appetizers, and main courses.
• DIP: Consider a remote control – it interacts with a TV without needing to know the
specifics of the TV’s inner workings.
https://www.c-sharpcorner.com/ebooks/ 7
3
Single Responsibility
Principle (SRP)
Overview
https://www.c-sharpcorner.com/ebooks/ 8
Detailed Explanation of SRP
The Single Responsibility Principle states that a class should have only one reason to change,
meaning it should have only one job or responsibility.
Before Refactoring
public class InvoiceService
{
public void CreateInvoice(Invoice invoice)
{
// Logic to create invoice
}
After Refactoring
public class InvoiceService
{
public void CreateInvoice(Invoice invoice)
{
// Logic to create invoice
}
}
https://www.c-sharpcorner.com/ebooks/ 9
public class EmailService
{
public void SendInvoiceEmail(Invoice invoice)
{
// Logic to send invoice email
}
}
https://www.c-sharpcorner.com/ebooks/ 10
4
Open/Closed Principle
(OCP)
Overview
https://www.c-sharpcorner.com/ebooks/ 11
Detailed Explanation of OCP
The Open/Closed Principle states that software entities (classes, modules, functions, etc.)
should be open for extension but closed for modification.
Importance of Writing Code That Is Open for Extension but Closed for
Modification
By adhering to OCP, the code becomes more stable and less prone to errors when new
functionalities are added.
Techniques to Implement OCP in C#
• Use abstract classes or interfaces to define extensions.
• Implement new functionalities through inheritance or composition.
Examples of Extending Functionality Using Interfaces and Inheritance
// Usage
IDiscount discount = new PercentageDiscount(10);
decimal discountedPrice = discount.ApplyDiscount(100);
https://www.c-sharpcorner.com/ebooks/ 12
Refactoring Examples to Adhere to OCP
Before Refactoring
public class Invoice
{
public decimal CalculateTotalAmount(decimal amount, string
discountType)
{
if (discountType == "Percentage")
{
return amount - (amount * 0.10m);
}
else if (discountType == "Flat")
{
return amount - 10;
}
return amount;
}
}
After Refactoring
public class Invoice
{
public decimal CalculateTotalAmount(decimal amount, IDiscount
discount)
{
return discount.ApplyDiscount(amount);
}
}
https://www.c-sharpcorner.com/ebooks/ 13
5
Liskov Substitution Principle
(LSP)
Overview
https://www.c-sharpcorner.com/ebooks/ 14
Detailed Explanation of LSP
The Liskov Substitution Principle states that objects of a superclass should be replaceable with
objects of a subclass without affecting the correctness of the program.
https://www.c-sharpcorner.com/ebooks/ 15
public class Ostrich : Bird
{
public override void Move()
{
// Running logic for Ostrich
}
}
https://www.c-sharpcorner.com/ebooks/ 16
6
Interface Segregation
Principle (ISP)
Overview
https://www.c-sharpcorner.com/ebooks/ 17
Detailed Explanation of ISP
The Interface Segregation Principle states that clients should not be forced to depend on
interfaces they do not use.
After refactoring
public interface IWorker
{
void Work();
}
public interface IEater
{
void Eat();
}
public class Worker : IWorker, IEater
{
public void Work()
{
// Work logic
}
public void Eat()
{
// Eat logic
}
}
https://www.c-sharpcorner.com/ebooks/ 18
7
Dependency Inversion
Principle (DIP)
Overview
https://www.c-sharpcorner.com/ebooks/ 19
Detailed Explanation of DIP
The Dependency Inversion Principle states that high-level modules should not depend on low-
level modules. Both should depend on abstractions. Additionally, abstractions should not
depend on details. Details should depend on abstractions.
After refactoring
public interface IEmailService
{
void SendOrderConfirmation(Order order);
}
https://www.c-sharpcorner.com/ebooks/ 20
}
https://www.c-sharpcorner.com/ebooks/ 21
8
Applying SOLID Principles in
a C# Project
Overview
https://www.c-sharpcorner.com/ebooks/ 22
Step-by-Step Guide on Applying SOLID Principles to a Sample Project
• Analyze the existing codebase.
• Identify areas violating SOLID principles.
• Refactor code incrementally to adhere to SOLID principles.
• Write unit tests to ensure the correctness of refactored code.
Refactoring an Existing Project to Adhere to SOLID Principles
• Example: Refactoring a library management system.
• Initial analysis and identifying SRP violations.
• Refactoring classes to follow SRP, OCP, LSP, ISP, and DIP.
• Writing and updating unit tests.
Best Practices for Maintaining SOLID Compliance Throughout the Project Lifecycle
• Regular code reviews.
• Automated testing.
• Continuous integration and continuous deployment (CI/CD) practices.
• Documentation and knowledge sharing within the team.
Tools and Frameworks in C# That Support SOLID Principles
• Dependency injection frameworks (e.g., Autofac, Unity, Ninject).
• Unit testing frameworks (e.g., NUnit, xUnit).
• Mocking frameworks (e.g., Moq, FakeItEasy).
https://www.c-sharpcorner.com/ebooks/ 23
OUR MISSION
Free Education is Our Basic Need! Our mission is to empower millions of developers worldwide by
providing the latest unbiased news, advice, and tools for learning, sharing, and career growth. We’re
passionate about nurturing the next young generation and help them not only to become great
programmers, but also exceptional human beings.
ABOUT US
CSharp Inc, headquartered in Philadelphia, PA, is an online global community of software
developers. C# Corner served 29.4 million visitors in year 2022. We publish the latest news and articles
on cutting-edge software development topics. Developers share their knowledge and connect via
content, forums, and chapters. Thousands of members benefit from our monthly events, webinars,
and conferences. All conferences are managed under Global Tech Conferences, a CSharp
Inc sister company. We also provide tools for career growth such as career advice, resume writing,
training, certifications, books and white-papers, and videos. We also connect developers with their poten-
tial employers via our Job board. Visit C# Corner
MORE BOOKS