Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
241 views

Mastering Solid Principles in Csharp

Uploaded by

echotr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
241 views

Mastering Solid Principles in Csharp

Uploaded by

echotr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Mastering SOLID Principles in C#

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.

Author/Co-Author – Vikash Singh


Publisher – C# Corner
Editorial Team – Deepak Tewatia, Baibhav Kumar
Publishing Team – Praveen Kumar
Promotional & Media – Rohit Tomar

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

In this chapter, we explore C# generics, covering their key


concepts and syntax. Prepare yourself for a comprehensive
journey that will empower you to effectively utilize the
flexibility of generics in C#.

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.

Importance of Clean, Maintainable, and Scalable Code


Clean code is readable and understandable by humans. Maintainable code can be easily
modified to fix bugs or add new features. Scalable code can handle growth in terms of data,
users, and functionalities without requiring a complete rewrite. These aspects are crucial for
long-term software success.

Overview of the SOLID Principles


The SOLID principles are five design principles intended to make software designs more
understandable, flexible, and maintainable. They are:

• Single Responsibility Principle (SRP)


• Open/Closed Principle (OCP)
• Liskov Substitution Principle (LSP)
• Interface Segregation Principle (ISP)
• Dependency Inversion Principle (DIP)

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

In this chapter, we explore C# generics, covering their key


concepts and syntax. Prepare yourself for a
comprehensive journey that will empower you to
effectively utilize the flexibility of generics in C#.

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)

Brief History and Background of SOLID Principles


The SOLID principles were introduced by Robert C. Martin, also known as Uncle Bob, in the
early 2000s. These principles are derived from his extensive experience in software
development and aim to address common issues encountered in software design.

Benefits of Applying SOLID Principles in Software Development

• Improved code readability and maintainability


• Enhanced testability and flexibility
• Reduced risk of introducing bugs
• Easier to extend and modify codebase
Real-World Examples and Analogies to Understand the Concepts

• 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

In this chapter, we explore C# generics, covering their


key concepts and syntax. Prepare yourself for a
comprehensive journey that will empower you to
effectively utilize the flexibility of generics in C#.

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.

Importance of Having a Single Responsibility for Each Class


By ensuring each class has a single responsibility, the code becomes more modular and easier
to understand, test, and maintain.

How to Identify Multiple Responsibilities in a Class

• Look for classes that handle multiple functionalities.


• Check for classes that have many methods of performing different tasks.
• Consider splitting classes that change for different reasons.

Refactoring Techniques to Achieve SRP

• Split classes into smaller classes with distinct responsibilities.


• Use composition over inheritance to delegate responsibilities.

C# Code Examples Demonstrating SRP

Before Refactoring
public class InvoiceService
{
public void CreateInvoice(Invoice invoice)
{
// Logic to create invoice
}

public void SendInvoiceEmail(Invoice invoice)


{
// Logic to send invoice email
}

public void SaveInvoiceToDatabase(Invoice invoice)


{
// Logic to save invoice to database
}
}

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
}
}

public class DatabaseService


{
public void SaveInvoiceToDatabase(Invoice invoice)
{
// Logic to save invoice to database
}
}

Common Pitfalls and How to Avoid Them


• Avoid over-engineering by creating too many classes.
• Ensure each class has a clear, single responsibility.

https://www.c-sharpcorner.com/ebooks/ 10
4
Open/Closed Principle
(OCP)

Overview

In this chapter, we delve into C# generics, covering their


key concepts and syntax. Prepare yourself for a
comprehensive journey that will empower you to
effectively utilize the flexibility of generics in C#.

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

public interface IDiscount


{
decimal ApplyDiscount(decimal price);
}

public class NoDiscount : IDiscount


{
public decimal ApplyDiscount(decimal price)
{
return price;
}
}

public class PercentageDiscount : IDiscount


{
private readonly decimal _percentage;

public PercentageDiscount(decimal percentage)


{
_percentage = percentage;
}

public decimal ApplyDiscount(decimal price)


{
return price - (price * _percentage / 100);
}
}

// 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);
}
}

Real-World Scenarios Illustrating OCP


• Add new payment methods to an e-commerce application without modifying existing
code.
• Extending logging mechanisms in a system by adding new loggers.

https://www.c-sharpcorner.com/ebooks/ 13
5
Liskov Substitution Principle
(LSP)

Overview

In this chapter, we will explore generics, covering their key


