# **Core Java** | Version | Date | Description | Author | | ------- | ------------ | --------------------------------- | -------------- | | 1.0 | 30 Oct. 2018 | Core Java Coding Standards | Ronak Vakharia | | 2.0 | 12 Jan. 2026 | Added new Java features standards | Ravi Bansode | ## **1. Introduction** ### **1.1 Purpose** This document describes the Java coding standard to be adhered to when writing software at Blast Radius. ### **1.2 Scope** This document is intended to be used by Blast Radius software developers. ### **1.3 Application** * In a team development environment, programmers often need to maintain code developed by other programmers. When a wide variety of coding styles exist in that environment, maintenance usually takes longer and is more defect-prone. Coding to a standard style creates an end product that is easier to read and maintain. Following an agreed-upon set of rules when programming also allows tools and utilities to be built that gather information about the source code. * If the rules and recommendations are followed, the result source code should be easy to maintain, have a style consistent with that produced by other developers on the project, and be free of practices that are error-prone. * The following is a list of some of the positive and negative impacts of using a set of coding standards: * **Consistency**: The team of developers can share a common view when reading, inspecting, and maintaining code. * **Reduce errors**: The coding standards restrict the use of error-prone language features, and formatting. * **Training**: Writing good code takes experience. If all existing code meets a minimal standard, new programmers are provided with good examples to start from. * **Freedom**: Developer implementation freedom is reduced. ### **2. Rules and Recommendations** #### **2.1 General** ##### **2.1.1 Rules:** * Every time a rule in the coding standard is broken, there must be a clearly documented reason for doing so. * No coding standard can anticipate every problem that a programmer will face, and this one doesn't pretend to. But be prepared to defend a divergence from the standard, and do so in a comment. This will prevent a well-intentioned attempt to fix the code later. * When there is a difference between this coding standard and that of the client, the client's coding standard will take precedence. ##### **2.1.2 Recommendations:** * Code for readability first. Optimize for performance only when there's a demonstrated and proven performance problem, and a clearly understood working solution is already available. * **Exceptions**: when it's known beforehand that the performance of the code will be a critical bottleneck (e.g., network interface, disk access, etc), and where this coding standard indicates a practice for performance reasons. #### **2.2 Coding Style** ##### **2.2.1 Rules:** * One level of indentation equals four spaces. Tabs must be replaced with four spaces. * Line length should not exceed 120 characters. * Opening and closing braces must be formatted using one of the following two methods: **Method 1:** On a line by themselves at the same level of indentation as the initiating keyword. ```Java if ( byteBuf == null ) { byteBuf = new ByteBuffer( BUFFER_SIZE ); } ``` **Exception**: the closing brace of the do-while statement. ```Java do { charNumber++; ch = clientName.getChar( charNumber ); } while ( ch != '\0' ); ``` **Method 2:** Opening brace on the same line as the initiating keyword and closing brace on a line by itself at the same level of indentation as the initiating keyword. ```Java if ( byteBuf == null ) { byteBuf = new ByteBuffer( BUFFER_SIZE ); } ``` **Exception**: the closing brace of the do-while and try statements. ```Java do { charNumber++; ch = clientName.getChar( charNumber ); } while ( ch != '\0' ); try { doSomeThing(); } catch (ExceptionClass e) { handleException(); } ``` * The two methods for formatting braces must not be mixed in same file or package. When modifying an existing file or package, the existing brace formatting style must be used and not changed. ##### **2.2.2 Recommendations:** * Always write the left parenthesis directly after a function name (no intervening space). * Surround operators with spaces. Don't do things like this: ```java newXPos+=recClient.Width()+recUpdate.Width()+margin*columns; ``` It makes the operators easy to miss in a quick inspection. Do this instead: ```Java newXPos += recClient.Width() + recUpdate.Width() + margin * columns; ``` * When a statement spans more than one line, break the statement in a way that each line is obviously syntactically incorrect, and indent the continued line or lines in a way that makes the continuation more visible. This prevents misreading of code. For example, the first line of the statement below could be interpreted as a complete statement: ``` Java String addressLine1 = getApartmentNumber() + getStreetAddress() + getStreetName(); ``` The code below provides a strong visual cue that it's continued on the next line: ```Java String addressLine1 = getApartmentNumber() + getStreetAddress() + getStreetName(); ``` #### **2.3 Javadoc Comments** ##### **2.3.1 Rules:** * All classes and public methods must be preceded by a javadoc comment. * Class javadoc comments must contain a meaningful description of the class and an @author tag for each person who has worked on any part of the class. ```Java /** * <p>COPYRIGHT</p> * <p>Blast Radius -- Copyright (C) 2007 Blast Radius * All rights reserved. No part of this computer program * may be used or reproduced in any form by any * means without prior written permission of * Blast Radius.</p> * * <p>DESCRIPTION</p> * <p>Contains the dimensions of a bounding box that will enclose * zero or more graphical objects on a screen. The dimensions * will increase as required when items are added to the box.</p> * * @author Pete Peterson * @version 1.0 * @see related_class */ class BoundingBox { // ... } ``` * Method javadoc comments must include a meaningful description of the method, @param tags for each parameter, and, if applicable, @return and @exception tags. ```Java /** * Adds a graphic object to the bounding box. If any of the object's * dimensions fall outside the box, the box's dimensions will grow to * include them. * * @param element the graphic element to be added to the box * @return true if the bounding box has expanded as a result of adding * the item, false if the dimensions are unchanged * @see see_related_method or material */ public boolean addItem( GraphicElement element ) { // ... } ``` ##### **2.3.2 Recommendations:** * Precede all non-public methods by a javadoc comment. ### **2.4 Files** ###### **2.4.1 Rules:** * All files or packages must include the standard comment header with copyright information as required by the project. ##### **2.4.2 Recommendations:** * Try to keep the size of source files to less than one thousand lines. If source files become larger than this, there's a good chance that the design should be looked at again, with more functionality being moved into smaller objects. ### **2.5 Naming Conventions** #### **2.5.1 Rules:** * Whenever mixed-case names are made up of more than one word, the first letter of each word following the first should be uppercase. ```Java closeFile(); Button okButton; int accountTotal; int average; ``` * Whenever all-uppercase names are made up of more than one word, each word should be separated with an underscore. ```java final int MAX_RANGE = 100; final String BUTTON_NAME = "a button name"; ``` * Methods should be named so that they describe what the method does, starting with an active verb whenever possible. ```Java protected void hideComponent() { /* ... */ } public int getAverage() { /* ... */ } public void refreshScreen() { /* ... */ } ``` * Accessor methods that retrieve an attribute should begin with "get". * Modifier methods should begin with "set". * Components should end with the type of the component. * This is to make the use of the variable a bit more obvious. For example `"ageTextField"` is unambiguous, while "age" may be mistaken for a numeric value. ```java Button cancelButton = new Button(); List customerNameList; BigGrid salesTrackingGrid; ``` * Class names should be a description of the class, and should be mixed case and begin with an uppercase letter. * Interface names should be a description of the interface's services. ```Java interface Compressable { /* ... */ } interface Singleton { /* ... */ } ``` * Package names should be all lower case, and be prefixed with the Internet domain of your organization, but with the components of the domain name in reverse order. * For example, a for-profit organization with a domain `"ourcompany.com"` should create packages with names like `"com.ourcompany.ourproject"`, `"com.ourcompany.anotherproject"`, and `"com.ourcompany.ourproject.packageabc"`. Do not use capitals for the class A prefix. * File names should be camel case. Java source files should match the name of the class they contain. Whether the first letter of the filename is upper or lower case should depend on the use of the file, standard conventions should be followed. Filenames should only contain `'a'-'z', 'A'-'Z', '0'-'9' and '_'`. ##### **2.5.2 Recommendations:** * Avoid the overuse of "i", "j", and "k" as variable names. * These variable names don't offer much in the way of providing readability. Compare: ```Java for ( int i = 0; i < totalMonthsDisplayed; i++ ) { for ( j = 0; j < totalSales; j++ ) { refresh( i, j ); } } ``` ... with ... ```Java for ( int row = 0; row < totalMonthsDisplayed; row++ ) { for ( column = 0; column < totalSales; column++ ) { refresh( row, column ); } } ``` #### **2.6 Class Member Access** ##### **2.6.1 Rules:** * **All non-final fields should be private.** * Hiding data provides all the benefits of using abstract data types, and limits the places that data can be changed (and/or corrupted). Giving an object the ability to prevent access to its internal state also allows it to test itself whenever its state is queried or changed to ensure that the change is consistent with the object's internal state. **Don't do this:** ```Java public class Foo { public int counter; } ``` **Do this instead:** ```Java public class Foo { private int counter; public int getCounter( void ) { return counter; } public void setCounter( int newCounter ) { counter = newCounter; } } ``` Another problem with public, protected, or package access fields becomes apparent when a variable name must be changed or removed from the class. Every derived class (or friends of the derived classes) that directly reference those variables must also be modified. * **Avoid having public member function return a reference to a private field.** * This allows outside code to change the state of an object without that object knowing about it. When possible, return a clone of the member object. #### **2.6.2 Recommendations:** * When a private data member has a public or protected access method, those methods should be used internally by the class as much as possible to provide consistency. **For example, given the following class:** ```Java class Dimensions { public void setDimensions( int width, int height ) { /* ... */ } public int getWidth( void ) { /* ... */ } public int getHeight( void ) { /* ... */ } public int getArea( void ) { /* ... */ } private int width; // width dimension private int height; // height dimension } ``` The code in the body of `Dimension.getArea()` could look like this: ```Java area = width * height; ``` This would work, but will need to be modified if the height or width were changed from a data member to a calculated value. The following code would require no such modification: ```Java area = getWidth() * getHeight(); ``` #### **2.7 Class Constructors & Initialization** ##### **2.7.1 Rules:** * **Instance initialization code blocks should only be used in anonymous classes.** Putting construction code in constructors keeps all this related code together. When various code blocks initialize data throughout the class definition, understanding what's being initialized by whom becomes difficult. * **Always explicitly call the base class constructor in any place that the compiler would implicitly call it.** In any constructor that does not have as its first line of code (a) a call to a base class constructor, or (b) a call to another "this" constructor, the compiler will implicitly insert a call to `super()`. This can lead to confusion when the base class has no no-argument constructor. An additional benefit is that tracing execution through a constructor chain makes more sense when there are explicit calls to `super()`. * **Always explicitly create any constructor that the compiler would implicitly create, even if it contains no statements other than a call to super().** The compiler will explicitly create an empty no-argument constructor when you define no constructors for a class. Explicitly coding one prevents some confusion when debugging, and makes more sense when tracing through constructor chains. ##### **2.7.2 Recommendations:** * Avoid methods with many arguments. * Avoid long and complex methods. #### **2.8 Variables and Types** ##### **2.8.1 Rules:** * Avoid the use of numeric values in code, use symbolic values instead. **For example:** ```java colWidth = strWidth + 10 + ( level * 3 ); // ... cellWidth = cellStrWidth + 10; ``` For the unfortunate programmer who has to maintain (or fix) the above code, there's no indication of what "10" or "3" represents, or whether both "10"s represent the same thing. And if the code maintainer finally figures out that "10" probably represents margin widths, and changes it to something smaller, there's an excellent chance that an instance will be missed, and more time will be wasted tracking down a difficult-to-find bug. Something like the following code should be written in the first place: ```Java final int COL_INDENT_WIDTH = 3; // amount to indent, per level final int COL_LEFT_MARGIN = 5; // width of column left margin in pixels final int COL_RIGHT_MARGIN = 5; // width of column right margin in pixels // pixel width of both margins combined final int COL_MARGINS_WIDTH = COL_LEFT_MARGIN + COL_RIGHT_MARGIN; colWidth = strWidth + COL_MARGINS_WIDTH + ( level * COL_INDENT_WIDTH ); // ... cellWidth = cellStrWidth + COL_MARGINS_WIDTH; ``` * Variables are to be declared with the smallest possible scope. * Each variable is to be declared in a separate declaration statement, and have a commented description. **Don't do this:** ```Java int moveAmount, selectedIndex; ``` **Do this:** ```Java int moveAmount; // number of items to move int selectedIndex; // currently selected item ``` #### **2.9 Flow Control Statements** ###### **2.9.1 Rules:** * The code which follows a case label must always be terminated by a break statement. * The switch statement must always contain a default branch, which handles unexpected cases. ```Java switch (tag) { case A: { // Do something break; } default: { // If no match in above cases, this is executed } } ``` **Exception: **when several different cases have identical handling. * Use opening and closing braces in case blocks that contain variable declarations. * A switch statement must always contain a default branch which handles unexpected cases. * All flow control statements (if, else, while, for and do) must have opening and closing braces, even if the block contains no statements. Empty loops can be deceiving. In the example below, it's easy to mistakenly think that the last line is contained in the loop: ```Java for ( int rowNumber = initialRow; ( rowNumber < totalRows ) && !getRow( rowNumber ).getIsSelected() && ( getRow( rowNumber ).getNumberOfCells() > 0 ); rowNumber++ ); numberOfRowFound = rowNumber; ``` When the braces are included, the empty loop is unmistakable: ```Java for ( int rowNumber = initialRow; ( rowNumber < totalRows ) && !getRow( rowNumber ).getIsSelected() && ( getRow( rowNumber ).getNumberOfCells() > 0 ); rowNumber++ ) { // empty } numberOfRowFound = rowNumber; ``` * Use an explicit if...else... structure rather than the ternary statement. The ternary statement acts as a shortcut for the if...else... statement. However, the statement: ```java ( rowNumber == 0 ) ? selectTable() : selectRow( rowNumber ); ``` ...will likely compile the same as the more readable: ```Java if ( rowNumber == 0 ) { selectTable(); } else { selectRow( rowNumber ); } ``` **Exception**: cases in which a ternary statement simplifies an assignment. ```Java double scale = ( isHalfScale() ? 0.5 : 1 ); // ...may be more readable than... double scale; if ( isHalfScale() ) { scale = 0.5; } else { scale = 1; } ``` ##### **2.9.2 Recommendations:** * **Use inclusive lower limits and exclusive upper limits.** Rather than say that x is the interval x >= 0 and x <= 9, use the limits x >= 0 and x < 10. If you do so, then: * the difference in the limits is the size of the interval (interval = 10-0 rather than interval = 9-0+1) * if the interval is zero, the limits will be equal * the upper limit will never be less than the lower limit. * **Avoid the use of continue.** `continue` tends to make loops harder to understand by concealing the structure of program execution. When tempted to use them, try to use an if...else.. statement instead. Exception: a `continue` statement near the top of a loop can sometimes make the code more readable by avoiding a series of if...else... statements, or a complex loop control structure. For example: ```Java while ( row != null ) { if ( row.getIsEmpty() ) { // row cannot contain data, do not process continue; } // ... process row ... row = row.getNext(); } ``` * **Avoid the use of break in anything but the switch statement.** break tends to make loops harder to understand by concealing their exit conditions. Here's an example of break that confuses the structure of a loop: ```Java while ( true ) { Rectangle areaRect = area.getRectArea(); if ( areaRect.pointInRect( firstPoint ) ) { if ( area.getType() == NON_CLIENT_AREA ) areaWidth -= areaRect.Width(); else break; } if ( area.getNext() == null ) break; else area = area.getNext(); } ``` **Exception**: break can sometimes be used judiciously to avoid messy nested if...else statements in loops or a large number of boolean conditions in the control statement at the top: ```Java while ( ch != '\u0000' ) { // if this is a metastring token, drop out of the loop if ( ch == '%' ) { tokenPosition = pos; break; // <------ early exit from loop } // ... more code to process 'ch' ... } ``` * **Avoid the use of multiple return statements.** The flow of control within a function is more difficult to understand when there are multiple exit points. **Exception**: early returns can sometimes be used at the beginning of a function to avoid long if...else.. constructions. When used in this way, it's recommended that they are documented in a way that draws attention to them. ```Java boolean setName( Client client, String name ) { int clientIndex = findClient( client ); if ( clientIndex == CLIENT_NOT_FOUND ) { return; // <--------- early return for invalid client } // ... } ``` #### **2.10 Comments** ##### **2.10.1 Recommendations:** * **Comment in a style that's easy to maintain.** Example of a hard-to-maintain commenting style: ```Java //--------------------------------------// // get the size of the buffer // //--------------------------------------// ``` Example of easy-to-maintain commenting styles: ```Java //------------------------------ // get the size of the buffer //------------------------------ /* * get the size of the buffer * then allocate another buffer of the same size. */ ``` * **Comment as you go.** Don't code with the intention of going back later and putting comments in. Try to comment first and code around the comments. * **Avoid non-data endline comments.** Endline comments are difficult to maintain because they have to aligned properly, are difficult to edit, and there usually isn't enough space to comment effectively. **Exceptions**: data declarations, and comments at the end of blocks. Example of these: ```Java int numberOfKeys; // number of virtual keystrokes // ... } // switch } // for ``` * **Don't duplicate the code in the comment.** The following comments are redundant: ```Java // if the allocation flag is more than zero if ( allocSize > 0 ) { // initialize buffer size to allocSize bufferSize = allocSize; } ``` This comment explains what's actually happening: ```Java // if a buffer was successfully allocated, record the size if ( allocSize > 0 ) { bufferSize = allocSize; } ``` #### **2.11 Exception-Handling** ##### **2.11.1 Rules:** * **Where there is a clear separation between presentation classes and integration classes, the integration class should repackage checked exceptions to pass to the presentation class to preserve encapsulation.** ```Java public class UserDAOImpl implements UserDAO { findByUserId(String userId) { User user = null; try { user = (User)getSqlMapClientTemplate().queryForObject(GET_USER, userId); } catch(DataAccessException ex) { //service class, must repackage exception logger.error("could not access database",ex); throw new ApplicationException("could not connect to database", ex); } } } ``` * **Preserve the original stack trace information throughout the life of the Exception.** If an exception is caught in an integration class, and an exception is to be re-thrown to the presentation class, the newly thrown exception must preserve the caught exception stack trace. * **Exceptions should be logged once whenever they are caught except as outlined by rule 4 and dealt with where they are caught, exceptions should not be passed to generic exception handling methods.** ```Java public class UserDAOImpl implements UserDAO { findByUserId(String userId) { User user = null; try { user = (User)getSqlMapClientTemplate().queryForObject(GET_USER, userId); } catch(DataAccessException ex) { //service class, must repackage exception logger.error("could not access database",ex); throw new ApplicationException("could not connect to database", ex); } } } ``` * **Swallowed checked exceptions should be avoided, and where they cannot be avoided proper commenting should document why an empty catch block exists. The general exception java.lang.Exception should never be caught.** ```Java try { AdditionalData additionalData = getAdditionalUserData(userId); } catch(UserNotRegistered ex) { /* * thrown if the user has not been registered in the third party service * which isn't necessary for updating the user information */ } ``` * **A function should not contain split try catch blocks, where multiple checked exceptions are caught they should be handled in subsequent catch blocks or if necessary in nested try blocks.** ```Java try { User user = (User)getSqlMapClientTemplate().queryForObject(GET_USER, userId); UserMetaData userMetaData = userMetaDataService.getUserMetaDataByUser(user); } catch(SQLException ex) { throw new ApplicationException("could not access database" , ex); } catch(WebServiceConnectionException ex) { throw new ApplicationException("could not connect to web service" , ex); } ``` * **List all normal exceptions thrown in the throws clause, not just base class of related exceptions.** In other words, if your method throws MyException and MyDerivedException (which is derived from MyException), don't just declare MyException. While this is legal in the language, it hides useful information from those using your class. * **Catch subclasses before base classes.** If you catch the base class of an exception before trying to catch classes derived from it, the first catch block will catch all derived exceptions: ```Java try { doSomething(); } catch ( BaseExceptionClass e ) // this should come after the next block { // ... } catch ( DerivedFromBaseExceptionClass e ) { // ... will never get here, because the previous catch // statement will catch all classes derived from // BaseExceptionClass } ``` #### **2.12 Event-Handling** ##### **2.12.1 Rules:** * **Don't call message handlers directly.** If another function needs to invoke code identical to that in a message handler, move the code out into a different function, and have both the message handler and the other function call the common code. * **Event handler methods should be lightweight and delegate complex logic to service or business logic classes.** Event handlers should primarily coordinate actions and delegate to appropriate service methods rather than containing complex business logic themselves. #### **2.13 Memory Management and Performance** ##### **2.13.1 Rules:** * **Always use try-with-resources for AutoCloseable resources.** This ensures proper resource cleanup and prevents resource leaks. ```Java // Good try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) { return reader.readLine(); } // Bad BufferedReader reader = new BufferedReader(new FileReader("file.txt")); try { return reader.readLine(); } finally { reader.close(); } ``` * **Close resources in the reverse order of their creation in finally blocks (when try-with-resources cannot be used).** * **Avoid creating unnecessary objects in loops.** ```Java // Bad for (int i = 0; i < 1000; i++) { String status = "Processing " + i; log.debug(status); } // Good for (int i = 0; i < 1000; i++) { log.debug("Processing {}", i); } ``` * **Never ignore InterruptedException without re-interrupting the thread.** ```Java try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // Preserve interrupt status throw new RuntimeException("Thread interrupted", e); } ``` ##### **2.13.2 Recommendations:** * **Use StringBuilder or StringBuffer for string concatenation in loops.** ```Java // Bad String result = ""; for (String item : items) { result += item; } // Good StringBuilder result = new StringBuilder(); for (String item : items) { result.append(item); } ``` * **Avoid premature optimization. Profile first, then optimize.** * **Consider using object pooling only for expensive-to-create objects (e.g., database connections, thread pools).** * **Avoid using finalizers. Use try-with-resources or explicit cleanup methods instead.** * **Be aware of autoboxing/unboxing costs in performance-critical code.** ```Java // Bad - autoboxing in loop Integer sum = 0; for (int i = 0; i < 1000000; i++) { sum += i; // Boxing and unboxing on each iteration } // Good int sum = 0; for (int i = 0; i < 1000000; i++) { sum += i; } ``` * **Use lazy initialization for expensive objects only when necessary.** ```Java private volatile ExpensiveObject instance; public ExpensiveObject getInstance() { if (instance == null) { synchronized (this) { if (instance == null) { instance = new ExpensiveObject(); } } } return instance; } ``` #### **2.14 Concurrency and Thread Safety** ##### **2.14.1 Rules:** * **Always use the highest-level concurrency utilities available** (Executor framework, concurrent collections) rather than wait(), notify(), and synchronized blocks when possible. * **Document thread-safety guarantees for all classes.** Use annotations like` @ThreadSafe`, `@NotThreadSafe`, or `@Immutable` in javadoc. ```Java /** * This class is thread-safe. All methods can be called concurrently. * @ThreadSafe */ public class ThreadSafeCounter { // ... } ``` * **Never expose mutable internal state without proper synchronization.** * **Always use the volatile keyword for flags that are set by one thread and read by others.** ```Java private volatile boolean shutdownRequested = false; ``` * **Avoid holding locks while calling methods on objects outside your control.** This can lead to deadlocks. * **Always acquire multiple locks in a fixed global order to prevent deadlock.** * **Use thread-safe collections instead of manually synchronizing collection access.** ```Java // Good Map<String, String> map = new ConcurrentHashMap<>(); // Bad Map<String, String> map = Collections.synchronizedMap(new HashMap<>()); ``` ##### **2.14.2 Recommendations:** * **Prefer immutable objects for thread safety.** ```Java public final class ImmutablePerson { private final String name; private final int age; public ImmutablePerson(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } ``` * **Use ExecutorService instead of creating threads directly.** ```Java // Good ExecutorService executor = Executors.newFixedThreadPool(10); executor.submit(() -> performTask()); executor.shutdown(); // Bad new Thread(() -> performTask()).start(); ``` * **Prefer ReentrantLock over synchronized when you need advanced features** (tryLock, timed locks, interruptible locks). * **Use CountDownLatch, CyclicBarrier, or Phaser for coordinating multiple threads.** * **Avoid ThreadLocal unless absolutely necessary, and always clean up ThreadLocal variables.** ```Java private static final ThreadLocal<DateFormat> dateFormat = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd")); public void cleanup() { dateFormat.remove(); // Always clean up } ``` * **Use CompletableFuture for asynchronous programming.** ```Java CompletableFuture.supplyAsync(() -> fetchData()) .thenApply(data -> processData(data)) .thenAccept(result -> saveResult(result)) .exceptionally(ex -> { log.error("Error in async chain", ex); return null; }); ``` * **Document lock ordering to prevent deadlocks.** * **Consider using the Fork/Join framework for recursive parallel tasks.** #### **2.15 API Design and Interfaces** ##### **2.15.1 Rules:** * **Prefer interfaces to abstract classes for defining types.** Interfaces provide more flexibility as Java supports multiple interface implementation but only single inheritance. * Use functional interfaces for single abstract method interfaces, and annotate with @FunctionalInterface. ```Java @FunctionalInterface public interface DataProcessor { void process(Data data); } ``` * **Never expose collection implementations in public APIs. Return interfaces instead.** ```Java // Good public List<String> getNames() { return new ArrayList<>(names); } // Bad public ArrayList<String> getNames() { return names; } ``` * **Return empty collections or arrays instead of null.** ```Java // Good public List<Customer> getCustomers() { return customers.isEmpty() ? Collections.emptyList() : new ArrayList<>(customers); } // Bad public List<Customer> getCustomers() { return customers.isEmpty() ? null : customers; } ``` * **Use defensive copying for mutable objects passed to or returned from methods.** ```Java public class DateRange { private final Date start; private final Date end; public DateRange(Date start, Date end) { this.start = new Date(start.getTime()); // Defensive copy this.end = new Date(end.getTime()); // Defensive copy } public Date getStart() { return new Date(start.getTime()); // Defensive copy } } ``` * **Never return null from methods that return collections or arrays** ##### **2.15.2 Recommendations:** * **Design interfaces for the clients, not for implementations.** * **Keep interfaces small and focused (Interface Segregation Principle).** * **Use default methods in interfaces sparingly, primarily for evolution.** ```Java public interface Repository { List<Entity> findAll(); default List<Entity> findAllSorted() { return findAll().stream() .sorted() .collect(Collectors.toList()); } } ``` * **Prefer method overloading to optional parameters for API design.** * **Use Builder pattern for classes with many parameters.** ```Java public class User { private final String name; private final String email; private final int age; private User(Builder builder) { this.name = builder.name; this.email = builder.email; this.age = builder.age; } public static class Builder { private String name; private String email; private int age; public Builder name(String name) { this.name = name; return this; } public Builder email(String email) { this.email = email; return this; } public Builder age(int age) { this.age = age; return this; } public User build() { return new User(this); } } } // Usage User user = new User.Builder() .name("John") .email("john@example.com") .age(30) .build(); ``` * **Document preconditions, postconditions, and invariants in javadoc.** * **Consider using marker interfaces for metadata (like Serializable, Cloneable).** * **Provide programmatic access to string representations (toString() should not be the only way).** #### **2.16 Collection Framework Best Practices** ##### **2.16.1 Rules:** * **Choose the correct collection type based on the use case:** * `ArrayList` for random access and iteration * `LinkedList` for frequent insertions/deletions * `HashSet` for fast lookups with no duplicates * `TreeSet` for sorted sets * `HashMap` for key-value pairs * `LinkedHashMap` for insertion-ordered maps * `TreeMap` for sorted maps * **Specify initial capacity for collections when the size is known in advance.** ```Java // Good List<String> list = new ArrayList<>(expectedSize); Map<String, String> map = new HashMap<>(expectedSize); // Bad List<String> list = new ArrayList<>(); // Will resize multiple times ``` * **Never remove elements from a collection while iterating with for-each loop.** ```Java // Bad - ConcurrentModificationException for (String item : list) { if (condition) { list.remove(item); } } // Good Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String item = iterator.next(); if (condition) { iterator.remove(); } } // Better (Java 8+) list.removeIf(item -> condition); ``` * **Use Collections.unmodifiable or List.of(), Set.of(), Map.of() to return immutable collections.*** ```Java // Good (Java 9+) List<String> immutableList = List.of("a", "b", "c"); Map<String, Integer> immutableMap = Map.of("key1", 1, "key2", 2); // Good (Java 8) List<String> immutableList = Collections.unmodifiableList( new ArrayList<>(Arrays.asList("a", "b", "c")) ); ``` * **Never use raw types; always parameterize collections.** ``` Java // Bad List list = new ArrayList(); // Good List<String> list = new ArrayList<>(); ``` ##### **2.16.2 Recommendations:** * **Use the diamond operator (<>) to avoid redundant type information.** ```Java // Good Map<String, List<String>> map = new HashMap<>(); // Bad Map<String, List<String>> map = new HashMap<String, List<String>>(); ``` * **Prefer Arrays.asList() or List.of() for fixed-size lists.** ``` Java // Good (immutable, Java 9+) List<String> list = List.of("a", "b", "c"); // Good (fixed-size, pre-Java 9) List<String> list = Arrays.asList("a", "b", "c"); ``` * **Use EnumSet instead of bit fields for enum collections.** ```Java // Good Set<DayOfWeek> weekend = EnumSet.of(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY); // Bad int weekend = SATURDAY | SUNDAY; ``` * **Use EnumMap for enum keys instead of HashMap.** ``` Java Map<DayOfWeek, String> schedule = new EnumMap<>(DayOfWeek.class); ``` * **Consider using Guava collections for advanced use cases (Multimap, BiMap, Table, etc.).** * **Use Collection.toArray(new T[0]) instead of Collection.toArray(new T[size]).** ```Java // Good String[] array = list.toArray(new String[0]); // Outdated String[] array = list.toArray(new String[list.size()]); ``` * **Sort collections using Comparator and Collection.sort() or Stream API.** ``` Java // Good list.sort(Comparator.comparing(Person::getName)); // Or using Stream List<Person> sorted = list.stream() .sorted(Comparator.comparing(Person::getName)) .collect(Collectors.toList()); ``` #### **2.17 Java 8+ Features Standards** ##### **2.17.1 Rules:** * **Use lambda expressions instead of anonymous inner classes for functional interfaces.** ```Java // Good list.forEach(item -> System.out.println(item)); // Bad list.forEach(new Consumer<String>() { @Override public void accept(String item) { System.out.println(item); } }); ``` * **Use method references when they are clearer than lambda expressions.** ```Java // Good list.forEach(System.out::println); // Acceptable list.forEach(item -> System.out.println(item)); ``` * **Use Optional to represent potentially absent values, but not for collections, arrays, or method parameters.** ```Java // Good public Optional<User> findUserById(String id) { return Optional.ofNullable(userMap.get(id)); } // Bad - don't use Optional for parameters public void processUser(Optional<User> user) { } // Bad - don't return Optional collections public Optional<List<User>> getUsers() { } ``` * **Never call Optional.get() without checking Optional.isPresent() first, or use proper Optional methods.** ```Java // Bad Optional<User> user = findUser(); User u = user.get(); // May throw NoSuchElementException // Good Optional<User> user = findUser(); User u = user.orElse(defaultUser); // Or user.ifPresent(u -> processUser(u)); ``` * **Use Stream API for collection processing, but avoid overusing streams for simple iterations.** ```Java // Good - streams add value List<String> names = users.stream() .filter(user -> user.isActive()) .map(User::getName) .sorted() .collect(Collectors.toList()); // Bad - simple loop is clearer users.stream().forEach(user -> processUser(user)); // Better for (User user : users) { processUser(user); } ``` * **Always close streams that are backed by I/O resources.** ```Java try (Stream<String> lines = Files.lines(Paths.get("file.txt"))) { lines.filter(line -> line.contains("error")) .forEach(System.out::println); } ``` * **Use java.time package (LocalDate, LocalDateTime, ZonedDateTime) instead of Date and Calendar.** ```Java // Good LocalDate today = LocalDate.now(); LocalDateTime now = LocalDateTime.now(); ZonedDateTime zonedNow = ZonedDateTime.now(ZoneId.of("UTC")); // Bad Date date = new Date(); Calendar calendar = Calendar.getInstance(); ``` ##### **2.17.2 Recommendations:** * **Prefer functional composition over imperative code when it improves readability.** * **Use Collectors for stream terminal operations.** ```Java // Collect to list List<String> names = users.stream() .map(User::getName) .collect(Collectors.toList()); // Collect to map Map<String, User> userMap = users.stream() .collect(Collectors.toMap(User::getId, Function.identity())); // Joining strings String csv = names.stream() .collect(Collectors.joining(", ")); // Grouping Map<Department, List<Employee>> byDept = employees.stream() .collect(Collectors.groupingBy(Employee::getDepartment)); ``` * **Use Optional.orElseThrow() for validation.** ```Java User user = findUserById(id) .orElseThrow(() -> new UserNotFoundException("User not found: " + id)); ``` * **Prefer flatMap for nested optionals or streams.** ``` Java Optional<String> result = user .flatMap(User::getAddress) .flatMap(Address::getZipCode); ``` * **Use parallel streams judiciously, only for CPU-intensive operations on large datasets.** ```Java // Use parallel streams only when appropriate long count = largeList.parallelStream() .filter(this::expensiveOperation) .count(); ``` * **Use Stream.iterate() or Stream.generate() for infinite streams with limit().** ```Java Stream.iterate(0, n -> n + 1) .limit(10) .forEach(System.out::println); ``` * **Use CompletableFuture for asynchronous programming.** * **Leverage default and static methods in interfaces for backward compatibility.** * **Use @FunctionalInterface annotation for functional interfaces.** * **Consider using var (Java 10+) for local variables when the type is obvious.** ``` Java // Good - type is obvious var list = new ArrayList<String>(); var user = userRepository.findById(id); // Bad - type is not obvious var result = process(); // What type is this? ``` #### **2.18 Logging Standards** ##### **2.18.1 Rules:** * **Use SLF4J as the logging facade, not Log4j or java.util.logging directly.** ```Java import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UserService { private static final Logger logger = LoggerFactory.getLogger(UserService.class); } ``` * **Initialize loggers as private static final fields.** * **Use appropriate log levels:** * **ERROR**: System failures, unrecoverable errors * **WARN:** Recoverable errors, deprecated API usag * **INFO**: Important business events, application lifecycle * **DEBUG**: Detailed information for debugging * **TRACE**: Very detailed information, typically for diagnosis * **Never log sensitive information (passwords, credit cards, PII, tokens, session IDs)** ```Java // Bad logger.info("User logged in: {}", user.getPassword()); // Good logger.info("User logged in: {}", user.getUsername()); ``` * **Use parameterized logging instead of string concatenation.** ```Java // Good logger.debug("Processing user {} with status {}", userId, status); // Bad logger.debug("Processing user " + userId + " with status " + status); ``` * **Always log exceptions with the exception object, not just the message.** ```Java // Good try { processData(); } catch (DataException e) { logger.error("Failed to process data for user {}", userId, e); } // Bad catch (DataException e) { logger.error("Failed to process data: " + e.getMessage()); } ``` * **Guard expensive log statements with level checks.** ```Java if (logger.isDebugEnabled()) { logger.debug("Complex calculation result: {}", expensiveCalculation()); } ``` ##### **2.18.2 Recommendations:** * **Use MDC (Mapped Diagnostic Context) for request tracking.** ```Java MDC.put("requestId", requestId); MDC.put("userId", userId); try { // Process request logger.info("Processing request"); } finally { MDC.clear(); } ``` * **Log method entry and exit only at DEBUG or TRACE level.** ```Java public void processOrder(Order order) { logger.debug("Entering processOrder with order: {}", order.getId()); try { // Process order logger.debug("Exiting processOrder successfully"); } catch (Exception e) { logger.debug("Exiting processOrder with error", e); throw e; } } ``` * **Use structured logging for complex data.** ```Java logger.info("Order processed: orderId={}, userId={}, amount={}, status={}", order.getId(), order.getUserId(), order.getAmount(), order.getStatus()); ``` * **Avoid logging in loops unless absolutely necessary.** ```Java // Bad for (User user : users) { logger.debug("Processing user: {}", user.getId()); processUser(user); } // Good logger.debug("Processing {} users", users.size()); for (User user : users) { processUser(user); } ``` * **Include context in log messages.** ```Java // Bad logger.error("Processing failed"); // Good logger.error("Order processing failed for orderId: {}, userId: {}", orderId, userId); ``` * **Use consistent log message formatting across the application.** * **Configure appropriate log rotation and retention policies.** * **Use asynchronous logging for high-throughput applications.** #### **2.19 Testing and Mocking Standards** ##### **2.19.1 Rules:** * **Follow naming convention for test classes**: `<ClassUnderTest>Test` ```Java // Class under test: UserService.java // Test class: UserServiceTest.java ``` * **Follow naming convention for test methods:** `testMethodName_StateUnderTest_ExpectedBehavior` or `methodName_StateUnderTest_ExpectedBehavior` ```Java @Test public void findUserById_UserExists_ReturnsUser() { } @Test public void findUserById_UserNotFound_ThrowsException() { } ``` * **Structure tests using the Arrange-Act-Assert (AAA) pattern.** ```Java @Test public void calculateTotal_WithDiscount_ReturnsDiscountedTotal() { // Arrange Order order = new Order(); order.addItem(new Item("Product", 100.0)); Discount discount = new Discount(0.1); // 10% discount // Act double total = order.calculateTotal(discount); // Assert assertEquals(90.0, total, 0.01); } ``` * **Each test method should test one specific behavior or scenario.** * **Use @Before/@BeforeEach for common setup and @After/@AfterEach for cleanup.** ```Java @BeforeEach public void setUp() { userRepository = mock(UserRepository.class); userService = new UserService(userRepository); } @AfterEach public void tearDown() { // Cleanup resources } ``` * **Always use assertion libraries (JUnit assertions, AssertJ, Hamcrest).** ```Java // Good - JUnit 5 assertEquals(expected, actual); assertThrows(IllegalArgumentException.class, () -> service.process(null)); // Good - AssertJ assertThat(result).isNotNull() .hasSize(3) .contains("item1", "item2"); ``` * **Never catch exceptions in tests; use assertThrows instead.** ```Java // Good assertThrows(UserNotFoundException.class, () -> userService.findById("invalid")); // Bad try { userService.findById("invalid"); fail("Expected UserNotFoundException"); } catch (UserNotFoundException e) { // Expected } ``` * **Mock external dependencies, but don't mock the class under test.** ```Java @Test public void createUser_ValidUser_SavesUser() { // Arrange UserRepository mockRepository = mock(UserRepository.class); UserService service = new UserService(mockRepository); User user = new User("John", "john@example.com"); when(mockRepository.save(any(User.class))).thenReturn(user); // Act User result = service.createUser(user); // Assert verify(mockRepository).save(user); assertEquals("John", result.getName()); } ``` ##### **2.19.2 Recommendations:** * **Use Mockito for mocking, avoid PowerMock unless absolutely necessary.** ```Java @ExtendWith(MockitoExtension.class) public class UserServiceTest { @Mock private UserRepository userRepository; @InjectMocks private UserService userService; @Test public void testFindUser() { when(userRepository.findById("123")).thenReturn(Optional.of(user)); // Test logic } } ``` * **Use ArgumentCaptor to verify complex method arguments.** ```Java @Test public void createUser_ValidUser_SavesWithCorrectData() { ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class); userService.createUser("John", "john@example.com"); verify(userRepository).save(userCaptor.capture()); User capturedUser = userCaptor.getValue(); assertEquals("John", capturedUser.getName()); assertEquals("john@example.com", capturedUser.getEmail()); } ``` * **Use @ParameterizedTest for testing multiple inputs.** ```Java @ParameterizedTest @ValueSource(strings = {"", " ", " "}) public void isBlank_BlankStrings_ReturnsTrue(String input) { assertTrue(StringUtils.isBlank(input)); } @ParameterizedTest @CsvSource({ "1, 1, 2", "2, 3, 5", "5, 5, 10" }) public void add_TwoNumbers_ReturnsSum(int a, int b, int expected) { assertEquals(expected, calculator.add(a, b)); } ``` * **Use test fixtures for complex test data setup.** ```Java public class UserFixtures { public static User createDefaultUser() { return new User("John", "john@example.com", 30); } public static User createAdminUser() { User user = createDefaultUser(); user.setRole(Role.ADMIN); return user; } } ``` * **Aim for high test coverage, but focus on critical paths and edge cases.** * **Use integration tests for testing component interactions, unit tests for isolated logic**. * **Use @SpringBootTest sparingly; prefer @WebMvcTest, @DataJpaTest, etc., for focused testing.** ```Java @WebMvcTest(UserController.class) public class UserControllerTest { @Autowired private MockMvc mockMvc; @MockBean private UserService userService; @Test public void getUser_ValidId_ReturnsUser() throws Exception { when(userService.findById("123")).thenReturn(user); mockMvc.perform(get("/users/123")) .andExpect(status().isOk()) .andExpect(jsonPath("$.name").value("John")); } } ``` * **Use test containers for integration testing with databases and external services** ```Java @Testcontainers public class UserRepositoryIntegrationTest { @Container static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:13"); @Test public void testDatabaseOperations() { // Test with real database } } ``` * **Never use System.out.println() in tests; use proper assertions and logging.** * **Keep tests fast. Slow tests won't be run frequently.** * **Use BDD style for better readability (given-when-then).** ```Java @Test public void userRegistration_ValidData_CreatesUser() { // Given String email = "test@example.com"; String password = "password123"; // When User user = userService.register(email, password); // Then assertThat(user).isNotNull(); assertThat(user.getEmail()).isEqualTo(email); assertThat(user.isActive()).isTrue(); } ``` * **Document complex test scenarios with comments.** * **Use @Disabled with a reason when temporarily disabling tests.** ```Java @Test @Disabled("Disabled until bug #123 is fixed") public void testComplexScenario() { // Test code } ``` **Document** - [Enovate Coding Standards - Core Java](https://docs.google.com/document/d/1EaOaSk-hbuje0igvIxl1DXcHQROc3KP-S49eD1IUGqg/edit?tab=t.0)