10 Most Useful Java Best Practice Quotes for Java Developers

star-trek-spock-java-best-practice-quotes

Quote 1: Avoid creating unnecessary objects and always prefer to do Lazy Initialization

Object creation in Java is one of the most expensive operation in terms of memory utilization and performance impact. It is thus advisable to create or initialize an object only when it is required in the code.

public class Countries {

	private List countries;
	
	public List getCountries() {
		
		//initialize only when required
		if(null == countries) {
			countries = new ArrayList();
		}
		return countries;
	}
}

Quote 2: Never make an instance fields of class public

Making a class field public can cause lot of issues in a program. For instance you may have a class called MyCalender. This class contains an array of String weekdays. You may have assume that this array will always contain 7 names of weekdays. But as this array is public, it may be accessed by anyone. Someone by mistake also may change the value and insert a bug!

public class MyCalender {
	
	public String[] weekdays = 
		{"Sun", "Mon", "Tue", "Thu", "Fri", "Sat", "Sun"};
	
	//some code	
	
}

Best approach as many of you already know is to always make the field private and add a getter method to access the elements.

	private String[] weekdays = 
		{"Sun", "Mon", "Tue", "Thu", "Fri", "Sat", "Sun"};
	
	public String[] getWeekdays() {
		return weekdays;
	}

But writing getter method does not exactly solve our problem. The array is still accessible. Best way to make it unmodifiable is to return a clone of array instead of array itself. Thus the getter method will be changed to.

	public String[] getWeekdays() {
		return weekdays.clone();
	}

Quote 3: Always try to minimize Mutability of a class

Making a class immutable is to make it unmodifiable. The information the class preserve will stay as it is through out the lifetime of the class. Immutable classes are simple, they are easy to manage. They are thread safe. They makes great building blocks for other objects.

However creating immutable objects can hit performance of an app. So always choose wisely if you want your class to be immutable or not. Always try to make a small class with less fields immutable.

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.

public class Employee {

	private String firstName;
	private String lastName;
	
	//private default constructor
	private Employee(String firstName, String lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}
	
	public static Employee valueOf (String firstName, String lastName) {
		return new Employee(firstName, lastName);
	}
}

Quote 4: Try to prefer Interfaces instead of Abstract classes

First you can not inherit multiple classes in Java but you can definitely implements multiple interfaces. Its very easy to change the implementation of an existing class and add implementation of one more interface rather then changing full hierarchy of class.

Again if you are 100% sure what methods an interface will have, then only start coding that interface. As it is very difficult to add a new method in an existing interface without breaking the code that has already implemented it. On contrary a new method can be easily added in Abstract class without breaking existing functionality.

Quote 5: Always try to limit the scope of Local variable

Local variables are great. But sometimes we may insert some bugs due to copy paste of old code. Minimizing the scope of a local variable makes code more readable, less error prone and also improves the maintainability of the code.

Thus, declare a variable only when needed just before its use.

Always initialize a local variable upon its declaration. If not possible at least make the local instance assigned null value.

Quote 6: Try to use standard library instead of writing your own from scratch

Writing code is fun. But “do not reinvent the wheel”. It is very advisable to use an existing standard library which is already tested, debugged and used by others. This not only improves the efficiency of programmer but also reduces chances of adding new bugs in your code. Also using a standard library makes code readable and maintainable.

For instance Google has just released a new library Google Collections that can be used if you want to add advance collection functionality in your code.

Quote 7: Wherever possible try to use Primitive types instead of Wrapper classes

Wrapper classes are great. But at same time they are slow. Primitive types are just values, whereas Wrapper classes are stores information about complete class.

Sometimes a programmer may add bug in the code by using wrapper due to oversight. For example, in below example:

int x = 10;
int y = 10;

Integer x1 = new Integer(10);
Integer y1 = new Integer(10);

System.out.println(x == y);
System.out.println(x1 == y1);

The first sop will print true whereas the second one will print false. The problem is when comparing two wrapper class objects we cant use == operator. It will compare the reference of object and not its actual value.

Also if you are using a wrapper class object then never forget to initialize it to a default value. As by default all wrapper class objects are initialized to null.

Boolean flag;

if(flag == true) {
	System.out.println("Flag is set");
} else {
	System.out.println("Flag is not set");
}

The above code will give a NullPointerException as it tries to box the values before comparing with true and as its null.

Quote 8: Use Strings with utmost care.

