Google

Jul 21, 2014

6 tips to writing loosely coupled Java applications with examples

Q. What is tight coupling?
A. If class OrderServiceImpl relies on parts of class PaymentServiceImpl that are not part of class PaymentServiceImpl's interface PaymentService, then the OrderServiceImpl and PaymentServiceImpl are said to be tightly coupled. In other words, OrderServiceImpl knows more than what it should about the way in which PaymentServiceImpl was implemented. If you want to change PaymentServiceImpl with a separate implementations BasicPaymentServiceImpl, then you need to modify the  OrderServiceImpl class as well by changing PaymentServiceImpl to BasicPaymentServiceImpl





Tip #1: Coding to interface will loosely couple classes. 

Q. What is loose coupling?
A. If the only knowledge that class OrderServiceImpl has about class PaymentServiceImpl, is what class PaymentServiceImpl has exposed through its interface PaymentService, then class OrderServiceImpl and class PaymentServiceImpl are said to be loosely coupled. If you want to change PaymentServiceImpl with a separate implementations BasicPaymentServiceImpl, then you don't need to modify OrderServiceImpl. Change only OrderServiceMain from

PaymentService payService  = new PaymentServiceImpl();


to


PaymentService payService  = new BasicPaymentServiceImpl();




This is what the Dependency Inversion Principle (DIP) states.



Q. Can the above classes be further improved in terms of coupling?
A. Yes. Change the PaymentService method signature from

   public abstract void handlePay(int accountNumber, BigDecimal amount);

to
     public abstract void handlePay(PaymentDetail paymentDetail);


Tip #2Design method signatures carefully by avoiding long parameter lists. As a rule, three parameters should be viewed as a practical maximum, and fewer is better (as recommended by Mr. Joshua Bloch.). This is not only from coupling perspective, but also in terms of readability and maintainability of your code.

It is likely that the PaymentService may need more parameters than account number and amount to process the payment. Every time you need to add a new parameter, your PaymentService interface  method signature will change, and all other classes like OrderService that depends on PaymentService has to change as well to change its arguments to passed. But, if you create a value object like PaymentDetail, the method signature does not have to change. You add the new field to the PaymentDetail class.



Tip #3: Design patterns promote looser coupling

The PaymentService will not only be used by the OrdersServiceMain, but can be used by other classes like RequestServiceMain, CancelServiceMain, etc. So, if you want to change the actual implementation of PaymentService between PaymentServiceImpl and BasicPaymentServiceImpl without having to change OrdersServiceMain, RequestServiceMain, and CancelServiceMain, you can use the factory design pattern as shown by the PaymentFactory class. You only have to make a change to the PaymentFactory class to return the right PaymentService implementation.

package com.coupling;

import java.math.BigDecimal;

public class OrderServiceMain {
 
 public static void main(String[] args) {
  //loosely coupled as it knows only about the factory
  PaymentService payService  = PaymentFactory.getPaymentService();
  OrderService orderService = new OrderServiceImpl(payService);
  orderService.process(12345, BigDecimal.valueOf(250.00));
 }
}
package com.coupling;

public final class PaymentFactory {

 private static PaymentService instance = null;
 
 private PaymentFactory(){}
 
 public static PaymentService getPaymentService(){
  if(instance == null){
   instance = new PaymentServiceImpl();
  }
  
  return instance;
 }
 
}


Tip #4: Using Inversion of Control (IoC) Containers like Spring, Guice, etc. 

Dependency Injection (DI) is a pattern of injecting a class’s dependencies into it at run time. This is achieved by defining the dependencies as interfaces, and then injecting in a concrete class implementing that interface to the constructor. This allows you to swap in different implementations without having to modify the main class. The Dependency Injection pattern also promotes high cohesion by promoting the  Single Responsibility Principle (SRP), since your dependencies are individual objects which perform discrete specialized tasks like data access (via DAOs) and business services (via Service and Delegate classes).

The Inversion of Control  (IoC) container is a container that supports Dependency Injection. In this you use a central container like Spring framework, Guice, or HiveMind, which defines what concrete classes should be used for what dependencies throughout your application. This brings in an added flexibility through looser coupling, and it makes it much easier to change what dependencies are used on the fly. The basic concept of the Inversion of Control pattern is that you do not create your objects but describe how they should be created.

You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up. Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

For example, in Spring you will wire up the dependencies via an XML file:

    <bean id="orderService" class="com.coupling.OrderServiceImpl">
  <constructor-arg ref="paymentService"/> 
    </bean>
 
    <bean id="paymentService" class="com.coupling.PaymentServiceImpl" />


You can also use annotations to inject dependencies. The @Resource annotation injects PaymentService.

package com.coupling;

import java.math.BigDecimal;
import javax.annotation.Resource;

public class OrderServiceImpl implements OrderService {

 @Resource
 PaymentService payService;

 public OrderServiceImpl(PaymentService payService) {
  this.payService = payService;
 }

 public void process(int accountNumber, BigDecimal amount) {
  // some logic
  payService.handlePay(new PaymentDetail(accountNumber, amount));
  // some logic
 }
}


Tip #5High cohesion often correlates with loose coupling, and vice versa.

What is cohesion? Cohesion is the extent to which two or more parts of a system are related and how they work together to create something more valuable than the individual parts. You don't want a single class to perform all the functions (or concerns) like being a domain object, data access object, validator, and a service class with business logic. To create a more cohesive system from the higher and lower level perspectives, you need to break out the various needs into separate classes like PaymentDetail, PaymentService, PaymentDao, PaymentValidator, etc. Each class concentrates on one thing.



Coupling happens in between classes or modules, whereas cohesion happens within a class. So, think, tight encapsulation, loose (low) coupling, and high cohesion.


Tip #6: Favor composition over inheritance for code reuse

You will get a better abstraction with looser coupling with composition as composition is dynamic and takes place at run time compared to implementation inheritance, which is static, and happens at compile-time.  The guide is that inheritance should be only used when subclass ‘is a’ super class. Don’t use inheritance just to get code reuse. If there is no ‘is a’ relationship then use composition for code reuse.  Overuse of implementation inheritance (uses the “extends” key word) can break all the subclasses, if the super class is modified. Do not use inheritance just to get polymorphism. If there is no ‘is a’ relationship and all you want is polymorphism then use interface inheritance with composition, which gives you code reuse. More elaborate explanation on this -- Why favor composition over inheritance in Java OOP?


