Showing posts with label Development. Show all posts
Showing posts with label Development. Show all posts

Best Practices for Java Developers

Sunday, August 7, 2011 Posted by Sudarsan 0 comments
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;
    }
}


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

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

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.

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.

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.

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.

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";

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

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.

That's it Folks !!, Keep visiting the blog for some more in future !!!
Labels:

28. Project Directory Structure for Realtime

Saturday, July 23, 2011 Posted by Sudarsan 2 comments
Hi Guys !
It's been long time , I think you guys are waiting for my posts, I just went through your comments and decided to post something which is useful to your future studies.

In this post i will demonstrate how the real time project will be organized, for this you can use any kind of IDE like Netbeans or Eclipse.For this time I will show you using Eclipse, since this IDE is very popular in development, so lets get started !!!

So, If we want to start a project, first we must identify the domain, which means the main object or the data you are going to deal with, let us say for instance ...if we want to calculate the payroll of an employee...our domain will be "Employee" or to provide an interface to an user to register in your website "User" will be our domain.

After identifying the "domain", we must think in such a way that "How to Implement the chosen Domain".For this identify the data which is best suited for your domain.

For example if our domain is "Employee", which means the best possible data which resides inside that domain will be "employeeId, firstName, lastName and salary etc..".After identifying the data for the domain, provide a public interface to access the data in implementation and call this implementatation as "EmployeeImpl or DomainImpl".

Now, we need to identify the "Services" we must provide to the implementation of our "Domain".The Services in the sense, the data manipulations and retrial of the data which can occur in our domain.For instance if we want to "Add" an employee to the database or to "Remove" an employee from the memory...or some times to "list all the employees" which are part of our domain, these are called services.

When we identify the "Services" for our domain, it is not difficult to provide the "implementation for our identified Services", we call this as "ServiceImpl".

In "Service Implementation" we can describe in what way we are providing the implementation, for instance if we want to implement a service called "Add Employee", this service needs to add a new "Employee" to memory, in the same way "List All Employees" service needs to display all the employees which are available in database to the UI(User Interface).

Finally, we need to identify what are the "Utilities"which provide basic interface to the end user to supply data to the "Domain". for example providing an UI (User Interface) to the user to enter data to the domain model.So by the help of the above entities we can create a project structure using "Domain, DomainImpl, Service, ServiceImpl and Utils".

So have a look at the fallowing image to understand the directory structure to implement "Employee" domain.


After creating the structure, write the code as I given below.

Employee.java
package domain;

/**
 * @author Sudarsan Domain Interface Employee
 */
public interface Employee {

 public int getId();

 public void setId(int id);

 public String getFirstName();

 public void setFirstName(String firstName);

 public String getLastName();

 public void setLastName(String lastName);

 public void setEmail(String email);

 public String getEmail();

 public int getPriority();

 public void setPriority(int priority);

 public String getDesignation();

 public void setDesignation(String designation);

 public String toDisplayString();

}

The above Employee code is a domain interface, it consists of the basic public interface to implement the domain, now we need to implement this interface to a class called EmployeeImpl.java and override the methods as shown below.

EmployeeImpl.java

package domain.impl;

import java.io.Serializable;

import domain.Employee;

/**
 * @author Sudarsan Implementing the domain interface Employee
 */

public class EmployeeImpl implements Employee, Serializable {

 private static final long serialVersionUID = 1L;

 private int id;
 private String firstName;
 private String lastName;
 private String email;
 private int priority;
 private String designation;

 @Override
 public int getId() {
  return id;
 }

 @Override
 public void setId(int id) {
  this.id = id;
 }

 @Override
 public String getFirstName() {
  return firstName;
 }

 @Override
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 @Override
 public String getLastName() {
  return lastName;
 }

 @Override
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public String getEmail() {
  return email;
 }

 @Override
 public void setEmail(String email) {
  this.email = email;
 }

 @Override
 public int getPriority() {
  return priority;
 }

 @Override
 public void setPriority(int priority) {
  this.priority = priority;
 }

 @Override
 public String getDesignation() {
  return designation;
 }

 // A method to set Employee Priority based on his designation
 @Override
 public void setDesignation(String designation) {
  if ("CEO".equalsIgnoreCase(designation)) {
   setPriority(1);
  } else if ("MD".equalsIgnoreCase(designation)) {
   setPriority(2);
  } else if ("HR".equalsIgnoreCase(designation)) {
   setPriority(3);
  } else {
   setPriority(4);
  }
  this.designation = designation;
 }

 @Override
 public String toString() {
  StringBuffer buffer = new StringBuffer();
  buffer.append("EmployeeImpl [id=");
  buffer.append(id);
  buffer.append(", firstName=");
  buffer.append(firstName);
  buffer.append(", lastName=");
  buffer.append(lastName);
  buffer.append(", email=");
  buffer.append(email);
  buffer.append(", priority=");
  buffer.append(priority);
  buffer.append(", designation=");
  buffer.append(designation);
  buffer.append("]");
  return buffer.toString();
 }

