Coding Guidelines

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

1

Coding Guidelines

May 2024

Confidential
Rohan Gupta
2

Index
● Variables
○ Descriptive Naming
○ Reduce Instance Variables
● Methods
○ Naming Convention
○ Do or Return
○ Train Wreeks
● Classes
● Comments & Logging
● Exception Handling
● Dynamic Values & Constants
● Reusability
Confidential
3

Index
● If Else Ladder
● Memory Efficiency
● Polymorphic vs Procedural Approach
● Data Structure
● Object Management
● String Usage
● Solid Principles
● Design Principles
● Real Time Implementation

Confidential
4

Variables
● Descriptive Naming Convention
○ Use Descriptive and meaningful naming conventions while declaring the variables.
○ Ex: int count is always better than x.
● Less Instance Variables
○ Classes should have small number of instance variables.
○ In general the more the variables a method manipulates the more cohesive that method to
its class.
○ A class in which each variable is used by each method is maximally cohesive.

Confidential
5

Variables
● Avoid Redundancy
○ Do not repeat variable declarations or use redundant variables.
○ Remove unused variables to keep code clean
● Encapsulation
○ Use private access modifiers for instance variables.
○ Provide public getter and setter methods to control access.
● Final
○ Final variables must be used as much as possible to avoid accidental modification during
code workflow.

Confidential
6

Methods
● Naming Conventions
○ Method name should be self explanatory and should be clear
● Do or Return
○ Methods should do something or answer something not both at a time.
○ Methods should not take more than 2 or 3 arguments. Imagine a method with 6 arguments
the probable combination of test cases would be 6 * 6.
● Train Wreeks
○ Train Wreeks is designed for functional programming be careful with normal programming.
○ Check below example 1 for functional programming and other one is normal java code.

Confidential
7

Classes
● Use meaningful naming conventions while writing classes.
● Classes should be nouns written in Upper Camel Case.
● Use access modifiers to control access to class members.
● Hide the implementation details of a class from its users by providing a clear and concise public
interface.
● When applicable try to create a class immutable to ensure thread safety and unintended
modification of state object.
● Class should be simple and focused which should follow Single Responsibility Principle of Solid
Principle.

Confidential
8

Comments and Logging


● Try to create Javadoc for each and every method and classes as well.
● Use Swagger as it very simple to integrate it will help in API docs as well.
● In case if you are writing some complex logic in the code try to add normal comments that what's the
purpose of that piece of code.

Confidential
9

Exception Handling
● Be Specific with Exception Types
○ Always throw the most specific exception possible to provide more context about the error.
● Avoid Swallowing Exceptions
○ Avoid empty catch blocks . Always handle the exception or log it properly.

Confidential
10

Exception Handling
● Use Finally Block For Cleanup
○ Use the finally block to release resources like file handles, database connections etc.
● Propagate Exceptions with Context
○ When rethrowing an exception, add context to help identify the problem.

● Catch Specific Exception


○ Always try to catch the most specific exception possible to handle known error conditions
and avoid avoid catching generic exceptions like Exception or Throwable.

Confidential
11

Dynamic Values and Constants


● Avoid Hardcoding config related values for ex: External Third-party API.
● Avoid Hardcoding constants in every file. Create specific Java Constant file and declare as static
final so it will be reused. No need to change in multiple places if any constant is changed and
also try to use Enums where it is applicable.
● Ex: private static final String JOB_ID = “job_id”;
● Try to use application.yml or application.properties as much as possible like you can put the
queries,database configs, kafka url etc in config file so that we can change the config without
impacting the jars.
● Ex: Database connection is just config driven now with Spring Boot. Just pass down the
url,drivername, username and password.


Confidential
@RefreshScope can be used to reload the values without restarting the application.
12

ReUsability
● ReuseObjects
○ Try to reuse the objects instead of creating new objects.
● Loosely Coupled Code
○ Code Should be loosely coupled. Do not write tightly coupled code.
○ Ex: If you are using a third party lib then it will be easy to unplug that lib with minimal
changes in the existing code.
● Reduce Workload of GC
○ Reusability helps reducing the workload of the Garbage Collector which help us in overall
performance of the software.
● Quality Product
○ Code becomes more granular and cleaner with reusability which will create a Quality
Software Product.

Confidential
13

If Else Ladder
● Complexity & Readability
○ If else chains can become lengthy and difficult to read.
○ Try to replace if else complex ladders wherever applicable replace multiple if statements
with switch case.
● Deep Nesting
○ Deep nesting make it harder to follow the code always try to use early returns or extract
nested logic into methods.
● Performance Issues
○ Large if else can led to performance issues. Optimize the solution try to use maps for
faster lookups, try to use Predicate, functions etx wherever applicable.
● Logical Error
○ Incorrect if conditions can lead to logical errors where any wrong block of code can be
executed. Always carefully test the code.

Confidential
14

