Thursday, May 27, 2010

Software Frameworks

(Courtesy: Wikipedia) A software framework, in computer programming, is an abstraction in which common code providing generic functionality can be selectively overridden or specialized by user code providing specific functionality. Frameworks are a special case of software libraries in that they are reusable abstractions of code wrapped in a well-defined Application programming interface (API), yet they contain some key distinguishing features that separate them from normal libraries.

Software frameworks have these distinguishing features that separate them from libraries or normal user applications:

  1. Inversion of control - In a framework, unlike in libraries or normal user applications, the overall program's flow of control is not dictated by the caller, but by the framework.[1]
  2. Default behavior - A framework has a default behavior. This default behavior must actually be some useful behavior and not a series of no-ops.
  3. Extensibility - A framework can be extended by the user usually by selective overriding or specialized by user code providing specific functionality.
  4. Non-modifiable framework code - The framework code, in general, is not allowed to be modified. Users can extend the framework, but not modify its code.
(Courtesy: Wantii) A Framework is similar to an API because it is used to accomplish a set of tasks within a project without spending time creating reusable components from scratch. What separates a framework from an API is size and scope. Most APIs are devoted to accomplishing a single task or implementing one protocol. Frameworks often provide facilities to manage much more complicated problems such as allowing a consistent code style within a large project, or providing a consistent look-and-feel within a large GUI-based project. A framework will often include related resources such as graphical elements or UI widgets to help the developers using the framework.

Wednesday, May 26, 2010

Design Patterns

Decorator Pattern
Allows new/additional behaviour to be added to an existing object dynamically.
Adapter Pattern
Allows incompatible classes work together by converting the interface of one class into an interface expected by the other.

Java 10 Best Practices

Quote 1: Avoid creating unnecessary objects and always prefer to do Lazy Initialization

Object creation in Java is one of the most expensive operation in terms of memory utilization and performance impact. It is thus advisable to create or initialize an object only when it is required in the code.

01public class Countries {
02
03 private List countries;
04
05 public List getCountries() {
06
07 //initialize only when required
08 if(null == countries) {
09 countries = new ArrayList();
10 }
11 return countries;
12 }
13}

Quote 2: Never make an instance fields of class public

Making a class field public can cause lot of issues in a program. For instance you may have a class called MyCalender. This class contains an array of String weekdays. You may have assume that this array will always contain 7 names of weekdays. But as this array is public, it may be accessed by anyone. Someone by mistake also may change the value and insert a bug!

1public class MyCalender {
2
3 public String[] weekdays =
4 {"Sun", "Mon", "Tue", "Thu", "Fri", "Sat", "Sun"};
5
6 //some code
7
8}

Best approach as many of you already know is to always make the field private and add a getter method to access the elements.

1private String[] weekdays =
2 {"Sun", "Mon", "Tue", "Thu", "Fri", "Sat", "Sun"};
3
4public String[] getWeekdays() {
5 return weekdays;
6}

But writing getter method does not exactly solve our problem. The array is still accessible. Best way to make it unmodifiable is to return a clone of array instead of array itself. Thus the getter method will be changed to.

1public String[] getWeekdays() {
2 return weekdays.clone();
3}

Quote 3: Always try to minimize Mutability of a class

Making a class immutable is to make it unmodifiable. The information the class preserve will stay as it is through out the lifetime of the class. Immutable classes are simple, they are easy to manage. They are thread safe. They makes great building blocks for other objects.

However creating immutable objects can hit performance of an app. So always choose wisely if you want your class to be immutable or not. Always try to make a small class with less fields immutable.

To make a class immutable you can define its all constructors private and then create a public static method
to initialize and object and return it.

01public class Employee {
02
03 private String firstName;
04 private String lastName;
05
06 //private default constructor
07 private Employee(String firstName, String lastName) {
08 this.firstName = firstName;
09 this.lastName = lastName;
10 }
11
12 public static Employee valueOf (String firstName, String lastName) {
13 return new Employee(firstName, lastName);
14 }
15}

Quote 4: Try to prefer Interfaces instead of Abstract classes

First you can not inherit multiple classes in Java but you can definitely implements multiple interfaces. Its very easy to change the implementation of an existing class and add implementation of one more interface rather then changing full hierarchy of class.

Again if you are 100% sure what methods an interface will have, then only start coding that interface. As it is very difficult to add a new method in an existing interface without breaking the code that has already implemented it. On contrary a new method can be easily added in Abstract class without breaking existing functionality.

Quote 5: Always try to limit the scope of Local variable

Local variables are great. But sometimes we may insert some bugs due to copy paste of old code. Minimizing the scope of a local variable makes code more readable, less error prone and also improves the maintainability of the code.

Thus, declare a variable only when needed just before its use.

