We continue from where we left on part I. On this, we will cover more of fundamental standards that every Java programmers should adhere to. Remember, these standards or guidelines are here to improve code readability, maintainability and general quality. Programmers can differ and follow their own guideline if it improves general quality of code.
1. Singleton class instance
Singleton classes should return their sole instance through method getInstance. |
---|
private final static UnitManager instance_ = new UnitManager(); public static UnitManager getInstance() { return instance_; } |
Don’t : get() or instance() or unitManager() |
The above layout is the preferred pattern, though not followed consistently by all. |
2. Import statement
Import statements must be sorted such that fundamental packages are first, and packages are grouped together with associated packages and a line must separate different groups. |
---|
import java.util.List; import java.util.ArrayList; import javax.swing.JPanel; import javax.swing.event.ActionEvent; |
The sorting and grouping makes it simple to browse import statements, manage more easily and collapse related dependencies in common units. |
3. Explicit import classes list
Import classes should always be explicitly listed |
---|
Do :
import java.util.List; import java.util.ArrayList; import java.util.HashSet |
Don’t :
import java.util.*; |
Explicit import classes list helps to maintain and understand the class and it’s documentation. |
4. No to implicit type conversion
Always perform explicit type conversion and avoid implicit type conversion. |
---|
Do : floatValue = (int) intvalue; |
Don’t : floatValue = intValue; |
Performing explicit type conversion helps to understand what that piece of code exactly does, while the later is vauge. |
5. Class variables should be private
Class variables should always be private. |
---|
Do : private String myVariable; |
Don’t : public String myVariable; |
Use of public access for class variable voilates the concept of Java information hiding and encapsulation. Instead use public function to access these class variables. |
6. Negated boolean variable name
Use of negated boolean varialbe must be avoided. |
---|
Do : boolean isEnabled; |
Don’t : boolean isNotEnabled |
Using negated boolean variable name decrease the readability of code. Apparently, it’s not always immediatly clear what does “!isNotEnabled” means! |
7. Executable statements
Avoid using excecutable statements in conditonals cases. |
---|
Do : InputStream stream = File.open(fileName, “w”); if (stream != null) { … } |
Don’t : if (File.open(fileName, “w”) != null)) { … } |