Java – Coding Styles and Programming Basics

By ongraph
January 22, 2015 | 710 Views

Latest Industry insights to keep you updated on the latest happenings.

We have touch marsh, Who thought that we can do this in first chance or even we can do this if we go back to 50-60 years in timewrap. But the main reasion behind this is not to just learn new technology but with that to learn how we can utilize existing one.

Same thing does happen with a programmer when he writes a line of code. A good programmer always looks for future and try to develop code that can be used and modified by others and support techologies with better manner and max utilization. Coding is not a big thing. Anyone can write a code by reading 1 or 2 books and learning in an institute but things that matter and come with experince is how to write code that helps in present development as well as in future

 

So lets start with first building blog of coding – how to write standard code with style. Below is some quick styling used by most programmers during development to make code easy-to-use or expandable.

 

Step 1. Formatting of code:

Formatting of code section includes number of subpoints in which I will let you know how can we properly use braces, spaces, brackets, variables etc. 

 

1.1 Indentation :

There are lots of style to indent code like using spaces, tabs etc. But the best and most popular practice is used spaces raither than tabs reasion is supposed you write a code having one tab indentation and pass it to your friend who have 8 space / tab setting in his editor than everything comes goofy.
Beat practice to use 4 – space  indentation raither than tabbing.

Braces :
There are two tricks to used braces, One is in the same line with method and other one is matching braces in same line up vertically in the same column as they construct.

    Style 1 :
void foo() {
// lines of code
}
Style 2 :
void foo()
{
// lines of code
}

 

1.2 Spaces :

 1.2.1 : Operators should be surrounded by a space character.

add = (var1 + var2) * var3; not like //add=(var1+var2)* var3

** But Unary operators should be immediately preceded or followed by their operand.

a++  not like // a ++

1.2.2 : Java reserved words should be followed by a white space.

while (test) not like // while(true)

1.2.3 : Commas should be followed by a white space.

Test(a, b, c, d);   not like //Test(a,b,c,d);

1.2.4 : Colons should be surrounded by white space.

Case : “testing” not like //Case:”testing”

1.2.5 : Semicolons in “for” statements should be followed by a space character.