 // To print the employee
 @Override
 public String toDisplayString() {
  StringBuffer buffer = new StringBuffer();
  buffer.append(this.getId());
  buffer.append("\t");
  buffer.append(this.getFirstName());
  buffer.append("\t");
  buffer.append(this.getLastName());
  buffer.append("\t");
  buffer.append(this.getEmail());
  buffer.append("\t");
  buffer.append(this.getDesignation());
  return buffer.toString();
 }
}

And now write services for Employee domain and implement those services, for this we need to write an interface called "EmployeeService.java" and this will be implemented in "EmployeeServiceImpl.java" and override the methods.Now have a look at the fallowing code.

EmployeeService.java

package service;

import java.util.List;

import domain.Employee;

/**
 * @author Sudarsan Interface for Employee Services
 */
public interface EmployeeService {

 // We can add more methods in future, like removeEmployee, UpdateEmployee
 
 List<Employee> getAll();

 void addEmployee(Employee employee);

}

Now !!!, write a class "EmployeeServiceImpl", implement the above interface and override the methods in this class as I shown below.

EmployeeServiceImpl.java

package service.impl;

import java.util.ArrayList;
import java.util.List;

import service.EmployeeService;
import domain.Employee;

/**
 * @author Sudarsan Implementing EmployeeService interface
 */
public class EmployeeServiceImpl implements EmployeeService {

 private List<Employee> employees = new ArrayList<Employee>();

 @Override
 public List<Employee> getAll() {
  return this.employees;
 }

 @Override
 public void addEmployee(Employee employee) {
  this.employees.add(employee);
 }
}

After writing the above code, in Utils package create a class called "KeyBoard.java" to provide input for accepting an Integer and String values.
Have a look at the fallowing code, so that you can get an idea.

KeyBoard.java

package utils;

import java.util.Scanner;

/**
 * @author Sudarsan Utility Class to take input from the KeyBoard
 */
public class KeyBoard {

 public static int readInt(String message) {
  System.out.print(message);
  Scanner scanner = new Scanner(System.in);
  try {
   int number = Integer.parseInt(scanner.next());
   return number;
  } catch (NumberFormatException e) {
   System.out.println("Invalid Number");
   return readInt(message);
  }
 }

 public static String read(String message) {
  System.out.print(message);
  Scanner scanner = new Scanner(System.in);
  return scanner.nextLine();
 }
}

Now write "EmployeeIO.java" to give input and to display output as I shown below.

EmployeeIO.java

package utils;

import java.util.List;

import domain.Employee;
import domain.impl.EmployeeImpl;

/**
 * @author Sudarsan Utility Class to manage Input and Output
 */
public class EmployeeIO {

 private static final long serialVersionUID = 1L;

 /* Method to read employee data from keyboard */
 public static Employee read() {
  Employee employee = new EmployeeImpl();
  employee.setId(KeyBoard.readInt("Enter Id :"));
  employee.setFirstName(KeyBoard.read("Enter First Name :"));
  employee.setLastName(KeyBoard.read("Enter Last Name :"));
  employee.setEmail(KeyBoard.read("Enter Email :"));
  employee.setDesignation(KeyBoard.read("Enter Designation :"));
  return employee;
 }
 /* Method to print employee data to console */
 public static void out(List<Employee> employees) {
  StringBuilder builder = new StringBuilder();
  builder.append("Id\tFirst Name\tLast Name\tEmail\tDesignation\n");
  for (int i = 0; i < employees.size(); i++) {
   builder.append(employees.get(i).toDisplayString());
   builder.append("\n");
  }
  System.out.println(builder);
 }
}

And finally write your Main class to execute this application, the code fallows below.... EmployeeMain.java
package utils;

import service.EmployeeService;
import service.impl.EmployeeServiceImpl;
import domain.Employee;

/**
 * @author Sudarsan Starting Point
 */
public class EmployeeMain {

 public static void main(String[] args) {
  int option = 1;
  /*Calling the EmployeeService*/
  EmployeeService empService = new EmployeeServiceImpl();
  do {
   Employee employee = EmployeeIO.read();
   /* Invoking the method addEmployee on empService object */
   empService.addEmployee(employee);
   option = KeyBoard
     .readInt("Do you want add another employee(1/0) :");
  } while (option == 1);
  /* Invoking the method getAll on employeeService object */
  EmployeeIO.out(empService.getAll());
 }
}
This is the structure everyone fallows in real time, so get acquainted with this..if you get the clear idea on this application, it is very easy to use and understand the frameworks like "Struts, Spring and Wicket etc". "Spring and Spring MVC" fallows the same pattern as I explained above.

So that's it guys...keep visiting the blog for updates !!!!
Labels: