java beans = default constructor + getters + setters

You want to model a person and in your model each person must have a name and surname.
In java beans convention you would have to
1) create a person and then
2) populate it with name and surname.

But in between 1 and 2 you have existing object that has inconsistent state, its a person without a name. in this trivial example it looks as a exaggeration but if you have a complex system it starts to matter.

Let’s see simple example

class Person {
   private String firstName;
   private String lastName;
   public String getFirstName() {return firstName;}
   public void setFirstName(String firstName) {this.firstName = firstName;}
   public String getLastName() {return lastName;}
   public void setLastName(String lastName) {this.lastName = lastName;}
}

The code creates instance of Person an initiates it:

Person president = new Person();
p.setFirstName("George");
p.setLastName("Bush");

From the above line of code the below can be incurred

  1. This means that the object is in constant state when all 3 lines are completed and in not consistent state before that.
  2. The object is indeed mutable: values that it calls may be changed by invoking of setter.

Our class Person is not thread-safe and therefore we cannot use it directly in multi threaded environment without thinking about syncrhonization.

Here is an example. Several years ago Barak Obama became the President of the US. How can we express this in code?

p.setFirstName("Barak");
p.setLastName("Obama");

In mutlti threaded environment the president object is in wrong state when when setFristName() had already completed and setLastName() has not called yet because the object contains “Barak Bush” that is obviously wrong.