For ( int i = 0; i < 10; i++) { not like // For ( int i = 0;i < 10;i++) {

1.2.6 : There should be a space after the comment identifier.

// comment  not like //comment

 1.2.7 : All method names should be immediately followed by a left parenthesis.

doMethod(abc); not like // doMethod (abc);

1.2.8 : All array dereferences should be immediately followed by a left square bracket.

Array1[0]; not like Array1 [0];

1.2.9 : Casting should be written with no spaces.

(MyClass) v.get(3);  // Wrong
( MyClass )v.get(3); // Wrong
(MyClass)v.get(3);   // Right

 

1.3 Naming Conventions :

1.3.1 :  Packages : Names representing packages should be in all lower case.

Ex. – mypackage

 1.3.2 : Classes : 

Class names are always nouns, not verbs. Avoid making a noun out of a verb, example DividerClass. If you are having difficulty naming a class then perhaps it is a bad class.

Class names begin with an uppercase letter and shoule not be pluralized unless it is a collection class

Ex. –  FoodItem  // Right
fooditem  // Wrong
Crackers  // Wrong

 1.3.3 : Interface :

Interface names should always be an adjective (wherever possible) describing the enforced behaviors of the class (noun). Preferably, said adjective should end in “able” following an emerging preference in Java. i.e. Clonable, Versionable, Taggable, etc.

Ex. – Digestable, Runnable

    1.3.4 : Constant :

Associated constants (final variables) should be prefixed by a common type name.

               final int COLOR_RED     = 1;
final int COLOR_GREEN     = 2;
final int COLOR_BLUE     = 3;

This indicates that the constants belong together, and what concept the constants represents.

An alternative to this approach is to put the constants inside an interface effectively prefixing their names with the name of the interface:

          interface Color
{
final int RED      = 1;
final int GREEN = 2;
final int BLUE    = 3;
}

 1.3.5 : Variables 

– Variable names must be in mixed case starting with lower case.

Ex-     line, audioSystem

– ‘is’ prefix should be used for boolean variables and methods.

Ex- isSet, isVisible

– Negated boolean variable names must be avoided.

Ex-     bool isError; // NOT: isNoError bool isFound; // NOT: isNotFound

The problem arise when the logical not operator is used and double negative arises. It is not immediately apparent what !isNotError means.

–    ‘No’ suffix should be used for variables representing an entity number.

Ex-     tableNo, employeeNo

–    ‘n’ prefix should be used for variables representing a number of objects.

Ex-     nPoints, nLines

Plural form should be used on names representing a collection of objects.

Ex-     Collection<Point> points;
int[] values;

Generic variables should have the same name as their type.

void setTopic(Topic topic) // NOT: void setTopic(Topic value)

Private class variables should have underscore suffix.

private String name_;

 

   1.3.6 : Method : 

Names representing methods must be verbs and written in mixed case starting with lower case.

Ex- getName(), computeTotalWidth()

The term find can be used in methods where something is looked up.

vertex.findNearestVertex();
matrix.findSmallestElement();

The term initialize can be used where an object or a concept is established.

printer.initializeFontSet();

The term compute can be used in methods where something is computed.

valueSet.computeAverage();
matrix.computeInverse();

The terms get/set must be used where an attribute is accessed directly.

employee.getName();
employee.setName(name);

The name of the object is implicit, and should be avoided in a method name.

line.getLength(); // NOT: line.getLineLength();

Abbreviations and acronyms should not be uppercase when used as name.

exportHtmlSource(); // NOT: exportHTMLSource();

 

Step 2. Coding Tricks and Styles :

Coding is not just to write code, It is of writting a better code with full utilization of resources. There are some common mistakes that we does while writting code and some tricks by which we can impove quality and code standard.

 

1. Constructs to Avoid

1.1 do..while : 

Reason : Mostly programmers execute code from tom to bottom, When he found a loop first thing that he search is terminating condition of loop. If you put that login at bottom, It would be hard to read.

So rather than:
boolean done = false;

        do
{} while (!done)
use:
boolean done = false;
while (!done)
{}

 

1.2 Never use return in middle of method :

Reason : Using return in the middle of a method makes it difficult to later break the method into smaller methods. It also forces the developer to consider more than one exit point to a method.

1.3 Never use Continue :

Reason : Using continue makes it difficult to later break the construct into smaller constructs or methods. It also forces the developer to consider more than one end point for a construct.

1.4 Never use break other than in a switch statement :

Reason : Using break, other than for switch statement control, makes it difficult to later break a construct into smaller constructs or methods. It also forces the developer to consider more than one end point for a construct.

1.5 User increment and decrement operator in separate line :

Reason: Compounding increment or decrement operators into method calls or math is not clear to less experienced programmers who may be required to modify your code.

     foo(a++); // NO!
foo(a);   // YES!
a++;
z += 100 * a++;  // NO!
z += 100 * a;    // YES!
a++;

1.6  Initialization :  

Initialize variable as much as closed they used. This will make easy and more understandable while reding or modifing code.

1.7 Access : 

Try to declare all fields private excepts for some constants.

1.8 Code must be clear :

Raither than writting code that computer can read, Write code that human can read. For example you can write following if condition in two ways

Instead of:

if ( (“x” == x) && ( (“y” == y) || (“z” == z) ) )

Use:

boolean isTrue = ( (“y” == y) || (“z” == z) );
if ( (“x” == x) && isTrue )

1.9 Keep constant code out of loop :

Code that value does remain unchanged in loop keep that out side of loop like –

Instead of :

        int length = 2 * y
for(int i = 0; i < 10; i ++ ) {
x = 2 * y;
}    

Use:

        int length = 2 * y
for(int i = 0; i < 10; i ++ ) {
x  = length;
}

1.10 Divide and conquer:

       How many times have you used the following pattern:

       StringBuilder sb = new StringBuilder(“Ingredients: “);

for (int i = 0; i < ingredients.length; i++) {
if (i > 0) {
sb.append(“, “);
}
sb.append(ingredients);
}

return sb.toString();

In above loop does one thing for a while and another thing from a certain point on.

Let’s take example. The if (i > 0) line starts as false for a single iteration, and from that point on it always evaluates to true. Why check the condition every time then? The compiler would compile that code as if it were written like so:

    StringBuilder sb = new StringBuilder(“Ingredients: “);

if (ingredients.length > 0) {
sb.append(ingredients[0]);
for (int i = 1; i < ingredients.length; i++) {
sb.append(“, “);
sb.append(ingredients);
}
}
return sb.toString();

This way, the redundant if (i > 0) is removed.

 

1.11 Compare two string by equals() instead ==   : Use equals() because this method internally checks == plus content equality check.

    String a = “test”;
String b = new String(“test”);
Insteat of using
a == b // false
Use:
a.equals(b) //True

 

1.12 Use StringBuilder for String concatenations instead of + operator : 

If you have more string concatenation operations, then prefer using StringBuilder object over + operator to increase your code performance.

 

1.13 Call equals on known string constants rather than unknown variable : 

Always use constant.equals raither than string.equals(constant) may throw nullPointerException.

String temp = null;
“test”.equals(temp) // false
temp.equals(“test”)// nullPointerException

 

1.14 Use switch( ) instead of multiple if else-if : 

If there is scenario to compare multiple strings then use switch over multiple if – else-if statements. As execution time of switch statement is much lesser than if – else – if

 

1.15 Use String.valueOf() instead of toString() : 

If obj needs to be converted to string then the result of obj.toString() and String.valueOf(obj) will be same but String.valueOf() is null safe, means it will never throw NullPointerException.

 

1.16 Create Strings as literals instead of creating String objects using ‘new’ :

    Always create string constants like String constant = “constantValue” because String implements Fly Weight design pattern, which maintains a pool, if “constantValue” string is already present in the pool then it will return the reference from pool, otherwise it will create a new object, put it into pool and then return the reference of this object.

If somewhere else in the code if we again create String constant1 = “constantValue” then it won’t create a new String object and will return reference of previously created object from pool.
While if String constant = new String(“constantValue”) is used to create a string, then it will not search the string “constantValue” in the pool instead it will create a new object every time and put it into pool and return new reference, means if we have new String(“constantValue”) ten places in the code, it will create 10 new object every time.

 

1.17 Use String.format() to format the the strings : 

User string.format() if you want to get string with some dyanmic values like –

    int a = 10;
int b = 20;
int c = a + b;
String.format(“Adding of [%d] and [%d] is %d”,a,b,c);
Will output like
Adding of [10] and [20] is 30

 

This is not a complete list. The conventions and best practices grow day by day as you write more code and Java touches new heights with new versions.

Key is

 DO MISTAKES AS MUCH AS YOU CAN BUT DO NOT REPEAT THEM.
LEARN FROM MISTAKES AND BE BETTER THAN PAST….

Good Luck!

Monthly industry insights to keep you updated on latest happenings

Follow us on Twitter
Follow us on Facebook
Follow us on Linkedin