Thursday, July 23, 2015

Favour Composition over Inheritance

There are 2 ways in which a class can inherit properties from another class in JAVA.

Inheritance (is-a) and Composition (has-a).


1) is-a takes place when we use extends keyword in JAVA.

public class Dog extends Animal

Here Dog inherits the properties of Animal. This can only be done at comile time and once the assignment is done cannot be changed at runtime.



2) has-a takes place when we use reference of one class in another class.

public class Dog
{
   Animal animalObj;
  
   Dog (Animal animalObj)
   {
       this.animalObj = animalObj; 
   }
 }

Here Dog gets the properties of Animal and the assignment can be changed at runtime as well.

This feature is famously used as Dependency Injection in Springs framework.



Hence Composotion is a better option than Inheritance to inherit properties from another class.
 

JAVA does not support multiple Inheritance

Why JAVA does not support multiple Inheritance ?

JAVA removes rarely used and confusing features from C++.

Multiple Inheritance gives rise to the common diamond problem.

 
 
In the above figure we have two classes B and C inheriting from A.

Assume that B and C are overriding an inherited method and they provide their own implementation.

Now D inherits from both B and C through multiple inheritance and thus D should inherit that overridden method.

Which overridden method will be used? Will it be from B or C?

This gives rise to ambiguity.

Hence it was felt better to remove this feature from JAVA.

If required this feature can be substituted by alternative design by using interfaces in JAVA.
 

public static void main (String[] args)

public static void main (String[] args)

What does this syntax mean in your JAVA program ?

public - This is the access modifier. Being declared as public means it can be called from anywhere. This makes sense because the JVM is going to call this method.

static - If we don't declare it as static then JVM will have to make an instance (object) to call this method. Static makes it a class level method which does not require any object to be called.

void - We dont have to return anything to the JVM, hence void declaration makes sense.

main - Predefined method name which the JVM tries to call automatically. Java is case-sensitive, Main is different from main.

String[] args - Argument list that can be passed from the command prompt to the JAVA program.

Wednesday, July 22, 2015

Agile Methodology

In Agile you have to keep deploying something to production quite frequently (every month).

This benefits the customer and developers since development becomes transparent and everyone can understand the business requirement better. Best practices can be put to use in upcoming releases by learning from the previous releases.

In order to make this work fully you need a deployment pipeline that ensures that software is built in small production-ready increments.

Nowadays Agile Methodology is best suited for development projects.

Roles defined in Agile Methodology are - Product Owner, Scrum Master and Development Team.
Product Owner owns the product and has a vision regarding that product.

Development team tries to implement that vision.

Scrum Master also plays a very important role by becoming the interface between Product Owner and Development Team. Any Impediment needs to be highlighted by the Scrum Master and if any external help is needed should be made available.

A common practice in agile projects is the short daily team meeting - called a stand-up meeting or scrum. This is supposed to be driven by the Scrum Master. Done well, these help team members coordinate their activities effectively, adding energy to the team. Done badly, they are a boring and empty ritual.

Scrum log is maintained to track the work done by every member of the development team on a daily basis.

Test Driven Development (TDD)

TDD Life Cycle

1) Write the test.

2) Run the test (There is no implementation code, test does not pass).

3) Write just enough implementation code to make the test pass.

4) Run all tests (Tests pass).

5) Refactor.

6) Repeat.


The Resulting code is -

1) Very well tested.

2) Almost self documented.

3) Easy to maintain.

4) Easy to learn by another developer.

5) Safe to refactor.

ClassNotFoundException VS NoClassDefFoundError

ClassNotFoundException : This exception occurs when class loader is not able to find the required class in class path.

NoClassDefFoundError : This exception occurs when at compile time the required classes are present, but at runtime the classes are changed or removed.

ResultSet and ResultSetMetaData

When we dont know what type of value the query will return, we have to use ResultSetMetaData otherwise go for ResultSet.

ResultSetMetaData.getColumnType(int column) returns a int value specifying the column type found in java.sql.Types.

ResultSetMetaData rsmd = rs.getMetaData();

int type = rsmd.getColumnType(i);

if (type == Types.VARCHAR)
    rs.getString(i);
else
    rs.getLong(i);

Platform Independent JAVA

Java is compiled to a byte code by the java compiler, which is the intermediate language between source code and machine code. This byte code is not platform specific and hence can be fed to any platform.

JVM is the interpretor that converts byte code to machine code.

Thus if we have JVM installed on any platform, java applications work perfectly fine.


Source Code (Program.java) -- Compiler --> Byte Code (Program.class)

Byte Code (Program.class) -- JVM --> Machine Code

JIT Compiler

JIT (Just-In-Time) compiler is used to improve performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.

JIT also known as second compiler is present in the JVM.

JIT is enabled by default and operates at runtime.

The JIT analyzes the behaviour of a program while it runs and looks for opportunities to optimize the bytecode.

To disable JIT, Djava.compiler = NONE parameter can be used.

Association, Aggregation and Composition

Association - Indicates the relationship between objects.
                       Example : Computer uses keyboard as input device.
                       An association is used when one object wants another object to perform a service for it.