You may also like How to create well designed Java classes?

Labels: ,

May 27, 2014

Understanding Open/Closed Principle (OCP) from the SOLID OO principles with a simple Java example

Spring Interview Questions and Answers Q1 - Q14 are FAQs

Q1 - Q4 Overview & DIP Q5 - Q8 DI & IoC Q9 - Q10 Bean Scopes Q11 Packages Q12 Principle OCP Q14 AOP and interceptors
Q15 - Q16 Hibernate & Transaction Manager Q17 - Q20 Hibernate & JNDI Q21 - Q22 read properties Q23 - Q24 JMS & JNDI Q25 JDBC Q26 Spring MVC Q27 - Spring MVC Resolvers

Q. Is there anything wrong with the following class design? If yes, can the design be improved?

package com.ocp;

import javax.management.RuntimeErrorException;

import org.apache.commons.lang.StringUtils;

public class MathOperation {
 
 public int operate(int input1, int input2, String operator){
  
  if(StringUtils.isEmpty(operator)){
   throw new IllegalArgumentException("Invalid operator: " + operator);
  }
  
  if(operator.equalsIgnoreCase("+")){
   return input1 + input2;
  }
  else if(operator.equalsIgnoreCase("*")){
   return input1 * input2; 
  } else {
   throw new RuntimeException("unsupported operator: " + operator);
  }
 }

}

JUnit test class.

package com.ocp;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;

public class MathOperationTest {
 
 MathOperation operation;
 
 @Before
 public void init(){
  operation = new MathOperation();
 }
 
 @Test
 public void testAddition() {
  Assert.assertEquals(8, operation.operate(5, 3, "+"));
 }
 
 @Test
 public void testMultiplication() {
  Assert.assertEquals(15, operation.operate(5, 3, "*"));
 }

}

A. It’s not a good idea to try to anticipate changes in requirements ahead of time, but you should focus on writing code that is well written enough so that it’s easy to change. This means, you should strive to write code that doesn't have to be changed every time the requirements change. This is what the Open/Closed principle is. According to GoF design pattern authors "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification". Spring framework promotes this principle.

In the above example, you can anticipate more operators like "-" (subtraction) and division (/) to be supported in the future and the class "MathOperation" is not closed for modification. When you need to support operators "-" and "%" you need to add 2 more "else if" statements. Whenever you see large if/else or switch statements, you need to think if "Open/Closed" design principle is more suited.


Let's open for extension and close for modifications

In the rewritten example below, the classes AddOperation and MultiplyOperation are closed for modificationbut open for extension by allowing you to add new classes like SubtractOperation and DivisionOperation by implementing the Operation interface.


Define the interface Operation.

package com.ocp;

public interface Operation {
       abstract int operate(int input1, int input2);
}


Define the implementations

package com.ocp;


public class AddOperation implements Operation {

 @Override
 public int operate(int input1, int input2) {
  return input1 + input2;
 }
 
}

package com.ocp;

public class MultiplyOperation implements Operation {

 @Override
 public int operate(int input1, int input2) {
  return input1 * input2;
 }
 
}


Finally, the JUnit test class

package com.ocp;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;

public class MathOperation2Test {
 
 Operation operation;
  
 @Test
 public void testAddition() {
  operation = new AddOperation();
  Assert.assertEquals(8, operation.operate(5, 3));
 }
 
 @Test
 public void testMultiplication() {
  operation = new MultiplyOperation();
  Assert.assertEquals(15, operation.operate(5, 3));
 }

}


This is only a trivial example, but in real life applications, wherever you have large if/else statements, you need to think if OCP can be applied. Spring framework promotes this principle.


Q. Can you explain if the following classes are badly designed? 

Labels: ,

May 23, 2014

Why favor composition over inheritance in Java OOP?

This is a very popular job interview question, and the correct answer depends on the problem you are trying to solve. You need to ask the right questions before deciding one over the other.

Q. How do you express an ‘is a’ relationship and a ‘has a’ relationship or explain inheritance and composition?
A. The ‘is a’ relationship is expressed with inheritance and ‘has a’ relationship is expressed with composition. Both inheritance and composition allow you to place sub-objects inside your new class. Two of the main techniques for code reuse are class inheritance and object composition.


Inheritance is uni-directional. For example House is a Building. But Building is not a House. Inheritance uses extends key word. Composition: is used when House has a Bathroom. It is incorrect to say House is a Bathroom. Composition simply means using instance variables that refer to other objects. The class House will have an instance variable, which refers to a Bathroom object.

Q. Which one to favor, composition or inheritance?
A. The guide is that inheritance should be only used when subclass ‘is a’ super class. Don’t use inheritance just to get code reuse. If there is no ‘is a’ relationship then use composition for code reuse.

Reason #1: Overuse of implementation inheritance (uses the “extends” key word) can break all the subclasses, if the super class is modified. Do not use inheritance just to get polymorphism. If there is no ‘is a’ relationship and all you want is polymorphism then use interface inheritance with composition, which gives you code reuse.

Reason #2: Composition is more flexible as it happens at run time whereas inheritance happens at compile-time.

Reason #3: Composition offers better testability than Inheritance. Composition is easier to test because inheritance tends to create very coupled classes that are more fragile (i.e. fragile parent class) and harder to test in isolation. The IoC containers like Spring, make testing even easier through injecting the composed objects via constructor or setter injection.


Q. Can you give an example of the Java API that favors composition?
A. The Java IO classes that use composition to construct different combinations using the decorator design pattern at run time.

//construct a reader
StringReader sr = new StringReader(“Some Text....”);
//decorate the reader for performance
BufferedReader br = new BufferedReader(sr);
//decorate again to obtain line numbers
LineNumberReader lnr = new LineNumberReader(br);

The GoF design patterns like strategy, decorator, and proxy favor composition for code reuse over inheritance.

Q. Can you a give an example where GoF design patterns use inheritance?
A. A typical example for using inheritance is in frameworks where the template method design pattern is used.

Another common pattern that would use inheritance is Composite pattern.


