The TechGuy

September 8, 2012

Java to Groovy by Example – HelloWorld

Introduction

Groovy is another language for Java Virtual Machine. It’s built on Java, seamlessly integrates with existing Java classes, and compiles to byte code. It’s Object-Oriented (even more where numbers are also objects), and supports the same programming model as Java. However, it’s also a dynamic language with additional powers like scripting and DSL. It reduces scaffolding code that makes it more readable, maintainable and increases productivity.

Groovy is very similar in syntax with java, so developers from java side can learn it easily. It also supports java syntax that means some of java programs can also run over groovy. To learn it we first look at a simple Hello World java program, and then we discuss line by line groovy versions of this java code.

Traditional Java Program

Let’s have a look at simple hello world java program,

  1. public class HelloWorld {
  2. public static void main(String[] args) {
  3. System.out.println("Hello World!");
  4. }
  5. }

HelloWorld is always used as very basic example to learn any programming language. We start with this to easily understandable class HelloWorld, which contains entry point method main. And it prints “Hello World!” on the program console. Now start migrating from this java code to groovy code/script.

First step to Groovy

As I mention earlier some of the java programs may also run over groovy without changing a single line of code. Exactly, this program can also run in groovy environment and it behaves same. Although, it can run over groovy but we can’t say it a groovy program. First of all we remove some scaffolding code to improve code readability.

If we look at the very first line of the java code, it’s a class declaration with public access modifier.

Class and all its methods are by default public in groovy.

So there is no need to explicitly specify public with class declaration or even with main method.

Semicolon is a very basic element in a program structure, in java semicolon is mandatory for statement termination.

Semicolons are optional in Groovy.

Note: But there are some situations where you need to use the semicolons in your groovy application for smooth execution.

For now we can remove all the semicolons in our program and it will work fine. Java is a statically typed language, whereas groovy is not that;

Groovy supports dynamic typing.

So we can drop argument’s type information from the main declaration.

Default return type is void

Based on this default behavior we can ignore void from main method and the signature of main would be just static main(args).

Lots of new helper methods are added to the groovy JDK. It gives handy methods and shortcuts for some routine tasks such as console printing. You can replace System.out.println() with just println(). At this level we are almost done with scaffolding and lets see how code looks like with these changes.

  1. class GreetWorld {
  2. static main(args) {
  3. println("Hello World!")
  4. }
  5. }

It’s really neat and handsome piece of code that is very easy to understand.

Wait for a minute

Groovy is a scripting language as it allows you to write some free form programs that don’t require you to define a class structure.  We may use these scripts in Unix shell, in our existing java code or just on command line.

We can optionally omit parentheses for top-level statements (a statement which is just a method call with some parameters). So at the end we leave main method back in java and use just the code as script in groovy.

Here it is, the smallest hello world example in groovy presented to you;

  1. println "Hello World!"

Wow! It’s really awesome; the groovyfied code is much more readable, succinct and crispy.

If we compile the above script to bytecode using groovyc, it will generate a single class named after the name of the script file. e.g. if this was saved in HelloWorld.script, a HelloWorld.class file will be the output just like java. When we execute this class, it execute the autogenerated main(String[] args) method in the bytecode.

Last but not Least

At the end we recap all in few points to summarize as a feature list that we learned in this post.

  • Class and all its methods are by default public.
  • Semicolons are optional.
  • Dynamic and static typing is supported.
  • Default return type is void.
  • May omit parentheses.
  • Groovy is a scripting language.

Where to go next

You can get more familiar with groovy, some advance concepts in the next part.

September 6, 2012

Java to Groovy by Example – Part 2

Introduction

In the last post we lean very basic concepts from groovy. We also map an example from java to groovy code and then a very simple script. We have also learned that classes are defined in Groovy similarly to Java. Each class in Groovy is a Java class at the bytecode / JVM level. Any methods declared will be available to Java and vice versa. We also learned some of the basic rules/features of groovy;

  • Class and all its methods are by default public.
  • Semicolons are optional.
  • Dynamic and static typing is supported
  • Default return type is void
  • Omit parentheses
  • Groovy is a scripting language

Java Sample Code

In this part we look at some advance HelloWorld java program,

  1. public class GreetWorld {
  2. private String salutation;
  3. public void setSalutation(String salutation) {
  4. this.salutation = salutation;
  5. }
  6. public String getSalutation() {
  7. return salutation;
  8. }
  9. public String greet(String name) {
  10. return salutation + " " + name + "!";
  11. }
  12. public static void main(String[] args) {
  13. GreetWorld hello = new GreetWorld();
  14. hello.setSalutation("Hello");
  15. System.out.println(hello.greet("Java"));
  16. }
  17. }

