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.
publicclassCountries{
private List countries;
public List getCountries(){
//initialize only when requiredif(null == countries) {
countries = new ArrayList();
}
return countries;
}
}
Code language:Java(java)
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!
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();
}
Code language:Java(java)
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.
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);
Code language:Java(java)
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");
}
Code language:Java(java)
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";
Code language:Java(java)
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);
}
Code language:Java(java)
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.
publicclassStudent{
private Date birthDate;
publicStudent(birthDate){
this.birthDate = birthDate;
}
public Date getBirthDate(){
returnthis.birthDate;
}
}
Code language:Java(java)
Now we may have some other code that uses the Student object.
publicstaticvoidmain(String []arg){
Date birthDate = new Date();
Student student = new Student(birthDate);
birthDate.setYear(2019);
System.out.println(student.getBirthDate());
}
Code language:Java(java)
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.
publicStudent(birthDate){
this.birthDate = new Date(birthDate);
}
Code language:Java(java)
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.
Hey great list… Here is one from me. 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.
A better solution would be to return an unmodifiable list rather than an array.
You have also made some statements about performance re primitive types and strings that might not always be relevant. The JVM and Hotspot does some amazing things these days and as a result some of these statements should be backed up by statistics.
On our large enterprise project we use concatenation and wrapper objects a lot and they are rarely the source of performance issues. We have used the Netbeans profiler to test them.
Poor design is by far the biggest problem, for instance; returning primitive types for keys leads to lockin that you may well regret later.
One more tip is the use of final. We use this where possible on member variables and on all parameters. This has quashed more bugs than anything – especially in the area of cut n paste!
>>> Do you have a quote that is not included in above list? I think it is done already, e.g. Effective Java Second Edition by by Joshua Bloch or Implementation Patterns by Kent Beck. BTW about tips #1 – Lazy Initialization is very bad approach in case of concurrency, you have to synchronize getter for getCountries() while object creation is not so expensive, look at http://www.ibm.com/developerworks/java/library/j-jtp04223.html “The performance impact of object creation, while certainly real, is not as significant in most programs as it once was or is still widely believed to be.”
Felt motivated reading this. I am a Java developer and i am very eager to create some new, innovative application some day. That is why i am going to attend Sun Tech Days 2010 conference in Hyderabad. Experts are going to share ideas on new technologies there. lets see what happens.
Quote 7: Why using “Integer x1 = new Integer(10);” anyway… it’s the old way, it’s slow and it creates a new instance. Instead: use “Integer x1 = Integer.valueOf(10);” or use the automatic boxing/unboxing with “Integer x1 = 10;”.
Quote 9: The “always” is simply not neccessary. Sometimes there is no collection I want return, e.g. in case of error. I don’t need an exception here nor want I know, why this Collection is null: there was an error and I don’t want to work on this list, not even on an empty list. Sure, returning null on error needs to be documented in some way. Other way round, always returning a collection/array (even if empty) needs to be documented either. I suppose better: “Quote 9: Prefer to return empty Collections and Arrays instead of null”
“Quote 3” and “Quote 10” correspond to each other, don’t they? I think, they describe the same principle on another level.
“Quote 11”: maybe a reference to “apache-commons-io” and “apache-commons-db” would be helpful, since they introduce “DbUtils.closeQuietly(conn/rs/stmt);” and “IOUtils.closeQuietly(reader/stream/etc.);”
You do not need a private constructor to make an object immutable. Immutable just means the state of the object cannot be changed, therefore an object with no accessors to the field is immutable (if none of the methods change the state either). The valueOf method is not required at all.
Sure Koalition, I agree with you in this. But the above example is just to make sure that the class is not overridden by writing a subclass and manipulating its field in subclass. Ofcourse this is not needed in most of the cases when we can just make sure a class is immutable by using either defensive copies or other mechanism.
quote 1 is silly unless you are creating ridiculous number of objects. classic case of premature optimization. added complexity for very very little benefit usually.
quote 2: I don’t buy this, if you need a really lightweight data class, why add boilerplate? if you start making the class more complex, ditch the public fields
quote 3-7: agree
quote 8: “For example if we concatenate strings using + operator in a for loop then everytime + is used, it
creates a new String object”
wrong. the compiler handles most of these cases. used to be true, not any more. if you are in a tight loop building a string, the compiler can’t handle this case, so using the stringbuilder class is appropriate.
Re Quote 1: In Effective Java – Item 71 – Use lazy initialization judiciously Bloch says “don’t do it unless you need too” – and the example you have isn’t thread safe either.
quote 1 is silly unless you are creating ridiculous number of objects. classic case of premature +1. This is very bad example. quote 1 only makes sense, if it computationally expensive (and then you would need to synchronize the block)
“Wherever possible try to use Primitive types instead of Wrapper classes”
Please don’t take this advice. It’s called “primitive obsession”, and it makes your code harder to understand and refactor.
The author seems obsessed with focusing on performance issues that may not even be of concern in a particular application.
Don’t focus on performance first. Focus on good design and communicating intent first.
The performance problems will never be where you think they are anyway. Optimize when you know you have a problem and you know where it is (use a profiler).
Viral why wee need this method in Empoyee in Quote 3? public static Employee valueOf (String firstName, String lastName) { return new Employee(firstName, lastName); } and making constructor private? Don’t you think making instance variable private is enough?
I agree with you in this. But the above example is just to make sure that the class is not overridden by writing a subclass and manipulating its field in subclass. Ofcourse this is not needed in most of the cases when we can just make sure a class is immutable by using either defensive copies or other mechanism.
Is it not always good to clone the Class as and when required and access the variables, rather than having getter method do a clone. this would give more flexibility to the designing.
Mayur, You are getting these result because in first case you are comparaing the primitives using == operator that compare the value that is 10 so it is printing 10 but in second case you are comparaing references Wrappers are just class object values are 10 but the references are different that is why you are getting false
“To make a class immutable you can define its all constructors private and then create a public static method”
If you want to make the class to be immutable, then simply don’t provide the mutators (setter methods), in addition to data hiding (private member variables). I don’t see how making a constructor private in combination with public static method addresses immutability!. I’m puzzled.
really interesting advices about java programming basics… I hope that soon you’ll post another article about java EE frameworks (like Seam, Struts..) and Hibernate,JPA :-) Great work !
Viral – nice list. i read it so late though Regarding Quote 5 “Always initialize a local variable upon its declaration. If not possible at least make the local instance assigned null value.”
I don’t see a benefit of doing it. Though I see a drawback i.e. you define a variable without initializing it to null and after a few lines of code, you do some value / null check on this variable, (without writing any logic in between that might have initialized its value,) the compiler would tell that you have not initialized the value as yet and you would know that you probably need to re-look at your logic. That would not happen if you initialize a variable to null.
Sunil, I am teaching programming at university, and I am pushing the students to always initialize local variables. Not because it is a good idea for java, but because if they go to a language like c or c++, then their local variables will have junk inside them. I think it is a good habit to get into for this reason. cheers, pete.
I am looking for help on Alfresco and Liferay help. Currently I am using Alfresco as my CMS, but after the recent release of Liferay Portal I am need of implementing the it.
So if someone previously has got any exp on integrating the Alfresco and Liferay than please do share with me. It would be great help for me at this phase.
I really highly recommend NOT doing the static valueOf() method and making your constructor private, unless you also provide an empty constructor, for your immutable objects. Unit Testing becomes much, much tougher when you do it as described.
Quote 1 is fud. Object creation is actually quite fast in Java. Thanks to generational garbage collection, objects in Java are typically created from a contiguously empty area of memory, so memory allocation time is trivial. More importantly, like Phil Swenson wrote above, it’s a case of premature optimization, which everyone knows is evil.
For your example case, please just assign the field in its declaration and make it final. (And if it’s mutable, for God’s sake return a defensive copy.)
Quote #15, It is worth remembering that Calendar object has month ranging from 0 to 11. Not from 1 to 12. Normally this is overlooked and bugs introduced.
The compiler will convert it to something like ids = new StringBuffer().append(ids).append(pid).append(” “).toString(); Impacting performance with all those StringBuffer and its arrays beign created and then dropped for later garbage collection
1: Unless the routine’s documentation specifically promises it will never return null, you should be checking for null, and failure to do so is poor quality and sloppy programming.
2: Null and Empty List quite often mean different things. For example if you pass invalid data to a search routine, it might return null. If you pass valid data, but there are no results, then it should return an empty list. The situations are semantically distinct, therefore the results should be distinct, too.
Lazy instantiation is good. Lazy programming, OTOH, is bad.
Lazy instantiation is probably premature optimization, especially in example #1.
An api shouldn’t return null in normal conditions, nullchecking everything leads to ugly code.
If an exceptional sitation occurs, an api should throw and not return null instead, because if you do return null, the burden for errorchecking (and raising an exception) lies at every caller.
Great article… Thanks… One question, though… Regarding the example with student class. Why would value of student.birthDate variable be changed???
Date birthDate = new Date(); Student student = new Student(birthDate); birthDate.setYear(2019);
You create a date object, you create a Student object passing it the value of newly created Date and then you change the value of it… I don’t get it… Student object when it’s created creates a private local member variable with the value that was passed when calling the constructor and that was Date()
This would make sense:
Date birthDate = new Date(); birthDate.setYear(2019); Student student = new Student(birthDate);
Can someone please clarify me this behaviour :) Thanks
Inside the Student class is not a private member variable. It’s a private member reference. Therefore you have 1 object, but 2 aliases. Changing one will affect the underlying object, and so any proceeding uses of either will have the last update in full effect.
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());
}
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.
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.
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.
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
“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.
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
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()?
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 + " ";
}
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.
@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.
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.
Please resolve the mistakes u have done in your examples. As a lot of may be learn wrong from there. Intentionally article is very good, but code is not correct or in valid convention.
Hey great list…
Here is one from me.
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.
Thanks Mark..
I have added your quote as #13 in above list :)
Nice list! Thanks for the advice!
I like this list: it might seem simple at first, but it can actually save a lot of troubles down the road.
Nice work!
p.s. I think there is a typo in the first sentence of quote 3: I think you meant to say “Making a class immutable is to make it unmodifiable
Did you mean immutable here?
“Making a class mutable is to make it unmodifiable. “
Item 2.
A better solution would be to return an unmodifiable list rather than an array.
You have also made some statements about performance re primitive types and strings that might not always be relevant. The JVM and Hotspot does some amazing things these days and as a result some of these statements should be backed up by statistics.
On our large enterprise project we use concatenation and wrapper objects a lot and they are rarely the source of performance issues. We have used the Netbeans profiler to test them.
Poor design is by far the biggest problem, for instance; returning primitive types for keys leads to lockin that you may well regret later.
One more tip is the use of final. We use this where possible on member variables and on all parameters. This has quashed more bugs than anything – especially in the area of cut n paste!
>>> Do you have a quote that is not included in above list?
I think it is done already, e.g. Effective Java Second Edition by by Joshua Bloch or Implementation Patterns by Kent Beck.
BTW about tips #1 – Lazy Initialization is very bad approach in case of concurrency, you have to synchronize getter for getCountries() while object creation is not so expensive, look at http://www.ibm.com/developerworks/java/library/j-jtp04223.html “The performance impact of object creation, while certainly real, is not as significant in most programs as it once was or is still widely believed to be.”
Felt motivated reading this. I am a Java developer and i am very eager to create some new, innovative application some day. That is why i am going to attend Sun Tech Days 2010 conference in Hyderabad. Experts are going to share ideas on new technologies there. lets see what happens.
A very useful list of pointers for Java devs. Thanks a ton!
Quote 7:
Why using “Integer x1 = new Integer(10);” anyway… it’s the old way, it’s slow and it creates a new instance.
Instead: use “Integer x1 = Integer.valueOf(10);” or use the automatic boxing/unboxing with “Integer x1 = 10;”.
Quote 9:
The “always” is simply not neccessary.
Sometimes there is no collection I want return, e.g. in case of error.
I don’t need an exception here nor want I know, why this Collection is null: there was an error and I don’t want to work on this list, not even on an empty list.
Sure, returning null on error needs to be documented in some way. Other way round, always returning a collection/array (even if empty) needs to be documented either.
I suppose better: “Quote 9: Prefer to return empty Collections and Arrays instead of null”
“Quote 3” and “Quote 10” correspond to each other, don’t they? I think, they describe the same principle on another level.
“Quote 11”: maybe a reference to “apache-commons-io” and “apache-commons-db” would be helpful, since they introduce “DbUtils.closeQuietly(conn/rs/stmt);” and “IOUtils.closeQuietly(reader/stream/etc.);”
@Firass @Jason Thanks for pointing out the typo. I have corrected this now.
You do not need a private constructor to make an object immutable. Immutable just means the state of the object cannot be changed, therefore an object with no accessors to the field is immutable (if none of the methods change the state either). The valueOf method is not required at all.
Sure Koalition, I agree with you in this. But the above example is just to make sure that the class is not overridden by writing a subclass and manipulating its field in subclass.
Ofcourse this is not needed in most of the cases when we can just make sure a class is immutable by using either defensive copies or other mechanism.
good
quote 1 is silly unless you are creating ridiculous number of objects. classic case of premature optimization. added complexity for very very little benefit usually.
quote 2: I don’t buy this, if you need a really lightweight data class, why add boilerplate? if you start making the class more complex, ditch the public fields
quote 3-7: agree
quote 8:
“For example if we concatenate strings using + operator in a for loop then everytime + is used, it
creates a new String object”
wrong. the compiler handles most of these cases. used to be true, not any more. if you are in a tight loop building a string, the compiler can’t handle this case, so using the stringbuilder class is appropriate.
Re Quote 1:
In Effective Java – Item 71 – Use lazy initialization judiciously Bloch says “don’t do it unless you need too” – and the example you have isn’t thread safe either.
Quote 14:
Do not take engineering advice from a blog.
quote 1 is silly unless you are creating ridiculous number of objects. classic case of premature
+1.
This is very bad example. quote 1 only makes sense, if it computationally expensive (and then you would need to synchronize the block)
Why would you not make an array of week names final? Or better yet, make it an enum? It’s not like the days of the week change very often….
I agree with Vic above. You knowledge of performance related to object creation and garbage collection is out of date.
“Wherever possible try to use Primitive types instead of Wrapper classes”
Please don’t take this advice. It’s called “primitive obsession”, and it makes your code harder to understand and refactor.
The author seems obsessed with focusing on performance issues that may not even be of concern in a particular application.
Don’t focus on performance first. Focus on good design and communicating intent first.
The performance problems will never be where you think they are anyway. Optimize when you know you have a problem and you know where it is (use a profiler).
Nice and useful tips. However I cannot agree with Quote 12. Throwing exceptions is not always a bad option.
>> Quote 1: Avoid creating unnecessary objects and always prefer to do Lazy Initialization
really?
Viral why wee need this method in Empoyee in Quote 3?
public static Employee valueOf (String firstName, String lastName) {
return new Employee(firstName, lastName);
}
and making constructor private?
Don’t you think making instance variable private is enough?
I agree with you in this. But the above example is just to make sure that the class is not overridden by writing a subclass and manipulating its field in subclass.
Ofcourse this is not needed in most of the cases when we can just make sure a class is immutable by using either defensive copies or other mechanism.
How come you modify private in subclass?
Is it not always good to clone the Class as and when required and access the variables, rather than having getter method do a clone. this would give more flexibility to the designing.
Hi,
I tried some of the examples that you gave and I got different results. Is this ‘coz of Java 6?
Ex:
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);
Result:
true
false
Good list, thanks for the tips.
Mayur, You are getting these result because in first case you are comparaing the primitives using == operator that compare the value that is 10 so it is printing 10 but in second case you are comparaing references Wrappers are just class object values are 10 but the references are different that is why you are getting false
Nice Tips…thanks :)
“To make a class immutable you can define its all constructors private and then create a public static method”
If you want to make the class to be immutable, then simply don’t provide the mutators (setter methods), in addition to data hiding (private member variables). I don’t see how making a constructor private in combination with public static method addresses immutability!. I’m puzzled.
Nice list! Thanks
very informative.
Very good list of best practices at the core java programming level !!!
@Mayur
Hi,
Integer x1 = new Integer(10);
Integer y1 = new Integer(10);
System.out.println(x1 == y1);
Result:
false
This is becuse you are comparing an object with another object.
Try System.out.println(x1.intValue() == y1.intValue());
This should work
really interesting advices about java programming basics… I hope that soon you’ll post another article about java EE frameworks (like Seam, Struts..) and Hibernate,JPA :-)
Great work !
Excellent stuff for java developers ..
keep on posting such more stuff..
very good tips.
thanks,,
Awesome tips for a java developer, thanks mate.
Viral – nice list. i read it so late though
Regarding Quote 5
“Always initialize a local variable upon its declaration. If not possible at least make the local instance assigned null value.”
I don’t see a benefit of doing it. Though I see a drawback i.e. you define a variable without initializing it to null and after a few lines of code, you do some value / null check on this variable, (without writing any logic in between that might have initialized its value,) the compiler would tell that you have not initialized the value as yet and you would know that you probably need to re-look at your logic. That would not happen if you initialize a variable to null.
Sunil, I am teaching programming at university, and I am pushing the students to always initialize local variables. Not because it is a good idea for java, but because if they go to a language like c or c++, then their local variables will have junk inside them. I think it is a good habit to get into for this reason.
cheers,
pete.
Hi,
What is the difference betweeen the two :
String slow = new String(“Yet another string object”);
//fast instantiation
String fast = “Yet another string object”;
How does it affects the performance ??
Hi,
I am looking for help on Alfresco and Liferay help. Currently I am using Alfresco as my CMS, but after the recent release of Liferay Portal I am need of implementing the it.
So if someone previously has got any exp on integrating the Alfresco and Liferay than please do share with me. It would be great help for me at this phase.
Dramil Dodeja
I need help on implementing the Solr with Alfresco.
Any help??
Dramil Dodeja
I really highly recommend NOT doing the static valueOf() method and making your constructor private, unless you also provide an empty constructor, for your immutable objects. Unit Testing becomes much, much tougher when you do it as described.
Quote 1 is fud. Object creation is actually quite fast in Java. Thanks to generational garbage collection, objects in Java are typically created from a contiguously empty area of memory, so memory allocation time is trivial. More importantly, like Phil Swenson wrote above, it’s a case of premature optimization, which everyone knows is evil.
For your example case, please just assign the field in its declaration and make it final. (And if it’s mutable, for God’s sake return a defensive copy.)
Quote #15, It is worth remembering that Calendar object has month ranging from 0 to 11. Not from 1 to 12. Normally this is overlooked and bugs introduced.
Quote #8
Why not declare the String variable as static to prevent the creation of a new String object during String concatenation in a loop?
Another Quote:
“Don’t use String + operator for succesive string addition. Use StringBuilder instead”
Suponse you’re constructing a large string in a for
String ids=””;
for (int pid : personIds)
ids = ids + pid + ” “;
The compiler will convert it to something like
ids = new StringBuffer().append(ids).append(pid).append(” “).toString();
Impacting performance with all those StringBuffer and its arrays beign created and then dropped for later garbage collection
Instead create your own StringBuilder like this
StringBuilder myBuilder=new StringBuilder();
for (int pid : personIds)
myBuilder.append(pid).append(” “);
String ids=myBuilder.toString();
Thanks. nice List
Nice compilation viral, and specially coupled with the comments, it became even more informative.
Good list, thanks for the tips.
Got to disagree with you on #9.
1: Unless the routine’s documentation specifically promises it will never return null, you should be checking for null, and failure to do so is poor quality and sloppy programming.
2: Null and Empty List quite often mean different things. For example if you pass invalid data to a search routine, it might return null. If you pass valid data, but there are no results, then it should return an empty list. The situations are semantically distinct, therefore the results should be distinct, too.
Lazy instantiation is good. Lazy programming, OTOH, is bad.
Lazy instantiation is probably premature optimization, especially in example #1.
An api shouldn’t return null in normal conditions, nullchecking everything leads to ugly code.
If an exceptional sitation occurs, an api should throw and not return null instead, because if you do return null, the burden for errorchecking (and raising an exception) lies at every caller.
Great article… Thanks…
One question, though…
Regarding the example with student class. Why would value of student.birthDate variable be changed???
Date birthDate = new Date();
Student student = new Student(birthDate);
birthDate.setYear(2019);
You create a date object, you create a Student object passing it the value of newly created Date and then you change the value of it… I don’t get it… Student object when it’s created creates a private local member variable with the value that was passed when calling the constructor and that was Date()
This would make sense:
Date birthDate = new Date();
birthDate.setYear(2019);
Student student = new Student(birthDate);
Can someone please clarify me this behaviour :) Thanks
Inside the Student class is not a private member variable. It’s a private member reference. Therefore you have 1 object, but 2 aliases. Changing one will affect the underlying object, and so any proceeding uses of either will have the last update in full effect.
Hey all nice comment . Good explanation it is necessary for all java programers to follow this steps . Thanks Man.
nice job
Great list, you could probably include some design patterns as well.
useful information for java programmers
nice information. Thanks for Sharing
Thanks for valuable post.Great work
Thanks alto Great expats.
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
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);
}
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.
Now we may have some other code that uses the Student object.
Can you please explain Quote10 in details
GP: Check how we modified
birthDate
object by callingsetYear
method. Note that the birthDate object reference is copied inStudent
object bythis.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:
This make sure that any changes done on birthDate object outside Student class does not propagate inside Student.
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.
I Like Java very much, because…….. Java is the best… best… best…
This is very useful. I’ve been coding java for only 5 months and this helped me alot. :)
Good post, keep up the good work. Feel free to browse my work on 400+ java/JEE interview questions and answers.
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.
Great work , keep going forward :)
Very Useful Information for Java Developers…Thanx and Please update it.
THanks Dude
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:
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
“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.
The quote 10 exemple seems quite flawed.
This constructor doesn’t compile, the type isn’t declared for the parameter.
Moreover, the Date instance of Student isn’t really protected as
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.
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.
Its good list.
Hello Viral!
I would like to know what are the reference/sources that you used to make this list.
Thanks in advance!
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.
Wow very nice explanation.
The information you have shared is awesome . Hope this helps lot more java enthusiasts like me. cheers.
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
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.
Martin Cazares
Android Architect/Developer
please revisit your quote #4. the quote and the ending line seems contradicting each other.
Very nice and use ful…!
I fine all these quotes very useful to write clean and efficient code
Big Up!
good list and useful
Nice list. good job
Great tips!
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.
Very good list . One should use above points while coding in java .
“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
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.
Thanks for nice compilation.
Good Java Code practice is necessary for a good programmer. You explained well.
In Quote 10: Defensive copies are savior, the modified constructor
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…
@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.
nice really helpfull
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.
Great post. Things are really helpful and worth to keep in mind.
This is an excellent article and will help a Java developer to write better code. Good work.
very good collection sir
Great!!! useful article!
Another one which i follow : use builder pattern to create objects .
Please resolve the mistakes u have done in your examples. As a lot of may be learn wrong from there. Intentionally article is very good, but code is not correct or in valid convention.
Nice article. Keep up the good work :)
Thanks a lot for share great Blog. I like your work
You have explained the topic very well. Thanks for sharing a nice article.