Aggregation - Is a special case of association, a directional association between objects. When an
                        object "has-a" another object, then you have got an aggregation between them.
                        Example : Room has a table, but the table can exist without the room.


                        public class Room
                        {
                           private Table table;
  
                           void setTable(Table table)
                           {
                              this.table=table;
                            }
                        }


Composition - Is a special case of aggregation. Composition is more restrictive. When there is a
                         composition between two objects, the composed object cannot exist without the outer 
                         object.This restriction is not there in aggregation.
                         Example : Rooms in a house, which cannot exist after the lifetime of the house.


                         public class House
                         {
                           private Room room;
 
                           House(Room roomSpecks)
                          {
                               room = new Room (roomSpecks);
                           }
                         }

How to create an Immutable class in JAVA

1) Make class as Final.
2) Private and Final variables.
3) No setter methods.
4) Values should be set only via public constructor.


public final class Contacts
{
   private final String name;
   private final String mobile;

   public Contacts (String name , String mobile)
   {
      this.name=name;
      this.mobile=mobile;
    } 

    public String getName()
    {
       return name;
    }

    public String getMobile()
    {
        return mobile;
     }
  }


Benefits of immutable classes in JAVA.

1) Immutable classes are by default thread-safe.

2) Immutable objects boost performance of Java application by reducing synchronization in code.

3) Reusability - You can cache immutable objects and reuse them much like string literals and 
    integers.
                You can use static factory methods to provide methods like valueOf(), which can return an existing immutable object from cache, instead of creating a new one.

 

Why wait(), notify() and notifyAll() are defined in Object rather than Thread

Locks are acquired on the object (monitor). One thread does not know which other thread has acquired the lock. it only knows that the monitor has been acquired and thus it has to wait.


In the above banking example, there are many ways (channels) to access any bank account.

If in a joint-account one person tries debit and other online, the person who comes first gets the money while the other has to wait.

In this example, the lock is acquired on the account and not on the channel.

Hence, wait(), notify() and notifyAll() are defined in Object rather than Thread.

Tuesday, July 21, 2015

Hybris - Some Information

Founded in 1997 in switzerland, hybris is one of the world's most popular large scale E-Commerce platforms.

Hybris is a single technology stack solution that provides customizable eCommerce solutions along with ->
1) Product Content Management
2) Web Content Management
3) Order Management

Hybris is built on Apache and Spring source components.

Hybris is compatible with third party applications.

Its model-driven and parallelized.

New features can be built into hybris with minimal efforts.

Availability of plugins for Endeca and Adobe.

Writing SQL queries is not overtly flexible, but the Full Text Search (FTS) technique allows examine all words in each document in your database rather that specifying the column names in the database table. Hybris ships with the FTS module based on the fast search engine Apache SOLR.

To work with hybris, you need to have good knowledge in Core JAVA, Springs and Hibernate.

80% of the code needed for eCommerce websites (Add to cart, Payment etc) comes in-built with hybris, you just have to mould it as per the customer needs.

Hybris is now owned by SAP.
 

Different ways to create an object in JAVA

There are 4 different ways to create an object in JAVA.


1) Using new keyword - This is the most common way to create an object in JAVA.
     Almost 99% of objects are created in this way.

     MyObject obj = new MyObject();


2) Using Class.forName() - Also known as dynamic/runtime object creation.

     MyObject obj = (MyObject) Class.forName("MyObject").newInstance();


3) Using clone() - Create a copy of an existing object.

     MyObject anotherObj = new MyObject();
     MyObject obj = anotherObj.clone();


4) Using object Deserialization - Create object from its serialized form.

    ObjectInputStream inStream = new  ObjectInputStream(aInputStream);
    MyObject obj = (MyObject) inStream.readObject();

 

Reflection in JAVA

Reflection is a very useful approach to deal with the Java class at runtime, it can be used to load the Java class and call any of its methods.

Sample.java

public class Sample
{
  public void display1()
  {
    System.out.println("Inside 1");
  }
 
  public void display2()
  {
    System.out.println("Inside 2");
  }
 
  public void display3()
  {
    System.out.println("Inside 3");
   }
}

Now we can load this class(Sample) and call each of its methods at runtime.


ReflectionTest.java

public class ReflectionTest
{
  public static void main(String[] args)
  {
     Class cls=Class.forName("Sample");
     Object obj=cls.newInstance();

     Method method = cls.getDeclaredMethod("display1");
     method.invoke(obj);

     Method method = cls.getDeclaredMethod("display2");
     method.invoke(obj);

     Method method = cls.getDeclaredMethod("display3");
     method.invoke(obj);
  }


Springs framework also works on the principle of Reflection :)



 

JDBC Driver Types

The various types of JDBC drivers are based on the way it is implemented by various developers/coders.


1) Type 1 (JDBC-ODBC Bridge)

     JAVA -> Driver -> Microsoft Driver -> DB

2) Type 2 (Part nature)

     JAVA -> Driver -> DB Client -> DB

3) Type 3

     JAVA -> Driver -> Middleware -> DB

4) Type 4 (Thin)

    JAVA -> Java Driver -> DB

Synchronous communication between JAVA and HYBRIS

Contact me on maluskarhrishikesh@yahoo.com to know the details.

I will send you the documents which i have prepared.
Home