It’s a simple class GreetingWorld, designed to generate greeting message. There is a private field to preserve salutation with associated setter and getter. You can find a method greet that used to generate the greeting message, it receives a parameter to associate name with the message. Now let’s see how groovy code looks like for this program.

Groovy version

If we look at line 2 to 10, there is a private field with associated setter and getter.

Groovy support properties - fields and properties have been merged in groovy so that they act and look the same.

Rather than creating a private field for salutation and writing a getter and setter, we can simply declare it as a property without any explicit access modifier. When groovy is compiles to byte code, following rules will apply;

  • If the data member is declared with an access modifier (public, private or protected) then a field is generated.
  • A data member declared with no access modifier generates a private field with public getter and setter (i.e. a property).
  • If a property is declared final the private field is created final and no setter is generated.
  • You can declare a property and also declare your own getter or setter.
  • You can declare a property and a field of the same name, the property will use that field then.
  • If you want a private or protected property you have to provide your own getter and setter which must be declared private or protected.

Note that properties need some kind of identifier: e.g. a variable type (String)

Based on these rules, our salutation property will be just String salutation, nothing more. A private field and associated getter and setter will be provided by Groovy automatically. For calling setSalutaion("Hello"), you need to write hello.salutation = "Hello", and for getSalutaion(), simply hello.salutaion. This also means that you can call getSalutaion() and setSalutaion("Hello") from a Java program(invoking our Groovy class) too.

As we move further in our java code, we have a public method greet ahead which receives a String parameter and returns a String as well. In java, there has to be a return statement if your method has the return type.

The return statement is optional in Groovy, it return the last statement of the method as return type.

But you can put it if you like to put. In our code, we can remove return keyword from the greet method. As you remember we already remove public modifier from each of our methods earlier, now code looks simpler and easy to read and understand.

There is another very nice feature that we can apply on this method and that is Groovy’s special string.

The GString, you can embed expressions inside strings.

Inside a normal string, you can put some place holders delimited with curly-brasses like ${someVariable} or just a dollar sign ahead like $someVariable, that will be replaced automatically by the value of the variable or expression when the string will be used. So you don’t need to bother about manually concatenating strings.

Java is a strongly typed language; whereas groovy,

Dynamic and static typing is supported – so you can omit the type declarations on methods, fields and variables.

Thus we can get rid of all the types if we wish so, and even don’t mention types with arguments of methods. For dynamic type variables there is a def keyword that we can use to define different properties/variables. Here we can change all String declarations to def and also can omit argument type in our greet method.

At this level we are almost done with the greet method. As we learned in the last post, groovy is a scripting language as it allows you to write some free form programs that don’t require you to define a class structure. So we don’t need main method and use just the code as script in groovy outside class.

  1. class GreetWorld {
  2. def salutation
  3. def greet(name) { "$salutation ${name}!" }
  4. }
  5. def hello = new GreetWorld()
  6. hello.salutation = "Hello"
  7. println hello.greet("Groovy")

Voila! It’s really neat and handsome piece of code that is very easy to understand.

Last but not Least

At the end we recap all in few points to summarize as a feature list that we learned in this post.

  • Support properties - fields and properties have been merged in groovy so that they act and look the same.
  • The return statement is optional in Groovy, it returns the last statement of the method as return type.
  • The GString, you can embed expressions inside strings.
  • Dynamic and static typing is supported

Where to go next

You can get more familiar with groovy, some advance concepts in the next part.

August 28, 2012

JS based Grid comparison

Filed under: Grid,Javascript,UI Components — Zeeshan Bilal @ 4:33 PM
Tags: , , , , , , , , ,
JS based Grid comparison – Matrix
  jqGrid SmartClient dojo ZK YUI DHX EditableGrid
               
Feature
Cell Editing

Yes

Yes

Yes

Yes

Yes

Yes

Row Editing

Yes

Yes

Yes

Yes

Textbox

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Checkbox

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Combo

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Radio

Yes

Yes

Yes

Yes

Calendar

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Textarea

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Button

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Custom edit

Yes

Yes

Yes

Yes

Yes

Disable edit

Yes

Yes

Yes

Yes