Q. What questions do you ask yourself to choose composition (i.e. has-a relationship) for code reuse over implementation inheritance (i.e. is-a relationship)? 

A. Do my subclasses only change the implementation and not the meaning or internal intent of the base class? Is every object of type House really “is-an” object of type Building? Have I checked this for “Liskov Substitution Principle

According to Liskov substitution principle (LSP), a Square is not a Rectangle provided they are mutable. Mathematically a square is a rectangle, but behaviorally a rectangle needs to have both length and width, whereas a square only needs a width.

Another typical example would be, an Account class having a method called calculateInterest(..). You can derive two subclasses named SavingsAccount and ChequeAccount that reuse the super class method. But you cannot have another class called a MortgageAccount to subclass the above Account class. This will break the  Liskov substitution principle because the intent is different. The savings and cheque accounts calculate the interest due to the customer, but the mortgage or home loan accounts calculate the interest due to the bank

Violation of LSP results in all kinds of mess like failing unit tests, unexpected or strange behavior, and violation of open closed principle (OCP) as you end up having if-else or switch statements to resolve the correct subclass. For example,

if(shape instanceof Square){
     //....
} 
else if (shape instanceof Rectangle){
    //...
}

If you cannot truthfully answer yes to the above questions, then favor using “has-a” relationship (i.e. composition). Don't use “is-a” relationship for just convenience. If you try to force an “is-a” relationship, your code may become inflexible, post-conditions and invariants may become weaker or violated, your code may behave unexpectedly, and the API may become very confusing. LSP is the reason it is hard to create deep class hierarchies.

Always ask yourself, can this be modeled with a “has-a” relationship to make it more flexible?

For example, If you want to model a circus dog, will it be better to model it with “is a” relationship as in a CircusDog “is a” Dog or model it as a role that a dog plays? If you implement it with implementation inheritance, you will end up with sub classes like CircusDog, DomesticDog, GuideDog, SnifferDog, and StrayDog. In future, if the dogs are differentiated by locality like local, national, international, etc, you may have another level of hierarchy like LocalCircusDog, NationalCicusDog, InternationalCircusDog, etc extending the class CircusDog. So you may end up having 1 animal x 1 dog x 5 roles x 3 localities = 15 dog related classes. If you were to have similar differentiation for cats, you will end up having similar cat hierarchy like WildCat, DomesticCat, LocalWildCat, NationalWildCat, etc. This will make your classes strongly coupled.


If you implement it with interface inheritance, and composition for code reuse, you can think of circus dog as a role that a dog plays. These roles provide an abstraction to be used with any other animals like cat, horse, donkey, etc, and not just dogs. The role becomes a “has a” relationship. There will be an attribute of interface type Role defined in the Dog class as a composition that can take on different subtypes (using interface inheritance) such as CircusRole, DomesticRole, GuideRole, SnifferRole, and StrayRole at runtime. The locality can also be modeled similar to the role as a composition. This will enable different combinations of roles and localities to be constructed at runtime with 1 dog + 5 roles + 3 localities = 9 classes and 3 interfaces (i.e. Animal, Role and Locality). As the number of roles, localities, and types of animals increases, the gap widens between the two approaches. You will get a better abstraction with looser coupling with this approach as composition is dynamic and takes place at run time compared to implementation inheritance, which is static.


Extracted from Core Java Career Essentials, which has more examples, code, and design topics.

Labels: ,

May 18, 2014

Is Java a 100% Object Oriented (OO) language? if yes why? and if no, why not?

This is a very common Java interview questionHere is the detailed answer to impress your interviewers.

A. I would say Java is not 100% object oriented, but it embodies practical OO concepts. There are 6 qualities to make a programming language to be pure object oriented. They are:

1. Encapsulation – data hiding and modularity.
2. Inheritance – you define new classes and behavior based on existing classes to obtain code reuse.
3. Polymorphism – the same message sent to different objects results in behavior that's dependent on the nature of the object receiving the message.
4. All predefined types are objects.
5. All operations are performed by sending messages to objects.
6. All user defined types are objects.

points 1- 3, stands for PIE (Polymorphism, Inheritance, and Encapsulation)

Reason #1: The main reason why Java cannot be considered 100% OO is due to its existence of 8 primitive variables (i.e. violates point number 4) like int, long, char, float, etc. These data types have been excused from being objects for simplicity and to improve performance. Since primitive data types are not objects, they don't have any qualities such as inheritance or polymorphism. Even though Java provides immutable wrapper classes like Integer, Long, Character, etc representing corresponding primitive data as objects, the fact that it allowed non object oriented primitive variables to exist, makes it not fully OO.

Reason #2:  Another reason why Java is considered not full OO is due to its existence of static methods and variables (i.e. violates point number 5). Since static methods can be invoked without instantiating an object, we could say that it breaks the rules of encapsulation.


Reason #3:  Java does not support multiple class inheritance to solve the diamond problem because different classes may have different variables with same name that may be contradicted and can cause confusions and result in errors.


In Java, any class can extend only one other class, but can implement multiple interfaces.

We could also argue that Java is not 100% OO according to this point of view. But Java realizes some of the key benefits of multiple inheritance through its support for multiple interface inheritance and in Java 8, you can have multiple behavior (not state) inheritance  as you can have default methods in interfaces.


Reason #4: Operator overloading is not possible in Java except for string concatenation and addition operations. String concatenation and addition example,

System.out.println(1 + 2 + ”3”);                   //outputs 33
System.out.println(“1” + 2 + 3);                   //outputs 123


Since this is a kind of polymorphism for other operators like * (multiplication), / (division), or - (subtraction), and Java does not support this, hence one could debate that Java is not 100% OO. Working with a primitive in Java is more elegant than working with an object like BigDecimal. For example,

int a,b, c;
//without operator overloading
a = b – c * d   


What happens in Java when you have to deal with large decimal numbers that must be accurate and of unlimited size and precision? You must use a BigDecimal. BigDecimal looks verbose for larger calculations without the operator overloading as shown below:

BigDecimal b = new BigDecimal(“25.24”);
BigDecimal c = new BigDecimal(“3.99”);
BigDecimal d = new BigDecimal(“2.78”);
BigDecimal a = b.subtract(c).multiply(d);                      //verbose and wrong