Always initialize a local variable upon its declaration. If not possible at least make the local instance assigned null value.

Quote 6: Try to use standard library instead of writing your own from scratch

Writing code is fun. But “do not reinvent the wheel”. It is very advisable to use an existing standard library which is already tested, debugged and used by others. This not only improves the efficiency of programmer but also reduces chances of adding new bugs in your code. Also using a standard library makes code readable and maintainable.

For instance Google has just released a new library Google Collections that can be used if you want to add advance collection functionality in your code.

Quote 7: Wherever possible try to use Primitive types instead of Wrapper classes

Wrapper classes are great. But at same time they are slow. Primitive types are just values, whereas Wrapper classes are stores information about complete class.

Sometimes a programmer may add bug in the code by using wrapper due to oversight. For example, in below example:

1int x = 10;
2int y = 10;
3
4Integer x1 = new Integer(10);
5Integer y1 = new Integer(10);
6
7System.out.println(x == y);
8System.out.println(x1 == y1);

The first sop will print true whereas the second one will print false. The problem is when comparing two wrapper class objects we cant use == operator. It will compare the reference of object and not its actual value.

Also if you are using a wrapper class object then never forget to initialize it to a default value. As by default all wrapper class objects are initialized to null.

1Boolean flag;
2
3if(flag == true) {
4 System.out.println("Flag is set");
5} else {
6 System.out.println("Flag is not set");
7}

The above code will give a NullPointerException as it tries to box the values before comparing with true and as its null.

Quote 8: Use Strings with utmost care.

Always carefully use Strings in your code. A simple concatenation of strings can reduce performance of program. For example if we concatenate strings using + operator in a for loop then everytime + is used, it creates a new String object. This will affect both memory usage and performance time.

Also whenever you want to instantiate a String object, never use its constructor but always instantiate it directly. For example:

1//slow instantiation
2String slow = new String("Yet another string object");
3
4//fast instantiation
5String fast = "Yet another string object";

Quote 9: Always return empty Collections and Arrays instead of null

Whenever your method is returning a collection element or an array, always make sure you return empty array/collection and not null. This will save a lot of if else testing for null elements. For instance in below example we have a getter method that returns employee name. If the name is null it simply return blank string “”.

1public String getEmployeeName() {
2 return (null==employeeName ? "": employeeName);
3}

Quote 10: Defensive copies are savior

Defensive copies are the clone objects created to avoid mutation of an object. For example in below code we have defined a Student class which has a private field birth date that is initialized when the object is constructed.

01public class Student {
02 private Date birthDate;
03
04 public Student(birthDate) {
05 this.birthDate = birthDate;
06 }
07
08 public Date getBirthDate() {
09 return this.birthDate;
10 }
11}

Now we may have some other code that uses the Student object.

1public static void main(String []arg) {
2
3 Date birthDate = new Date();
4 Student student = new Student(birthDate);
5
6 birthDate.setYear(2019);
7
8 System.out.println(student.getBirthDate());
9}

In above code we just created a Student object with some default birthdate. But then we changed the value of year of the birthdate. Thus when we print the birth date, its year was changed to 2019!

To avoid such cases, we can use Defensive copies mechanism. Change the constructor of Student class to following.

1public Student(birthDate) {
2 this.birthDate = new Date(birthDate);
3}

This ensure we have another copy of birthdate that we use in Student class.

Two bonus quotes

Here are two bonus Java best practice quotes for you.

Quote 11: Never let exception come out of finally block

Finally blocks should never have code that throws exception. Always make sure finally clause does not throw exception. If you have some code in finally block that does throw exception, then log the exception properly and never let it come out :)

Quote 12: Never throw “Exception”

Never throw java.lang.Exception directly. It defeats the purpose of using checked Exceptions. Also there is no useful information getting conveyed in caller method.

Quote #13: Avoid floating point numbers

It is a bad idea to use floating point to try to represent exact quantities like monetary amounts. Using floating point for dollars-and-cents calculations is a recipe for disaster. Floating point numbers are best reserved for values such as measurements, whose values are fundamentally inexact to begin with. For calculations of monetary amounts it is better to use BigDecimal.

Tuesday, May 25, 2010

HIBERNATE - Getting Started With Hibernate

Hibernate is Free Software. The LGPL license is sufficiently flexible to allow the use of Hibernate in both open source and commercial projects (see the LicenseFAQ for details). Hibernate is available for download at http://www.hibernate.org/

We wll take up an simple java example
that authenticates users based on the credentials to get started with hibernate.

HIBERNATE - Features of Hibernate