Yes

Yes

Style(cell BG)

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Validation

Yes

Yes

Yes

Add row

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Delete row

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Hidden column

Yes

Yes

Yes

Yes

Events

Yes

Yes

Yes

Selection Tree

Possible

Yes

Yes

No

General
License GPL & MIT LGPL GPL LGPL BSD GPLv2 GPL & MIT
IE support 6+ 6+ 6+ 6+ 6+ 6+ 6+
Demo Examples Showcase Examples Demo Examples Samples Demo
Related links
http://en.wikipedia.org/wiki/Comparison_of_JavaScript_frameworks
http://www.hotscripts.com/blog/15-javascript-data-grids-enhance-html-tables/
http://msdn.microsoft.com/en-us/library/ee536561.aspx

July 30, 2012

BitBucket(Git) configuration in xcode

Filed under: iOS,xcode — Zeeshan Bilal @ 12:10 AM
Tags: , , ,

Please follow these steps to configure bitbucket repository in xcode

  1. Opens xcode and use option ‘connect to a repository’
  2. Specify following location https://bitbucket.org/location/project.git, i didn’t use username as in repository url in bitbucket
  3. specify the name as ‘project’ and ‘git’ as type and press clone
  4. specify folder name and location to clone the repo and press clone again
  5. there may be an access deny message, don’t be afraid just press try again
  6. a prompt for user name and password will appear, specify the credentials and press ok
  7. close xcode and delete if these is any directory as it may created in step 4
  8. open keychain and find key named bitbucket.org and open it
  9. go to access control tab and chose very first option ‘allow all application to access this item’ and save changes
  10. repeat step 1-5, remember this time maybe some error messages will come but be patient and keep trying 2-3 times. Eventually you will succeed.

Note: At this time, due to tight schedule i didn’t investigate the problems. And i knew this method seems not that good, but results are definite.

feel free to comment. :)

August 12, 2011

Java 7 – Language Enhancements (Part 2)

Previously (in Part 1), we had learned the basic enhancements of Java 7, which includes Binary Literals, Underscores in Numeric Literals, Strings in switch Statements and Type Inference for Generic Instance Creation. Here we will take a look at exception handling updates like try-with-resources statement, catching multiple exceptions in single catch and more. Lets continue our topic:

The try-with-resources Statement

The try-with-resources statement is a try statement that declares one or more resources. A resource is as an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:


 
static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException { BufferedReader br = new BufferedReader(new FileReader(path)); try { return br.readLine(); } finally { if (br != null) br.close(); } }
 

As we can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. Java SE 7, provides a new try-with-resources statement to perform the same operation with better managibility:


 
static String readFirstLineFromFile(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } }
 

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resources statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

However, in the first example, if the methods readLine and close both throw exceptions, then the method readFirstLineFromFileWithFinallyBlock throws the exception thrown from the finally block; the exception thrown from the try block is suppressed. In contrast, in the example readFirstLineFromFile, if exceptions are thrown from both the try block and the try-with-resources statement, then the method readFirstLineFromFile throws the exception thrown from the try block; the exception thrown from the try-with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions.

You may declare one or more resources in a try-with-resources statement. The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:


 
public static void writeToFileZipFileContents(String zipFileName, String outputFileName) throws java.io.IOException { java.nio.charset.Charset charset = java.nio.charset.Charset.forName("US-ASCII"); java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName); // Open zip file and create output file with try-with-resources statement try ( java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName); java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset) ) { // Enumerate each entry for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) { // Get the entry name and write it to the output file String newLine = System.getProperty("line.separator"); String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine; writer.write(zipEntryName, 0, zipEntryName.length()); } } }
 

In this example, the try-with-resources statement contains two declarations that are separated by a semicolon: ZipFile and BufferedWriter. When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of the BufferedWriter and ZipFile objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation.

