Friday, 2 November 2012

How to call a C program from Java?

Calling a C program may be useful when we prefer to use C libraries and to reuse an existing C program. When we compile a C program, the source gets converted to obj file. It is a platform dependent intermediate machine code which will be converted to exe and then executed.
Java native interface (JNI) is a framework provided by java that enables java programs to call native code and vice-versa.

Using JNI a java program has the capability to call the native C code. But we lose the core objective of java which is platform independence. So calling a C program from java should be used judiciously.
JNI provides the specification and native code should be written/ported accordingly. JDK vendor should provide the needed implementation for the JNI.

Steps to call a C program from Java

1. Write the Java Program and Compile
2. Generate header file from java class
3. Write the C Program
4. Generate Shared Library File
5. Run Java Program

1. Write the Java Program

public class JavaToC {
          public native void helloC();

          static {
                     System.loadLibrary("HelloWorld");
           }

          public static void main(String[] args) {
                   new JavaToC().helloC();
          }
}

Note two things in this program,
  • Use of native keyword. This is a method declaration and it informs the java compiler that the implementation for this method is a native one. This method helloC() is present in C source file and that is what we are going to call.
  • Loading the library HelloWorld using static keyword. This library file will be compiled out of the C source in the coming steps.

2. Generate header file from java class

  • JDK provides a tool named javah which can be used to generate the header file.
  • We will use the generated header file as include in C source.
  • Remember to compile the java program before using javah
javah JavaToC
Following is the header file generated,


/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class JavaToC */
 
#ifndef _Included_JavaToC
#define _Included_JavaToC
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class:     JavaToC
* Method:    helloC
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_JavaToC_helloC
(JNIEnv *, jobject);
 
#ifdef __cplusplus
}
#endif
#endif

3. Write the C Program

#include <stdio.h>
#include <jni.h>
#include "JavaToC.h"
JNIEXPORT void JNICALL Java_JavaToC_helloC(JNIEnv *env, jobject javaobj)
{
  printf("Hello World: From C");
  return;
}
  • stdio.h is the standard C header file include.
  • jni.h is the header file that provides the java to C mapping and it is available in JDK.
  • JavaToC.h is the header file generated from the java source file.

4. Generate Shared Library File

  • Now compile the above C source file. We need a C compiler and I have chosen Tiny C.
  • Tiny C can be downloaded from http://mirror.veriportal.com/savannah//tinycc/tcc-0.9.25-win32-bin.zip
    Download and unzip the file and set OS path to tcc.exe
  • tcc HelloWorld.C -I C:/Progra~1/Java/jdk1.7.0_07/include -I C:/Progra~1/Java/jdk1.7.0_07/include/win32 -shared -o HelloWorld.dll
  • Above is the command to generate the shared library file dll which is loaded in the java program. Two directories are included in the compile command, those are to include the jni.h and jni_md.h

5. Run Java Program

We are all set, now run the java program to get the following output,
Hello World: From C

Wednesday, 26 September 2012

Top 10 Java Classes

