Friday, February 25, 2011

Language Features of Java Generics

One of the main features introduced with Java 2SE 5.0 are generics; which provide the means to create general implementations for different types (a class or an Interface). Think about the possibility of creating a single Generic Stack class for every different type you wish to store, without the need to implement the same Stack functionality for the different types over and over again (StackOfIntegers, StackOfString, StackOfDoubles), just because it will hold elements of different types. It would be even nicer if besides the previous feature we could detect type mismatches at compile time; known as compile-time type safety. For example, if a Stack stores only Integers, attempting to push a String on to that Stack should issue a compile-time error. That is exactly what Java Generics is about; generic methods and classes enable programmers to specify with a single method declaration a set of related methods or, with a single class declaration a set of related types respectively. As well as providing compile-time type safety that allows programmers to catch invalid types at compile time.

Motivation of Generics

a) Code Reuse

Overloaded methods are often used to perform similar operations on different types. In the next example we can see three overloaded printArray methods, these methods print the String representation of the elements Integer, Double and Character arrays. It is important to note that only reference types can be used with generics, that’s why we cannot use their respective primitive types (int, double, char).
public static void printArray( Integer[] inputArray ){
for ( Integer element : inputArray )
System.out.printf( "%s ", element );
}

public static void printArray( Double[] inputArray ){
for ( Double element : inputArray )
System.out.printf( "%s ", element );
}

public static void printArray( Character[] inputArray ){
for ( Character element : inputArray )
System.out.printf( "%s ", element );
}
As you can see these three overloaded methods perform the exact same logic, the only difference between them is the type each method receives as a parameter and the type the for statement loops through. This example should be a good opportunity to write a generic method; it appears that if we can replace the array's element type in each of the three methods with a single generic type, then we should be able to declare one printArray method that can display the String representations of the elements of any array that contains objects. Let’s see how the new generic method will look:
    public static <T> void printArray( T[] inputArray )
{
// display array elements
for (T element : inputArray)
System.out.print(element + " ");

System.out.println();
} // end method printArray
Method printArray ‘s type parameter section declares type parameter T, as the placeholder for the array element type that printArray will process. T is replaced in the parameter list as the array element type as well it will be replaced in the for statement. These are the exact same locations where the overloaded printArray methods made use of Integer, Double, Character as the array element type.

As you can see writing overloaded methods to perform the same implementation might be in many cases time consuming, error prone and will make our code harder to maintain. By declaring printArray as a generic method we saved nearly 20 lines creating a reusable method that implements the same functionality regardless the type of element we are sending to it.

b) Compile-time type safety

Before Java 2SE 5.0 this kind of generic programming was achieved by means of Object references. For example a generic list was implemented as a collection of Object references. Since Object is the superclass of all classes the list of Object references can hold references to any type of Object. Elements were added to the collection by passing an element reference. Each time it was extracted an object from a collection it was received an Object reference. Before the retrieved element could be effectively used, we were suposed to restore the element’s type information. For this purpose it was required to cast the returned Object reference down to the elements type. Here is an example:
LinkedList list = new LinkedList();
list.add(new Integer(0));
Integer i = (Integer) list.get(0);
It was required to cast the Object reference returned from method get()and promise the compiler that we were going to assign an Integer reference to i . The cast is safe because it is checked at runtime. If we tried a cast to a type different from the extracted element’s actual type, a ClassCastException would be raised, like in the example below:
// fine at compile-time, but fails at runtime with a ClassCastException
String s = (String) list.get(0);
Now, this latter approach is not that effective because we cannot identify possible bugs until runtime (When the application crashes or in best case throws an error). Additionally, the lack of information about the collection’s element type required countless casts in all places where elements are extracted from a collection, making our code harder to read and unsafe. With generics, information about the type elements a collection might contain is provided to the compiler. Instead of treating every collection as a collection of Object references, we will distinguish between collections of references to integers and collections of references to Strings and so on. A collection type would be a parameterized (or generic) type that has a type parameter, which would specify the element type. With a generic list, the previous example would look like this:
LinkedList <Integer> list = new LinkedList <Integer> ();
list.add(new Integer(0));
Integer i = list.get(0);
With this approach the get()method of a generic list returns a reference to an object of a specified type, in this case Integer, that means the cast from Object to Integer is not required because the compiler knows the method will return an Integer from the list. As well, if the extracted element was of a different type would now be caught at compile time already, rather than at runtime. The example below would simply not compile:
String s = list.get(0); // compile-time error
This way, Java Generics provide programmers with a powerful capability for software reuse with compile-time type safety.

Wednesday, February 23, 2011

What is a Package?

Packages are namespaces that organize a group of related classes and interfaces. Packages can be thought as folders on your computer system. Many projects might contain html pages in one folder, images in another, scripts, interfaces and so on. Normally, a real world software written in Java contains hundreds or even thousands of Java classes, so it makes sense to keep all these files organized by placing related files into packages. Packages make easier to find related files and use them. As well packages are helpful because they avoid naming conflicts and facilitate control access.

Typical project structure using packages in Eclipse

The previous image depicts a project called Restaurant with 3 different packages: restaurant.api, restaurant.lib and test. And within the packages a set of related classes. One common example of packages can be found in the Java platform itself. In it, classes are included on various packages that bundle classes by function: fundamental classes are in java.lang, classes for reading and writing (I/O) are in java.io and so forth.

Suppose you write a group of classes that represent graphic objects, such as circles, rectangles, lines, and points. You also write an interface, Draggable, that classes implement if they can be dragged with the mouse.

//in the Draggable.java file
package graphics;
public interface Draggable {
. . .
}

