Java Best Practices Notes

  • Use length() to check empty String. Do not use equal().
  • Wherever possible try to use Primitive types instead of Wrapper classes.
  • When using wrapper class, use faster method to create it. Example:
    • Integer i = Integer.valueOf(100). Do not use Integer i = new Integer(100)
    • String s = “ariestania”. Do not use String s = new String(“ariestania”)
  • Avoid creating unnecessary objects and always prefer to do Lazy Initialization.
    public class ExampleClass {
        private List students;
    	public List getStudents(){
    		if(students==null) {
                students = new ArrayList();
    			//add the list
            return students;
  • Never make an instance fields of class public.
    public class ExampleClass {
        //this is WRONG 
        public String[] workDays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
        //the resolve is make it private then create getter method
    	private String[] privateWorkDays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
    	// Best way to make it unmodifiable is to return a clone of array instead of array itself
    	public String[] getPrivateWorkDays(){
    		return privateWorkDays.clone();
  • Always try to minimize mutability of a class. Choose wisely when you need to create the class immutable or not. To make a class immutable you can define its all constructors private and then create a public static method to initialize and object and return it.
  • Avoid to returning NULL value.

Will be nice if you add another notes about it. Thanks šŸ™‚

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s