Search This Blog

Friday 20 January 2017

Strings in switch statements


Design Pattern

What's New in Java 8

Java Platform, Standard Edition 8 is a major feature release. Java 8 contains a large number of new features. Although all are important, the three most important one are:
  • Lambda expressions
  • The stream API in java.util.stream
  • Default interface methods

Lambda Expressions
The most important new Java 8 feature is the lambda expression.
Lambda expressions are very important as they add functional programming features to Java. Lambda expressions can simplify and reduce the amount of source code needed to create certain constructs, such as some types of anonymous classes. This is particularly helpful when implementing a number of commonly used event handlers.
To support lambda expressions Java has been expanded by the inclusion of a new operator (the –>) and a new syntax element.


To understand the benefits that lambda expressions bring, consider the following ActionEvent handler, which uses the traditional, anonymous class, approach:

myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
myLabel.setText("Button pressed.");
}
});

With JDK 8, this event handler can be written using a lambda expression

myButton.addActionListener(
(ae) -> myLabel.setText("Button pressed.")
);


As we observe code is shorter, that is more direct and to the point.



The Stream API
Another important feature of Java 8 is the new stream API, which is packaged in java.util.stream.
A stream represents a sequence of data. The key aspect of the stream API is its ability to perform pipeline operations that search, filter, map, or otherwise manipulate data.

Let’s assume we have a list that stores employee names, department, e-mail and phone numbers. Using the stream API, we can efficiently pipeline the operations that search for entries that match some criterion, for example department name, sort the matching items, and then extract only the e-mail addresses In many cases, such actions can be performed in parallel, thus providing a high level of efficiency. The stream API provides a powerful means of handling data in an efficient, yet easy to use way.

Default Methods
With the release of Java 8, it is now possible for an interface method to define a default implementation. This new capability is called the default method.

Default method enables us a means by which interfaces could be expanded without breaking pre-existing code.
In simple terms default methods enable us to add new functionalities to interfaces without breaking the classes that implements that interface.


When a non-abstract class implements an interface, it must implement all methods defined by that interface. If a new method is to an existing interface, then the addition of that method would break pre-existing code, because no implementation would be found for that new method in pre-existing classes. The default method solves this problem by supplying an implementation that will be used if no other implementation is explicitly provided. Thus, the addition of a default method will not cause pre-existing code to break. This enables interfaces to be gracefully evolved over time without negative consequences.


Tuesday 17 January 2017

Object Relational Mapping

Object Relational Mapping (ORM) in computer science is a programming technique for converting data between incompatible type systems in object-oriented programming languages.
In object-oriented programming, data-management tasks act on object-oriented (OO) objects that are almost always non-scalar values.
For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a "Person object" with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain "PhoneNumber objects" and so on. The address-book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various methods can be associated with the object, such as a method to return the preferred phone number, the home address, and so on.
However, many popular database products such as SQL database management systems (DBMS) can only store and manipulate scalar values such as integers and strings organized within tables. The programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping implements the first approach.
The heart of the problem involves translating the logical representation of the objects into an atomized form that is capable of being stored in the database, while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be persistent.

Persistence

ORM is concerned with helping your application to achieve persistence.
Persistence means that we would like our application’s data to outlive the applications process. In Java terms, we would like the state of (some of) our objects to live beyond the scope of the JVM so that the same state is available later.

Relational Databases

Specifically, ORM is concerned with data persistence as it applies to relational databases (RDBMS). RDBMS is a very popular persistence mechanism.

The Object-Relational Impedance Mismatch

'Object-Relational Impedance Mismatch' (sometimes called the 'paradigm mismatch') is a way of saying that object models and relational models do not work very well together. RDBMSs represent data in a tabular format, whereas object-oriented languages, such as Java, represent it as objects. Loading and storing objects using a tabular relational database exposes us to 5 mismatch problems…​

Granularity

Sometimes you will have an object model which has more classes than the number of corresponding tables in the database, we says the object model is more granular than the relational model.

Subtypes (Inheritance)

Inheritance is a natural paradigm in object-oriented programming languages. However, RDBMSs do not define anything similar on the whole.

Identity

A RDBMS defines exactly one notion of 'sameness': the primary key. Java, however, defines both object identity a==b and object equality a.equals(b).

Associations

Associations are represented as unidirectional references in Object Oriented languages whereas RDBMSs use the notion of foreign keys. If you need bidirectional relationships in Java, you must define the association twice.
Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.

Data navigation

The way you access data in Java is fundamentally different than the way you do it in a relational database. In Java, you navigate from one association to another walking the object network.

This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.

Object-relational mapping

Object-relational mapping


Sunday 15 January 2017

Singleton Design Pattern in Java

Singleton Design Pattern in Java
Intent
Ensure a class only has one instance, and provide a global point of access to it.

Motivation
It's important for some classes to have exactly one instance.
There are some instances in the application where we have to use just one instance of a particular class
A very simple example is Logger, suppose we need to implement the logger and log it to some file according to date time. In this case, we cannot have more than one instances of Logger in the application otherwise the file in which we need to log will be created with every instance.
Singleton pattern is used for logging, drivers objects, caching and thread pool.

Applicability
Use the Singleton pattern when
·         There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
·         When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

Consequences
The Singleton pattern has several benefits:
1. Controlled access to sole instance. Because the Singleton class encapsulates its sole instance, it can have strict control over how and when clients access it.
2. Reduced name space. The Singleton pattern is an improvement over global variables. It avoids polluting the name space with global variables that store sole instances.
3. Permits refinement of operations and representation. The Singleton class may be subclassed, and it's easy to configure an application with an instance of this extended class. You can configure the application with an instance of the class you need at run-time.
4. Permits a variable number of instances. The pattern makes it easy to change your mind and allow more than one instance of the Singleton class. Moreover, you can use the same approach to control the number of instances that the application uses. Only the operation that grants access to the Singleton instance needs to change.

How do we ensure that a class has only one instance and that the instance is easily accessible?
·         A global variable makes an object accessible, but it doesn't keep you from instantiating multiple objects.
·         A better solution is to make the class itself responsible for keeping track of its sole instance. The class can ensure that no other instance can be created, and it can provide a way to access the instance.

Creating Singleton design pattern
To create the singleton class, we need to have static member of class, private constructor and static factory method.

  • Static member: It gets memory only once because it is static, and the only instance of the Singleton class.
  • Private constructor: It will prevent the instantiation of the Singleton class from outside the class.
  • Static factory method: It will provide the global point of access to the Singleton object and returns the instance to the caller.
Implementation

package com.jasdhir.blog.single;

public class SingletonObject {
      //create an object of SingletonObject class
         private static SingletonObject single = new SingletonObject();

         //make the constructor private so that this class cannot be instantiated
         private SingletonObject(){}

         //Get the only object available
         public static SingletonObject getInstance(){
            return single;
         }
}

package com.jasdhir.blog.single;

public class Main {
public static void main(String[] args) {
      SingletonObject Obj1=SingletonObject.getInstance();
      System.out.println("Object 01 : "+Obj1);
     
      SingletonObject Obj2=SingletonObject.getInstance();
      System.out.println("Object 02 : "+Obj2);
}
}

Output :
Object 01 : com.jasdhir.blog.single.SingletonObject@6d06d69c
Object 02 : com.jasdhir.blog.single.SingletonObject@6d06d69c

Both the objects Obj1 and Obj2 are referring to same instance