Thought of compiling a list of classes that are popular among java programmers. Should I say most essential? There is no strict rules for the selection, in fact there are no rules followed. Classes that popped up on top of mind are listed below. You are welcome to add your own list. This list will vary depending on the type of java project you work on. These classes I have listed does not require any introduction and they are as popular as Salmankhan in java world.
  1. java.lang.String
    String class will be the undisputed champion on any day by popularity and none will deny that. This is a final class and used to create / operate immutable string literals. It was available from JDK 1.0
  2. java.lang.System
    Usage of System depends on the type of project you work on. You may not be using it in your project but still it is one of the popular java classes around. This is a utility class and cannot be instantiated. Main uses of this class are access to standard input, output, environment variables, etc. Available since JDK 1.0
  3. java.lang.Exception
    Throwable is the super class of all Errors and Exceptions. All abnormal conditions that can be handled comes under Exception. NullPointerException is the most popular among all the exceptions. Exception is at top of hierarchy of all such exceptions. Available since JDK 1.0
  4. java.util.ArrayList
    An implementation of array data structure. This class implements List interface and is the most popular member or java collections framework. Difference between ArrayList and Vector is one popular topic among the beginners and frequently asked question in java interviews. It was introduced in JDK 1.2
  5. java.util.HashMap
    An implementation of a key-value pair data structure. This class implements Map interface. As similar to ArrayList vs Vector, we have HashMap vs Hashtable popular comparisons. This happens to be a popular collection class that acts as a container for property-value pairs and works as a transport agent between multiple layers of an application. It was introduced in JDK 1.2
  6. java.lang.Object
    Great grandfather of all java classes. Every java class is a subclass of Object. It will be used often when we work on a platform/framework. It contains the important methods like equals, hashcode, clone, toString, etc. It is available from day one of java (JDK 1.0)
  7. java.lang.Thread
    A thread is a single sequence of execution, where multiple thread can co-exist and share resources. We can extend this Thread class and create our own threads. Using Runnable is also another option. Usage of this class depends on the domain of your application. It is not absolutely necessary to build a usual application. It was available from JDK 1.0
  8. java.lang.Class
    Class is a direct subclass of Object. There is no constructor in this class and their objects are loaded in JVM by classloaders. Most of us may not have used it directly but I think its an essential class. It is an important class in doing reflection. It is available from JDK 1.0
  9. java.util.Date
    This is used to work with date. Sometimes we feel that this class should have added more utility methods and we end up creating those. Every enterprise application we create has a date utility. Introduced in JDK 1.0 and later made huge changes in JDK1.1 by deprecating a whole lot of methods.
  10. java.util.Iterator
    This is an interface. It is very popular and came as a replacement for Enumeration. It is a simple to use convenience utility and works in sync with Iterable. It was introduced in JDK 1.2

Saturday, 22 September 2012

 Top 10 Java Debugging Tips with Eclipse

About debugging java applications using Eclipse. Debugging helps us to identify and fix defects in the application. We will focus on run-time issues and not compile time errors. There are command line debuggers like gdb available. In this tutorial we will focus on GUI based debugger and we take our favourite IDE Eclipse to run through the tutorial. Though we say Eclipse, the points are mostly generic and is suitable for debugging using most of the IDEs like NetBeans too.
Before going through this tutorial, I recommend you to have a look at Eclipse shortcuts and it will really help. My Eclipse version is Juno as of writing this tutorial.
  • Do not use System.out.println  as a tool to debug.
  • Enable detailed log level of all the components involved.
  • Use a log analyzer to read logs.

1. Conditional Breakpoint

Hope we know how to add a breakpoint. If not, just click on the left pane (just before the line number) and a breakpoint will be created. In debug perspective, ‘Breakpoints’ view will list the breakpoint created. We can add a boolean condition to it. That is, the breakpoint will be activated and execution will hold only if the boolean condition is met otherwise this breakpoint will be skipped.

2. Exception Breakpoint

In Breakpoints view there is a button labeled as J! We can use that button to add a java exception based breakpoint. For example we want the program to halt and allow to debug when a NullPointerException is thrown we can add a breakpoint using this.

3. Watch Point

This is one nice feature I love. When a chosen attribute is accessed or modified program execution will halt and allow to debug. Select a class variable in Outline view and from its context menu select Toggle Watchpoint. This will create a watch point for that attribute and it will be listed in Breakpoints view.

4. Evaluation (Display or Inspect or Watch)

Ctrl+Shift+d or Ctrl+Shift+i on a selected variable or expression will show the value. We can also add a permanent watch on an expression/variable which will be shown in Expressions view when debug is on.

5. Change Variable Values

We can change the value of a variable on the fly during debug. Choose a variable and go to Variables view and select the value, type and enter.

6. Stop in Main

In Run/Debug Settings, Edit Configuration we can enable a check box that says Stop in main. If enabled when we debug a java program that launches with a main method, the execution halts at first line of main method.

7. Environment Variables

Instead of going to System properties to add an environment variable, we can conveniently add it through Edit Configuration dialog box.

8. Drop to Frame

This is the second best feature I love. We can just return the control to any frame in the call stack during debug. Changes made to variables will not be reset. Choose the stack level which you want to go back and restart debug from there and click the drop to frame button from debug toolbar. Eclipse is cool!

9. Step Filter

When we Step Into (F5) a method we may go into external libraries (like java) and we may not need it. We can add a filter in preferences and exclude packages.

