Monday, August 26, 2013

JAVA: OOPS Concepts - Classes and Objects, Encapsulation, Inheritance, Polymorphism

OOPS Concepts

What is OOPS?


Object Oriented Programming Concepts (OOPS) is a programming paradigm using "objects" to design applications. In yet simpler terms, it is like building a group of co-operating objects that accomplish desired tasks.


Classes and Objects:


Object is any real world entity that participates in some activity within a system. 

When you design a class, think about the objects that
will be created from that class type. Think about:
􀀀 Things the object knows
􀀀 Things the object does

For example, within Banking system, Customer is an object which participates in day to day activity. Since Object Oriented Programming implements the behavior and interaction of real world objects, real world objects should be used as an object in Programming.

Customer in Banking system may have first name, last name, address and based on activity and account balance you can consider it as Regular customer or Premium Customer, etc. 
Bank may have more than one customer and each customer has unique account number. Similar way, in programming when you create customer objects, each will have its own account number and properties like first name, last name, address etc.

Also a customer may do some things like he may withdraw amount, deposit amount, apply for loan, etc. 


Things that object knows about itself are called instance variables.

Things that objects does are called methods.

Thus, to summarize, objects have instance variables and methods, but those are also a part of the class.

NOTE:
So class is not an object, but is used to construct an object. Thus, a class is a blue print for an object. It tells the JVM how to create the object of that particular type.


Making an Object:

public class Customer 
{
 /**
  * Creating instance variables. What object knows.
  */
 int accNo;
 String firstName;
 String lastName;
 String address;
 String email;
 double mobileNo;
 
 /**
  * Creating methods. What object does.
  */
 void withdrawAmt()
 {
  System.out.println("Withdrawing Amount");
 }
 
 void depositAmt()
 {
  System.out.println("Depositing Amount");
 }
 
 
 /**
  * Main Method to test our Customer class
  */
 
 public static void main(String args[])
 {
  Customer customer =new Customer();
  
  /**
   *  Using the dot operator we set the account Number
   */
  customer.accNo=578598;
  
  /*
   * Calling withdrawAmt() method of Customer
   */
  customer.withdrawAmt();
 }
}

**NOTE**:

Often I have seen confusion with people as to what does the below statement exactly is and does:

Customer customer =new Customer();

Stick these few points:

1. There is nothing like object variable.

2. There is only a object reference variable (In our case it is customer).
    An object reference variable holds a way (address) to access that object. Consider it         like a pointer to that object.
   
3. Think of the customer reference variable as a remote control to access the instance           variables and methods of the Customer object by using the Dot (.) operator.

Encapsulation:


We saw above how we can access instance variables and methods of a class. 

But, in doing so we missed out a serious flaw that we made by ignoring that anyone could easily access our data as it was easily accessible to the world. Leaving our data exposed is a big threat.

customer.accno=578599;


Think about the idea that some one can get to use our remote control and change our dataThis leads to serious security concerns.

So how exactly to protect and hide our data is what ENCAPSULATION provides. 

NOTE:

This is done by private modifiers i.e. declare your instance variables as private and allow the access to these variables through public setter and getter methods. 

It is a thumb rule that the instance variables should be private for achieving Encapsulation.


public class Customer {

 /**
  * Encapsulating our instance variables by making them private.
  */
 private int accNo;
 private String firstName;
 private String lastName;
 private String address;
 private int amount;
 private double mobileNo;

 /**
  * Creating public setter and getters for accessing the instance variable
  * 
  */

 public int getAccNo() {
  return accNo;
 }

 public void setAccNo(int accNo) {
  this.accNo = accNo;
 }

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

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }

 public int getAmount() {
  return amount;
 }

 public void setAmount(int amount) {
  this.amount = amount;
 }

 public double getMobileNo() {
  return mobileNo;
 }

 public void setMobileNo(double mobileNo) {
  this.mobileNo = mobileNo;
 }

 void withdrawAmt() {
  System.out.println("Withdrawing Amount");
 }

 void depositAmt() {
  System.out.println("Depositing Amount");
 }

 /**
  * Main Method to test our Customer class
  */

 public static void main(String args[]) {
  Customer customer = new Customer();

  int verifyAccNo = 578598;

  /**
   * Using the dot operator we set the account Number
   */
  customer.setAccNo(578598);

  if (customer.getAccNo() == verifyAccNo) {
   /**
    * Calling withdrawAmt() method of Customer
    */
   customer.setAmount(5000);
   customer.withdrawAmt();
  }
 }
}


