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.

Get our Articles via Email. Enter your email address.

You may also like...

102 Comments

  1. madhavan says:

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

    nice job

    • java67 says:

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

  2. lakshmipathi-lucky says:

    useful information for java programmers

  3. Nitin Gautam says:

    nice information. Thanks for Sharing

  4. vijay says:

    Thanks for valuable post.Great work

  5. Glory says:

    Thanks alto Great expats.

  6. srishti says:

    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

  7. Marius Bozga says:

    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);
    }

  8. gp says:

    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 says:

      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.

  9. Marius Bozga says:

    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.

  10. Bambang Irianto says:

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

  11. Clare Ciriaco says:

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

  12. arulk says:

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

  13. Harish says:

    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.

  14. hanan says:

    Great work , keep going forward :)

  15. karthik says:

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

  16. Rudresha says:

    THanks Dude

  17. Konrad Zuse says:

    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

  18. Lew Bloch says:

    “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.

  19. Richard Roe says:

    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.

  20. Its good list.

  21. Julio Indriago says:

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

  22. Titus Kurian says:

    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.

  23. Venkey says:

    Wow very nice explanation.

  24. Apoorva says:

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

  25. Saravanan says:

    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

  26. Martin says:

    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

  27. Ak says:

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

  28. santhosh says:

    Very nice and use ful…!

  29. sergi sergeo says:

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

  30. Anilkumar says:

    good list and useful

  31. Rishu Raj says:

    Nice list. good job

  32. Jaizon Lubaton says:

    Great tips!

  33. Jawahar says:

    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.

  34. javahungry says:

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

  35. Vahe says:

    “Object creation in Java is one of the most expensive operation in terms of memory utilization and performance impact.” FALSE.
    http://programmers.stackexchange.com/questions/149563/should-we-avoid-object-creation-in-java

  36. Guillaume says:

    Hello!
    Doesn’t quote 9 contradict quote 1?
    If you create an object instead of returning null, it’s more convenient, but it’s a useless object, as discribe in quote 1.

  37. Saurzcode says:

    Thanks for nice compilation.

  38. Arvind says:

    Good Java Code practice is necessary for a good programmer. You explained well.

  39. Rahil Khan says:

    In Quote 10: Defensive copies are savior, the modified constructor

    public Student(birthDate) {
    this.birthDate = new Date(birthDate);
    }
    is ok but we can always get the Date’s instance from getter method and modify it .

    Either we perform defensive copying in getter also or avoid getters and make class Cloneable and implement deep copying…

  40. Rahil Khan says:

    @Guillame : Point 1 advocates lazy loading – dont create an object untill it is needed.
    At point 9, we need an object, empty it may be, to avoid null checks or potential bugs, so we initialized it.

  41. nice really helpfull

  42. Quote 1: Premature optimization. Clutters the code.

    Quote 2: This applies to all fields and is called encapsulation!

    Quote 3: Using factory methods only makes sense if you have for instance a pool of objects. I don’t see the benefit of having it in the Employee example.

    Quote 4: In Java 8 the support for evolving interfaces improved drastically with default methods.

    Quote 5: The intention is good, but the problem is often rather a symptom of too large methods. Break methods down to smaller methods and you’ll have smaller scopes as a bonus.

    Quote 6: No rules without exceptions of course. It’s healthy to have a threshold to importing new libraries. I’ve seen people import Joda time library just to have ISO-formatting of a Date. Import libraries judiciously.

    Quote 7: I have never seen any one use new Integer(10) out of thin air.

    Quote 8: Premature optimization. (Also, I’ve never seen someone do new String(“The String”).)

    Quote 9: Good advice, but the example code doesn’t talk about collections or arrays.

    Quote 10: This does incurr a slight memory overhead. Had there been a Date.unmodifiableDate(date) you would probably have used that as an example, no? A better example would thus be Collections.unmodifiableCollection.

  43. Java programming tutorial says:

    Great post. Things are really helpful and worth to keep in mind.

  44. Java Papers says:

    This is an excellent article and will help a Java developer to write better code. Good work.

Leave a Reply

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