Also, the last line above is wrong. The rules of precedence have changed. With chained method calls like this, evaluation is strictly left-to-right. Instead of subtracting the product of c and d from b, we are multiplying the difference between b and c by d. We would have to rewrite the last line as shown below:

BigDecimal a = b.subtract(c.multiply(d)); //correct


So, it is error prone as well. Another point is that the BigDecimal class is immutable and, as such, each of the “operator” methods returns a new instance. In future Java versions, you may have operator overloading for BigDecimal, and it would make your code more readable as shown below.

BigDecimal a = b – (c * d); //much better 




This blog post has covered OO basics, Daiamond problem, and operator overloading concepts as well with examples.

Labels:

May 9, 2014

Top 5 OO tips with Java examples

Tip #1: Tightly encapsulate your classes. A class generally contains data as well as methods, and is responsible for the integrity of its own data. The standard way to protect the data is to make it private, so that no other class can get direct access to it, and then write a couple of public methods to get the data and set the data.

In the example below,

package com.oo;

import java.math.BigDecimal;

import org.apache.commons.lang.StringUtils;

public class Employee {

 private String name;
 private int age;
 private BigDecimal salary;
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  if(StringUtils.isEmpty(name)){
   throw new IllegalArgumentException("Invalid name !!!");
  }
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  if(age < 0 || age > 100) {
   throw new IllegalArgumentException("Invalid age !!!");
  }
  this.age = age;
 }
 public BigDecimal getSalary() {
  return salary;
 }
 public void setSalary(BigDecimal salary) {
  if(salary.compareTo(BigDecimal.ZERO) < 0){
   throw new IllegalArgumentException("Invalid salary !!!");
  }
  this.salary = salary;
 }
 
}


Data: name, age, and salary are made private. So, you can't directly set these values from out side like


Employee employee1 = new Employee();
employee1.age = -20;  //Illegal. Compile Error

The data is encapsulated, and only access is possible via the public methods. The public methods fail-fast by validating the input data. It won't allow any negative ages by throwing an "IllegalArgumentException" at run time. So, your data is protected via compile-time and run time checks. The other fields like name and salary are encapsulated as well from illegal use.

Employee employee1 = new Employee();
employee1.setAge(20); // okay


Tip #2:  Hide non-essential details through abstraction. A good OO design should hide non-essential details through abstraction. Encapsulation is about hiding the implementation details  whereas, abstraction is about providing a generalization.

For example, say you want to capture employment type like part-time, full-time, casual, semi-casual, and so on, it is a bad practice to define them as classes as shown below.

package com.oo;

public class PartTimeEmployee extends Employee {

}

package com.oo;

public class FullTimeEmployee extends Employee {

}


You will end up creating new classes for each new employment type, making your code more rigid and tightly coupled. The better approach is to abstract out the employmentType as a field. This way, instead of creating new classes for every employment type, you will be just creating new objects at run time with different employmentType.

public class Employee {

 enum EmploymentType {PART_TIME, FULL_TIME, CASUAL, SEMI_CASUAL}
 
 private String name;
 private int age;
 private BigDecimal salary;
 private EmploymentType employmentType;

    // ... getters and setters 
 
}

Another detailed example on abstraction  Java OO interview Questions and Answers


Tip #3: Loosely couple your classes. There are basically three relationships between classes

  1. is a relationship. Also known as an inheritance and in UML terms generalization
  2. has a relationship. Also known as a composition and in UML  terms association
  3. uses a relationship. Also known as a delegation in UML terms.
Coupling is about the flow of data between modules. Which of the following definitions is loosely coupled?

Definition 1:

package com.oo;

import java.math.BigDecimal;

public interface SalaryProcessor {
        BigDecimal processSalary(Employee employee);
}



Definition 2:

package com.oo;

import java.math.BigDecimal;

public interface SalaryProcessor {
        BigDecimal processSalary(String name, BigDecimal salary);
}


The Definition 1 is more loosely coupled. If in the future the method processSalary(...) requires employmentType to process the salary, adding a new parameter to the method processSalary(...) can break all the classes that depends on it. But if you were to pass the Employee object as an argument, you don't have to change the  processSalary(...) definition, but just change the implementation to use the employmentType.

Even if the processSalary(..) method needed a new parameter like say leaveLoading, you don't have to change the signature of the processSalary( ) method, and just add the new field to the Employee class, and include that in the implementation. The interfaces provide the contract, and you need to make minimal changes. The implementations can change as they don't break the contract.

public class Employee {

 enum EmploymentType {PART_TIME, FULL_TIME, CASUAL, SEMI_CASUAL}
 
 private String name;
 private int age;
 private BigDecimal salary;
 private EmploymentType employmentType;
 private BigDecimal leaveLoading;

    //.....getters and setters
 
}


With the advent of IoC frameworks like Spring, you can increase loose coupling through dependency injection. Use the  Dependency Inversion principle for loose coupling.

Being loosely coupled goes hand in hand with the idea of Separation of Concerns (SoC), which is the process of breaking a program into distinct features in order to reduce overlapping functionalities.

For example, the following Employee class tries to do too many things like being a model class, data access logic, and validation logic.

public class Employee {

 enum EmploymentType {PART_TIME, FULL_TIME, CASUAL, SEMI_CASUAL}
 
 private String name;
 private int age;
 private BigDecimal salary;
 private EmploymentType employmentType;
 private BigDecimal leaveLoading;
 
 
 public List<employee> loadEmployees() {
  //sql logic to load emplyees
 }
 
 public boolean validateEmployeeSalary() {
  //validation logic
 }
     
    //getters and setters   
}

The data access logic can be extracted out to a separate class.

public interface EmployeeDao {
   abstract List loadEmployees() ;
}


public class EmployeeDaoImpl implements EmployeeDao {

 @Override
 public List<employee> loadEmployees() {
  // TODO .....................
  return null;
 }

}


Similarly, a Validator interface can be used for validation.

Tip #4: Favor composition over inheritance to get code reuse.
  • With composition, you will have full control of your implementations. i.e., you can expose only the methods you intend to expose.
  • With composition, it's easy to change behavior on the fly with Dependency Injection / Setters. Inheritance is more rigid as most languages do not allow you to derive from more than one type.
