Coding Guidelines
Coding Guidelines
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
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.
Confidential
11
●
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
Confidential
17
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
Confidential