Inheritance: 

Consider a scenario where you want to write code for some similar purpose. Take shapes as example. The figure below explains Inheritance:






If you observe the above figure, we had 4 shapes, all of which did similar tasks of rotating and playing sound. If you code the above scenario you would have to write same methods in all 4 classes with very similar code. This is not a good programming practice. 

NOTE:

To remove the above disadvantage of code duplication and facilitate the design to keep the similar objects performing similar tasks, we have Inheritance.


When you design with Inheritance, you put common code in a class and then say to the more specific classes that the common (more abstract class) is their superclass. We say the subclass inherits (extends in terms of JAVA) from the superclass.

When we say subclass inherits from superclass, subclass not only inherits the methods but also the instance variables of the superclass.

If you again observe the figure the Amoeba Class, has rotate() which performs some specific task which is different from rest of the subclasses (This you can understand as amoeba would have some different way of rotating as it doesnot have a fixed shape as other other shapes), so some different logic is required for amoeba to rotate. 

Thus, with Inheritance if some subclass performs more specifc task then we can do this by overriding the super class (also known as the base class) method.  We say that amoeba overrides the inherited rotate() method.


public class Shape {
  
 private int width;
 private int height;
 private int area;
 
 
 public int getWidth() {
  return width;
 }
 public void setWidth(int width) {
  this.width = width;
 }
 public int getHeight() {
  return height;
 }
 public void setHeight(int height) {
  this.height = height;
 }
 public int getArea() {
  return area;
 }
 public void setArea(int area) {
  this.area = area;
 }
 
 public void rotate(){
  
  System.out.println("Shape rotated");
 }
 
}

/**
 * For indicating that a subclass inherits from the superclass we use extends keyword. 
 *
 */

class Square extends Shape{
 
 /**
  * Square class inherits all the instance variables and methods of the Shape Class.
  */
 
}


class Circle extends Shape{
 
 /**
  * Circle class also inherits all the instance variables and methods of the Shape Class.
  * But it has its own specific instance variable "radius", and an additional method, calcCircumference().
  */
  int radius;
  
  public void calcCircumference(){
   
   System.out.println("Circumference calculated.");
  }
}


class Triangle extends Shape{
 
 /**
  * Triangle class inherits all the instance variables and methods of the Shape Class.
  */
 
}


class Amoeba extends Shape{
 
 /**
  * Amoeba class inherits all the instance variables and methods of the Shape Class.
  * But it also overrides the inherited rotate() method to perform some specific task
  * which doesnot hold for other shapes.
  */
 
 public void rotate(){
  System.out.println("This is amoeba specific rotate().");
 }
 
}

Polymorphism:

Polymorphism means one thing having many forms.

The above statement seems quite simple, now lets analyse this in more detail w.r.t to JAVA.

Consider the previously used example of shapes, you can create an object for a particular shape as follows:



If you see the above figure, this is the normal scenario of object creation.

Now what polymorphism provide is you can have something like below:


i.e. with polymorphism the reference type can be the super class of the actual object type.

How does this help:

You can make polymorphic arrays.


        Shape[] shapes = new Shape[4];

        shapes[0] = new Square();

        shapes[1] = new Circle();

        shapes[2] = new Triangle();

        shapes[3] = new Amoeba();
        
        for(int i=0; i<shapes.length; i++){
         
         shapes[i].rotate();
        }
                           

The advantage is when i=0, square's rotate() method gets executed likewise for i=1, circle's rotate() method gets executed and so on. Now even if you add a new shape you do this with minimal impact on the code.