This does not mean that you can't use inheritance. Apply "Liskov Substitution & Interface Segregation Principles" to ensure that it makes sense to use inheritance. 

In a more simpler terms, when you use inheritance to reuse code from the super class, rather than to override methods and define another polymorphic behavior, it's often an indication that you should use composition instead of inheritance. A typical example is that

In geometry a "Square is a rectangle". But in programming, a square is not a rectangle as explained in detail here.

A template-method design pattern is a good example for using inheritance, which is often used in frameworks.  The Gang of Four (GoF) design patterns favor composition over inheritance.


Tip #5: Use polymorphism.

So, use

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


instead of

ArrayList<Emplyee> employees = new ArrayList<Employee>();


As a List can take different forms like ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, and Vector as they all implents the List interface. So, you can easily swith to CopyOnWriteArrayList if you want thread-safety, etc.




Finally.....be aware of the OO design principles and judiciously apply them where appropriate.


  • DRY (Don’t repeat yourself): Don’t write duplicate code, instead use abstraction to abstract common things in one place.
  • Open Closed Principle(OCP): The Open Close Principle states that the design and writing of the code should be done in a way that new functionality should be added with minimum changes in the existing code. The design should be done in a way to allow the adding of new functionality as new classes, keeping as much as possible existing code unchanged.
  • Single Responsibility Principle (SRP): If you put more than one functionality in one Class in Java it introduce coupling between two functionality. This is also aknown as the SoC (Separation of Concerns) they was discussed earlier with EmployeeDao example.
  • Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.
  • Interface Segregation Principle (ISP):  a client should not implement an interface if it doesn’t use that. So, don't have fat interface with 10+ methods. Segregate them into separate interfaces.
  • Liskov Substitution Principle (LSP): This is related to Single Responsibility Principle and Dependency Inversion Principle. Subtypes must be substitutable for super type. When you use inheritance to reuse code from the super class, rather than to override methods and define another polymorphic behavior, it's often an indication that you should use composition instead of inheritance as it breaks the LSP. 

All these principles are explained with code in "Core Java Career Essentials. Design is always a trade-off, and there is no black and white answers.



Labels:

May 21, 2013

Java Coding Interview Questions on decorator and composition design pattern


Q. When would you use a decorator design pattern?
A. The Decorator pattern should be used when:
  •     Object responsibilities and behaviors should be dynamically modifiable
  •     Concrete implementations should be decoupled from responsibilities and behaviors

Q. Can you write a class using the decorator design pattern to print numbers from 1-10, and then decorators that optionally print only even or odd numbers?
A. This can be done by sub classing or via inheritance. But too much sub classing is definitely a bad thing. Composition is more powerful than sub classing as you can get different behaviors via decorating at run time. Here is the code, you will realize the power of object composition and why GoF design patterns favors composition to inheritance.


Step 1: Define the interface class.

package com.arul;

public interface NextNumber
{
    abstract int getNextNumber();
}


Step 2: Define the implementation classes. The class that gets the numbers.

package com.arul;

public class PrintNumbers implements NextNumber
{
    protected int num;
    
    public PrintNumbers(int num)
    {
        this.num = num;
    }
    
    @Override
    public int getNextNumber()
    {
        return ++num; // incremented, assigned, and then returned
    }
    
}

Step 3: The class that gets the odd numbers.

package com.arul;

public class PrintOddNumbers implements NextNumber
{
    
    protected final NextNumber next;
    
    public PrintOddNumbers(NextNumber next)
    {
        if (next instanceof PrintEvenNumbers)
        {
            throw new IllegalArgumentException("Cannot be decorated with " + PrintEvenNumbers.class);
        }
        this.next = next;
        
    }
    
    @Override
    public int getNextNumber()
    {
        int num = -1;
        
        if (next != null)
        {
            
            num = next.getNextNumber();
            //keep getting the next number until it is odd
            while (num % 2 == 0)
            {
                num = next.getNextNumber();
            }
        }
        
        return num;
    }
    
}


Step 4: The class that gets the even numbers

package com.arul;

public class PrintOddNumbers implements NextNumber
{
    
    protected final NextNumber next;
    
    public PrintOddNumbers(NextNumber next)
    {
        if (next instanceof PrintEvenNumbers)
        {
            throw new IllegalArgumentException("Cannot be decorated with " + PrintEvenNumbers.class);
        }
        this.next = next;
        
    }
    
    @Override
    public int getNextNumber()
    {
        int num = -1;
        
        if (next != null)
        {
            
            num = next.getNextNumber();
            //keep getting the next number until it is odd
            while (num % 2 == 0)
            {
                num = next.getNextNumber();
            }
        }
        
        return num;
    }
    
}

Step 5: The class that gets the multiples of 3s

package com.arul;

public class PrintMultipleOfThreeNumbers implements NextNumber
{
    
    protected final NextNumber next;
    
    public PrintMultipleOfThreeNumbers(NextNumber next)
    {
        this.next = next;
    }
    
    @Override
    public int getNextNumber()
    {
        int num = -1;
        
        if (next != null)
        {
            
            num = next.getNextNumber();
            //keep getting the next number until it is odd
            while (num % 3 != 0)
            {
                num = next.getNextNumber();
            }
        }
        
        return num;
    }
    
}






Step 6:  Finally, a  sample file that shows how the above classes can be decorated at run time using object composition to get different outcomes. Additional  implementations of NextNumber  like PrintPrimeNumbers, PrintMultiplesOfSevenPrintFibonacciNumber, etc can be added using the Open-Closed design principle.

package com.arul;

