1. Use lowercase for package name
Example: com.myapp.services
2. Class or Interface should be noun and in camel case
Example: LookerService,Line, ConfigurationDao
3. Variable should be camel case starting with lower case
Example: myVar;
4. Use of constant should be minimized. Use method which return the value instead.
Example: Use public int getMaxAge(){ return 100;} =>OK
Rather than, private int MAXAGE=100 => If possible avoid
5. Method name should be verb with camel case starting with lower case.
6. Abbreviations and acronyms should not be uppercase when used as name.
getHtmlSource => Correct;
getHTMLSource => Incorrect
7. Variable with large scope should have long names while the one with small scope should be short name
Example: is i, j, k used in for loop as the scope is small.
8. No need to use the object name in the method name as that is implicit
Example:
aws.getConnection() => OK;
aws.getAwsConnection => NOK
9. The term ‘compute’ can be used for method that do some computation. Generally associated with mathematical calculation
Example: person.computeMaximumAge()
10. The term ‘find’ can be used for method which lookup something.
Example: findCopiedFiles()
11. The term initialized can be used for the where an concept is established
Example: initializedClientFromJson()
12. Use plural for list or set of collection
Example: List<String> filters=new ArrayList<>();
13. Use empty diamond operator while declaration of generics
Example:
List<String> filters=new ArrayList<String>(); => OK
List<String> filters=new ArrayList<>(); => Better
14. Use 'is' as prefix of a method that returns boolean or boolean variables
Example:
public boolean isCompleted(){ return false;}
pivate boolean isValid=false;
15. Functions (methods returning an object) should be named after what they return and procedures (void methods) after what they do.
Example: public View generateView(){.....return view;}
16. Check all the stream like inputstream/outputstream/buffered inputstream or opened file. Ensure that these are closed. Use try-with-resource from java 7 or explicitly close them
Example:
try (InputStream objectData = s3object.getObjectContent()) {
jsonAsString = IOUtils.toString(objectData, "UTF-8");
}
17. Use log.error() in place of all e.printstacktrace
18. Combine multiple exception according to java 8
Example:
try{
......
}
catch (NoSuchAlgorithmException | IOException | RuntimeException e){...}
19. Do not use log.error and throws from the same catch statement. This will result in duplicate message, one from log and one from throws
Example: Below is wrong
try{
......
}
catch (NoSuchAlgorithmException e)
{
log.error("message {}",e);
throws new Exception();
}
20. Check if some library is already present to do complex things, before re-inventing the wheel for which code has already been written, tested and maintained
21. If null is returned use optional.ifPresent to ensure that operation is allowed for non-null able value. This is from Java 8.
Example:
Optional<DashboardConfig> dashboardConfig = dashboardConfigRepository
.findByClient(clientRepository.getOne(clientId));
if (dashboardConfig.isPresent()) {
....
}
22. Use the following format for logging. Log.info("message {}", e.message).This is effective and faster then concatenation version Log.info("message "+e.message)
23. Do not make class or instance variable public without any good reason.
24. Do not use object to access static method
Example:
myStaticMethod() =>OK
MyClass.myStaticMethods()=>OK
myObj.myStaticMethod=>NOK
25. No use of magic number in code directly except 0 and 1. All other numberic constant should be declared as private static instance variable
26. Use String carefully. If a string is getting modified number of times see we can use StringBuilder append method instead for concatenation. This also conforms to the the principle of avoiding creating too many short lived object as this will make the garbage collector work continuously.
Example: This is bad
String str="";
for(int i=0; i<10000; i++){
str=str+"i";
}
27. String instantiation should happen directly rather than through constructor.
Example:
String s=new("XXX"); =>Slower
String s="XXX"; =>Fast
28. Use double instead of float. Double provide more precision then float with same computation speed
29. Variables should be initialized where they are declared and they should be declared in the smallest scope possible.
30. Complex conditional expressions must be avoided. Introduce temporary boolean variables instead
Example :
If((x==10 && y==20) || (m==5 && n==100)){} is not good,
Use instead,
boolean conditionFirst=if((x==10 && y==20))
boolean conditionSecond=if( (m==5 && n==100))
if(conditionFirst || conditionSecond){}
31. Executable statements in conditionals must be avoided
Example:
if(line.getLength(p1,p2)>10)=> NOK
int length=line.getLength(p1,p2);
if(length>10){}=>OK
32. Refer to objects by their interfaces if appropriate interface exists
Example: List<String> filters=new ArrayList<>();
33. Abbreviations in names should be avoided
Example: getAverage()->OK; getAvg()->NOK
34. Use parentheses liberally in expression even if it precedence seems to be clear
35. All fields must be private, except for some constants.
36. Never use return in the middle of a method. This will make it difficult to break the function in future as there are multiple exit points
37. Try no to use continue. Reason same as above
38. Only use break for switch statement.
39. All public method should be commented with its intended purpose
40. Do not log sensitive data such as password,secret, file paths, server names, host names. Also ensure that these information do not skip through exception
41. Externalized configuration data in .properties file or environment variables
42. Do not rely on Package Scope. There can be security risk if hacker introduce some rough classes in package, which can access and modify data located within it. Prefer private to protected.
43. Declare and initialize a new local variable rather than reusing (reassigning) an existing one whose value happens to no longer be used at that program point. This will minimize bad assumptions about values of variables.
44. Avoid overloading methods on argument type. (Overriding on arity is OK, as in having a one-argument version versus a two-argument version).
45. Minimize reliance on implicit initializers for instance variables (such as the fact that reference variables are initialized to null). This will minimize initialization errors
46.Use altr-ctrl-O to remove unused imports (Eclipse)
47. Use altr-ctrl-F for proper indentation (Eclipse)
Resources
1. http://geosoft.no/development/javastyle.html2. http://www.javaranch.com/style.jsp
3. http://www.oracle.com/technetwork/java/codeconvtoc-136057.html
4. http://users.csc.calpoly.edu/~jdalbey/SWE/CodeStdCheck.html
5. http://www.java-success.com/30-java-code-review-checklist-items/
6. https://www.toptal.com/java/top-10-most-common-java-development-mistakes
No comments:
Post a Comment