Code conventions followed in Rokomari.com
-
Naming Conventions : Describe various programming naming schema (ex: variable, method names etc)
-
Base Conventions : Descibe the basic coding conventions.
-
Java Conventions : Describe the JAVA programming language conventions
-
Spring Conventions : Describe the Spring Framework project related conventions.
- should be noun
- should be all
lowercase - should be only one word after each dot
- only use English words, avoid especial characters (
_/$etc)
package com.rokomari.model- should be noun
- should be
UpperCammelCase - should bound the namming upto 2 words
- should not start/end with
_/$ - for domain classes, use
UPERCASEdomain part postfix. (Ex:RefundDTOinstead ofRefundDto) - if any Design Pattern used, should add the patterns name in the postfix. (Ex:
CustomerObserver,ItemObservable,CakeFactory) - avoid uncommon abbreviations in naming. (Ex: use
AbstractCakeinstead ofAbsCake)
public class CompanyService {
...
}- should be
UpperCammelCase - should be Adjective, Ex:
Eatable - can be noun if the interface marked as parent class (Ex:
LocationService) or presented as a family of classes (Ex:List,Map) - should not start/end with
_/$
public interface Focusable {
...
}- should be verb, like giving a command/action
- should be
lowerCammelCase - should contains upto highest 5 params. If required > 5 params, params should wrap around into a model and pass.
- if the language support named params, priotize them.
- should be bound upto 3 words
- should not start/end with
_/$(exception for_if language required_for private modification) - avoid writting
Booleanveriable'sgetter/setterusingis. usegetValue()/setValue(). (Ex:void setCompleted(Boolean boolean),Boolean getCompleted())
List<User> getAllUsers(Integer id) {
...
}- should be noun
- should be in
lowerCammelCase - should bound upto 2 words
- should not start/end with
_/$(exception for_if language required_for private modification) - avoid using
isprefix forBooleandata type. (Ex: usecompletedinstead ofisComplete/isCompleted)
String firstName;- should be
UPPERCASEwithUNDER_SCOREbetween words - should be noun
- should bound upto 2 words
- should not start/end with
_/$
private Double MAX_PRICE == 99.0D;- same as
classnaming convention, but hasBase/Abstractprefix
abstract class BaseActivity {
...
}- same as
classnaming convention, but hasExceptionpostfix
public class MessageNotFoundException extends Exception {
...
}- should be noun
- should be
UPPERCASEwithUNDER_SCOREbetween words - upto 2 words
public enum Status {
NOT_COMPLETE,
COMPLETE
}Tfor general purpose useEfor collection elementsK&Vfor key-value pair
public interface StudentMap<K,V> {
....
}- should be
UpperCammelCase - can be noun/adjective/verb based on use-case
public @interface EnableCaching
public @interface Depricated- should follow
class-under-test's package structure for the test class - name should be same as
class-under-test's name withTestpostfix
public class TransactionTest {
...
}- should follow
class-under-test's package structure for the test class - name should be same as
class-under-test's name withIntegTestpostfix
public class TransactionIntegTest {
...
}- method name breaks down into
4sections. (method-under-test,GIVEN block[Optinal],WHEN block,THEN block). each block should followlowerCammelCase& between them should haveunder_score. GIVEN,WHEN,THENblocks should prefix with respective type names.GIVENblock describe the precondition of the test.WHENblock describe the condition of the test.THENblock describe the desired output of the test.
@Test
void getAllUsers_givenDBAccessFailure_whenDBReturnEmpty_thenShouldReturnEmptyList() {
...
}-
Add copyright text in the start of every file. For example :
Copyright (c), Onnorokom Web Services Ltd (OWSL) and/or its affiliates. All rights reserved. OWSL PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
- use
4spaces for block indentation. - Use a single blank line to separate sections with the same logic or semantics.
- A space before opening brace.
- No line break before the opening brace.
- Line break after the opening brace.
- Line break before the closing brace.
- Line break after the closing brace, only if that brace terminates a statement or terminates the body of a method, constructor, or named class. For example, there is no line break after the brace if it is followed by else or a comma.
return () -> {
while (condition()) {
method();
}
};
class MyClass() {
@Override
public void method() {
if (condition()) {
try {
something();
} catch (ProblemException e) {
recover();
}
} else if (otherCondition()) {
somethingElse();
} else {
lastThing();
}
}
}- always use braces for single-line blocks.
if (condition()) { statement(); }
- for empty blocks, block should be closed in the next line.
if (condition()) { }
- No space is used between the
(character and its following character. Same for the)character and its preceding character.void statement(Integer i) { ... }
- if method has multiple parameters, their should be a space between them in the method declaration & metthod calling
void statement(Integer i, String st, Status status) { ... } statement(1, "Hello", Status.FINISHED);
- There must be one space between keywords, such as if/for/while/do/switch/try/catch/finally etc, and parentheses.
- There must be one space at both left and right side of operators, such as
=,&&,+,-, ternary operator, etc.Integer i = 10; Boolean b = false; if (i == 10 && b == true) { i = i + 1 ? 0 : -10; i++; }
- In a
switchblock, each case should be finished by break/return. If not, a note should be included to describe at which case it will stop. Within everyswitchblock, a default statement must be present, even if it is empty.
- Always import all classes separately, donot import all classes of a package using wildclause character (for example:
*).
import com.rokomari.app.service.A;
import com.rokomari.app.service.B;
import com.rokomari.app.service.C;
import com.rokomari.app.service.D;
import com.rokomari.app.service.E;
import com.rokomari.app.service.F;- avoid using premitive data type if the language provide equivalent reference type. (Ex: for Java use
Integerinstead ofint) - for Array, use
[]after type, instead of variable name. (Ex: useString[] names;instead ofString names[]) - for
Longvalue useLinstead ofl, & forDoublevalue useDinstead ofd. use these literals when ever possible. - if language supports, use
under_scorebetween big integer value for easy reading purpose.Integer money = 1_00_000;
-
for OOP languages, every file should contains
1top level class. -
source file should contains followings in order
- License or copyright information, if present
- Package statement
- Import statements
- Exactly one top-level class
Exactly one blank line separates each section that is present.
-
inside the class, following conventions should be followed in order
- final variables
- static variables
- public variables (P.S: using getter/setter of a private veriable instead is recommendend)
- private variables
- static methods
- constructors (default constructor at the first)
- public methods & thier dependent private methods
- inner static class
- inner class
- supporting enum class
Exactly one blank line separates each section that is present.
Exactly one blank line before first section that is present.
-
use different classes for configurations/utilities/constants based on their type. Avoid using one big file for all types. Ex ->
wallet related constant should go to WalletConstants. Account related constant should go to Account Constansts.
Dagger Library config should go to DaggerConfig. Swagger Library config should go to SwaggerConfig.
Validation related utilities should go to ValidationUtils. Convertion related utilities should go to ConvertionsUtils.
-
[Mandatory] An overridden method from an interface or abstract class must be marked with
@Overrideannotation. -
[Mandatory] Using a deprecated class or method is prohibited.
-
[Mandatory] Since
NullPointerExceptioncan possibly be thrown while calling the equals method ofObject, equals should be invoked by a constant or an object that is definitely ot null.Positive example:
"test".equals(object);Counter example:object.equals("test"); -
[Mandatory] Use the
equalsmethod, rather than reference equality==, to compare primitive wrapper classes. -
[Recommended] Multiple constructor methods or homonymous methods in a class should be put together for better readability.
-
[Recommended] Keyword final should be used in the following situations:
- A class which is not allow to be inherited.
- A variable which is not allow to be modified.
- A method which is not allow to be overridden.
-
[Recommended] Define the access level of members in class with severe restrictions:
- Constructor methods must be
privateif an allocation usingnewkeyword outside of the class is forbidden. - Constructor methods are not allowed to be
publicordefaultin a utility class. - Nonstatic class variables that are accessed from inheritants must be
protected. - Nonstatic class variables that no one can access except the class that contains them must be
private. - Static variables that no one can access except the class that contains them must be
private. - Static variables should be considered in determining whether they are
final. - Class methods that no one can access except the class that contains them must be
private. - Class methods that are accessed from inheritants must be
protected.
Note: We should strictly control the access for any classes, methods, arguments and variables. Loose access control causes harmful coupling of modules. Imagine the following situations. For a
privateclass member, we can remove it as soon as we want. However, when it comes to apublicclass member, we have to think twice before any updates happen to it. - Constructor methods must be
-
[Mandatory] Do not catch Runtime exceptions defined in JDK, such as
NullPointerExceptionandIndexOutOfBoundsException. Instead, pre-check is recommended whenever possible.Note: Use try-catch only if it is difficult to deal with pre-check, such as
NumberFormatException.
Positive example:if (obj != null) {...}
Counter example:try { obj.method() } catch(NullPointerException e){…} -
[Mandatory] It is irresponsible to use a try-catch on a big chunk of code. Be clear about the stable and unstable code when using try-catch. The stable code that means no exception will throw. For the unstable code, catch as specific as possible for exception handling.
-
[Mandatory] Do not suppress or ignore exceptions. If you do not want to handle it, then re-throw it. The top layer must handle the exception and translate it into what the user can understand.
-
[Mandatory] Make sure to invoke the rollback if a method throws an Exception.
-
[Mandatory] Closeable resources (stream, connection, etc.) must be handled in finally block. Never throw any exception from a finally block.
Note: Use the try-with-resources statement to safely handle closeable resources (Java 7+).
-
[Mandatory] Never use return within a finally block.
-
[Recommended] If a method can return
null, then wrap the return type of the method withOptional<Type>. returnOptional.empty()instead ofnull. -
[Recommended] Do not throw
RuntimeException,Exception, orThrowabledirectly. It is recommended to use well defined custom exceptions such asDAOException,ServiceException, etc. -
[For Reference] Avoid duplicate code (Do not Repeat Yourself, also known as DRY principle).
Note: Copying and pasting code arbitrarily will inevitably lead to duplicated code. If you keep logic in one place, it is easier to change when needed. If necessary, extract common codes to methods, abstract classes or even shared modules.
-
[For Reference] Try simple solution instead of complex one (Keep It Simple Silly (KISS))
- [Mandatory] Do not use API in log system (Log4j, Logback) directly. API in log framework SLF4J is recommended to use instead, which uses Facade pattern and is conducive to keep log processing consistent.
import org.slf4j.Logger; import org.slf4j.LoggerFactory; private static final Logger logger = LoggerFactory.getLogger(Abc.class);
-
Do not use Gradle wrapper. Manually install Gradle in development machine and update it regularly.
-
Use all small letter naming conventions for project naming. Do not use any underscore(_) or hyphen(-) for multiple word project names. i.e rokomari, orderservice, quotationservice etc. This will keep the package names clean.
-
Place the Hibernate entity classes in the entity package.
-
Use repository and service packages for Repository and Service classes.
-
Place view template based controllers in the web.controller package and rest controllers in the web.restcontroller package.
-
For cloud projects (config server, eureka server, cloud services etc) and services i.e you need to add cloud dependencies in gradle.build file. Make sure you have these property blocks in your build.gradle file -
ext { set('springCloudVersion', "Hoxton.SR3") } dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } }
-
You should not directly map database tables into the API. So Entity/Document classes should never be exposed by an API. Use a DTO class instead.
-
Do not directly receive Entity/Document class object from request. Use a DTO class instead.
-
Do not use 'DTO' suffix for a DTO class. more on this later
-
Avoid using verb in API URL. Use resource name instead.
-
Use versioning in API. For example -
GET walletservice/api/v1/transactions- We are accessing a walletservice API in this example.
- This in API version 1
- We are accessing transaction resource
-
Use HTTP verb to specify action on resources.
1. GET walletservice/api/v1/transactions 2. GET walletservice/api/v1/transactions/[transation_id] 3. POST walletservice/api/v1/transactions [body with transation info] 4. PUT walletservice/api/v1/transactions/[transaction_id] [body with transation info] 5. DELETE walletservice/api/v1/transactions/[transaction_id]- Returns list of Transaction
- Returns a single Transaction with given transaction_id
- Creates a new Transaction with given transaction info in the body
- Updates existing transaction of given transaction_id with given transaction info in the body
- Deletes the transaction wtih given transaction_id
-
Add filtering values in the URL with parameter.
GET walletservice/api/v1/transactions?status=ACTIVE&name=asdf -
in, gt these can be used for advanced filtering.
-
Add pagination in the URL with parameter. page_size should be optional. Use a upper boundary value for page_size in the service.
GET walletservice/api/v1/transactions?page_no=5&page_size=50
- Do no Inject Repository classes directly into Controller classes. Repository layer should close to database and Service layer with all the business logic.
-
For Monolithic application always use these properties as first two. Although application.name property is not that useful in monolithic case, but we will use it for the sake of future microservice migration. Server port is not fixed, it better to mention it explicitly.
spring.application.name=spring-boot-mysql server.port=8080
-
Use these properties for MySQL -
spring.datasource.url=jdbc:mysql://localhost:3306/spring-boot-mysql_db spring.datasource.username=root spring.datasource.password=root
-
Remove MySQL properties from production. Try to maintain this type of difference using profile. ddl-auto's default value is none, which does to do any database changes from hibernate entity. Production database change should be executed separately.
spring.jpa.show-sql = true spring.jpa.hibernate.ddl-auto = update
-
Use following folder structure.
└───springbootmysql ├───config <- all the configs, use inner package if needed | ├───redis | └───solr ├───domain <- hibenate mapping classes ├───enumeration <- enumerations which are used multiple class wide ├───exception <- custom exceptions ├───model <- model classes used inside application or for REST APIs | ├───receive <- model classes for REST APIs, received from another service | └───send <- model classes for REST APIs, send to another service ├───repository ├───service ├───utility └───web ├───controller <- view template based controllers └───restcontroller └───v1 <- 1st version rest controllers
-
Add custom banner in the Spring Boot project.
- From here - http://patorjk.com/software/taag/#p=display&f=Graffiti&t=Type
- Use Big font
-
Add project info text under the banner. Add main project name before service name for microservice.
:: rokomari_notificationservice :: Spring Boot${spring-boot.formatted-version} :: (c) OWSL 2012-2020 ::
-
Whatever database you choose just add ‘_db’ after the application name and use that as the database name. For the quotationservice application, the database name will be quotationservice_db. If it is a microservice add the application name in from of it. If quotationservice is a microservice and part of notebook application, use notebook_quotationservice_db as the database name.
-
Use underscore based small letter naming convention for table names and table column names. i.e customer_order, product_purchase. Avoid any sort of short name or acronym for table names.
- Do not use Float or Double for monetory calculations. Use BigDecimal.
-
Use container_name property in docker_compose.yml file. Naming format would be [application_name][service_name][container_service_name]. If redis is used for Rokomari application's quotationservice service -
version: "3.5" services: redis: container_name: rokomari_quotationservice_redis image: redis ports: - "6380:6379" restart: on-failure
- View files
- Static folders (image, css, javascript, favicon etc)
- Controllers and methods
- Services and methods
- Repositories and methods
- Do not use Property level Autowiring. Use Constructor level Autowiring.
-
Use just the @Entity annotation on top of a Entity class. Spring Boot automatically derives table name from class name (i.e PostDoc to post_doc), so @Table annotation is not needed.
@Entity public class Tag { ... }
-
Use Enum for multi valued properties (i.e Status with value ACTIVE and INACTIVE). Place those at the bottom of the Entity class. Create an enum in enumeration package only if it is usable in more than one classes.
@Entity public class Tag { ... ... public enum Status {ACTIVE, INACTIVE} }
-
These are 5 must have properties for every Domain - id, createdBy, updatedBy, createdAt, updatedAt. Use AbstractAuditingEntity. All the fields except id is managed by the AuditingEntityListener class.
-
id, createdBy, updatedBy, createdAt, updatedAt - these are 5 must have properties for all the Entity classes. Do not define these in all classes. Use an AbstractAuditingEntity class and extend this from all the Entity classes. There could be some special cases, when primary key generation strategy is not same all over the project. But this is very unlikely.
import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import javax.validation.constraints.NotNull; import java.time.Instant; @MappedSuperclass @EntityListeners(AuditingEntityListener.class) public abstract class AbstractAuditingEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @DateTimeFormat(pattern = "dd-MMM-yyyy") private Instant createdAt; @DateTimeFormat(pattern = "dd-MMM-yyyy") private Instant updatedAt; @NotNull private String createdBy; private String updatedBy; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Instant getCreatedAt() { return createdAt; } public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; } public Instant getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Instant updatedAt) { this.updatedAt = updatedAt; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public String getUpdatedBy() { return updatedBy; } public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } }
@Entity public class Tag extends AbstractAuditingEntity { ... }
-
Use Hibernate/JPA annotations on property level. Mixing up annotation on property and setter levels creates compilation issue.
-
Use Long data type and IDENTITY GenerationType for the id property (primary key). Do not use TABLE or SEQUENCE GenerationType. Those strategies maintains an extra table in the database. Define the id property in AbstractAuditingEntity class. This is applicable for SQL databases. Need to figure out the way for no-SQL databases.
@@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
-
Use @NotNull annotation to define not null validation for a property. Using this annotation will also create the column with nullable in database. So no need to use @Column(nullable = true) annotation. Use @Size annotaion to define minimum and maximum length limit. This will be used for entity validation. max value will be used as varchar length in database. Do not use @NotEmpty or @NotBlank annotations. Using those will not create not nullable column in database.
@NotNull @Size(min = 5, max = 1023) private String title;
-
Use following for huge texts. This will create text type column in database. Drop the @NotNull annotation if not neede.
@NotNull @Column(columnDefinition = "TEXT") private String content;
-
Use @Enumerated annotation for enum properties. Most of the cases @NotNull property will be needed.
@NotNull @Enumerated(EnumType.STRING) private Status status;
-
If nullable=false needed in database column (which makes not nullable in application), use @NotNull annotion in Entity.
-
Use 127, 255, 511, 1023, 2047, 4095 as String length. For lengthier cases use TEXT. These are few examples.
@NotNull @Size(min = 1, max = 255) private String name; @NotNull @Size(min = 5, max = 255) private String password; @NotNull @Size(min = 5, max = 255) @Column(unique = true) private String email; @NotNull @Size(min = 5, max = 255) @Column(unique = true) private String phone; @DateTimeFormat(pattern = "dd-MMM-yyyy") private Date dateOfBirth; @NotNull @Size(min = 5, max = 1023) private String title; @NotNull @Size(min = 5, max = 2047) private String topSummary; @NotNull @Column(columnDefinition = "TEXT") private String content;
-
JOINs - yet to come....
-
Explicitly disable Entity class default constructor with a private access modifier. Use a static method for instance creation. Use newObjectWithDefaults as method name. Assign all the default properties in this method.
private Tag() { } public static Tag newObjectWithDefaults() { Tag tag = new Tag(); tag.postCount = 0; return tag; }
-
Use Config server’s (configserver) port as 8888.
-
Use Eureka server’s (eurekaserver) port as 8761.
-
Use hyphen separated small case for URL.
rokomari.com/this-is-an-example-url