Transparent persistence without byte code processing
Transparent persistence
JavaBeans style properties are persisted
No build-time source or byte code generation / processing
Support for extensive subset of Java collections API
Collection instance management
Extensible type system
Constraint transparency
Automatic Dirty Checking
Detached object support
Object-oriented query language
Powerful object-oriented query language
Full support for polymorphic queries
New Criteria queries
Native SQL queries
Object / Relational mappings
Three different O/R mapping strategies
Multiple-objects to single-row mapping
Polymorphic associations
Bidirectional associations
Association filtering
Collections of basic types
Indexed collections
Composite Collection Elements
Lifecycle objects
Automatic primary key generation
Multiple synthetic key generation strategies
Support for application assigned identifiers
Support for composite keys
Object/Relational mapping definition
XML mapping documents
Human-readable format
XDoclet support
HDLCA (Hibernate Dual-Layer Cache Architecture)
Thread safeness
Non-blocking data access
Session level cache
Optional second-level cache
Optional query cache
Works well with others
High performance
Lazy initialization
Outer join fetching
Batch fetching
Support for optimistic locking with versioning/timestamping
Highly scalable architecture
High performance
No "special" database tables
SQL generated at system initialization time
(Optional) Internal connection pooling and PreparedStatement caching
J2EE integration
JMX support
Integration with J2EE architecture (optional)
New JCA support

Hibernate Overview

High level architecture of Hibernate can be described as shown in following illustration.





Hibernate makes use of persistent objects commonly called as POJO (POJO = "Plain Old Java Object".) along with XML mapping documents for persisting objects to the database layer. The term POJO refers to a normal Java objects that does not serve any other special role or implement any special interfaces of any of the Java frameworks (EJB, JDBC, DAO, JDO, etc...).

Rather than utilize byte code processing or code generation, Hibernate uses runtime reflection to determine the persistent properties of a class. The objects to be persisted are defined in a mapping document, which serves to describe the persistent fields and associations, as well as any subclasses or proxies of the persistent object. The mapping documents are compiled at application startup time and provide the framework with necessary information for a class. Additionally, they are used in support operations, such as generating the database schema or creating stub Java source files.

Typical Hibernate code

sessionFactory = new Configuration().configure().buildSessionFactory();

Session session = sessionFactory.openSession();

Transaction tx = session.beginTransaction();

Customer newCustomer = new Customer();
newCustomer.setName("New Customer");
newCustomer.setAddress("Address of New Customer");
newCustomer.setEmailId("NewCustomer@NewCustomer.com");

session.save(newCustomer);

tx.commit();

session.close();

First step is hibernate application is to retrieve Hibernate Session; Hibernate Session is the main runtime interface between a Java application and Hibernate. SessionFactory allows applications to create hibernate session by reading hibernate configurations file hibernate.cfg.xml.

After specifying transaction boundaries, application can make use of persistent java objects and use session for persisting to the databases.

Hibernate

HIBERNATE TUTORIAL

HIBERNATE - Introduction to Hibernate

Hibernate is an open source object/relational mapping tool for Java. Hibernate lets you develop persistent classes following common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework.

Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC.

Hibernates goal is to relieve the developer from 95 percent of common data persistence related programming tasks.


Hibernate is Free Software. The LGPL license is sufficiently flexible to allow the use of Hibernate in both open source and commercial projects (see the LicenseFAQ for details). Hibernate is available for download at http://www.hibernate.org/. This tutorial aims to provide insight into Hibernate version 3.0RC and its usage

Some of the main features of hibernate are listed below and we have tried to explain some of them in detail later in this tutorial.

Transparent persistence without byte code processing
Transparent persistence
JavaBeans style properties are persisted
No build-time source or byte code generation / processing
Support for extensive subset of Java collections API
Collection instance management
Extensible type system
Constraint transparency
Automatic Dirty Checking
Detached object support
Object-oriented query language
Powerful object-oriented query language
Full support for polymorphic queries
New Criteria queries
Native SQL queries
Object / Relational mappings
Three different O/R mapping strategies
Multiple-objects to single-row mapping
Polymorphic associations
Bidirectional associations
Association filtering
Collections of basic types
Indexed collections
Composite Collection Elements
Lifecycle objects
Automatic primary key generation
Multiple synthetic key generation strategies
Support for application assigned identifiers
Support for composite keys
Object/Relational mapping definition
XML mapping documents
Human-readable format
XDoclet support
HDLCA (Hibernate Dual-Layer Cache Architecture)
Thread safeness
Non-blocking data access
Session level cache
Optional second-level cache
Optional query cache
Works well with others
High performance
Lazy initialization
Outer join fetching
Batch fetching
Support for optimistic locking with versioning/timestamping
Highly scalable architecture
High performance
No "special" database tables
SQL generated at system initialization time
(Optional) Internal connection pooling and PreparedStatement caching
J2EE integration
JMX support
Integration with J2EE architecture (optional)
New JCA support