NOTE: The JVM on runtime decides what method to execute based on the object passed             to the shape, as the decision to execute which object's method is taken at                       runtime, this type of polymorphism is called as runtime polymorphism also called               method overriding as we saw in case of rotate() method of amoeba.


Another kind of polymorphism is Compile Time Polymorphism also called as Method Overloading :

This has nothing to do with Inheritance. This is just so that different methods of the same class has same method names, but the argument passed to each method is different.

public class Shape {
 
 
 static int  calculateArea(int width, int height){
  
  int area=width*height;
  
  return area;
  
 }
 
 static double calculateArea(int width, double height){
  
  double area=0.5*width*height;
  
  System.out.println("Area of triangle is" + area ); 
  
  return area;
  
 }
 
 static double calculateArea(int radius){
  
  double area=Math.PI * Math.pow(radius, 2);
  
  System.out.println("Area of circle is" + area ); 
  
  return area;
  
 }
 
 public static void main(String r[]){
  
  double height=15;
  int width=10;
  int ht=5;
  int radius=7;
  
  /**
   * Now when we pass ht and width to calculate area i.e. both int                  *  types
   * we get area of rectangle
   */
  
  int areaSquare=calculateArea(width,ht);
  System.out.println("Area of rectange is " + areaSquare );
  
  /**
   * Similarly when we pass height and width to calculate area i.e.                 * 1 int type
   * and 1 double type we get area of triangle
   */
  
  double areaTriangle=calculateArea(width,height);
  System.out.println("Area of triangle is " + areaTriangle );
  
  /**
   * Similarly for area of circle
   */
  
  double areaCircle=calculateArea(radius);
  System.out.println("Area of circle is " + areaCircle );
  
  
 }
}


**More OOPS concepts coming Soon


Conclusion:


Please send in your suggestions in the comment section about the quality of the post. You can also request for any particular topic which you want me to put in. Your feedback is highly valuable. 

Happy Programming!!

Friday, August 16, 2013

JAVA Spring Tutorial-DI (Dependency Injection) and AOP (Aspect Oriented Programming)

Spring Basic Concepts


This post talks about JAVA Spring Dependency Injection and AOP. Its a small Spring Tutorial to learn the basic Spring Concepts.

What is Spring?

Spring is an open source framework. Spring was created to address the complexity of enterprise application development, and makes it possible to use plain-vanilla JavaBeans to achieve things that were previously only possible with EJBs. But Spring’s usefulness isn’t limited to server-side development. Any Java application can benefit from Spring in terms of simplicity, testability, and loose coupling.

Spring simplifies Java development. That’s a bold statement! Many JAVA frameworks claim and also do simplify the development. But how does Spring is doing it?

Spring does it by using four key strategies:

 Lightweight and minimally invasive development with plain old Java objects
   (POJOs)
 Loose coupling through dependency injection(DI) and interface orientation
 Declarative programming through aspects and common conventions (AOP)

Boilerplate reduction through aspects and templates

Let us take a closer look at each of the above strategies:



1. Unleashing the power of POJOs:


Some frameworks compelled you to extend, implement or even sometimes write methods in your program which are unnecessary from a programmers point of view. For Example in EJB 2.0 users need to include ejbActivate(), ejbPassivate() methods necessarily. 

Spring avoids (as much as possible) littering your application code with its API.

Spring almost never forces you to implement a Spring-specific interface or extend a

Spring-specific class. Instead, the classes in a Spring-based application often have no

indication that they’re being used by Spring. At worst, a class may be annotated with

one of Spring’s annotations, but is otherwise a POJO.


To illustrate, consider a small example HelloWorldBean class shown below:

package com.habuma.spring;
public classHelloWorldBean
{
   public StringsayHello()
   {
       return"HelloWorld";
   }
}

Isnt this as simple as core JAVA, without the code being littered by any lifecycle methods, no implements, no extends and moreover no imports from Spring. 

NOTE: 
Despite their simple form, POJOs can be powerful. One of the ways Spring empowers POJOs is by assembling them using dependency injection. Let’s see how dependency injection can help keep application objects decoupled from each other.


2. Dependency Injection (DI): 