Memory Efficiency
● Try with Resources
○ Always use try with resources when dealing with files, db connection etc as it implements
AutoCloseable interface as sometime we may forgot to close connection and that will led
to very adverse impact.
● Right Collection Types
○ Always initialize collections.
○ Ensure optimal memory usage and performance.
○ Ex: Use ArrayList if you need fast random access and are not concerned about frequent
insertions/deletions
● Static
○ Be careful with static methods as it will make permanent address in memory irrespective of
its use.
● Leverage Lazy Initialization
○ Initialize Objects when they are actually needed. Just not create random objects
○ It will be clear with the following example
Confidential
15

Memory Efficiency

Confidential
16

Polymorphic Approach Better than Procedural Approach


● Polymorphic approach is always better than Procedural approach.
● Using Polymorphism you can write code that works with Objects of different classes in a generic
way.

Confidential
17

Polymorphic Approach Better than Procedural Approach

Confidential
18

Data Structure
● Data Structure plays a very crucial role in the overall software development process.
● Choose the data structure wisely as it will cost you memory, always prefer to give the exact size.
● When the data size is in bulk try to use parallel processing.
● Need to consider time and space complexity when selecting data structure.

Confidential
19

Object Management
● Object Pool
○ Try to reuse the objects specifically when it comes to heavy objects. It will reduce the
overload of Garbage Collectors
● Lazy Initialization
○ Initialize only when it is required for ex: You need to use an object when some condition of
a method is true but what we generally do we create the object at the start of the method.
● Primitive vs Wrapper
○ Try to use primitive instead of wrapper classes it will save memory.
● Singleton
○ When you know that we need exactly 1 instance of the class throughout the programs life
cycle the do use Singleton pattern. For Ex: Database Connection Pools, Logging etc.

Confidential
20

String Usage
● StringBuffer or StringBuilder for String Concatenation
○ Avoid using the “+” operator repeatedly when concatenating multiple strings. This can
create unnecessary string objects, leading to poor performance. Instead, use StringBuilder
(or StringBuffer for thread safety) to efficiently concatenate strings.
● Prefer StringBuilder over StringBuffer
○ If thread safety is not a concern, use StringBuilder instead of StringBuffer. StringBuilder is
faster because it’s not synchronized.
● Utilize String Formatting
○ Instead of concatenating values using the “+” operator, use String formatting with
placeholders (%s, %d, etc.) to improve readability and maintainability.
● Use the equals() Method for String Comparison
○ When comparing string content, use the equals() method or its variants (equalsIgnoreCase(),
startsWith(), endsWith(), etc.) instead of the “==” operator, which compares object
references.

Confidential
21

Solid Principles
● Solid Principles plays a vital role in overall development process. If used correctly it created a
big impact
● The single responsibility principle states that every Java class must perform a single
functionality.
● The open-closed principle states that according to new requirements the module should be
open for extension but closed for modification.
● The Liskov Substitution Principle (LSP) was introduced by Barbara Liskov. It applies to
inheritance in such a way that the derived classes must be completely substitutable for their
base classes. In other words, if class A is a subtype of class B, then we should be able to
replace B with A without interrupting the behavior of the program.
● It extends the open-close principle and also focuses on the behavior of a superclass and its
subtypes. We should design the classes to preserve the property unless we have a strong
reason to do otherwise.

Confidential
22

Solid Principles
● The principle states that the larger interfaces split into smaller ones. Because the
implementation classes use only the methods that are required. We should not force the client to
use the methods that they do not want to use.
● The principle states that we must use abstraction (abstract classes and interfaces) instead
of concrete implementations. High-level modules should not depend on the low-level module
but both should depend on the abstraction.

Confidential
23

Design Patterns
● Scalability
○ Patterns like SIngleton or Factory help manage resource allocation and object creation,
enabling the application to scale more effectively by ensuring that resources are used
optimally.
● Separation Of Concern
○ Patterns like MVC separate the concerns of the application, leading to a clearer structure
where each part of the codebase has a distinct responsibility.
● Decoupling
○ Design patterns promote loose coupling between classes.
○ Ex: The Observer pattern decouples the subject from its observers, making the system
more modular and easier to extend.
● Error Reduction
○ Using proven patterns reduces the likelihood of errors since the patterns provide reliable
solutions that have been thoroughly tested and widely used in various scenarios.

Confidential
Real Time Implementation

Confidential
25

Real Time Implementation


● We recently performed the code refactoring based on the above steps and results are
surprising. Examples are mentioned below:
○ File Upload & Validation: Excel File and Upload for files greater than 5 mb is not
validating even after 1 day, We refactored the code and now complete process for same
file is completed in 4 Seconds.
○ Reduced Multiple WebClient Calls: For Larger Excel Sheets we are making multiple
Webclient call and the number of call is directly proportional to number of sheets. Here the
need is to do a Webclient call only when the device id is unique.
○ Code Cleanup: Removed unnecessary code and traditional for loop with Stream API.
Also we used and implemented Predicates, Functions, Bifunctions and all functional stuffs
in most of the places.
○ Parallel Processing: We implemented Parallel Processing wherever it is applicable as
we are processing bulk data.
○ Database Indexing: We focused on adding indexes in most of the tables and also
optimized the queries to get the query results fast.
Confidential
Thank You

Confidential

You might also like