The following example uses a try-with-resources statement to automatically close a java.sql.Statement object:


 
public static void viewTable(Connection con) throws SQLException { String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES"; try (Statement stmt = con.createStatement()) { ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String coffeeName = rs.getString("COF_NAME"); int supplierID = rs.getInt("SUP_ID"); float price = rs.getFloat("PRICE"); int sales = rs.getInt("SALES"); int total = rs.getInt("TOTAL"); System.out.println(coffeeName + ", " + supplierID + ", " + price + ", " + sales + ", " + total); } } catch (SQLException e) { JDBCTutorialUtilities.printSQLException(e); } }
 

The resource java.sql.Statement used in this example is part of the JDBC 4.1 and later API.

Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

Handling More Than One Type of Exception

In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.

Consider the following example, which contains duplicate code in each of the catch blocks:


 
catch (IOException ex) { logger.log(ex); throw ex; catch (SQLException ex) { logger.log(ex); throw ex; }
 

In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable ex has different types.

The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:


 
catch (IOException|SQLException ex) { logger.log(ex); throw ex; }
 

The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).

Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.

Bytecode generated by compiling a catch block that handles multiple exception types will be smaller (and thus superior) than compiling many catch blocks that handle only one exception type each. A catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler; the bytecode has no replication of exception handlers.

Rethrowing Exceptions with More Inclusive Type Checking

The Java SE 7 compiler performs more precise analysis of rethrown exceptions than earlier releases of Java SE. This enables you to specify more specific exception types in the throws clause of a method declaration.

Consider the following example:


 
static class FirstException extends Exception { } static class SecondException extends Exception { } public void rethrowException(String exceptionName) throws Exception { try { if (exceptionName.equals("First")) { throw new FirstException(); } else { throw new SecondException(); } } catch (Exception e) { throw e; } }
 

This examples’s try block could throw either FirstException or SecondException. Suppose you want to specify these exception types in the throws clause of the rethrowException method declaration. In releases prior to Java SE 7, you cannot do so. Because the exception parameter of the catch clause, e, is type Exception, and the catch block rethrows the exception parameter e, you can only specify the exception type Exception in the throws clause of the rethrowException method declaration.

However, in Java SE 7, you can specify the exception types FirstException and SecondException in the throws clause in the rethrowException method declaration. The Java SE 7 compiler can determine that the exception thrown by the statement throw e must have come from the try block, and the only exceptions thrown by the try block can be FirstException and SecondException. Even though the exception parameter of the catch clause, e, is type Exception, the compiler can determine that it is an instance of either FirstException or SecondException:


 
public void rethrowException(String exceptionName) throws FirstException, SecondException { try { // ... } catch (Exception e) { throw e; } }
 

This analysis is disabled if the catch parameter is assigned to another value in the catch block. However, if the catch parameter is assigned to another value, you must specify the exception type Exception in the throws clause of the method declaration.

In detail, in Java SE 7 and later, when you declare one or more exception types in a catch clause, and rethrow the exception handled by this catch block, the compiler verifies that the type of the rethrown exception meets the following conditions:

  • The try block is able to throw it.
  • There are no other preceding catch blocks that can handle it.
  • It is a subtype or supertype of one of the catch clause’s exception parameters.

The Java SE 7 compiler allows you to specify the exception types FirstException and SecondException in the throws clause in the rethrowException method declaration because you can rethrow an exception that is a supertype of any of the types declared in the throws.

In releases prior to Java SE 7, you cannot throw an exception that is a supertype of one of the catch clause’s exception parameters. A compiler from a release prior to Java SE 7 generates the error, “unreported exception Exception; must be caught or declared to be thrown” at the statement throw e. The compiler checks if the type of the exception thrown is assignable to any of the types declared in the throws clause of the rethrowException method declaration. However, the type of the catch parameter e is Exception, which is a supertype, not a subtype, of FirstException andSecondException.

August 9, 2011

Java 7 – Language Enhancements (Part 1)

After nearly five year (on July 2011), Java SE 7 has been released! With Project Coin, the new Fork/Framework, the New File System API (NIO.2), and more. Java SE 7 is an important step in Java’s evolution. There are number of enhancements in the programming language, listed below.

  • Binary Literals
  • Underscores in Numeric Literals
  • Strings in switch Statements
  • Type Inference for Generic Instance Creation
  • Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods
  • The try-with-resources Statement
  • Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking

Binary Literals

In Java SE 7, the integral types (byteshortint, and long) can also be expressed using the binary number system. To specify a binary literal, add the prefix 0b or 0B to the number. Declarative uses of binary literals are demonstrated below:

An 8-bit byte value:


byte
ab = (byte)0b00100001;

An 16-bit short value:


short
as = (short)0b1010000101000101;

Few 32-bit int values:


int
ai = 0b10100001010001011010000101000101;
int ai2 = 0B101; // The B can be upper or lower case.

An 64-bit long value. Note the L suffix:


long
al = 0b1010000101000101101000010100010110100001010001011010000101000101L;

Binary literals can make relationships among data more apparent than they would be in hexadecimal or octal. For example, each successive number in the following array is rotated by one bit:


public static final int
[] phases = {
   0b00110001,
   0b01100010,
   0b11000100,
   0b10001001,
   0b00010011,
   0b00100110,
   0b01001100,
   0b10011000
}

In hexadecimal, the relationship among the numbers is not readily apparent:


public static final int
[] phases = {
   0×31, 0×62, 0xC4, 0×89, 0×13, 0×26, 0x4C, 0×98
}

You can use binary literals to make a bitmap more readable:


public static final short
[] HAPPY_FACE = {
   (short)0b0000011111100000;
(
short)0b0000100000010000;
(
short)0b0001000000001000;
(
short)0b0010000000000100;
(
short)0b0100000000000010;
(
short)0b1000011001100001;
(
short)0b1000011001100001;
(
short)0b1000000000000001;
(
short)0b1000000000000001;
(
short)0b1001000000001001;
(
short)0b1000100000010001;
(
short)0b0100011111100010;
(
short)0b0010000000000100;
(
short)0b0001000000001000;
(
short)0b0000100000010000;
(
short)0b0000011111100000;
}

Uses of binary literals in bit wise operations also help to understand the logic and program structure.

Underscores in Numeric Literals

Any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code. For instance, if your code contains numbers with many digits, you can use an underscore character to separate digits in groups of three, similar to how you would use a punctuation mark like a comma, or a space, as a separator. The following example shows other ways you can use the underscore in numeric literals:


long
creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
float pi = 3.14_15F;
long hexBytes = 0xFF_EC_DE_5E;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_ffff_ffff_ffffL;
byte nybbles = (byte)0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;

You can place underscores only between digits; you cannot place underscores in the following places:

  • At the beginning or end of a number
  • Adjacent to a decimal point in a floating point literal
  • Prior to an F or L suffix
  • In positions where a string of digits is expected

The following examples demonstrate valid and invalid underscore placements (which are highlighted) in numeric literals:


float
pi1 = 3_.1415F;
// Invalid; cannot put underscores adjacent to a decimal point
float pi2 = 3._1415F; // Invalid; cannot put underscores adjacent to a decimal point
long socialSecurityNumber1 = 999_99_9999_L; // Invalid; cannot put underscores prior to an L suffix
int x1 = _52; // This is an identifier, not a numeric literal
int x2 = 5_2; // OK (decimal literal)
int x3 = 52_; // Invalid; cannot put underscores at the end of a literal
int x4 = 5_______2; // OK (decimal literal)
int x5 = 0_x52; // Invalid; cannot put underscores in the 0x radix prefix
int x6 = 0x_52; // Invalid; cannot put underscores at the beginning of a number
int x7 = 0x5_2; // OK (hexadecimal literal)
int x8 = 0x52_; // Invalid; cannot put underscores at the end of a number
int x9 = 0_52; // OK (octal literal)
int x10 = 05_2; // OK (octal literal)
int x11 = 052_; // Invalid; cannot put underscores at the end of a number

Strings in switch Statements

You can use the String class in the expression of a switch
statement.


public
String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
String typeOfDay;
switch (dayOfWeekArg) {
case “Monday”:
typeOfDay = “Start of work week”;
break;
case “Tuesday”:
case “Wednesday”:
case “Thursday“:
typeOfDay = “Midweek”;
break;
case “Friday”:
typeOfDay = “End of work week”;
break;
case “Saturday”:
case “Sunday”:
typeOfDay = “Weekend”;
break;
default:
throw new IllegalArgumentException(“Invalid day of the week: “ + dayOfWeekArg);
}
return typeOfDay;
}

The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-else-then statements.

Type Inference for Generic Instance Creation

You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond. For example, consider the following variable declaration:


Map<String, List<String>> myMap = new HashMap<String, List<String>>();

In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>):


Map<String, List<String>> myMap = new HashMap<>();

Note that to take advantage of automatic type inference during generic class instantiation, you must specify the diamond. In the following example, the compiler generates an unchecked conversion warning because the HashMap() constructor refers to the HashMap raw type, not the Map<String, List<String>> type:


Map<String, List<String>> myMap = new HashMap(); // unchecked conversion warning

Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:


List<String> list = new ArrayList<>();
list.add(“A”);
// The following statement should fail since addAll expects Collection<? extends String>
list.addAll(new ArrayList<>());

Note that the diamond often works in method calls; however, it is suggested that you use the diamond primarily for variable declarations.

In comparison, the following example compiles:


// The following statements compile:
List<? extends String> list2 = new ArrayList<>();
list.addAll(list2);

There are some other examples and uses of Type Interface of Generic Instance Creation that we will cover in our next part (Part 2) with remaining three language enhancements.

June 18, 2011

Charts in iOS

Filed under: Chart,Framework/APIs,iOS — Zeeshan Bilal @ 4:49 AM
Tags: , ,

Last day i was working on client requirments to provide prototype for an iOS based application. I was looking for some chart API or some framework that helps me to draw chart in native or as alternate in UIWebView. I found some and want to share with you guys.

1) http://code.google.com/p/core-plot/