Always carefully use Strings in your code. A simple concatenation of strings can reduce performance of program. For example if we concatenate strings using + operator in a for loop then everytime + is used, it creates a new String object. This will affect both memory usage and performance time.

Also whenever you want to instantiate a String object, never use its constructor but always instantiate it directly. For example:

//slow instantiation
String slow = new String("Yet another string object");

//fast instantiation
String fast = "Yet another string object";

Quote 9: Always return empty Collections and Arrays instead of null

Whenever your method is returning a collection element or an array, always make sure you return empty array/collection and not null. This will save a lot of if else testing for null elements. For instance in below example we have a getter method that returns employee name. If the name is null it simply return blank string “”.

public String getEmployeeName() {
	return (null==employeeName ? "": employeeName);
}

Quote 10: Defensive copies are savior

Defensive copies are the clone objects created to avoid mutation of an object. For example in below code we have defined a Student class which has a private field birth date that is initialized when the object is constructed.

public class Student {
	private Date birthDate;
	
	public Student(birthDate) {
		this.birthDate = birthDate;
	}
	
	public Date getBirthDate() {
		return this.birthDate;
	}
}

Now we may have some other code that uses the Student object.

public static void main(String []arg) {

	Date birthDate = new Date();
	Student student = new Student(birthDate);

	birthDate.setYear(2019);
	
	System.out.println(student.getBirthDate());
}

In above code we just created a Student object with some default birthdate. But then we changed the value of year of the birthdate. Thus when we print the birth date, its year was changed to 2019!

To avoid such cases, we can use Defensive copies mechanism. Change the constructor of Student class to following.

public Student(birthDate) {
	this.birthDate = new Date(birthDate);
}

This ensure we have another copy of birthdate that we use in Student class.

Two bonus quotes

Here are two bonus Java best practice quotes for you.

Quote 11: Never let exception come out of finally block

Finally blocks should never have code that throws exception. Always make sure finally clause does not throw exception. If you have some code in finally block that does throw exception, then log the exception properly and never let it come out :)

Quote 12: Never throw “Exception”

Never throw java.lang.Exception directly. It defeats the purpose of using checked Exceptions. Also there is no useful information getting conveyed in caller method.

More Quotes from Java Developers

Do you have a quote that is not included in above list? Well, feel free to add your Java best practice quote using comment below. Write your quote and explain it in 2-3 lines. I will add all those user generated quotes in this section.

Quote #13: Avoid floating point numbers

It is a bad idea to use floating point to try to represent exact quantities like monetary amounts. Using floating point for dollars-and-cents calculations is a recipe for disaster. Floating point numbers are best reserved for values such as measurements, whose values are fundamentally inexact to begin with. For calculations of monetary amounts it is better to use BigDecimal.