//in the Graphic.java file
package graphics;
public abstract class Graphic {
. . .
}

//in the Circle.java file
package graphics;
public class Circle extends Graphic implements Draggable {
. . .
}

//in the Rectangle.java file
package graphics;
public class Rectangle extends Graphic implements Draggable {
. . .
}

//in the Point.java file
package graphics;
public class Point extends Graphic implements Draggable {
. . .
}

//in the Line.java file
package graphics;
public class Line extends Graphic implements Draggable {
. . .
}

Some of the advantages programmers can get by bundling related classes and interfaces in a package include the following :

  • You and other programmers can easily determine that these types(classes & interfaces) are related.

  • You and other programmers know where to find types that can provide graphics-related functions.

  • The names of your types won't conflict with the type names in other packages because the package creates a new namespace.

  • You can allow types within the package to have unrestricted access to one another yet still restrict access for types outside the package.

Thursday, February 17, 2011

What are interfaces?

As it was seen methods (behaviors) in objects define their interaction with the outside world. These method's form the interface which as well can interact with the outside world. Imagine the following scenario: You have been using the previous bike object defined before and you are very familiar with how to speedUp, changeGear, changeCadence, applyBrakes and so on. However, your bike is kind of old and you got a brand new bike. But, it turns out that even when the new bike speeds up, chages gear and applies breaks these methods are named different, so when you try to call the "applyBrakes" method you are used to your new bike simply won't respond because the method name was "bikeBrake", and after that things start getting very ugly.

Interfaces are special contracts that state which operations are performed and how to interact with certain objects. The remote control of your TV is the interface between you and the TV; you just press the turn on button and the TV turns on regardless the brand of the TV, so you don't need to know the details of how to turn on the TV for every kind of vendor; you just know that all TVs have a press turn on button and it will turn the TV on. (Additionally, probably the ACME TV's turn on implementation is different from SUPER TV, but you don't care!).

Software objects also communicate via interfaces. A Java interface describes a set of methods that can be called on an object, to tell the object to perform some task or return some piece of information.

In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:
interface Bicycle {

void changeCadence(int newValue);

void changeGear(int newValue);

void speedUp(int increment);

void applyBrakes(int decrement);
}
To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such as ACMEBicycle), and you'd use the implements keyword in the class declaration:
class ACMEBicycle implements Bicycle {

// remainder of this class implemented as before

}
Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

Interfaces have another very important role in the Java language and is that unlike C++ Java does not support multiple inheritance. However, a class can extend one superclass and implement as many interfaces as needed. This is very useful when you want to share behavior of unrelated objects. This allows objects of unrelated classes to be processed polymorphically, objects of classes that implement the same interface can respond to the same method calls.

This latter benefit of using interfaces will be discussed later, so if it sounds confusing don't bother much for the moment, and think about interfaces as a way of contract between the class and the outside world, and that this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile. Remember the example provided, if there was an standard interface between bike manufacturers probably its user would have known how to break because all bikes implementing the interface would have the same methods in this case applyBrakes.

Tuesday, February 15, 2011

StackOverflow & Programmers

One good way to keep yourself updated specially if you are out of university is reading and writing as much code as possible. Two excellent sites I usually peek daily are http://stackoverflow.com/ & http://programmers.stackexchange.com/ which are websites featuring questions and answers on a wide range of topics in computer programming. So basically the sites feature the ability for users to ask and answer questions, and, through membership and active participation, to vote questions and answers up or down and edit questions and answers in a wiki fashion. Users of Stack Overflow can earn reputation points and "badges"; for example, a person is awarded 10 reputation points for receiving an "up" vote on an answer given to a question, and can receive badges for their valued contributions.

They are very useful, addictive, and you can get very professional answers from amazing programmers. Many of them work for the most important companies in the software industry (i.e Google, Microsoft, Amazon, Oracle ..) have incredible curriculums and probably some of them have been involved in the development of many of your favorite applications.

Today I was a bit concerned about what managers and team leaders expect from Junior Programmers (yes.. I’m starting in 2 Weeks yay!!) and received really good advices from some of them. I think it's always good to hear different perspectives other than your owns and even better when they come from such a group of talented people..

If you are interested to read them here’s the link of the post and some of the answers. They are all really great, I still need to go through all of them to finally decide which answer to accept.

Link: Which skills would you expect and appreciate in a Junior Software Engineer??

So don’t wait and get advantage of it, start asking them for advices in how to improve your code or simply spend some time reading some of the posts; These sites are completely free and I can guarantee you will never stop learning and getting surprise of some people’s knowledge..

Monday, February 14, 2011

What is inheritance?

Real objects often have a certain amount of common similarities with each other. For example there are many types of Bicycles: mountain bikes, road bikes, tandem bikes and so on. However all of these bicycles share similarities like: current speed, current pedal, cadence, current gear. Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio. But, wouldn't it be great if we could just tell all our bikes to absorb sharing similarities and just worry about the new features the new bike will offer. Well, we can achieve this by using inheritance. (I won't write here about when to use inheritance, best practices, types of inheritance and so on. Hopefully, more on that in future posts, by now just the basic definition)

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:



With inheritance, programmers save time during program development by reusing proven and debugged high-quality software. This also increases the likelihood that a system will be implemented effectively.

When creating a class, rather than declaring completely new shared state and behaviors, you can designate that the new class should inherit them of an existing class. The existing class is called the superclass, and the new class is the subclass. (The C++ programming language refers to the superclass as the base class and the subclass as the derived class.) Each subclass can become the superclass for future subclasses.

The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from

class MountainBike extends Bicycle {

//new fields and methods defining a mountain bike would go here

}
In this example this gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.