Java conventions
A.K.M. Ashrafuzzaman
Java code conventions
Some of the code conventions of Java,
suggested by sun, followed by the article
below,
 
Code Conventions for the Java TM
Programming Language Revised April 20, 1999
Java code conventions
● Indentation
● Statements
● Naming Conventions
● Programming Practices
 
Classes and methods good, bad and ugly
Indentation
Four spaces should be used as the unit of
indentation
 
 
Line Length
Avoid lines longer than 80 characters.
Wrapping Lines
Break after a comma
 
someMethod(longExpression1, longExpression2, longExpression3,
             longExpression4, longExpression5);
 
var = someMethod1(longExpression1,
                    someMethod2(longExpression2,
                                    longExpression3));
Wrapping Lines
Break before an operator
 
longName1 = longName2 * (longName3 + longName4 - longName5)
              + 4 * longname6; // PREFER

longName1 = longName2 * (longName3 + longName4
              - longName5) + 4 * longname6; // AVOID
 
Wrapping Lines
● If the above rules lead to confusing code or
  to code that's squished up against the right
  margin, just indent 8 spaces instead
● Align the new line with the beginning of the
  expression at the same level on the
  previous line
Wrapping Lines
//CONVENTIONAL INDENTATION
someMethod(int anArg, Object anotherArg, String yetAnotherArg,
            Object andStillAnother) {
  ...
}

//INDENT 8 SPACES TO AVOID VERY DEEP INDENTS
private static synchronized horkingLongMethodName(int anArg,
       Object anotherArg, String yetAnotherArg,
       Object andStillAnother) {
   ...
}
Wrapping Lines
//DON'T USE THIS INDENTATION
if ((condition1 && condition2)
    || (condition3 && condition4)
    ||!(condition5 && condition6)) { //BAD WRAPS
    doSomethingAboutIt();           //MAKE THIS LINE EASY TO MISS
}

//USE THIS INDENTATION INSTEAD
if ((condition1 && condition2)
      || (condition3 && condition4)
      ||!(condition5 && condition6)) {
    doSomethingAboutIt();
}

//OR USE THIS
if ((condition1 && condition2) || (condition3 && condition4)
      ||!(condition5 && condition6)) {
    doSomethingAboutIt();
}
Statements
if (condition) {
   statements;
} else if (condition) {
   statements;
} else {
   statements;
}
Statements
Always prefer foreach statement
//ugly code
void cancelAll(Collection<TimerTask> c) {
   for (Iterator<TimerTask> i = c.iterator(); i.hasNext(); )
      i.next().cancel();
}
//clean code
void cancelAll(Collection<TimerTask> c) {
   for (TimerTask t : c)
      t.cancel();
}
Naming Conventions
Packages
● all lower case
● starts with domain name[ com, edu, gov,
  mil, net, org]
● the rest is organizational standards
Examples
com.sun.eng
com.apple.quicktime.v2
edu.cmu.cs.bovik.cheese
Naming Conventions
Classes/Interfaces
● Should be noun
● Cap init camel case
 
Note: If you can not name a class then that is
an indication of "Something went wrong, when
you were splitting the responsibility"
Naming Conventions
Methods
● Should be verbs
● Init small camel case
 
Examples
run();
getBackground();
findByUser(user);
Naming Conventions
Variables
● Init small camel case
● meaningful
 
Example
Product product;
List<Product> products;
 
Note: Usually IDE suggestions are good candidates.
Naming Conventions
Constants
● All caps separated by '_'
 
Examples
static final int MIN_WIDTH = 4;
static final int MAX_WIDTH = 999;
static final int GET_THE_CPU = 1;
Programming Practices
Providing Access to Instance and Class
Variables
● Don't make any instance or class variable
  public
Programming Practices
Referring to Class Variables and Methods
 
Use class to access the method, as the
responsibility goes to the class not the object.
 
AClass.classMethod();      //OK
anObject.classMethod();   //AVOID!
Programming Practices
Keep the code consise
if (booleanExpression) {
    return true;
} else {
    return false;
}
should instead be written as,
return booleanExpression;
Programming Practices
if (condition) {
    return x;
}
return y;
 
Better be,

return (condition ? x : y);
Classes, objects and methods




    Thinking in terms of "object"
      Not as easy as you think
Object


                    Has
     Object               Property


              Has
                          Behaviour
Object
● An actor (Noun)
● Has some properties
● Has some behavior
Object
Example
● An actor (Noun)     => Car
● Has some properties => Fuel
● Has some behavior => start, stop,
  accelerate, etc
Object




         Nothing special
            right???
Object
car.addFuel(10);
Object
car.start();
Object
Now let us say we have a driver
Object
● Driver drives a car
● A car is driven by a driver



               Driven by   Drives
       Car                          Driver
The big question
           ???.addFuel(10);
 




           VS
Object
● Responsibility
● Which object is being impacted
  ○ Which are the properties that are changed
  ○ Which object has changed his behavior
                  car.addFuel(10);
Object
Anyone can add fuel to the car, even the
driver
 
Class Driver {
 ...

    public void refillCar() {
      car.addFuel(10);
    }
}
Methods




       Behavior of an object,
 that can change the properties of
            that object
Relationships




 How we set the relationship of driver with
                the car ???
Relationships
Relationships
● Driver owns a car
● Driver drives a car
● Loves a car
In short
When we design a software
● Search for classes (Entity)
● Search for behavior
● Identify which is the behavior of which
  entity
● Identify the relationship between the
  entities
Methods
● Should properly express an action
● Should have very few arguments
● Should be readable as a plain english
  language not as a geeky programming
  language
● Better be an active voice
● Should be short, should look like a pseudo
  code, which means the details should be
  hidden in the sub methods
Methods
Examples
user.isPermitedToEdit(task);
story.totalEstimatedHours();
classService.findClassesFor(user);
classService.findClasseByTeacherAndSemester(teacher, semester);
Conclusion
● Follow the conventions
● Any code is 20% of its time is written and
  80% time is read, so write it well
● Top level method should only contain a
  pseudo code
● Methods should be small
● Think in terms of object and identify
  responsibilty

Java conventions