92 Comments

  • madhavan 2 February, 2012, 12:58

    Hey all nice comment . Good explanation it is necessary for all java programers to follow this steps . Thanks Man.

    nice job

    • java67 24 August, 2012, 10:18

      Great list, you could probably include some design patterns as well.

  • lakshmipathi-lucky 4 February, 2012, 16:02

    useful information for java programmers

  • Nitin Gautam 11 February, 2012, 8:02

    nice information. Thanks for Sharing

  • vijay 21 February, 2012, 16:30

    Thanks for valuable post.Great work

  • Glory 27 February, 2012, 12:38

    Thanks alto Great expats.

  • srishti 27 February, 2012, 17:45

    useful post indeed.. being enrolled in Core Java for Beginners @ http://www.wiziq.com/course/1617-core-java-for-beginners-icse-students I was looking for such post to help me with JAVA.. thanks

  • Marius Bozga 3 March, 2012, 13:36

    For Quote 10: Defensive copies are savior the getter should also be fixed to return a copy of the birthDate instead of the reference:

    public Date getBirthDate() {
    return new Date(this.birthDate);
    }

  • gp 7 March, 2012, 1:53

    Very good job. I am bit confused about Quote 10

    Quote 10: Defensive copies are savior

    Defensive copies are the clone objects created to avoid mutation of an object. For example in below code we have defined a Student class which has a private field birth date that is initialized when the object is constructed.

    public class Student {
        private Date birthDate;
     
        public Student(birthDate) {
            this.birthDate = birthDate;
        }
     
        public Date getBirthDate() {
            //return this.birthDate; instead of this line better to write like this as in next line, please clarify its advantage
        return new Date(this.birthDate);  
        }
    }
    

    Now we may have some other code that uses the Student object.

    public static void main(String []arg) {
     
        Date birthDate = new Date();
        Student student = new Student(birthDate);
     
        birthDate.setYear(2019);
     
        System.out.println(student.getBirthDate());
    }
    

    Can you please explain Quote10 in details

    • Viral Patel 7 March, 2012, 15:11

      GP: Check how we modified birthDate object by calling setYear method. Note that the birthDate object reference is copied in Student object by this.birthDate = birthDate; Thus whatever changes we do on birthDate object, gets reflected inside Student object.

      Thus ideal way of handling this should be by creating new object as noted in article:

      public Student(birthDate) {
          this.birthDate = new Date(birthDate);
      }
      

      This make sure that any changes done on birthDate object outside Student class does not propagate inside Student.

  • Marius Bozga 8 March, 2012, 15:56

    As Viral Patel stated, by working directly with the given references – constructors, setters – and returning a direct reference to an object’s field – getters – breaks Encapsulation as it provides the outside world with ‘hooks’ that allow it to directly change an object’s state without its control / knowledge, as opposed to using a setter or any other method that changes that object’s state / fields.

    It should be noted that the true power of defensive copies is observed in multi-threaded applications, as their usage makes an object ‘more’ thread-safe by eliminating a whole bunch of thread interference issues.

  • Bambang Irianto 24 April, 2012, 7:14

    I Like Java very much, because…….. Java is the best… best… best…

  • Clare Ciriaco 26 April, 2012, 7:52

    This is very useful. I’ve been coding java for only 5 months and this helped me alot. :)

  • arulk 30 August, 2012, 11:43

    Good post, keep up the good work. Feel free to browse my work on 400+ java/JEE interview questions and answers.

  • Harish 21 September, 2012, 15:36

    really nice guidelines for new java programmers. although every programmer has its own style but keeping in mind the performance optimization, the above quotes are really helpful.

  • hanan 24 September, 2012, 5:19

    Great work , keep going forward :)

  • karthik 30 September, 2012, 8:32

    Very Useful Information for Java Developers…Thanx and Please update it.

  • Rudresha 15 November, 2012, 17:49

    THanks Dude

  • Konrad Zuse 23 November, 2012, 5:31

    Hi,
    I’d like you to think about your suggestions again. They are problematic:
    #1: Besides the example being senseless, this is a case of premature optimization (google Dijkstra). Did you measure that there is a problem? Then there isn’t one! One the other hand you’re returning a mutable collection that represents part of the internal state of your object. DON’T DO THAT!
    #2: Some like the style of having public _final_ references to immutable classes or primitives – and that’s OK.
    #3: Just adds complexity – in an immutable class instance fields can and should be final, and references should be references to final classes. Again: Performance must be measured, not guessed!
    #4: The answer here is: It depedends. Apply Test-Driven Development and see which style fits best for your component. The SWT developers preferred abstract classes and they had good arguments that in their case this was a good idea.
    #5: The most important thing is to not reassign local variables and declaring them final. This is possible in 98% of all cases.
    #6: The Java RT solves a lot of problems. Before including any 3rd party code, even high quality code from Google, check that you’re don’t include a 2MB JAR for two static methods and that there are no side-effects.
    #7: But remember:
    Integer x = 10;
    Integer y = 10;
    assertTrue(x == y); // autoboxing uses Integer value cache from -128 to 128!

    #8: Again, please measure first using a profiler. In a typical JEE application performance losses by misconfigured DB connection pools and stuff like that will rule out these problems by magnitudes.
    #9: Valid for Empty collections. But: Why was the employeeName initialized with null in the first place?
    Check preconditions in the constructor:

      public class MyPerson {
         private final String employeeName;
        
         public MyPerson(final String employeeName) {
             Object.requireNonNull(employeeName); // Java 7
             this.employeeName = employeeName;
         }
        // ...
    }
    

    A property getter to be Java Beans compatible should not twist data, as this regularly breaks O/R-Mappers and the like. Check preconditions and class invariants, always.
    #10: OK, but choosing immutable value objects (like joda time) is even better.
    #11: Hm, depends. Depending on the error handling architecture it can be valid to throw a subtype of RuntimException if any checked exception was thrown when for example one or more close operations threw checked exceptions.
    #12: Better: Never throw checked exceptions! All modern frameworks have banned checked exceptions (Spring, Java EE) where possible and for good reason. I hope I’ll never see stuff like

    myMethod(..) throws RemoteException, BusinessException, TechnicalException, SQLException

    again in my life! What can a business method possibly do about a RemoteException? NOTHING! Checked Exceptions are just a glorified GOTO statement.

    Cheers,
    Konrad

  • Lew Bloch 13 December, 2012, 4:10

    “Object creation in Java is one of the most expensive operation in terms of memory utilization and performance impact.”
    False. Object creation is only expensive if the object has a lot of initialization to do. Memory allocation is on the order of 12 machine instructions, and takes on the order of nanoseconds.
    Lazy instantiation is an antipattern and very easy to get wrong. You completely ignore concurrency concerns.

    Statements about the effects of ‘String’ concatentation on performance are not likely to be true. You need to measure. Modern Java optimizes one-line String operations quite well. Are you *quite* certain it has a major performance impact? Evidence, please!

    Type name ‘MyCalender’ should be ‘MyCalendar’. Misspelling doesn’t matter to Java, but it’s bad style.

    On immutability, you completely forgot to make the members ‘final’. Oops.

    You need a major grammar and spelling overhaul. There are too many such mistakes.

    Local instances getting assigned ‘null’ initially, even though that value is never actually used – useless, unnecessary and often harmful.

    Testing a Boolean/boolean with ‘if(flag == true)’ is silly.

  • Richard Roe 14 December, 2012, 16:30

    The quote 10 exemple seems quite flawed.

    public Student(birthDate) {
            this.birthDate = birthDate;
        }

    This constructor doesn’t compile, the type isn’t declared for the parameter.

    Moreover, the Date instance of Student isn’t really protected as

    public Date getBirthDate() {
            return this.birthDate;
        }

    returns the instance. If you use the getter, you can get the instance, and then modify it. You should apply defensive copy in this function too.

    public Date getBirthDate() {
            return new Date(this.birthDate);
        }

    As said before, using JodaTime is a better idea than using the default Date type, but that’s not really the main point in this question.

  • HowToDoInJava 18 December, 2012, 15:13

    Its good list.

  • Julio Indriago 22 February, 2013, 0:45

    Hello Viral!
    I would like to know what are the reference/sources that you used to make this list.
    Thanks in advance!

  • Titus Kurian 25 February, 2013, 18:48

    Halo Viral, your points really excellent.
    Its really so impressive to see all suggessions & replies as it gives more information to Java Programmers like me

    Tankx very much…tank you..frienD.

  • Venkey 13 March, 2013, 10:12

    Wow very nice explanation.

  • Apoorva 22 March, 2013, 14:46

    The information you have shared is awesome . Hope this helps lot more java enthusiasts like me. cheers.

  • Saravanan 22 March, 2013, 21:14

    Hi Viral,

    Can you please demonstrate Quote # 2 with some code on how can that String array be tampered if we do not use clone() and also how can it be made immutable by use of clone()?

    - Saravanan

  • Martin 13 April, 2013, 3:24

    Quote # XXX
    Make use of StringBuilder for extensive String processing in stead of concatenating common Strings, it really does make a difference when the number of strings goes huge.

     
    //Good way to go
    StringBuilder sb = new StringBuilder();
    String[] words = {"hello", "java", "world"};
    for(String word : words){
        sb.append(word).append(" ");
    }
    
    //Bad way to go
    
    String sentence = "";
    String[] words = {"hello", "java", "world"};
    for(String word : words){
       senteces+= word + " ";
    }
    

    Martin Cazares
    Android Architect/Developer

  • Ak 17 April, 2013, 8:58

    please revisit your quote #4. the quote and the ending line seems contradicting each other.

  • santhosh 8 May, 2013, 12:42

    Very nice and use ful…!

  • sergi sergeo 30 May, 2013, 14:35

    I fine all these quotes very useful to write clean and efficient code
    Big Up!

  • Anilkumar 18 July, 2013, 12:21

    good list and useful

  • Rishu Raj 11 August, 2013, 5:13

    Nice list. good job

  • Jaizon Lubaton 3 February, 2014, 4:17

    Great tips!

  • Jawahar 21 February, 2014, 20:38

    I tried Quote 2: Never make an instance fields of class public.

    Its not working. I’m able to modify the value of the variable.

  • javahungry 17 March, 2014, 12:41

    Very good list . One should use above points while coding in java .

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]