10. Step Into, Over and Return

I kept this as the last point as this is the first thing to learn in debugging :-)
  • F5 – Step Into: moves to next step and if the current line has a method call the control will go into the first line of the called method.
  • F6 – Step Over: moves the control to next line. If there is a method call in the current line, it executes the method call internally and just moves the control to next line.
  • F7 – Step Return: When done from inside a method the control will move to the calling line from where the current method is invoked.
  • F8 – Move to next breakpoint.

Friday, 14 September 2012

Java Versions, Features and History

A popular interview question in java is “what is new in Java version X?”. Is that an intelligent question is debatable. I have summarized below important new features added in each major java release till now. I target to highlight important features added in respective release. Apart from below list of features, every release has enhancements and lots of bug fixes.

Java Version SE 8

Java 8 was released on 18 March 2014. The code name culture is dropped with Java 8 and so no official code name going forward from Java 8.
New features in Java SE 8
  • Lambda Expressions
  • Pipelines and Streams
  • Date and Time API
  • Default Methods
  • Type Annotations
  • Nashhorn JavaScript Engine
  • Concurrent Accumulators
  • Parallel operations
  • PermGen Error Removed
  • TLS SNI

Java Version SE 7

Code named Dolphin and released on July 28, 2011.
New features in Java SE 7
  • Strings in switch Statement
  • Type Inference for Generic Instance Creation
  • Multiple Exception Handling
  • Support for Dynamic Languages
  • Try with Resources
  • Java nio Package
  • Binary Literals, underscore in literals
  • Diamond Syntax
  • Automatic null Handling

Java Version SE 6

Code named Mustang and released on December 11, 2006.
New features in Java SE 6
  • Scripting Language Support
  • JDBC 4.0 API
  • Java Compiler API
  • Pluggable Annotations
  • Native PKI, Java GSS, Kerberos and LDAP support.
  • Integrated Web Services.
  • Lot more enhancements.

J2SE Version 5.0

Code named Tiger and released on September 30, 2004.
New features in J2SE 5.0
  • Generics
  • Enhanced for Loop
  • Autoboxing/Unboxing
  • Typesafe Enums
  • Varargs
  • Static Import
  • Metadata (Annotations)
  • Instrumentation

J2SE Version 1.4

Code named Merlin and released on February 6, 2002 (first release under JCP).
New features in J2SE 1.4
  • XML Processing
  • Java Print Service
  • Logging API
  • Java Web Start
  • JDBC 3.0 API
  • Assertions
  • Preferences API
  • Chained Exception
  • IPv6 Support
  • Regular Expressions
  • Image I/O API

J2SE Version 1.3

Code named Kestrel and released on May 8, 2000.
New features in J2SE 1.3
  • Java Sound
  • Jar Indexing
  • A huge list of enhancements in almost all the java area.

J2SE Version 1.2

Code named Playground and released on December 8, 1998.
New features in J2SE 1.2
  • Collections framework.
  • Java String memory map for constants.
  • Just In Time (JIT) compiler.
  • Jar Signer for signing Java ARchive (JAR) files.
  • Policy Tool for granting access to system resources.
  • Java Foundation Classes (JFC) which consists of Swing 1.0, Drag and Drop, and Java 2D class libraries.
  • Java Plug-in
  • Scrollable result sets, BLOB, CLOB, batch update, user-defined types in JDBC.
  • Audio support in Applets.

JDK Version 1.1

Released on February 19, 1997
New features in J2SE 1.1
  • JDBC (Java Database Connectivity)
  • Inner Classes
  • Java Beans
  • RMI (Remote Method Invocation)
  • Reflection (introspection only)

JDK Version 1.0

Codenamed Oak and released on January 23, 1996.

Tuesday, 10 April 2012

Exception Handling Best Practices

Let’s review some basic exception design guidelines, summarized from Object Design: Roles, Responsibilities, and Collaborations (Rebecca Wirfs-Brock and Alan McKean, Addison-Wesley, 2003). 

Don’t try to handle coding errors.

Unless your software is required to take extraordinary measures in error scenarios, don’t spend a lot of time designing it to detect and recover from programming errors. In the case of an out-of-bounds array index, divide-by zero error, or any other programming error, the best strategy is to fail fast (and leave an audit trail of the problem that can be used to troubleshoot it). 