2) http://code.google.com/p/s7graphview/

3) http://github.com/duivesteyn-enterprises/deSimpleChart

4) http://www.rgraph.net/ (Will work on UIWebView only)

5) http://sebkade.wordpress.com/2010/05/06/basic-graph-class-for-iphone/ (a blog where demo is given to create a graph)

April 28, 2011

Design Patterns by Examples – Decorator Pattern

Introduction

This series of articles will help you to build a good understanding of design patterns using different examples from real life and some from well-known frameworks or APIs. There are many articles around the web that discuss design patterns but they sometimes lack appropriate examples to quote. So, either their purpose stays unclear or we cannot memorize the patterns longer and sooner they slip out of mind. More importantly, we understand them but to employ within our problem domain is again out of the quest.

Expert designers reuse solutions that they had worked on in the past and they re-engage them whenever they faced with the same problems. Rookie designers can also use design patterns to solve their problems efficiently. This article is intended to help both naive and expert developers by making them understand the application of patterns and opening up new dimensions in solutions domain.

Decorator Pattern

For the sake of continuity, let’s look at the formal definition first.

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.


At this stage you might not understand it clearly but as you go through the whole article you will gain better understanding of the pattern and would defiantly want to use it to solve your own domain problems.

In this part of the article I totally concerned about dynamic behaviors that most readers expect from pattern, decorator is not just design as well as analysis pattern too, we will discuss this in next part. So ignore NewState field in ConcreteDecoratorA for this time.

