Coding Principles
Coding Principles
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-harpcorner.com/ebooks/ 2
About Author
I am Vinoth Arun Raj Xavier, with over 13 years of hands-on experience specializing in
Microsoft.NET technology, various JavaScript frameworks, DevOps tools, and other essential
programming languages.
My expertise lies in developing Windows, web, and mobile applications. I have a keen interest in
microservices, cloud integration, and DevOps practices.
Continuously staying abreast of technological advancements across different technology stacks
is something I find personally rewarding.
I focus on writing about current technical trends on social media platforms, sharing knowledge
and insights with the community.
https://www.c-harpcorner.com/ebooks/ 3
Solid
Short introduction about the topic,
• To enable scalable architecture and software development, principles are best practices
to adhere to.
• Design patterns are methods for structuring and designing your code for a solution.
Each design pattern has a unique use case and can be used in a variety of situations. On the
other hand, to have high-quality code, you almost always need to adhere to certain standards.
Certain design patterns are required by certain principles.
To create an understandable, readable, and testable code that many developers can
collaboratively work on.
https://www.c-harpcorner.com/ebooks/ 4
Single Responsibility Principle
The single-responsibility principle (SRP) states that each class, module, or function in your
program should be limited to carrying out a single duty. In other words, each class, module, or
function should be fully accountable for just one feature. Only variables and methods necessary
for the class's functioning should be included.
Real-Time
We need to write a code to save student information while registering and send mail to him and
the admin to know if a student has raised the registration request successfully or failed.
Please check the below sample codes,
#SRP Not Applied Code:
https://www.c-harpcorner.com/ebooks/ 5
Please check the above code “StudentBusinessAccess” was owned for save the Student
Information. The SOLID Principle isn't being used, though. The code will be difficult to maintain
and unable to be improved if all business requirements are contained in a single class.
Let's explore how we can implement SRP in the code.
#SRP Applied Code:
https://www.c-harpcorner.com/ebooks/ 6
Open - Closed Principle
Building a plugin system where new features can be added by implementing a common
interface without impacting the existing functionality. Let’s take the EMailUtil Class here for the
process. Initially, we have implemented a direct email send method. After some time, we need
to implement the SendGrid API or Outlook 365 SMTP for Send Emails.
In Future, we can be able to add one newer implementation if needed without touching the
existing code.
https://www.c-harpcorner.com/ebooks/ 7
Liskov Substitution Principle
Objects in a program should be replaceable with instances of their subtypes without altering the
correctness of that program."Robert c. Martin
The Liskov substitution principle (LSP) is a specific definition of a subtyping relation created by
Barbara Liskov and Jeannette Wing. The principle says that any class must be directly
replaceable by any of its subclasses without error.
https://www.c-harpcorner.com/ebooks/ 8
In other words, each subclass must maintain all behaviour from the base class along with any
new behaviours unique to the subclass. The child class must be able to process all the same
requests and complete all the same tasks as its parent class.
In practice, programmers tend to develop classes based on behaviour and grow behavioural
capabilities as the class becomes more specific. The advantage of LSP is that it speeds up the
development of new subclasses as all subclasses of the same type share a consistent use. You
can trust that all newly created subclasses will work with the existing code. If you decide that
you need a new subclass, you can create it without reworking the existing code.
Classes must only be able to carry out behaviours that are necessary to achieve their intended
functionality following the interface segregation principle (ISP). Thus, classes do not cover
behaviours that they do not practise. This is connected to the first SOLID principle because
when combined, these two principles deprive a class of any variables, processes, or behaviours
that do not directly advance their function. The entire purpose of a method must be the same as
the result.
In the below, Image, we have an interface for List Operations, which Contains both number and
string (word) operations. It was wrong.
https://www.c-harpcorner.com/ebooks/ 9
To correct the implementation, See the below image,
Make an interface named IListOperations for list operations, then make separate interfaces for
numbers and words that are unrelated to one another and use IListOperations.
https://www.c-harpcorner.com/ebooks/ 10
Abstractions should not depend on details. Details (like concrete implementations) should
depend on abstractions.
In the above code, StudentAccess Class will return Name, so It implements the IStudentAccess
interface.
https://www.c-harpcorner.com/ebooks/ 11
In the above code, we created a factory class for StudentFacotry create StudentAccess class
object and return as IStudentAccess.
The above logic will access the created to access the StudentAccess.
https://www.c-harpcorner.com/ebooks/ 12
To apply the DRY principle effectively, developers should identify patterns of duplicated code
and refactor them into reusable components. These components can take the form of functions,
methods, classes, or even libraries and frameworks, depending on the programming language
and the nature of the code.
Our use case involves the automated sending of emails under specific conditions. Whenever
user details are saved or updated in the database, an email should be sent to the Admin Team.
In case of any exceptions during this process, the Tech Support Team should also be notified
via email. Similarly, when an order is placed, the Admin Team should be informed to initiate
order processing, and any exceptions related to orders should trigger an email notification to the
Tech Support Team.
One significant issue we face is redundancy in our codebase. For each of these business logic
scenarios, we’ve written separate code segments to send emails. This redundancy has led to a
total of 14 lines of code, and the duplication percentage exceeds 100%.
We’ve taken steps to adhere to the DRY (Don’t Repeat Yourself) principle in our codebase. To
achieve this, we’ve introduced a new class called “EmailUtil.” This class is responsible for
handling email-sending operations through a static method called “SendWithMailMessage.” This
method accepts a parameter of type MailMessage for email content and delivery.
https://www.c-harpcorner.com/ebooks/ 13
By adopting this approach, we’ve successfully reduced code duplication in our existing business
logic. This change not only enhances maintainability but also aligns with the Single
Responsibility Principle (SRP). Furthermore, we’re working towards extending this design to
support the Open-Closed Principle (OCP) and the Interface Segregation Principle (ISP) in the
future. See below code,
Project Management: The KISS principle applies to project management as well. Maintaining
clear project plans and processes might help to minimize excessive bureaucracy and streamline
development efforts.
The KISS concept does not imply that all software should be simple or uncomplicated. Rather, it
implies that complexity should be justified by actual needs and advantages. When presented
https://www.c-harpcorner.com/ebooks/ 14
with various alternatives, developers and designers should choose the simplest one that fits the
project’s requirements.
Improved Maintainability: Because simple code and architecture are more predictable and
have fewer moving parts, they are easier to maintain.
Bugs are reduced: Complex code is more prone to bugs and errors. Code simplification can
lead to more reliable software. Simpler solutions are frequently easier to implement and debug.
Improved User Experience: Simple and intuitive interfaces result in improved user
experiences.
ComplexCodeMethodTwo(int gameType): Like the first method, this one also retrieves game
types. However, it suffers from complexity in terms of code maintenance and error handling.
https://www.c-harpcorner.com/ebooks/ 15
Here is a list of overall benefits:
• Code Reusability
• Code Maintenance
• Readability
• Debugging and Testing
• Scalability
• Consistency
Consistency and Readability: Imagine a team project where everyone writes differently.
Standards ensure a uniform codebase, making it easier for developers to understand and
https://www.c-harpcorner.com/ebooks/ 16
collaborate on each other's code. Consistent formatting, indentation, and naming conventions
improve readability, allowing everyone to quickly grasp the code's logic.
Maintainability: Code standards promote maintainability in the long run. When a developer
needs to modify or fix a section of code written by someone else, clear, and consistent code
makes the process smoother. This saves time and reduces the risk of introducing errors.
Reduced Errors: Following coding best practices often involves techniques that prevent
common bugs. Standards might dictate proper error handling or data validation methods, which
can catch issues early in the development process.
Overall, coding standards and principles are not just about uniformity; they're about creating a
foundation for well-written, understandable, and maintainable software. This benefits everyone
involved in the development process, from individual developers to the overall quality of the final
product.
https://www.c-harpcorner.com/ebooks/ 17
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