Avoid declaring lots of exception classes.

Create a new exception class only when you expect some handling of the code to take a significantly different action, based on the exception type. In my experience it is rarely the case and exception classes available in java API serve the purpose. Recast lower-level exceptions to higher-level ones whenever you raise an abstraction level. 

Don’t let implementation details leak out of a method invocation as exceptions.

Otherwise, your users might think your software is broken. When low-level exceptions percolate up to a high-level handler, there’s little context to assist the handler in making informed decisions or reporting conditions that are traceable to any obvious cause. Recasting an exception whenever you cross an abstraction boundary enables exception handlers higher up in the call chain to make more informed decisions. If you want to include a problem trace when recasting them, you can always create a chained exception. A chained exception provides added context and holds a reference to the original lower level exception. You can repeatedly chain exceptions. 

Provide context along with an exception.

What’s most important in exception handling is information that helps create an informed response. Exception classes hold information. You can design them to be packed with information in addition to the bare-bones stack trace information provided by default. You might include values of parameters that raised the exception, specific error text, or detailed information that could be useful to plan a recovery.

Handle exceptions as close to the problem as you can.

As a first line of defense, consider the initial requestor. If the caller knows enough to perform a corrective action, you can rectify the condition on the spot. If you propagate an exception far away from the source, it can be difficult to trace the source. Often objects further away from the problem can’t make meaningful decisions.

Use exceptions only to signal emergencies.

Exceptions shouldn't be raised to indicate normal branching conditions that will alter the flow in the calling code. For example, a find operation may return zero, one, or many objects, so I wouldn't raise an exception in this case. Instead, I’d design my find() method to return a null object or an empty collection. A dropped database connection, on the other hand, is a real emergency. There’s nothing that can be done to continue as planned.

Don’t repeatedly re-throw the same exception.

Although exceptions don’t cost anything until they’re raised, programs that frequently raise exceptions run more slowly.

Thursday, 29 March 2012

"Copy-Paste" is really a problem? DRY-"Don’t Repeat Yourself" Principal

We’ve all seen it. We’ve all done it. Duplication! But why? In this post I will discuss some ways duplication happens in code. But first, why do we care about duplication?


It has been my experience that a majority of my time is spend maintaining code –even when writing a new application. Maintenance it’s not going away anytime soon. Therefore, the way to keep maintenance costs down is to speed up the task. The key to that is to make sure that “every piece of knowledge must have a single, unambiguous, authoritative representation within a system”.

The opposite of the statement above, is to express the same knowledge in multiple places. Which creates parallel maintenance –when one is changed the other must change. Can you say, “Hello bugs!”

This is where the “Don’t Repeat Yourself” (DRY) principle gets its roots. There are several ways that duplication happens, here are a few: 
  • When we are rushed or impatient. Sometimes eliminating duplication requires more time and effort. To remove duplication we have to modify our design. Whether it be extract a method, extract a class, etc –something has to change. But we say “it can wait, because it’s working and we don’t want to break it”. 
  • When we follow examples or ‘patterns’ that already exist in code. This is the easiest duplication to spot, but sometimes the hardest to remove. “Copy and paste is a design error”, says David Parnas. Instead, when possible, we should follow Object Orientated principles and use code generation tools to remove duplication. 
  • When we are unfamiliar with the code, which is caused by working in a team or being a new developer to a language. Sometimes we don’t know what classes and methods are available. Without due diligence during research we create duplication because we WILL write it ourselves. 
We must head off this maintenance nightmare by treating duplication as evil. Remove duplication as soon as it’s spotted.

Happy Coding!

Sunday, 11 March 2012

Dependency Inversion Principle. Is it IoC?

Today we are going to talk about one of the most confusing topics of all and see if we can unravel the mess of Dependency Inversion, Inversion of Control and Dependency Injection.

It’s not completely important that we understand the specifics of each of these names, because many people end up using them interchangeably. It’s pretty unlikely that we are going to correct all that in this blog post.

What is important is that we understand the concepts and ideas behind each of these topics and understand what architectural problems each one is trying to solve.


Today, we are going to focus on Dependency Inversion and get a little bit into inversion of control.


Dependency inversion is the root