concepts and syntax. Prepare yourself for a comprehensive
journey that will empower you to effectively utilize the
flexibility of generics in C#.

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.

Importance of Substitutability in Object-Oriented Design


LSP ensures that a derived class can stand in for its base class, promoting reusability and
reliability.
Rules to Follow to Ensure LSP Compliance
• Subclasses should only extend behavior, not modify existing behavior.
• Subclasses should follow the contract defined by the base class.
C# Code Examples Showcasing LSP
public abstract class Bird
{
public abstract void Fly();
}

public class Sparrow : Bird


{
public override void Fly()
{
// Fly logic for Sparrow
}
}

public class Ostrich : Bird


{
public override void Fly()
{
throw new NotImplementedException("Ostriches cannot fly");
}
}

Refactoring to adhere to LSP


public abstract class Bird
{
public abstract void Move();
}

public class Sparrow : Bird


{
public override void Move()
{
// Fly logic for Sparrow
}
}

https://www.c-sharpcorner.com/ebooks/ 15
public class Ostrich : Bird
{
public override void Move()
{
// Running logic for Ostrich
}
}

Refactoring Techniques to Fix LSP Violations


• Redefine the base class to accommodate variations in behavior.
• Use composition over inheritance if subclasses significantly differ from the base class.
Practical Examples and Use Cases
• Substituting different types of payment processors in an application.
• Replacing different types of notification senders (email, SMS, push notifications).

https://www.c-sharpcorner.com/ebooks/ 16
6
Interface Segregation
Principle (ISP)

Overview

In this chapter, we explore C# generics, covering their key


concepts and syntax. Prepare yourself for a comprehensive
journey that will empower you to effectively utilize the
flexibility of generics in C#.

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.

Importance of Having Client-Specific Interfaces


ISP ensures that interfaces are tailored to the needs of specific clients, leading to more modular
and easier-to-maintain code.
How to Split Large Interfaces into Smaller, More Specific Ones
• Identify the different clients that use the interface.
• Break down the interface into smaller, client-specific interfaces.
C# Examples Demonstrating ISP
Before refactoring
public interface IWorker
{
void Work();
void Eat();
}

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
}
}

Techniques for Identifying and Correcting ISP Violations


• Analyze interface usage across different clients.
• Refactor interfaces that have methods unused by some clients.
Real-World Scenarios and Benefits of ISP
• Defining different user roles and permissions in an application.
• Creating modular services in a microservices architecture.

https://www.c-sharpcorner.com/ebooks/ 18
7
Dependency Inversion
Principle (DIP)

Overview

In this chapter, we explore C# generics, covering their key


concepts and syntax. Prepare yourself for a comprehensive
journey that will empower you to effectively utilize the
flexibility of generics in C#.

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.

Importance of Decoupling High-Level and Low-Level Modules


DIP promotes flexibility and reusability by reducing the dependency between high-level and low-
level modules.

How to Depend on Abstractions Rather Than Concretions


• Define interfaces or abstract classes to represent the dependencies.
• Implement the interfaces or abstract classes in the low-level modules.
Examples of Applying DIP in C# Using Dependency Injection
Before refactoring
public class OrderService
{
private readonly EmailService _emailService = new EmailService();

public void ProcessOrder(Order order)


{
// Process order
_emailService.SendOrderConfirmation(order);
}
}

After refactoring
public interface IEmailService
{
void SendOrderConfirmation(Order order);
}

public class EmailService : IEmailService


{
public void SendOrderConfirmation(Order order)
{
// Send email logic
}
}

public class OrderService


{
private readonly IEmailService _emailService;

public OrderService(IEmailService emailService)


{
_emailService = emailService;

https://www.c-sharpcorner.com/ebooks/ 20
}

public void ProcessOrder(Order order)


{
// Process order
_emailService.SendOrderConfirmation(order);
}
}

Refactoring Techniques to Achieve DIP


• Introduce interfaces or abstract classes for dependencies.
• Use dependency injection to provide concrete implementations.
Case Studies Demonstrating the Impact of DIP
• Refactoring a monolithic application into a decoupled system.
• Implementing different storage mechanisms (e.g., SQL, NoSQL) without modifying the
core application logic.

https://www.c-sharpcorner.com/ebooks/ 21
8
Applying SOLID Principles in
a C# Project

Overview

In this chapter, we explore C# generics, covering their key


concepts and syntax. Prepare yourself for a comprehensive
journey that will empower you to effectively utilize the
flexibility of generics in C#.

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

You might also like