Any nontrivial application (pretty much anything more complex than a Hello World example) is made up of two or more classes that collaborate with each other to perform some business logic. 

Traditionally, each object is responsible for obtaining its own references to the objects it collaborates with (its dependencies). This can lead to highly coupled and hard-to-test code. For more on what is coupling refer here.


Coupling is a two-headed beast. On one hand, tightly coupled code is difficult to test, difficult to reuse, difficult to understand, and typically exhibits “whack-a-mole” bug behavior (fixing one bug results in the creation of one or more new bugs). On the other hand, a certain amount of coupling is necessary—completely uncoupled code doesn’t do anything. In order to do anything useful, classes need to know about each other somehow. Coupling is necessary, but should be carefully managed.

NOTE:
With Dependency Injection, on the other hand, objects are given their dependencies at creation time by some third party that coordinates each object in the system. **Objects aren’t expected to create or obtain their dependencies—dependencies are injected into the objects that need them**.

**That’s the key benefit of DI—loose coupling**. If an object only knows about its dependencies by their interface (not by their implementation or how they’re instantiated), then the dependency can be swapped out with a different implementation without the depending object knowing the difference.





DI follows the behaviour as shown in the figure. As opposed to Foo having required to acquire its dependencies on its own, DI involves giving of the dependencies to Foo.

All of this is done by simple configuration file used in Spring called application context.

Example:

Consider a BraveKnight who performs some quest:

public classBraveKnightimplementsKnight{
privateQuestquest;
public BraveKnight(Questquest)
{
    this.quest=quest;
}
public voidembarkOnQuest()throwsQuestException
{
    quest.embark();
}
}

BraveKnight doesn’t create his ownquest. Instead, he’s given a quest at construction time as a constructor argument. This is a type of dependency injection known as constructor injection. What’s more, the quest he’s given is typed as Quest, an interface that all quests
implement. So BraveKnight could embark on a RescueDamselQuest, a SlayDragonQuest, a MakeRoundTableRounderQuest, or any other Quest implementation he’s given.

The point here is that BraveKnight isn’t coupled to any specific implementation of
Quest. It doesn’t matter to him what kind of quest he’s asked to embark upon, so long
as it implements the Quest interface. That’s the key benefit of DI—loose coupling. If
an object only knows about its dependencies by their interface (not by their implemen-
tation or how they’re instantiated), then the dependency can be swapped out with a
different implementation without the depending object knowing the difference.

INJECTING A QUEST INTO A KNIGHT

Now that your BraveKnight class is written in such a way that you can give him any quest you want, how can you specify which Quest to give him? 

The act of creating associations between application components is commonly referred to as wiring. In Spring, there are many ways to wire components together, but a common
approach has always been via XML. The following listing shows a simple Spring config-
uration file, knights.xml, that gives a BraveKnight a SlayDragonQuest.


<?xml version="1.0"encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="knight"class="com.springinaction.knights.BraveKnight">
<constructor-argref="quest"/>
</bean>
<bean id="quest"
class="com.springinaction.knights.SlayDragonQuest"/>
</beans>

As we see a "quest"  is injected to a knight. Now if you want to give a knight some other quest, then you just need to add on more bean in the above config file without affecting your JAVA code implementation.


In a Spring application, an application context loads bean definitions and wires them together. The Spring application context is fully responsible for the creation of and wiring of the objects that make up the application. Spring comes with several implementations of its application context, each primarily differing only in how they load their configuration.


3. Aspect Oriented Programming (AOP):


AOP is a good example of Declarative programming which I covered in my earlier post.

Although DI makes it possible to tie software components together loosely, aspect oriented programming enables you to capture functionality that’s used throughout your application in reusable components.

AOP is often defined as a technique that promotes separation of concerns within a software system. Systems are composed of several components, each responsible for a specific piece of functionality. Often these components also carry additional responsibility beyond their core functionality. System services such as logging, transaction management, and security often find their way into components whose core responsibility is something else. These system services are commonly referred to as cross-cutting concerns because they tend to cut across multiple components in a system.