It all started with this simple concept introduced by Uncle Bob in his article in the C++ Report of May 1996, The Dependency Inversion Principle.

This principle is actually very simply stated:
  • High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend upon details. Details should depend upon abstractions.
  • I think this concept is easily misunderstood and misapplied, because the reason why we apply this principle is often neglected.

If you are familiar with IoC and Dependency Injection, you can see how both are based from this definition of Dependency Inversion.


What problem does dependency inversion solve?

Dependency inversion solves the problem of higher level modules being dependent on and coupled to the interfaces of lower level modules and their details.

Let me give you a real world example of a current problem that could be solved by dependency inversion.

Take a look around your house and count up all the devices that have batteries that must be charged somehow.

Things like:
  • Digital camera
  • Cell phone
  • Camcorder (flip cam)
  • Wireless headphones
  • Game controllers

What do all of these things have in common? They don’t have a charging interface in common. Some use micro-usb, some use mini-usb, some use their own funky plug.

So as a result, you can’t just have one thing that charged all your devices. You have to have a different thing for each device. Your home’s “charging mobile devices module” is dependent on the device. If you change your cell phone, you need a new charger. If you upgrade your camera, you need a new charger.

The dependency is going the wrong way. Lower-level appliances are defining the interface that your home has to use to charge them. Your home’s charging capability should define the interface the devices have to use. The dependency should be inverted. It would make your life a lot easier.

Let’s look at one more example of a place where I would bet dependency inversion is used. Now, I don’t know about Walmart’s IT structure, but I would venture to guess that when they receive invoices from all of their many distributors the invoices come in the file format that Walmart specifies and not the other way around.

I would bet that Walmart specifies the schema for all of the data it receives from its many business partners. Let’s assume they do. In this case they have inverted the dependency, actually they have inverted the control. Instead of their vendors controlling their interface, Walmart controls the vendors through their interface.

What this means is that every time the vendor changes their internal system they have to still conform to Walmarts interface instead of Walmart having to make changes to accommodate each vendors changes to their format.

Back to your code…

Now let’s look at a code example to see how dependency inversion helps us out. Let’s say you are creating a high level module for parsing log files and storing some basic information into a database.

In this case you want to be able to handle several different log files from a number of different sources and write some common data they all share to a database.
One approach to this kind of problem is to have your module handle each kind of log file based on what kind of data and format it contains and where it is. Using this approach, in your module you would handle various kinds of log files based on the interface those individual log files present to you. (When I use interface here, I am not talking about the language construct, but the concept of how we interface with something.)

Using this approach, in our module we might have a switch statement or series of if-else statements that lead us to a different code path depending on what kind of log file we are processing. For one log file we might open up a file on disk, and read a line, then split that line based on some delimiter. For another perhaps we open a database connection and read some rows.

The problem is the log files are defining the interface our higher level code has to use. They are in effect “in control” of our code, because they are dictating the behavior our code must conform to.

We can invert this control, and invert the dependencies by specifying an interface that the log files we process must conform to. We don’t even have to use a language level interface.

We could simply create a data class called LogFile that is the input to our module. Anyone who wanted to use our module would first have to convert their files to our format.

We could also create an ILogFileSource interface that classes could implement to contain the logic of parsing log files from different sources. Our module would depend on ILogFileSource and specify what kind of methods and data it needs to parse the log files instead of the other way around.

The key point here is that our high level module should be controlling the interface (non language construct kind) that the lower level modules need to adhere to instead of being at the whim of the interfaces of each lower level module.

One way to think of this is that lower level modules provide a service to higher level modules. The higher level modules specifies the interfaces for that service and the lower level module provides that service.

One thing I want to point out in this example is that we knew there would be more than one log file source. If we were writing a log file parsing module that was only ever going to work against one source it might not be worth trying to invert this dependency because we wouldn’t see any benefit from doing so. It isn’t very hard for us to write out code as cleanly as possible working with one source and then refactor it later to invert the dependencies once we have additional sources.

Just because you can invert dependencies doesn’t mean you should.

In this case since we are always writing to a database, I don’t feel any particular need to invert our dependency on writing out the log files. However, there is some real value in encapsulating all of our code that interacts with the database into one place, but that is for another post.