public class TestNumbersWithDecorators
{
    public static void main(String[] args)
    {
        
        //without decorators
        PrintNumbers pn = new PrintNumbers(0);
        for (int i = 0; i < 10; i++)
        {
            System.out.print(pn.getNextNumber() + " "); // print next 10 numbers
        }
        
        System.out.println();
        
        PrintNumbers pn2 = new PrintNumbers(0);
        //print odd numbers with decorators
        PrintOddNumbers pOdd = new PrintOddNumbers(pn2); // decorates pn2
        for (int i = 0; i < 10; i++)
        {
            System.out.print(pOdd.getNextNumber() + " "); //print next 10 odd numbers
        }
        
        System.out.println();
        
        PrintNumbers pn3 = new PrintNumbers(0);
        //print even numbers with decorators
        PrintEvenNumbers pEven = new PrintEvenNumbers(pn3); // decorates pn3
        for (int i = 0; i < 10; i++)
        {
            System.out.print(pEven.getNextNumber() + " "); //print next 10 even numbers
        }
        
        System.out.println("");
        
        PrintNumbers pn4 = new PrintNumbers(0);
        //print odd numbers with decorators
        PrintOddNumbers pOdd2 = new PrintOddNumbers(pn4); // decorates pn4
        //print multiples of 3 with decorators
        PrintMultipleOfThreeNumbers threes = new PrintMultipleOfThreeNumbers(pOdd2); // decorates pOdd2
        for (int i = 0; i < 10; i++)
        {
            System.out.print(threes.getNextNumber() + " "); // print next 10 odd numbers
                                                            // that are multiple of threes
        }
        
        System.out.println("");
        
        PrintNumbers pn5 = new PrintNumbers(0);
        //print even numbers with decorators
        PrintEvenNumbers pEven2 = new PrintEvenNumbers(pn5); // decorates pn5
        //print multiples of 3 with decorators
        PrintMultipleOfThreeNumbers threes2 = new PrintMultipleOfThreeNumbers(pEven2); // decorates pEven2
        
        for (int i = 0; i < 10; i++)
        {
            System.out.print(threes2.getNextNumber() + " ");  // print next 10 even numbers
                                                             // that are multiple of threes
        }
        
        System.out.println("");
        
        PrintNumbers pn6 = new PrintNumbers(0);
        //print multiples of 3 with decorators
        PrintMultipleOfThreeNumbers threes3 = new PrintMultipleOfThreeNumbers(pn6); // decorates pn6
        //print even numbers with decorators
        PrintEvenNumbers pEven3 = new PrintEvenNumbers(threes3); // decorates threes3
        
        for (int i = 0; i < 10; i++)
        {
            System.out.print(pEven3.getNextNumber() + " ");  // print next 10 multiple of threes
                                                            // that are even numbers
        }
        
    }
}

The output of running the above class is

1 2 3 4 5 6 7 8 9 10 
1 3 5 7 9 11 13 15 17 19 
2 4 6 8 10 12 14 16 18 20 
3 9 15 21 27 33 39 45 51 57 
6 12 18 24 30 36 42 48 54 60 
6 12 18 24 30 36 42 48 54 60 


Labels: , ,

Sep 23, 2011

Java coding interview questions and answers

Core Java Coding Questions and Answers for beginner to intermediate level

Q1 Q2 Q3 Q4 Q5 - Q8 Q9 Q10 Q11 Q12 - Q14 Q15

These Java coding questions and answers are extracted from the book " Core Java Career Essentials. Good interviewers are more interested in your ability to code rather than knowing the flavor of the month framework.


Q. Can you write an algorithm to swap two variables?
A.


package algorithms;

public class Swap {
    
    public static void main(String[ ] args) {
        int x = 5;
        int y = 6;
        
        //store 'x' in a temp variable
        int temp = x;
        x = y;
        y = temp;
        
        System.out.println("x=" + x + ",y=" + y);
   }
}


Q. Can you write  code to bubble sort { 30, 12, 18, 0, -5, 72, 424 }?
A.

package algorithms;
import java.util.Arrays;

public class BubbleSort {

    public static void main(String[ ] args) {
        Integer[ ] values = { 30, 12, 18, 0, -5, 72, 424 };
        int size = values.length;
        System.out.println("Before:" + Arrays.deepToString(values));

        for (int pass = 0; pass < size - 1; pass++) {
            for (int i = 0; i < size - pass - 1; i++) {
                // swap if i > i+1
                if (values[i] > values[i + 1])
                    swap(values, i, i + 1);
            }
        }

        System.out.println("After:" + Arrays.deepToString(values));
    }

    private static void swap(Integer[ ] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
} 


Q. Is there a more efficient sorting algorithm?
A. Although bubble-sort is one of the simplest sorting algorithms, it's also one of the slowest. It has the O(n^2) time complexity. Faster algorithms include quick-sort and heap-sort. The Arrays.sort( ) method uses the quick-sort algorithm, which on average has O(n * log n) but can go up to O(n^2) in a worst case scenario, and this happens especially with already sorted sequences.

Q. Write a program that will return whichever value is nearest to the value of 100 from two given int numbers?
A. You can firstly write the pseudo code as follows:

  • Compute the difference to 100.
  • Find out the absolute difference as negative numbers are valid.
  • Compare the differences to find out the nearest number to 100.
  • Write test cases for +ve, -ve, equal to, > than and < than values.
package chapter2.com;



public class CloseTo100 {

    

    public static int calculate(int input1, int input2) {

         //compute the difference. Negative values are allowed as well 

        int iput1Diff = Math.abs(100 - input1);

        int iput2Diff = Math.abs(100 - input2);

        

        //compare the difference

        if (iput1Diff < iput2Diff) return input1;
        else if (iput2Diff < iput1Diff) return input2;
        else return input1;          //if tie, just return one
    }
    
    public static void main(String[ ] args) {
        //+ve numbers
        System.out.println("+ve numbers=" + calculate(50,90));
        
        //-ve numbers
        System.out.println("-ve numbers=" + calculate(-50,-90));
        
        //equal numbers
        System.out.println("equal numbers=" + calculate(50,50));
        
        //greater than 100
        System.out.println(">100 numbers=" + calculate(85,105));

        System.out.println("<100 numbers=" + calculate(95,110));
    } 
}



Output:

+ve numbers=90
-ve numbers=-50
equal numbers=50
>100 numbers=105
<100 numbers=95


Q. Can you write a method that reverses a given String?
A.
public class ReverseString {

    

    public static void main(String[ ] args) {

        System.out.println(reverse("big brown fox"));

        System.out.println(reverse(""));       

    }