AOP makes it possible to modularize these services and then apply them declaratively to the components that they should affect. This results in components that are more cohesive (For more on cohesion see here) and that focus on their own specific concerns, completely ignorant of any system services that may be involved. In short, aspects ensure that POJOs remain plain.

To illustrate this refer images below:

Without AOP:

As you can see logging, transaction and security related code is often scattered system wide across modules which makes the code less modular.

With AOP:


With AOP, common concerns like Logging, Transaction and Security forms a blanket to the components that they impact. 

This is a powerful concept, as it keeps the cross cutting concerns from littering the application’s core business logic.

Consider in our Knight example that a Knight has a Minstrel which sings on the successful completion of a quest by the Knight.

package com.springinaction.knights;
public classMinstrel{
public voidsingBeforeQuest()
{
    System.out.println("Falala;Theknightissobrave!");
}
public voidsingAfterQuest()
{
    System.out.println("Tee heehe;Thebraveknightdidembarkonaquest!");
}
}

Now without AOP:


package com.springinaction.knights;
public classBraveKnightimplementsKnight{
privateQuestquest;
privateMinstrelminstrel;
public BraveKnight(Questquest,Minstrelminstrel)
{
    this.quest=quest;
    this.minstrel=minstrel;
}
public voidembarkOnQuest()throwsQuestException
{
    minstrel.singBeforeQuest();
    quest.embark();
    minstrel.singAfterQuest();
}
}

The above code should work correctly. But if you note, the Knight each time has to remind Minstrel to do its job. Now is it Knight's business to remind Minstrel each time. According to me she itself should perorm the task that is assigned to her.

Now with AOP we declare Minstrel as an Aspect:


<?xml version="1.0"encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<bean id="knight"class="com.springinaction.knights.BraveKnight">
<constructor-argref="quest"/>
</bean>

<bean id="quest"
class="com.springinaction.knights.SlayDragonQuest"/>

<bean id="minstrel"
class="com.springinaction.knights.Minstrel"/>

<aop:config>
<aop:aspectref="minstrel">
<aop:pointcutid="embark" expression="execution(* *.embarkOnQuest(..))"/>
<aop:beforepointcut-ref="embark" method="singBeforeQuest"/>
<aop:afterpointcut-ref="embark" method="singAfterQuest"/>
</aop:aspect>
</aop:config>

</beans>


Two important points to NOTE:

First, Minstrel is still a POJO—nothing about it indicates that it’s to be used as an aspect. Instead Minstrel became an aspect when we declared it as such in the Spring context.

Second, and most important, Minstrel can be applied to the BraveKnight without the BraveKnight needing to explicitly call on it

In fact, BraveKnight remains completely unaware of the Minstrel’s existence. I should also point out that although you used some Spring magic to turn Minstrel into an aspect, it was declared as a Spring <bean> first. The point here is that you can do anything with Spring aspects that you can do with other Spring beans, such as injecting them with dependencies.


4. Eliminating Boilerplate Code:



Boilerplate code—the code that you often have to write over and over again to accomplish common and otherwise simple tasks.

Spring seeks to eliminate boilerplate code by encapsulating it in templates.

For Example: The JDBC code is written over and over again whenever you want to execute any db query.

To avoid this in Spring there is template for JDBC named jdbcTemplate.

Conclusion:

As listed above Spring simplifies much of your tasks and lets developers to concentrate more on the core business logic.

For more on the above topics with more examples refer Spring In Action 3rd Edition by Craig Walls.

Give in your feedbacks and queries in the comments section below.

Tuesday, August 13, 2013

JAVA:Declarative Programming, CallBack Methods, Cohesion and Coupling

General Programming Terms

About: 

There are many general programming terms that we come across while using programming languages. Today I would explain such terms w.r.t to java programming language with examples.

Description:


1. Declarative Programming:

There are two approaches to programming called 
a) Imperative programming and 
b) Declarative programming

Imperative programming gives a list of instructions to execute in a particular order -- Java program that counts the number of words in a text file is an example of the imperative approach. 

Declarative programming describes a set of conditions, and lets the system figure out how to fulfill them. The SQL statement SELECT COUNT(*) FROM XYZ is an example for the declarative approach. 