Notice we haven’t talked about unit testing yet

You see the problem of dependency inversion and inversion of control has nothing specifically to do with unit testing.

Simply slapping an interface on top of a class and injecting it into another class may help with unit testing, but it doesn’t necessarily invert control or dependencies.

I want to use the log parsing example to illustrate my point. Let’s say we had created our log parser to have a switch statement to handle each type of log file, and now we want to unit test the code.

There is no reason why we can’t create IDatabaseLogFile, ICSVFileSystemLogFile, IEventLogLogFile andIAnNotReallyDoingIoCLogFile, pass them all into the constructor of our LogFileParser as dependencies and then write our unit tests passing in mocks of each.

That in an extreme example for sure, but the point is slapping an interface onto a class does not an IoC make.

We shouldn’t be trying to implement this principle to make it easier to write unit tests. Difficult to write unit tests should give us hints like:
  • Our class is trying to do too much
  • Our class has lots of different dependencies
  • Our class requires a lot of setup to do work
  • Our class is just like this other class that does the same thing only for a different input

All of these kinds of hints tell us that we might want to invert control and invert dependencies to improve the overall design of our class, not because it makes it easier to test. (Although it should also make it easier to test.)

Ok, ok, so is dependency inversion the same as inversion of control or what?

Short answer: yes.

It depends on what you mean by control. There are three basic “controls” that can be inverted.
  1. The control of the interface. (How do these two systems, modules, or classes, interact with each other and exchange data?)
  2. The control of the flow. (What controls the flow the program? This control inversion happens when we go from procedural to event driven.)
  3. The control of dependency creation and binding. (This is the kind of inversion of control IoC containers do. This inversion is passing the control of the actual creation of and selection of dependencies to a 3rd party which is neutral to either of the other 2 involved.)
Each of these 3 is a specific form of dependency inversion and may even involve multiple kinds of dependencies being inverted.

So when someone says “inversion of control”, you should be thinking “what control is being inverted here?”

Dependency inversion is a principle that we use in architecting software.

Inversion of control is a specific pattern that is applied to do so.

Most people only think of inversion of control as #3 above, inverting the control of dependency creation and bind. This is where IoC containers and dependency injection take root.

What can we learn from this?

My goal is that we stop grouping the concepts of inversion of control and dependency inversion automatically with dependency injection.

We have learned that dependency inversion is the core principle that guides many of the other practices that have derived from it.

Whenever we apply a pattern we should be looking for the core principle it is tied to and what problem it is helping us solve.

With this base understanding of dependency inversion and inversion of control, we have the prerequisite knowledge to look at dependency injection and understand better what specific problem it tries to solve.

Saturday, 10 March 2012

The Wizard Design Pattern


The Wizard Design Pattern
We all love wizards.... (Software wizards I mean). We are always happy to jump on those ''Next" buttons like we were dancing the funky chicken on our… well you get the point. So today we bring you your beloved wizard into your coding experience. Let's jump right into an example.

Say you want to design a ConservativePerson class.

import java.util.List;

class ConservativePerson{
    private boolean isVirgin;
    private boolean isMarried;
    private List<string> children;
 
    ConservativePerson(boolean virgin, boolean married, List<string> children) {
        this.isVirgin = virgin;
        this.isMarried = married;
        this.children = children;
    }
 
    public boolean isVirgin() {
        return isVirgin;
    }
    public boolean isMarried() {
        return isMarried;
    }
 
    public List<string> getChildren() {
        return children;
    }
}

As such it has some constrains.

  • He must be married before he can be... well, not a virgin.
  • He can't be a virgin before he can have children (as far as we know).

In the old days, which is basically all days until today..., you would probably define all kinds of modifiers methods for this class which will throw an exception in case of invariant invalidation such as NotMarriedException and VirginException. Not anymore.

Today we will do it by using the Wizard Design Pattern. We use a fluent interface style and utilize the power of a modern IDE to create a wizard-like feeling when building a ConservativePerson object. We know, we know, stop talking and show us the code... but before we will present the wizard code we will show you it usage so you will get a grasp of what we are talking about...