    public static String reverse(String input) {

        if(input == null || input.length( ) == 0){

            return input;

        }

       

        return new StringBuilder(input).reverse( ).toString( ); 

    }

}


It is always a best practice to reuse the API methods as shown above with the StringBuilder(input).reverse( ) method as it is fast, efficient (uses bitwise operations) and knows how to handle Unicode surrogate pairs, which most other solutions ignore. The above code handles null and empty strings, and a StringBuilder is used as opposed to a thread-safe StringBuffer, as the StringBuilder is locally defined, and local variables are implicitly thread-safe.

Some interviewers might probe you to write other lesser elegant code using either recursion or iterative swapping. Some developers find it very difficult to handle recursion, especially to work out the termination condition. All recursive methods need to have a condition to terminate the recursion.


public class ReverseString2 {
    
    public String reverse(String str) {
        // exit or termination condition
        if ((null == str) || (str.length( )  <= 1)) {
            return str;
        }
        
        // put the first character (i.e. charAt(0)) to the end. String indices are 0 based. 
        // and recurse with 2nd character (i.e. substring(1)) onwards  
        return reverse(str.substring(1)) + str.charAt(0);
    }
}

There are other solutions like
public class ReverseString3 {
    
    public String reverse(String str) {
        // validate
        if ((null == str) || (str.length( )  <= 1)) {
            return str;
        }
        
        char[ ] chars = str.toCharArray( );
        int rhsIdx = chars.length - 1;
        
        //iteratively swap until exit condition lhsIdx < rhsIdx is reached
        for (int lhsIdx = 0; lhsIdx < rhsIdx; lhsIdx++) {
            char temp = chars[lhsIdx];
            chars[lhsIdx] = chars[rhsIdx];
            chars[rhsIdx--] = temp;
        }
        
        return new String(chars);
    }
} 



Or
 
public class ReverseString4 {
     
    public String reverse(String str) {
        // validate
        if ((null == str) || (str.length( )  <= 1)) {
            return str;
        }
         
        
        char[ ] chars = str.toCharArray( );
        int length = chars.length;
        int last = length - 1;
         
        //iteratively swap until reached the middle
        for (int i = 0; i < length/2; i++) {
            char temp = chars[i];
            chars[i] = chars[last - i];
            chars[last - i] = temp;
        }
         
        return new String(chars);
    }
    
    
    public static void main(String[] args) {
      String result = new ReverseString4().reverse("Madam, I'm Adam");
      System.out.println(result);
   }
} 

Relevant must get it right coding questions and answers


Labels: , ,

Java OO Interview Questions and Answers

If you asked me to pick a section that is most popular with the interviewers, this is it. If you don't perform well in Object Oriented (i.e. OO) programming , your success rate in interviews will be very low. Good interviewers will be getting you to analyze or code for a particular scenario. They will be observing your decisions with interfaces and classes, and question your decisions to ascertain your technical skills, analytical skills, and communication skills. You can't memorize your answers. This section requires some level of experience to fully understand.

In this blog, I cover some OO interview questions and answers. If you are interested in more questions and answers, the "Core Java Career Essentials" book has a whole chapter dedicated for OO questions and answers with enough examples to get through your OO interview questions with flying colors.

Q. How do you know that your classes are badly designed?
A.

  • If your application is fragile – when making a change, unexpected parts of the application can break.
  • If your application is rigid – it is hard to change one part of the application without affecting too many other parts.
  • If your application is immobile – it is hard to reuse the code in another application because it cannot be separated.

Overly complex design is as bad as no design at all. Get the granularity of your classes and objects right without overly complicating them. Don't apply too many patterns and principles to a simple problem. Apply them only when they are adequate. Don't anticipate changes in requirements ahead of time. Preparing for future changes can easily lead to overly complex designs. Focus on writing code that is not only easy to understand, but also flexible enough so that it is easy to change if the requirements change.


Q. Can you explain if the following classes are badly designed?
The following snippets design the classes & interfaces for the following scenario. Bob, and Jane work for a restaurant. Bob works as manager and a waiter. Jane works as a waitress. A waiter's behavior is to take customer orders and a manager's behavior is to manage employees.


package badrestaurant;

public interface Person {}


package badrestaurant;

public interface Manager extends Person {
    public void managePeople( );
}

package badrestaurant;

public interface Waiter extends Person {
    public void takeOrders( ); 
}


package badrestaurant;

public class Bob implements Manager, Waiter {

    @Override
    public void managePeople( ) {
        //implementation goes here
    }

    @Override
    public void takeOrders( ) {
        //implementation goes here
    }
}


package badrestaurant;

public class Jane implements Waiter {

    @Override
    public List<string> takeOrders( ) {
        //implementation goes here
    }
}

The Restaurant class uses the above classes as shown below.

package badrestaurant;

public class Restaurant {
    
    public static void main(String[ ] args) {
        
        Bob bob = new Bob( );
        bob.managePeople( );
        bob.takeOrders( );
        
        Jane jane = new Jane( );
        jane.takeOrders( );
    }
}


A. The above classes are badly designed for the reasons described below.

The name should be an attribute, and not a class like Bob or Jane. A good OO design should hide non-essential details through abstraction. If the restaurant employs more persons, you don't want the system to be inflexible and create new classes like Peter, Jason, etc for every new employee.

The above solution's incorrect usage of the interfaces for the job roles like Waiter, Manager, etc will make your classes very rigid and tightly coupled by requiring static structural changes. What if Bob becomes a full-time manager? You will have to remove the interface Waiter from the class Bob. What if Jane becomes a manager? You will have to change the interface Waiter with Manager.

The above drawbacks in the design can be fixed as shown below by asking the right questions. Basically waiter, manager, etc are roles an employee plays. You can abstract it out as shown below.


package goodrestuarant;

public interface Role {
    public String getName( );
    public void perform( );
}


package goodrestuarant;

public class Waiter implements Role {
    
    private String roleName;
    
    public Waiter(String roleName) {
        this.roleName = roleName;
    }

    @Override
    public String getName( ) {
       return this.roleName;
    }

    @Override
    public void perform( ) {
       //implementation goes here
    }
}

package goodrestuarant;

public class Manager implements Role {
    
    private String roleName;   
    
    public Manager(String roleName) {
        this.roleName = roleName;
    }

    @Override
    public String getName( ) {
       return this.roleName;
    }

    @Override
    public void perform( ) {
       //implementation goes here
    }
}



The Employee class defines the employee name as an attribute as opposed to a class. This makes the design flexible as new employees can be added at run time by instantiating new Employee objects with appropriate names. This is the power of abstraction. You don't have to create new classes for each new employee. The roles are declared as a list using aggregation (i.e. containment), so that new roles can be added or existing roles can be removed at run time as the roles of employees change. This makes the design more flexible.

package goodrestuarant;

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

public class Employee {
    
