Java Best Practices
Use meaning full names
The
name must specify where the parameter is used for. For example if you want to
store the elapsed time in days, name it that way. Of course don't make it all
too long, the more you need to read, the slower you will have read it.
good
|
|
bad
|
Int
elapsedTimeInDays
|
|
Int n; //
elapsed time in days
|
|
int
elapsedTime; // in days
|
|
int elapsedNumberOfDaysFromStarttime
|
|
void
postPayment( ) { ... }
|
|
void
do(){...}
|
Use
pronounceable and searchable names. Unpronounceable names make it difficult to
search through your code and find errors
Date generationTimestamp;
|
|
Date genymdhms; // generate year month day hour minute second
|
|
Date randTime; // sounds like ran time
|
Use
names for constant numbers. When you need to search for a certain pattern,
these words help you telling where a number is used for and you don't need to
guess it. Write constants in capitols.
Const int WEEKDAYS = 7;
for (int i = 0; i < WEEKDAYS;
i++) { ... }
|
|
for (inti=0;i<7;i++) {...}
//whatdoes7mean?
|
Use
camel casing. It's easier to read words when a new word is marked with a
capitol. Start small when you write functions or
variables. Start with a capitol when you write a class name.
int aNewInteger;
|
|
int anewinteger;
|
|
int
Anewinteger;
|
|
int
AnewInteger;
|
|
public class
MyClass { ... }
|
|
public class
Myclass { ... }
|
|
public class
myClass { ... }
|
1.
Classes are objects and therefore should not be a
verb
2.
Method names should have verb or verb phrase names
like postPayment, deletePage, save or getName. They are the actions objects can
perform.
public class Car { ... }
|
|
public class Drive { ... }
|
|
postPayment( ... ) { ... }
|
|
do(...){...}
|
|
setName( ... ) { ... }
|
|
name( ... ) { ... }
|
|
getName( ) { ... }
|
Keep it simple and straight. If you want to use delete, use delete
always. If you rather use remove or setActive, all ok. But don't use more than
one word for a type of action. Don't pick too clever words. Inactivate, kill or
disable will finally be functions only the author will know of. A moderator
could easily look over the function and make the same function under another
name. Say what you mean, mean what you say. Special attention to the function
adds. This is used too many times. For specific purposes choose to use insert
or append.
taskList.append(task); OR taskList.add(task);
|
|
taskList.push(task);
|
|
delete( ); OR remove( );
|
|
deleteItemFromPage( );
|
|
inactivate( );
|
Add
meaningful context and don't add gratuitous context. If your function is
getting too long you can extract parts to new functions and give those good
names which will tell you what will happen
NOT RECOMMENDED
String
printTopBarGuestMessage(List<Message> guestMessages) {
if
(guestMessages.size( ) == 0) { ... a lot of code ...
} else if
(guestMessages.size( ) == 1) { ... a lot of code ...
} else { ...
a lot of code ...
} return
outcome;
}
RECOMMENDED
String
getMessage(List<Message> messages) {
if (messages.size( ) == 0)
return getNoMessages( );
else if (messages.size( ) ==
1){
return getOneMessage( );
else
return getMoreMessages(
messages.size( ) );
}
|
Comments
Nothing beats a well-placed comment. Everyone agreed, the more comment lines your code has, the better it gets readable. Martin disagrees. Comments are needed when your code is not clean. You can better write extra code to make it clear than to write a comment line.
//Set the email pattern
string Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
Or this
Const String EMAIL_PATTERN = ".+@.+\\.[a-z]+";
Pattern emailChecker = Pattern.compile(EMAIL_PATTERN);
Format source code and Organize imports in Eclipse:
If you do this, your code will be
readable and easy to understand. We can follow some other way also.
If you are a lazy, you can use
eclipse shortcut to do the same
- Ctrl + Shift + F – Formats the source code.
- Ctrl + Shift + O – Organizes the imports and removes the unused ones.
Else you will be a more and more lazy
fellow like me :) , Please follow below step in eclipse
·
Window -> Preferences -> Java -> Editor -> Save Actions
·
enable
Perform the selected actions on save
·
check
Format source code + Organize imports
Simplify if-else methods:
Try to simplify you method.. but it
should be understandable at least you on later stage.
NOT RECOMMENDED
private boolean isEligible(int age){
boolean result;
if(age > 18){
result = true;
}else{
result = false;
}
return result;
}
RECOMMENDED
private boolean isEligible(int age){
return age > 18;
}
|
Combine multiple if statements into one
Wherever possible, try to
combine multiple if statements into single one. This one only I will
follow every time.
NOT RECOMMENDED
if(age > 18){
if( voted == false){
// eligible to vote.
}
}
RECOMMENDED
if(age > 18 && !voted){
// eligible to vote
}
|
Avoid multiple returns in same method.
Make sure that you have
only one exit point. Do not use returns in more than one place in a method body
(in this point you can ask why… I don’t have an answer… if you know Wright it
down)
NOT RECOMMENDED
private
boolean isEligible(int age){
if(age > 18){
return true;
}else{
return false;
}
}
RECOMMENDED
private
boolean isEligible(int age){
boolean result;
if(age > 18){
result = true;
}else{
result = false;
}
return result;
}
|
Do not create new instances of Boolean, Integer or String
Avoid creating new
instances of Boolean, Integer, String etc.
Ex:..
Instead of using new Boolean(true),
use Boolean.valueOf(true)
This is same effect of format, but
performance wise 2 one hold a first place.
Use curly braces around block statements
I am usually not
following this way. But this causes some issues so many times. Never forget to
use curly braces around block level statements such as if, for, while.
NOT RECOMMENDED
if(age >
18)
return true;
else
return false;
RECOMMENDED
if(age >
18){
return true;
}else{
return false;
}
|
Mark method parameters as final, wherever applicable:
Always mark
the method parameters as final wherever applicable. If you do so, when
you accidentally modify the value of the parameter, you’ll get a compiler
warning
private boolean
isEligible(final int age){ ... }
Name public static final fields in UPPERCASE:
Always name the public
static final fields (also known as Constants) in UPPERCASE. This
lets you to easily differentiate constant fields from the local variables.
NOT RECOMMENDED
public
static final String testAccountNo = "12345678";
RECOMMENDED
public
static final String TEST_ACCOUNT_NO = "12345678";,
|
Avoid duplicate string literals, instead create a constant
As a developer this step
is very difficult, if you have to use a string in several places, avoid using
it as a literal. Instead create a String constant and use it.
NOT RECOMMENDED
private void
someMethod(){
logger.log("My Application" + e);
....
....
logger.log("My Application" + f);
}
NOT RECOMMENDED
public
static final String MY_APP = "My Application";
private void
someMethod(){
logger.log(MY_APP + e);
....
....
logger.log(MY_APP + f);
}
|
Comments
Post a Comment