What is the solution? Let’s make `Person immutable:

class Person {
   private final String firstName;
   private final String lastName;
   Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
   }

   public String getFirstName() {return firstName;}
   public String getLastName() {return lastName;}
}

As you can see there is not way to change either first or last name stored in object. The fields a final and do not have setters. So, our example looks like:

Person president = new Person("George", "Bush"); 
// elections..... 
president = new Person("Barak", "Obama");

Since Person is immutable we cannot re-use the old instance of Person and change its attribute. We have to create the new instance instead. If president is volatile reference assignment is atomic and therefore the code is thread safe.

Disadvantage
The problem of constructors is that they are not flexible. Our example has only 2 parameters. But think about real world when class Person has probably 20 or more field. In this case creating of such object is pretty verbose.

Moreover some fields can be optional. In this case you will probably want to create several overloaded constructors with different number of parameters. To avoid dupplicate assignemnt code it is common technique to use so called telescopic constructors

Few FAQ’s
Is using JavaBeans for data storage a bad practice and should be avoided, or is it perfectly safe?
No, is not a bad practice. Is not perfectly safe either. Depends on the situation.

The problem with mutable objects ( not with JavaBeans per se ) is using different threads to access them.

You have to synchronize the access to avoid one thread modify the object while other is accessing it.

Immutable objects doesn’t have this problem, because, .. well they can’t change, and thus, you don’t have to synchronize anything.

To make sure an object is immutable you have to declare your attributes as final.

class MyBean  {
    private final int i;
}

If you want to assign a reasonable value to MyBean.i you have to specify it in the constructor:

public MyBean( int i ) {
     this.i = i;
 }

Since the variable is final, you can’t use a setter. You can just provide a getter.

This is perfectly thread-safe and the best is, you don’t have to synchronize the access, because if two threads try to get the value of i they both will always see the value that was assigned on instantiation, you don’t have to synchronize anything.

Is not bad practice or good practice. Must of us have to work with a single thread, even in multithread environments like servlets.

How to set and change values if Immutable Objects
The Solution is to create immutable beans, and still provide a
bunch of setters is using Builders like

Setting Value

Employee e = new EmployeeBuilder()
                  .setName("Oscar")
                  .setLastName("Reyes")
                  .setAge(0x1F)
                  .setEmployeeId("123forme")
                  .build(); 

Which looks pretty similar to the regular setXyz used in regular beans with the benefit of using immutable data.

If you need to change one value, you can use a class method

Employee e = Employee.withName( e, "Mr. Oscar");

Which takes the existing object, and copy all the values, and set’s a new one….

public static EmployeeWithName( Employee e , String newName ){
      return new Employee( newName, e.lastName, e.age, e.employeeId );
}

But again, in a single thread model is perfectly safe to use getters/setters.

What is Static Factory Method

  1. static factory method pattern is a way to encapsulate object creation.This prevents unnecessary object creation through constructors
  2. The constructors are marked private, so they cannot be called except from inside the class, and the factory method is marked as static so that it can be called without first having an object.

Examples

  1. Limit the No of Instances to be Created – If the construction and destruction are expensive processes it might make more sense to build them once and recycle them. The factory method can return an existing, unused instantiated object if it has one, or construct one if the object count is below some lower threshold, or throw an exception or return null if it’s above the upper threshold.
  2. We can provide a meaningful name for our constructors

RandomIntGenerator.java

public class RandomIntGenerator {
  private final int min;
  private final int max;

  private RandomIntGenerator(int min, int max) {
    this.min = min;
    this.max = max;
  }

  public static RandomIntGenerator between(int max, int min) {
    return new RandomIntGenerator(min, max);
  }

  public static RandomIntGenerator biggerThan(int min) {
    return new RandomIntGenerator(min, Integer.MAX_VALUE);
  }

  public static RandomIntGenerator smallerThan(int max) {
    return new RandomIntGenerator(Integer.MIN_VALUE, max);
  }

  public int next() {...}
}
Foo x = new Foo() 

With this pattern, you would instead call the factory method:

Foo x = Foo.create()

The constructors are marked private, so they cannot be called except from inside the class, and the factory method is marked as static so that it can be called without first having an object.

When to use Static Factory Method
1.One is that the factory can choose from many subclasses (or implementers of an interface) and return that. This way the caller can specify the behavior desired via parameters, without having to know or understand a potentially complex class hierarchy.

2.Controlling access to a limited resource such as connections. This a way to implement pools of reusable objects – instead of building, using, and tearing down an object, if the construction and destruction are expensive processes it might make more sense to build them once and recycle them. The factory method can return an existing, unused instantiated object if it has one, or construct one if the object count is below some lower threshold, or throw an exception or return null if it’s above the upper threshold.

3.Alternate to constructor overloading.

Example1 – Returning Object of many Subclass as per parameter

class Employee {
   private int empType;
   static final int ENGINEER = 0;
   static final int SALESMAN = 1;
   static final int MANAGER = 2;

   Employee (int type) {
       empType = type;
   }

I want to make subclasses of Employee to correspond to the type codes. So I need to create a factory method

static Employee create(int type) {
      return new Employee(type);
 }

I then change all callers of the constructor to use this new method and make the constructor private

client code...
   Employee eng = Employee.create(Employee.ENGINEER);

 class Employee...
   private Employee (int type) {
      empType = type;
}

So far I dont have any advantage from the code.The advantage come when I code the create method to return instances of different subclass of Employee.

static Employee create(int type) {
       switch (type) {
           case ENGINEER:
              return new Engineer();
           case SALESMAN:
              return new Salesman();
           case MANAGER:
              return new Manager();
           default:
              throw new IllegalArgumentException("Incorrect type code value");
       }
   }  

If you want to avoid making changes in the switch when ever new classes are added the above code can be replaced as below

static Employee create (String name) {
       try {
           return (Employee) Class.forName(name).newInstance();
       } catch (Exception e) {
           throw new IllegalArgumentException ("Unable to instantiate" + name);
       }
}

Now the calling class should be

 Employee.create("Engineer")

Example2 – Controlling access to Resources

public class DbConnection
{
   private static final int MAX_CONNS = 100;
   private static int totalConnections = 0;

   private static Set<DbConnection> availableConnections = new HashSet<DbConnection>();

   private DbConnection()
   {
     // ...
     totalConnections++;
   }

   public static DbConnection getDbConnection()
   {
     if(totalConnections < MAX_CONNS)
     {
       return new DbConnection();
     }

     else if(availableConnections.size() > 0)
     {
         DbConnection dbc = availableConnections.iterator().next();
         availableConnections.remove(dbc);
         return dbc;
     }

     else {
       throw new NoDbConnections();
     }
   }

   public static void returnDbConnection(DbConnection dbc)
   {
     availableConnections.add(dbc);
     //...
   }
}
  1. The maximum connection allowed in the above case is 100
  2. Incase the no of connection created is above 100, Old connection is sent back in else part of code

Example3 – Alternate to Constructor Overloading
Link

There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes and String class is immutable

Immutable objects have a number of properties that make working with them easier, including relaxed synchronization requirements and the freedom to share and cache object references without concern for data corruption.

An immutable object is one whose externally visible state cannot change after it is instantiated. The String, Integer, and BigDecimal classes in the Java class library are examples of immutable objects — they represent a single value that cannot change over the lifetime of the object.

Immutable classes generally make the best map keys.

Potential problem with a mutable Date object

  Date d = new Date();
  Scheduler.scheduleTask(task1, d);
  d.setTime(d.getTime() + ONE_DAY);
  scheduler.scheduleTask(task2, d);

Since Date is mutable, the scheduleTask method must be careful to defensively copy the date parameter into its internal data structure. Otherwise, task1 and task2 might both execute tomorrow, which is not what was desired.

Classic Value Objects
Strings and integers and are often thought of as values. Therefore its not surprising to find that String class and the Integer wrapper class (as well as the other wrapper classes) are immutable in Java. A color is usually thought of as a value, thus the immutable Color class.

Playing Cards

Ever write a playing card program? I did. I could have represented a playing card as a mutable object with a mutable suit and rank. A draw-poker hand could be 5 fixed instances where replacing the 5th card in my hand would mean mutating the 5th playing card instance into a new card by changing its suit.

However, I tend to think of a playing card as an immutable object that has a fixed unchanging suit and rank once created. My draw poker hand would be 5 instances and replacing a card in my hand would involve discarding one of those instance and adding a new random instance to my hand.

Simple Immutable Class Code

public final class Employee
   {  
    final String pancardNumber;  
      
    public Employee(String pancardNumber){  
    this.pancardNumber=pancardNumber;  
    }  
      
    public String getPancardNumber(){  
    return pancardNumber;  
  }  
 }  
  1. The instance variable of the class is final i.e. we cannot change the value of it after creating an object.
  2. The class is final so we cannot create the subclass.
  3. There is no setter methods i.e. we have no option to change the value of the instance variable.

Scenario

Event – Parent Event
Sub-Event – Child Event

1.The Events contains multiple sub events.
2.When there is Parent event, there should be No sub event of that Parent event in that same period
3.There can me more than one sub event of the same Parent event in the same period.There can be overlapping sub event.

 SELECT COUNT(ParentEventId)    
    FROM Events
   WHERE lower(status) = 'open'
     AND ParentEventId = p_parent_id
      AND (ChildEvent is null or p_child_event IS NULL OR
          ChildEvent = NVL(p_child_event, child_event))
     AND (p_startdate BETWEEN StartDate AND
          EndDate OR
          p_admin_enddate BETWEEN StartDate AND
          EndDate OR
          (p_startdate <= StartDate AND
          p_enddate >= EndDate));

How to check for overlapping events in a period

Case1: No Event between Period Start Date and Period End Date
Case2: No Event which subsets another event Period Start Date and Period End Date
Case3: No Event which starts before period start date and ends in between some other events end date
Case4: No Event which starts after some other event period start date and ends after events end date

oVERLAPPING eVENT

Where Clause:

SELECT count(event) 
  FROM tblEvent
 WHERE (new_event_start_date BETWEEN old_event_start_date and old_event_end_date OR
        new_event_end_date BETWEEN old_event_start_date and old_event_end_date) OR 
        new_event_start_date <= old_event_start_date OR new_event_end_date >= old_event_start_date

Case1,2,3:

     new_event_start_date BETWEEN old_event_start_date and old_event_end_date OR
     new_event_end_date BETWEEN old_event_start_date and old_event_end_date

Case4:

new_event_start_date <= old_event_start_date OR new_event_end_date >= old_event_start_date

Simple Search based on Three Parameters

The Search should happen even when one element of the form is not Empty.


isParamNotEmpty = false;

if(param1.isNotEmpty())
{
  .
  .
  Other Coding Lines
  .
  isParamNotEmpty = true;
}

if(param2.isNotEmpty())
{
  .
  isParamNotEmpty = true;
}

if(param3.isNotEmpty())
{
  .
  . 
  isParamNotEmpty = true;
}

if(isParamNotEmpty)
{ 
  doSearch(); 
}