    private String name;
    private List<role> roles = new ArrayList<role>(10);
    
    public Employee(String name){
        this.name = name;
    }

    public String getName( ) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<role> getRoles( ) {
        return roles;
    }

    public void setRoles(List<role> roles) {
        this.roles = roles;
    }
    
    public void addRole(Role role){
        if(role == null){
            throw new IllegalArgumentException("Role cannot be null");
        }
        roles.add(role);
    }
    
    public void removeRole(Role role){
        if(role == null){
            throw new IllegalArgumentException("Role cannot be null");
        }
        roles.remove(role);
    }
}

The following Restaurant class shows how flexible, extensible, and maintainable the above design is.

package goodrestuarant;

import java.util.List;

public class Restaurant {
    
    public static void main(String[ ] args) {
        
        Employee emp1 = new Employee ("Bob");
        Role waiter = new Waiter("waiter");
        Role manager = new Manager("manager");
        
        emp1.addRole(waiter);
        emp1.addRole(manager);
        
        Employee emp2 = new Employee("Jane");
        emp2.addRole(waiter);
        
        List<role> roles = emp1.getRoles( );
        for (Role role : roles) {
            role.perform( );
        }
        
        //you can add more employees or change roles based on 
        //conditions here at runtime. More flexible.   
    }
}



Q. What do you achieve through good class and interface design?
A.

  • Loosely coupled classes, objects, and components enabling your application to easily grow and adapt to changes without being rigid or fragile.
  • Less complex and reusable code that increases maintainability, extendability and testability.

Q. What are the 3 main concepts of OOP?
A. Encapsulation, polymorphism, and inheritance are the 3 main concepts or pillars of an object oriented programming. Abstraction is another important concept that can be applied to both object oriented and non object oriented programming. [Remember: a pie ? abstraction, polymorphism, inheritance, and encapsulation.]


Q. What problem(s) does abstraction and encapsulation solve?
A. Both abstraction and encapsulation solve same problem of complexity in different dimensions. Encapsulation exposes only the required details of an object to the caller by forbidding access to certain members, whereas an abstraction not only hides the implementation details, but also provides a basis for your application to grow and change over a period of time. For example, if you abstract out the make and model of a vehicle as class attributes as opposed to as individual classes like Toyota, ToyotaCamry, ToyotaCorolla, etc, you can easily incorporate new types of cars at runtime by creating a new car object with the relevant make and model as arguments as opposed to having to declare a new set of classes.


Q. How would you go about designing a “farm animals” application where animals like cow, pig, horse, etc move from a barn to pasture, a stable to paddock, etc? The solution should also cater for extension into other types of animals like circus animals, wild animals, etc in the future.


A.

package subclass0;

public abstract class Animal {
    private int id;                                // id is encapsulated

    public Animal(int id) {
        this.id = id;
    }

    public int getId( ) {
        return id;
    }

    public abstract void move(Location location);
}


package subclass0;

public class FarmAnimal extends Animal {

    private Location location = null;                   // location is encapsulated

    public FarmAnimal(int id, Location defaultLocation) {
        super(id);
        validateLocation(defaultLocation);
        this.location = defaultLocation;
    }

    public Location getLocation( ) {
        return location;
    }

    public void move(Location location) {
        validateLocation(location);
        System.out.println("Id=" + getId( ) + " is moving from "
                + this.location + " to " + location);
        this.location = location;
    }

    private void validateLocation(Location location) {
        if (location == null) {
            throw new IllegalArgumentException("location=" + location);
        }
    }
}

package subclass0;

public enum Location  {
    Barn, Pasture, Stable, Cage, PigSty, Paddock, Pen
}



package subclass0;

public class Example {

    public static void main(String[ ] args) {
        Animal pig = new FarmAnimal(1, Location.Barn);
        Animal horse = new FarmAnimal(2, Location.Stable);
        Animal cow = new FarmAnimal(3, Location.Pen);

        pig.move(Location.Paddock);
        horse.move(Location.Pen);
        cow.move(Location.Pasture);
    }
}  


Output:

Id=1 is moving from Barn to Paddock
Id=2 is moving from Stable to Pen
Id=3 is moving from Pen to Pasture

In the above example, the class FarmAnimal is an abstraction used in place of an actual farm animal like horse, pig, cow, etc. In future, you can have WildAnimal, CircusAnimal, etc extending the Animal class to provide an abstraction for wild animals like zebra, giraffe, etc and circus animals like lion, tiger, elephant, etc respectively. An Animal is a further abstraction generalizing FarmAnimal, WildAnimal, and CircusAnimal. The Location is coded as an enumeration for simplicity. The Location itself can be an abstract class or an interface providing an abstraction for OpenLocation, EnclosedLocation, and SecuredLocation further abstracting specific location details like barn, pen, pasture, pigsty, stable, cage, etc. The location details can be represented with attributes like “name”, “type”, etc.

The FarmAnimal class is also well encapsulated by declaring the attribute “location” as private. Hence the “location” variable cannot be directly accessed. Assignment is only allowed through the constructor and move(Location location) method, only after a successful precondition check with the validateLocation(...) method. The validateLocation(...) itself marked private as it is an internal detail that does not have to be exposed to the caller. In practice, the public move(..) method can make use of many other private methods that are hidden from the caller. The caller only needs to know what can be done with an Animal. For example, they can be moved from one location to another. The internal details as to how the animals are moved is not exposed to the caller. These implementation details are specific to FarmAnimal, WildAnimal, and CircusAnimal classes.

The above code does not satisfy the following questions.

1) Why does the Employee class need to be mutable?
2) Why aren't the roles defensive copied?
3) Why would the Employee need to know how to add and remove roles?
4) Waiter and Manager are placed in a collection but don't override hashcode and equals. That will cause the contains method on a List to not behave as expected.
5) You check if the role is null then throw an IllegalArgumentException, that should instead be a NullPointerException.
6) The code that checks for null roles being added is duplicated, thus defeating the DRY principle.


Some of the above questions are answered in How to write immutable Java classes?

Labels: ,