Problem Domain

To keep things simpler we take an example of a subsystem, where employees are working with different responsibilities (such as team members, team leads and a manager). A team member is responsible to do his assigned tasks and to coordinate with other members for the completion of group tasks. On the other hand, a team lead has to manage and collaborate with his team members and plan their tasks. Similarly, a manager has some extra responsibility over a team lead such as employee profiling, work assignment.

Following are the system entities and their behaviors:

Employee: calculate salary, join, terminate.

Team member: perform task, coordinate with others.

Team lead: planning, motivate.

Manager: assign task, employee profiling, create requirements.

There may be some other entities like Team, Task, etc. but my focus here is to convey the idea of a Decorator while keeping things simple and paying attention on root of pattern.

Traditional Approach

In such a system, the most followed approach is to make an employee super class and extend it to all three classes. Even this is an object oriented approach but it has some drawbacks.

Whenever a team member becomes a team lead, we have to create a new object of team lead and the previous object that points to that employee (team member) may be destroyed or archived. That’s not a recommended approach when employee is still a part of your organization. Same is the case with manager, when an employee turns into a manager from a team lead/team member.

Another case is when an employee can perform responsibilities of a team member as well as those of a team lead or a manager can perform team leads responsibilities. In that case you need to create two objects for the same employee which is totally wrong.

In these scenarios a team member/team lead can have extra responsibilities at run time. And their responsibilities can be assigned/revoked at run time.

Decorator Pattern Approach

Let’s see how design patterns help in these cases. If we look at Decorator Pattern it says:

Attach additional responsibilities to an object dynamically.

Wow, can it really solve my problem, let’s see.

At this moment we defector our previous approach in such a way that we always register just an Employee and TeamMember, TeamLead and Manager will be decorator of that employee object.

Now, if we want to change responsibilities of an employee to manager we just need a new Manager (Decorator) and assigning that employee to it will solve our problem. Same is the case when a team lead’s responsibilities are revoked, and some other member becomes team lead, we just need to swap employee objects within TeamMember and TeamLead decorators.

As for the case where an employee can perform the responsibilities of a team member as well as those of a team lead, we just need TeamMember and TeamLead decorators that are pointing to same employee object.