public class Main {
public static void main(String[] args) {
    ConservativePersonWizardBuilder wizard = new ConservativePersonWizardBuilder();
    ConservativePerson singlePerson = wizard.
            createConservativePerson().
            whichIsSingle().
            getObject();
    ConservativePerson familyManPerson = wizard.
            createConservativePerson().
            whichIsMarried().
            andNotVirgin().
            andHasChildNamed("Noa").
            anotherChildNamed("Guy").
            lastChildName("Alon").
            getObject();
  }
 
}

Now, it may look just like an ordinarily fluent interface, but the cool thing here is that a method is available for calling only if the current object state allows it. This means you will not be able to call the method andNotVirgin if you haven't called the method whichIsMarried.
See the following set of screen shots:


and after we state he is married we can:

Here is the wizard code. I urge you to copy/paste it to your IDE and give it a try by building an object with it.

import java.util.ArrayList;
import java.util.List;
   
   public class ConservativePersonWizardBuilder {
     private boolean isVirgin;
     private boolean isMarried;
     private List<String> children = new ArrayList<String>();
       
     public SetMarriedStep createConservativePerson(){
         return new SetMarriedStep();
     }
   
     class SetMarriedStep {
        public SetVirginStep whichIsMarried(){
             isMarried = true;
             return new SetVirginStep();
         }
   
         public FinalStep whichIsSingle(){
             isMarried = false;
             return new FinalStep();
         }
     }


     class SetVirginStep {
         public AddChildrenStep andNotVirgin(){
             isVirgin = false;
             return new AddChildrenStep();

         }
         public FinalStep butStillAVirgin(){
             isVirgin = true;
             return new FinalStep();
         }
     }
 
     class FinalStep {
         public ConservativePerson getObject(){
             return new ConservativePerson(isVirgin, isMarried, children);
         }
     }
 

     class AddChildrenStep {
         public AddChildrenStep andHasChildNamed(String childName) {
             children.add(childName);
             return new AddChildrenStep();
         }
         public AddChildrenStep anotherChildNamed(String childName) {
             children.add(childName);
             return new AddChildrenStep();
         }
         public FinalStep lastChildName(String childName){
             children.add(childName);
             return new FinalStep();
         }
     }
 }

As you can see the wizard consists of several steps. Each step is represented by a dedicated inner class. Each step reveals the legal available operations by its methods. Each method will then return a new step according to the change it has made. This way an attempt to create an illegal object will be detected at compile time instead of runtime.

This pattern is actually being used in our production code. One example that comes to mind is the MediaJob class. This class describes a manipulation on some media files. In order to submit a job to the system, one has to create aMediaJob object. The problem is that this object has many parameters that could be assigned with contradicting values that create an illegal object state. By using the Wizard pattern, one can easily build a legal job without the need to know the entire (and complicated…) set of constrains.

That is all for now. Hope you'll give it a try..... We plan to write a more formal description of it (GOF style) in the near future.

Sunday, 4 March 2012

Do it short but do it right !! (Java Best Practices)

Writing concise, elegant and clear code has always been a difficult task for developers. Not only will your colleagues be grateful to you, but you would also be surprised to see how exciting it is to constantly look forward to refactoring solutions in order to do more (or at least the same) with less code. One used to say that good programmers are lazy programmers. True, true... But really good programmers are adding beauty to it.
You can easily improve the readability of your code, exploiting the power of the Java language, even for pretty basic things.

Let's start with a concrete example:
1String color = "green";
2...
3if  ( color!=null && color.equals("red") ) {
4    System.out.println("Sorry, red is forbidden !");
5}
One of the first lessons you probably learned from your Java (or Object-Oriented programming) teacher is the importance of testing the nullity of an object before invoking a method on it. Null pointer exceptions (NPEs) are indeed among the most common (and irritating) faults raised in the code of object-oriented languages.

In the above example, it is safe to ensure the 'color' String object is not null before comparing it to a constant. I personally have always considered this as an unnecessary burden on the programmer – especially for modern OO languages such as Java. As a workaround, there exists a (really stupid) trick for rewriting the condition without having to test for nullity. Remember, the equals() method is symmetric (if a=b then b=a).
1if  "red".equals(color) ) {
2    System.out.println("Sorry, red is forbidden !");
3}
At first glance, it might be seen a bit contra-natural when read, but eliminating the polluting code is certainly not worthless.

