Clean Coding Notes_updated (1)
Clean Coding Notes_updated (1)
Clean code makes the code more readable and hence easily maintainable. In
short, clean coding is the way of writing the code such that it is easily readable,
testable and less prone to errors.
any code that leads to problems in the long run can be referred to as Bad Code.
The problems can be:
1. Structure
there is no such rule to follow a particular structure for your project but it does
not mean that you should not.
src
├── main
│ ├── java
│ └── resources
└── test
├── java
└── resources
2. Proper Naming
For example, If you want to create a variable for counting, name it 'counter'
instead of naming it 'c' or something like that. You should always avoid
naming variables with a single character like 'a', 'b', 'c', etc.
Normally the elements placed in the source file are in the following order:
Package statement
Import statements
o All static imports
o All non-static imports
Exactly one top-level class
o Class variables
o Instance variables
o Constructors
o Methods
While in this function, whitespaces and indentation are properly taken cared.
5. Method Parameters
avoid adding more than 3 parameters if possible as it can create unnecessary
confusion for other developers or programmers who are going to deal with that
code in future.
You can also go for refactoring if possible, like we have done in the example
given below:
// before
private void employeeDetails(String name, String age, String awards,
String ctc, String experience).
// after
private void employeeDetails(String name, Details employeeDetails).
6. Avoid Hardcoding
Hardcoding is the practice of adding the data directly into the source code of a
program instead of getting the data from external sources. Remember that heavy
hardcoding can make your program difficult to maintain and it also leads to
bugs in your program.
some common practices to avoid hard-coding in Java:
1. Use Constants
Define constants for values that do not change. This way, you can change the
value in one place if needed.
7. Code Comments
Commenting is also considered as one of the best practises to make the code
easily understandable.
In Java, two kinds of comments are allowed:
Documentation comments [ /**…. */ ] - Documentation comments are
usually used to write large programs for a project or software application
as it helps to create documentation API. These APIs are needed for
reference, i.e., which classes, methods, arguments, etc., are used in the
code.
Single line comments [ // ]- The single-line comment is used to comment
only one line of the code. It is the widely used and easiest way of
commenting the statements.
The multi-line comment [ /* …. */ ] is used to comment multiple lines
of code.
8. Logging
Logging in Java is the process of recording information about a program's
execution for debugging, monitoring, and auditing purposes. Logs can help
developers understand what the application is doing, track down bugs, and
monitor application performance.
Logging is one of the most important factors in clean coding. A well logged
code is easy to debug and can save hours of work for a developer.
Key Concepts of Logging
1. Logger: The main component used to log messages. It is responsible for
sending log messages to different destinations (known as handlers or
appenders).
2. Log Levels: Indicates the severity or importance of a log message.
Common log levels include:
o FATAL: Severe error that will prevent the application from
continuing.
o ERROR: An error that might allow the application to continue
running.
o WARN: Potentially harmful situation.
o INFO: General informational messages that highlight the progress
of the application.
o DEBUG: Detailed information on the flow through the system,
mainly used for debugging.
o TRACE: Even more detailed information than debug.
9. S.O.L.I.D principles:
The SOLID principles are five design principles intended to make software
designs more understandable, flexible, and maintainable.
Single Responsibility Principle (SRP)
Open/Closed Principle (OCP)
Liskov Substitution Principle (LSP)
Interface Segregation Principle (ISP)
Dependency Inversion Principle (DIP)
Example:
Imagine you have a Book class. The Book class should only handle
things related to the book itself, like getting the title or author. If you also
add code to print the book, it would violate SRP.
Open-Closed Principle: This principle states that our code should
ideally be open to any kind of extension and closed for any type of
modification. In simple words, our code should be easy to extend but
good enough that no modification is required in our code.
Classes should be open for extension but closed for modification. This
means you should be able to add new functionality without changing
existing code.
Example: Let's say we have a Shape class with a method to calculate area.
Liskov Substitution Principle(LSP): This principle states that the
objects of a superclass should be replaceable with the objects of its
subclasses but without causing the application to break.
DRY is an acronym that stands for "Don't Repeat Yourself". DRY emphasises
on not repeating the same code again and again. In simple words, the main
motive behind this principle is to make the code reusable.
KISS is an acronym that stands for "Keep It Simple, Stupid". As the words of
this acronym suggests, this principle states that the code should be made as
simple as possible which is of course to avoid the understanding confusions. If
this principle is followed properly, the whole code eventually becomes easy to
understand i.e. simple.
1. The variable, class and method are named according to the naming
convention like class has the first letter capital, variable and method are
named as per camelCase naming convention and they also reflect a
specific meaning according to their name.
2. We made sure that our method is doing only one thing i.e. getting
employee name.
3. Whitespaces and indentation are also properly utilized.
Code Smells
Code Smells are not the bugs of the program. With code smells too, your
program might work just fine. They do not prevent the program from
functioning or are incorrect. They just signify the weakness in design and
might increase the risk of bugs and program failure in the future.
Code Smells motivates for Code Refactoring(do changes in code and do not
change it behavior)
Within Classes
Between Classes
Code Smells Within Classes
1. Data Classes: A class that just store data and no methods. These
classes don’t contain any functionality. They can’t independently
operate on the data that they own. A class should contain both
data and methods. Use global or local variables to refactor this code
smell. If the data class contains public data, we can use the
Encapsulation Method to hide it.
4. Refused Bequest: A class inherits from other classes but not using
the inheritance methods of its parent class. For example, Assume a
class, body, human class, and animal class both are inherited from
the class body. A car has a body too, it could inherit from the body
class too, but that will not make any sense.
Refactoring Techniques to deal with this are: Replace inheritance
with the delegation and Extract superclass.
1. Bloaters:
Bloaters are code, methods, or classes that have grown excessively large.
They can make the code harder to understand and maintain.
Long Method: Methods that are too long and do too much.
Large Class: Classes that have too many responsibilities or too many
methods and fields.
Primitive Obsession: Overuse of primitive data types instead of small
objects for simple tasks.
Long Parameter List: Methods that take too many parameters.
Data Clumps: Groups of data that frequently appear together.
Refer this link for more detailed explanation about each category of Code
smells: https://sourcemaking.com/refactoring/smells