Employee (Decorated/Component)

Implementation of Employee is as follows:


public interface
Employee {

public void join(Date joinDate);
public void terminate(Date terminateDate);

// other behaviors may reside (see sample code)
}

EmployeeImpl

This is the core implementation class of Employee interface, EmployeeImpl is given below:


public class
EmployeeImpl implements Employee {


// other behaviors and properties may reside (see sample code)
public void join(Date joinDate){
print(this.getName() + ” joined on “ + joinDate);
}

public void terminate(Date terminateDate){
print(this.getName() + ” terminate on “ + terminateDate);
}
}

EmployeeDecorator (Abstract Decorator)

This is an abstraction of Employee decorator, EmployeeDecorator is given below:


public abstract class EmployeeDecorator implements Employee {

protected Employee employee;

protected EmployeeDecorator(Employee employee) {
this.employee = employee;
}

// other behaviors may reside (see sample code)

public void join(Date joinDate) {
employee.join(joinDate);
}

public void terminate(Date terminateDate) {
employee.terminate(terminateDate);
}
}

TeamMember/TeamLead/Manager (Concrete Decorator)

These are concrete implementations of EmployeeDecorator, classes are given below:


public class TeamMember extends EmployeeDecorator {

protected TeamMember(Employee employee) {
super(employee);
}

public void performTask() {
print(employee.getName() + ” is performing his assigned tasks.”);
}

public void coordinateWithOthers() {
print(employee.getName() + ” is coordinating with other members of his team.”);
}

}

public class TeamLead extends EmployeeDecorator {

protected TeamLead(Employee employee) {
super
(employee);
}


public void planing() {
print(this.employee.getName() + ” is planing.”);
}

public void motivate() {
print(this.employee.getName() + ” is motivating his members.”);
}

}

public class Manager extends EmployeeDecorator {

protected Manager(Employee employee) {
super
(employee);
}

public void assignTask() {
print(this.employee.getName() + ” is assigning tasks.”);
}

public void profileEmployee() {
print(this.employee.getName() + ” is profiling employees.”);
}

public void createRequirments() {
print(this.employee.getName() + ” is creating requirement documents.”);
}

}

Some Example from APIs

There are many application of decorator in our routine APIs, like in I/O Streams and Readers use decorator pattern extensively.

In this example FilterInputStream, BufferedInputStream, DataInputStream and PushbackInputStream are decorators and FileInputStream and ByteArrayInputStream are decorated objects.


InputStream inStream = new FileInputStream(“data.txt”);

Here inStream is a simple file input stream and



inStream = new BufferedInputStream(inStream);

Now inStream is decorated by BufferedInputStream decorator. At runtime the BufferedInputStream, which is a decorator, forwards the method call to its decorated object FileInputStream. The decorator will apply the additional functionality of buffering around FileInputStream.

SiteMash is also one of the examples of decorator pattern in java web frameworks to decorate page.

Basic steps to use Decorator

To implement the decorator pattern you can just follow these steps:

  1. Create an abstract class or interface that you want to decorate. (e.g; Employee) and provide concrete implementation of that class/interface by extending it.
  2. Create an abstract decorator (e.g; EmployeeDecorator) that contains pointer field of decorated class, decorator must extend same decorated class/interface. (e.g; Employee)
  3. Pass the object that you want to decorate in the constructor of decorator.
  4. Redirect methods of decorator to decorated class’s core implementation.
  5. Override methods where you need to change behavior.

Conclusions

  • Decorators are very flexible alternative of inheritance.
  • Decorators enhance (or in some cases restrict) the functionality of decorated objects.
  • They work dynamically to extend class responsibilities, even inheritance does same but in a static fashion (means compile time).

Design Patterns

The key to any solution is to understand the problem. When we have complete requirements of our problem domain, the proper analyses of those requirements will facilitate us when incorporating any possible changes in the future. We have to suggest some design that can support current requirements and any possible changes. Therefor we use our past experience or shared thoughts of experts (Design Patterns) to design an elegant, flexible and reusable solution, and try to avoid redesigning or at least minimize it.


Design patterns are solutions to design problems you find again and again in real world application development.

Design patterns are not actually APIs that can be programmed in classes and reused as they are, neither are they are not domain-specific designs for any application or module. Design patterns actually are guidelines for communicating objects and classes that are customized to solve a general design problem in a particular context.

The Rubric Theme Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 39 other followers