Let's continue our example, and imagine we now want to compare our color with multiple values. Java beginners would usually write something like:
1if "red".equals(color) ||
2     "yellow".equals(color) ||
3     "blue".equals(color) ) {
4    System.out.println("This is a primary color");
5}
Sometimes met more experienced Java programmers shortening such long if statement with: 
1if "red|yellow|blue".indexOf(color)>=0 ) {
2    System.out.println("This is a primary color");
3}
Smart isn't it ? Not that much actually. Playing with substrings can be a dangerous game. For instance the following code might not give the expected results, especially if you are a man:
1String type = "man";
2...
3if "woman|child".indexOf(type)>=0 ) {
4    System.out.println("Women and children first !");
5}
If you are looking for a good balance between elegance and readability, you had better opt for one of the following alternatives.
01import java.util.HashSet;
02import java.util.Set;
03
04public static final Set<string> PRIMARY_COLORS;
05static {
06    PRIMARY_COLORS = new HashSet<string>();
07    PRIMARY_COLORS.add("red");
08    PRIMARY_COLORS.add("yellow");
09    PRIMARY_COLORS.add("blue");
10}
11...
12if ( PRIMARY_COLORS.contains(color) ) {
13    System.out.println("This is a primary color");
14}
Few people know it, but there is still a way to reduce code verbosity when initializing the Set of primary colors:
1public static final Set<string> PRIMARY_COLORS = new HashSet<string>() {{
2    add("red");
3    add("yellow");
4    add("blue");
5}};
In the event concision of code becomes an obsession, the Java Collections Framework can also come to the rescue:
1import java.util.Arrays;
2import java.util.Collection;
3
4public static final Collection<string> PRIMARY_COLORS = Arrays.asList("red""yellow", "blue");
5...
6if ( PRIMARY_COLORS.contains(color) ) {
7    System.out.println("This is a primary color");
8}
The final keyword prevents the PRIMARY_COLORS variable from being re-assigned to another collection of values – this is particularly important when your variable is defined as public. If security is a major concern, you should also wrap the original collection into an unmodifiable collection. This will guarantee a read-only access.
1import java.util.Arrays;
2import java.util.Collection;
3import java.util.Collections;
4
5public static final Collection<string> PRIMARY_COLORS =
6   Collections.unmodifiableCollection( Arrays.asList("red""yellow", "blue") );
7</string>
It must be noticed that, though more readable, using a collection of values (especially with large collections) will generally remain slower than classical lazy OR's (ie using '||' instead of '|') because of theshort-circuit evaluation. Nowadays such considerations become futile.

After 16 years of complaints, Java 7 has - at last! - introduced the support of String in switch-case statements. This allows us to code things such as:
01boolean primary;
02switch(color) {
03 case "red":
04     primary=truebreak;
05 case "green":
06     primary=truebreak;
07 case "blue":
08     primary=truebreak;  
09 default:
10     primary=false;
11}
12if (primary) System.out.println("This is a primary color");
Let us finally end with what is probably the most object-oriented solution to our (so to say) problem. Java enumerations are primarily classes, and can therefore have methods and fields just like any other classes. By applying the Template Method design pattern, one can define an abstract method (modeling the test) which has to be implemented by all subclasses (modeling the response of the test applied to a particular item of the enumeration):
01Color c = Color.valueOf("RED");
02if ( c.isPrimaryColor() ) {
03  System.out.println("This is a primary color");
04}
05
06public enum Color {
07     RED() {
08          @Override
09          public boolean isPrimaryColor() {
10              return true;
11          }
12     },
13     BLUE() {
14         @Override
15         public boolean isPrimaryColor() {
16               return true;
17          }
18     },
19     YELLOW() {
20         @Override
21         public boolean isPrimaryColor() {
22               return true;
23          }
24     };
25     GREEN() {
26         @Override
27         public boolean isPrimaryColor() {
28               return false;
29          }
30     };
31     public abstract boolean isPrimaryColor();
32}
The resulting code is clear and self-documenting. Using this pattern is a great alternative in many cases to the more common “if - else if” logic since it is easier to read, extend, and maintain.

To conclude, as very often - and this is the power of the Java language – for one problem, there exist so many different solutions in terms of implementation. But deciding which one is the best is another story...