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

Coding Principles

Uploaded by

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

Coding Principles

Uploaded by

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

Coding Principles

Vinoth Arun Raj Xavier

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 – Vinoth Arun Raj Xavier


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

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.

• Using the Open/Closed principle as an example, a strategy pattern is highly suggested.


• IoC Design Pattern and its connection to DI Principle are the foundation of .NET Core.
Following the SOLID principles when creating software has several benefits, including:

• Improved maintainability: The SOLID principles encourage the production of modular,


adaptable code that is less prone to errors and more resistant to changes in
requirements, so you can create code that is easier to maintain and adjust over time.
• Reduced complexity: The SOLID principles encourage the use of abstraction and
encapsulation, which can make the code easier to comprehend and work with. This
helps to reduce the complexity of software.
• Increased flexibility: These guidelines support the development of adaptable code that
is open to expansion but closed to alteration, which fosters adaptability without
compromising current functioning.
• Increased scalability: The SOLID principles can aid in increasing the scalability of
software.
Solid Principle: It's a rule to write code.

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:

We have three distinct classes, including StudentDAL, StudentBusinessAccess, and EMailUtil


for carrying out their responsibilities.
EMailUtil class will take care of the job of sending emails.
StudentDAL class will take care of the job of Database connectivity and data operations.
StudentBusinessAccess class will call methods of Data Access and Until Jobs for the needs.

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.

Interface segregation principle


Create small, focused interfaces catering to clients’ needs. Avoid creating interfaces with
methods that aren’t relevant to all implementing classes.

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.

Dependency Inversion Principle


The dependency inversion principle (DIP) has two parts:
High-level modules should not depend on low-level modules. Instead, both should depend on
abstractions (interfaces)

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.

DRY and KISS


The basic rules and ideas that guide the design of software code are known as coding
principles. These criteria assist programmers in writing code that is scalable, legible, and error-
free. Following coding best practices can lead to more stable and long-lasting software.
We already discussed the SOLID concept in the last post, so let’s move on to other principles in
this area. Let us now look at the principles.

• DRY - Do not Repeat Yourself


• KISS - Keep It Simple, Stupid

Dry: (Don’t Repeat Yourself)


The DRY (Don’t Repeat Yourself) principle is a fundamental coding principle that emphasizes
the importance of avoiding code duplication in software development. Instead of duplicating the
same code in multiple places within a codebase, developers are encouraged to create reusable
functions, methods, or classes to encapsulate common functionality.

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.

Use Case Overview

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.

Challenges in the above code

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%.

Implementing the DRY Principle

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,

KISS :(Keep it Simple, Stupid)


The KISS principle, which stands for “Keep It Simple, Stupid,” is a design and programming
principle that advocates for simplicity in all elements of software development, including code,
architecture, and user interface design. The KISS principle is based on the idea of avoiding
needless complexity and keeping things as simple as possible while yet achieving the intended
functionality. The KISS will give flexibility to easy to human-readable code structures.
This approach can be utilized in a variety of situations:

Code Simplicity: The KISS principle encourages developers to avoid overcomplicating


solutions while writing code. It recommends employing simple and easy-to-understand
algorithms and structures. Complex code can be challenging to maintain, debug, and
understand, resulting in errors and extra development time.

Architecture Simplicity: The KISS principle in software architecture advocates against


constructing unnecessarily complicated, confusing structures. Architects should instead strive
towards simple, well-organized designs. Complex architectures might result in poor
performance, scalability concerns, and higher project risks.

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.

Following the KISS concept has the following advantages:

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.

ComplexCodeMethodOne(int gameType): This method is currently responsible for extracting


game types from input values. However, it is challenging to maintain and prone to code growth
issues when new game types are introduced.

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.

KISS_SimpleCodeMethod(int sportsType): This method follows the “Keep It Simple, Stupid”


(KISS) principle. It is designed for easy understanding and readability, reducing code
complexity. Both humans and compilers find it straightforward.

https://www.c-harpcorner.com/ebooks/ 15
Here is a list of overall benefits:

• Code Reusability
• Code Maintenance
• Readability
• Debugging and Testing
• Scalability
• Consistency

Coding standards and principles are fundamental to creating high-quality software.

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

You might also like