In other words, "specifying how" describes imperative programming and "specifying what is to be done, not how" describes declarative programming.

In JAVA context we have examples of Declarative programming in EJBs and Annotations.

What makes EJB components special is the declarative programming model through which we can specify the services such as security, persistence, transaction etc., that the container should provide. An EJB only implements the business logic; the services are associated through a deployment descriptor, which essentially acts as metadata for the EJB. At runtime, the container uses the metadata specified in the deployment descriptor to provide the services. The deployment descriptor is an XML file, not part of the Java classes that make up the EJBs. 

To add even more simplicity and ease to this after JDK1.5 we now have Annotations which makes our life even more simple with the programming.

Annotations provide a standard way by which we can annotate the JAVA classes and make up the EJBs so that the developer so that a developer can look at the class definition, together with annotations, and know everything about that class.

With annotations we just "say what to do" and "how it is to be done is handled by the JVM at runtime.

Lets consider simple HTML and CSS, even these are declarative programming languages. For instance, the HTML example <table border="1">, indicates a thin border. A CSS example is color: blue. This specifies the text color. As can be seen in these examples, HTML and CSS specify what should appear on a web page but not how to do so.
So to conclude, the advantage of declarative programming languages is mainly two-fold. The programs are concise; this makes it easy even for non-programmers to obtain solutions. In the SQL example above, an analyst or business support person can get the desired information. Similarly, laypersons can write acceptable web pages with simple HTML and CSS commands.
The second advantage of the declarative programming model is that repetitive imperative code that indicates how to solve things is provided in the computer system behind the scenes. Such code can be made highly efficient and can incorporate the best ideas from computing. It can take advantage of parallelism.

2. CallBack Methods:

Callbacks methods are the way of managing life cycle of an instance. Callback methods are generally used by containers. The methods are called at specific time during the lifetime of an instance. 

For example in JAVA servlet destroy() method is called by the servlet container that indicates that the servlet is being taken out of service. This type of methods are generally called by the container, the developer does not need to call these methods explicitly. 

Most of the languages specifies the callback method by passing the address of the subroutine to the system to the request is calling back from, 

But JAVA performs the same thing(i.e. specifying callback methods) by using interfaces. JAVA does not allow passing the address of subroutine but allows passing an instance of a class that implements the standard interface. For this purpose anonymous classes are mainly used as they support a better compact definition of the class that is required as a new class. One more example of callback methods is ejbCreate method that is used by an ejb container to create a ejb bean - the developer does not call it explicitly in code- the container calls it- although the developer can override it- or put stuff in it.

3. Cohesion and Coupling:

 One of the most important goals of object oriented design is to have high cohesion classes and loose coupling between these classes.

Coupling refers to links between separate units of a program. In object oriented programming, if two classes depend closely on many details of each other, we say they are tightly coupled.

Coupling is a measure of the interdependence between classes. If every object has a reference to every other object, then there is tight coupling, and this is undesirable. Because there's potentially too much information flow between objects. Loose coupling is desirable. It means that objects work more independently of each other. Loose coupling minimizes the "ripple effect" where changes in one class cause necessity for changes in other classes.

Cohesion, on the other hand, refers to the number and diversity of tasks that a class is designed for. If a class is responsible for a few related logical tasks, we say it has high cohesion.

Cohesion is a measure of strength of the association of variables and methods within a class. High cohesion is desirable because it means the class does one job well. Low cohesion is bad because it indicates that there are elements in the class which have little to do with each other. Modules whose elements are strongly and genuinely related to each other are desired. Each method should also be highly cohesive. Most methods have only one function to perform. Don't add extra instructions into methods that cause it to perform more than one function.

Loose coupling makes it possible to:
·         Understand one class without reading others
·         Change one class without affecting others
·         Thus: improves maintainability

High cohesion makes it easier to:
·         Understand what a class or method does
·         Use descriptive names
·         Reuse classes or methods

<<More General Terms Coming Soon>>

Conclusion:

Feel free to post in your comments. Happy Programming!.