iPhone SDK – Initial Thoughts

I have been following iPhone since its inception. Initially, when Steve Jobs revealed that there was not going to be any developer SDK, I was just one of the millions to be really upset. Then, one fine day the iPhone SDK was released, the now infamous App Store was released, all are happy and the rest is history. I did try out some examples immediately after the SDK was released but then got busy with other interesting stuff (like trying out a startup) and didn’t focus much on it – until recently.

A few months ago, my company picked me to get trained on the iOS SDK. Five days of Objective-C and XCode and Interface Builder later, I was coding for the fifth mobile platform in my career. I initially started with BREW, moved on to J2ME (now Java ME), then Blackberry (includes J2ME), then into the Bold and Beautiful Android and now into iOS.

I cannot help but compare my Android experience with iOS. Coming from a Java background, it should not be a surprise that I will be comfortable with Android SDK than with the iOS SDK. Even when that is the case, I feel that the iOS SDK and its tools is not all that developer friendly compared to Android. Apple has created the best layman products ever but they are quite bad at creating developer products, I guess.

Objective-C as a language is a lot more difficult to master than Java. The complex memory management gymnastics, multiple files to define one class and weird method definition syntax are just a few of my gripes. XCode 3.x is a hell to work with at least from an Eclipse/Netbeans/Idea user perspective. Why should I have to move between two applications called XCode and Interface Builder to develop one iPhone app? Why can’t I develop in Windows or Linux if I want to? Why doesn’t the debugger work well most of the times? Why isn’t Garbage Collection part of the language? Why isn’t incremental compilation available? These are just a few questions that come to my mind when I develop for iOS…

That said there are quite a bit to like about the iOS platform as well. Objective-C has some cool features like id type, protocols, named parameters and categories that I would have loved Java to have. I keep hearing from people that once you deploy an iPhone app in the App Store, the benefit in terms of payback is good enough to justify the pain. Interface Builder is very good at what it does compared to the equivalent Android designer. XCode 4.x vastly improves the development experience by integrating Interface Builder tightly.

Although both iOS and Android are vastly different platforms, they are together ruling the world today. As developers we don’t have a choice other than learning and working with these heavenly beasts until the cross-platform world for mobile (like PhoneGap, Titanium, Rho Mobile etc) matures

Intellij IDEA key map for Eclipse

Eclipse and IDEA logo

It is not the least easy to switch to Eclipse after years of addiction to Intellij IDEA. IDEA is the best IDE I have worked with until now and will continue to remain that way until there is another visionary who attempts to improve the developer pleasure instead of just technical modularity. Eclipse may (or may not) have a better architecture, better design, better modularity, incomparable number of plug-ins and better written code than IDEA, but that doesn’t seem to attract the end developers like me.

I just love IDEA for the way it understands me, knows what I am trying to do at any moment and most importantly for the complete integrated development experience it gives. That doesn’t mean that Eclipse is not famous. Eclipse is very famous and many people love it too. But I think it is because it is free and more so because every other software vendor creates plug-ins for eclipse and that level of community support is not there for Netbeans or IDEA.

Anyways, recently when I had to switch to Eclipse for a few months for one particular development project, I was not a happy camper. I wanted to bring at least some level of IDEA like familiarity into Eclipse and with a happy accident I was able to get to the IDEA key scheme for Eclipse. I sincerely thank Santhosh for having created an Eclipse plug-in for that. It works as advertisied except for a very few gotchas.

To create an IDEA key scheme for your Eclipse Helios installation, download the plug-in from here. Drop the downloaded jar file into $ECLIPSE_HOME\plugins folder and restart Eclipse. Then goto Window -> Preferences -> General -> Keys and modify the scheme drop-down to change it from “Default” to “Intellij IDEA”. Click Apply and OK and you are done. Every key combination like Ctrl+N, Ctrl+Shift+N, Alt+F7, Shift+F6, Ctrl+F12, Ctrl+Shift+-, etc should work as expected.

It did not give me THE COMPLETE IDEA experience but I guess this is the best I could get for now. If anyone has any suggestions for a better IDEA experience please do share them in the comments section. I most definitely will be grateful.

Android: My HTC Desire

I bought an HTC Desire few months back and I am loving it. It is powerful, has froyo, Wifi Hotspot, Voice to Text, a powerful Swype Keyboard (I bought it), AMOLED display, excellent applications and looks pretty cool too. I even bought an expensive Piel Frama case for it.

Got a few gripes though. It’s battery doesn’t last a whole day with 3G or WiFi switched on. So, initially I had to manually switch back and forth a couple of times to get through the day. After I bought another USB charger, exclusively for office, that problem is kind of solved.

Another issue is its internal storage. It just has 512 MB of internal storage and I frequently keep receiving the “Low space” notification and froyo’s official APP2SD is not of much help. After I rooted my phone and installed the unofficial APP2SD, that problem is also kind of solved. Further research revealed that with some more geeky stuff I can make Android think of my SD card as internal memory. Haven’t tried that yet though… Will keep my blog updated when I succeed.

I have another minor issue too. I use todoist regularly to manage my tasks and I couldn’t find any one good todoist android app. There are quite a few unofficial and buggy apps but they are just not usable to say the least. I guess this is a problem I can solve myself. I am thinking of writing my own todoist client for android. Let’s see how this works out… Again, will keep my blog updated on the happenings…

Tomcat 5.5 and above doesn’t need the JDK

Most of us who install Tomcat on our development machines wouldn’t have noticed that Tomcat versions before 5.5 required the full blown Java Development Kit (JDK) to be installed on the machine. Just installing the Java Runtime Environment (JRE) wasn’t enough. The JDK is meant for developers to be able to compile Java programs, and has the development tools such as the compiler, debugger and other development libraries. Tomcat versions prior to 5.5 used the Java compiler that comes with the JDK to compile JSP pages at runtime and consequently required a full blown JDK.

Tomcat versions 5.5 and above have a Java compiler (the Eclipse JDT Java compiler) packaged along with it. Now, this is used to compile the JSP pages dynamically instead of the JDK compiler. Hence, it is enough if we just install JRE starting from Tomcat version 5.5 and above.

Groovy: List Operations

Anybody who has programmed in Java for sometime would attest to how frustrated they could get while operating on the Collection API. Even simple operations demand unnecessary lines of code increasing the LOC and reducing expressiveness of the intended logic. Fortunately, Java has noticed the pain and has been adding utility classes to the Collections API to improve readability of the code since Java 5. Even better, there are a couple of libraries, Lambdaj and op4j, that implement the powerful Fluent interface that takes readability to the next higher plane.

Libraries and utilities are good for Java, but we are still bound by the constraints of the language itself. Isn’t it? That is where Groovy steps in. Groovy is in a totally different league when it comes to expressiveness of code. It was designed with the “Principle of least surprise” in mind. Best of all, Groovy source compiles to java byte-code thereby only adding a jar file as a dependency to your projects.

To whet your appetite, here are a few code snippets for list operations in Groovy that will make you smile…

Create lists in groovy: Keeping the literal notation the same, you can define different implementations of the collections framework

// Returns an ArrayList by default
def personalities = ["Steve", "Bill", "Larry"]

// Returns a LinkedList
def personalities = ["Steve", "Bill", "Larry"] as LinkedList

// Returns a String array
def personalities = ["Steve", "Bill", "Larry"] as String[]

Basic list operations: There are many more operations. But this gives you a feel for how easy it is to add, remove and retrieve elements off of the list

// Defines a list of strings
def personalities = ["Steve", "Bill", "Larry"]

// Retrieving an element
assert "Larry" == personalities[2]

// Retrieving a range of elements
assert ["Bill", "Larry"] == personalities [1..2]

// Adding an element
assert ["Steve","Bill","Larry","Scott"] == (personalities< <"Scott")

// Removing an element
assert ["Steve", "Bill", "Larry"] == (personalities -= ["Scott"])

Other cool operations: These are some operations that you typically don't find in Java. Correct usage of these operations will lead you towards strong and idiomatic Groovy programming.

// Transforming one list into another
assert [2,4,6] == [1,2,3].collect{ it*2 }

// Finding every element matching the closure
assert [1,3] == [1,2,3].findAll{ it % 2 == 1 }

// Print each element of the list
[1,2,3].each{ println it }

// Spread Dot operator operates on every element of the list
assert [1,2,3] == ["a", "bb", "ccc"]*.size()   

// Spread operator is used to pass a list as method parameters
def add(a, b, c) { return a+b+c }
assert 6 == add(*[1,2,3])

There are many many more features that support the Collections framework. To list it all is not the intention of this post, rather this post is intended to give a quick feel for how easy it is to write Groovy code when dealing with a Collection of objects.

Groovy: No-arg constructor is always there

Do you usually write a no-arg constructor for your Java classes? You don’t have to – unless you need to initialize something in that constructor. Behind the scenes, the Java compiler adds the no-arg constructor directly into the byte-code if none is provided. But when one or more overloaded constructors are provided for that class, the compiler doesn’t add the default no-arg constructor to the byte-code. This has been part of Java since the beginning.

Fast forward to today. I was doing some work with Groovy. All of a sudden, i realized that i forgot to add a no-arg constructor inspite of adding multiple constructors to a class and the code was still working without errors. That is when I found out that the Groovy compiler adds the no-arg constructor to the byte-code regardless of other overloaded constructors. I just thought I should share this learning with the world and hence this blog!

Does JRuby, Jython, Scala and other JVM languages do it too? Will have to check…

Don’t get me started on why i should use overloaded constructors when Groovy provides dynamic constructors out of the box. The short answer is “API Requirement” from the client.

Hibernate never stops surprising me

I have a simple form in my web application where a user can fill in his personal details and address details. User specific fields include firstName, middleName and lastName while Address specific fields include street, city and zip. On the server side, I have POJOs for User and Address. Finally I use Hibernate to map these POJOs to the database. Since, the Address will not be used outside the context of the User, I decided to map it as a Component of the User class.

The User class and its corresponding mapping is given below:

@Entity @Table(name = "user")
public class User {

     @Column(name = "first_name")
     private String firstName;
     
     @Column(name = "middle_name")
     private String middleName;
     
     @Column(name = "last_name")
     private String lastName;
    
     @Embedded
     private Address homeAddress;

     ... Getters and Setters
}

The Address class is mapped to User as a component. You can see the specifics of the mapping below.

@Embeddable
public class Address {
     @Column(name = "address_street")
     private String street;
     
     @Column(name = "address_city")
     private String city;
     
     @Column(name = "address_state")
     private String state;

     ... Getters and Setters
}

As you may already know, mapping components using hibernate is a very useful feature. This feature and support for nested components and components referring to other entities are the primary source of support for rich and fine grained domain model in hibernate. But while i was using Component mapping, I recently stepped on an interesting Feature (or it could be an Issue) and I was happily surprised by it.

Want to know the surprise? Keep reading…

In this case you map an Address as a value type using @Embedded annotation in the “homeAddress” field of the User class. The Address class itself is declared to be @Emeddable. This is the standard Hibernate/JPA way to map value types. The Address class has street, city and zip and it gets stored into the same table as the User class’s table. Now, when you insert an instance of User into the database, while specifying all null values for Address‘s fields maybe because the user didn’t give his address, then what would you expect in return at some point in time when you retrieve this User back from the database.

I for one expected user.getAddress() will return an Address instance. Then address.getStreet() will return null. But that is not what happened. user.getAddress() returned null by itself. That was interesting and even helped me in my case because, if the user hasn’t given any details for his home address, then it probably means that his address itself is not there in the system. So, returning null for getAddress() is semantically the right thing to do. I was surprised and when i checked the hibernate documentation it was even mentioned there that if all properties of a component are null, then the component itself is considered null.

In another situation this could have been bad, I don’t know, but for my purpose I was happily surprised with this nice touch from hibernate. These kind of small things is what differentiates a great product from a good product. Ain’t it?

Final Modifier for method arguments. What do you think?

The IT industry today is sodden with TLAs like SOA, ESB… and FLAs like AJAX, SOAP and JUNK. i was thinking about refreshing myself with some fundamentals again. Blogging about a basic concept may not be cool, but refreshing – don’t you think? I know what you are thinking. You are thinking that i am digressing too much. Ok, lets cut to the chase.

One of the best practices i follow religiously is to use final modifiers for method arguments where applicable. This is “supposedly” a best-practice written by somebody somewhere. Regardless of whether it is documented as a best-practice or not it is an important concept to understand and use. I have 2 valid reasons to use them for my method arguments.

First, final variables cannot be modified. Come on, everybody knows that. Maybe, but its use is significantly enhanced when it is a method argument and more importantly when you are in a big team environment.

Lets assume that a method takes List as its argument. Typically, the intention of that method is to work with the List – add to it, remove elements from it, use its elements in some way, sort it and what not. Consequently when the method returns, the caller can investigate the passed List and work with the modifications the callee introduced. But the caller will be on for a big surprise if the callee changes the instance that reference points to itself.

We know that java uses “Pass by copy of reference”. If the callee points the received reference to a different List and then modifies this List, the caller will not be able to see any change at all. This is because the copy of the reference held by the caller still points to the same old List. More often than not this is done by mistake and is not intentional. If such a behavior is intentional, final modifier is not required. In all other cases since this leads to bugs in code, it is a good practice to use final modifier for method arguments.

Second, if the method uses the infamous anonymous inner-class syntax to do something, and that inner class wants to use the methods arguments, java requires those arguments to be declared final. This is more of a rule than a valid reason.

Are there more valid reasons? I will be glad to receive information from you guys.

Hibernate: Why should I Force Discriminator?

Hibernate is an ambitious project that aims to be a complete solution to the problem of managing persistent data in java. Even with such an arduous task before them, the hibernate team tries very hard to expose a simple API for developers like us. Still, the complexity behind the API shows its ugly face time and again and I believe it is unavoidable as long as the mismatch between Object and Relational world exists.

That said, although I have worked with hibernate for many years and have been its advocate in all my organizations, I keep facing newer issues and keep finding newer ways to work with it efficiently and effectively. Recently, when I was working for nboomi.com, I faced an issue when mapping a OneToMany relationship to the sub-classes of “Single Table Inheritance” strategy. After a frustrating couple of hours of debugging I finally landed on the correct solution. So, I thought other developers who will travel this path could get benefited and started writing this blog post.

Let me explain the issue I faced with an example. Assume you have a normal User Entity with the typical id, version and loginId properties. Assume this User can have many AboutUs sections and many Service sections. You don’t need to be an architect to model them as OneToMany relationships from User. So, I modelled UserAboutSection and UserServiceSection entities and created a OneToMany relationship between User and these entities. Looking at the commonality between these two, I decided to factor out the common fields into a superclass called UserSection. Now, both UserAboutSection and UserServiceSection extends UserSection. I chose to map this Inheritance hierarchy using “Single Table Inheritance” strategy to keep it simple and since most of the fields were common and only a few were specific.

The User entity is given below. Notice the List<UserAboutSection> and a List<UserServiceSection> mapped using OneToMany relationship.

The getters, setters, adders, imports and static imports are omitted for brevity.

@Entity @Table(name = "user")
public class User extends BaseEntity {

    @Column(name = "login_id")
    private String loginId;

    @Column(name = "password")
    private String password;

    ...

    @OneToMany(cascade = {CascadeType.ALL})
    @JoinColumn(name = "user_id", nullable = false)
    @IndexColumn(name = "user_section_position")
    List<UserAboutSection> aboutUs;

    @OneToMany(cascade = {CascadeType.ALL})
    @JoinColumn(name = "user_id", nullable = false)
    @IndexColumn(name = "user_section_position")
    List<UserServiceSection> services;

    ... Getters, Setters and Adders
}

Here goes the UserSection entity that acts as the base class in this “Single Table Inheritance” strategy. Hibernate uses the @DiscriminatorColumn annotation to distinguish between sub-classes.

@Entity @Table(name = "user_section")
@Inheritance(strategy= InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="user_section_type", discriminatorType = STRING) 
public class UserSection extends BaseEntity {
    
    @Column(name = "title")         
    protected String title;

    @Column(name = "description")   
    protected String description;

    ... Getters and Setters
}

Here goes the UserAboutSection entity that derives from the UserSection entity. Hibernate uses the @DiscriminatorValue annotation to decide if a row in the database belongs to an instance of this class.

@Entity @DiscriminatorValue("ABOUT")
public class UserAboutSection extends UserSection {
    @ManyToOne 
    @JoinColumn(name="user_id",updatable=false,insertable=false,nullable=false)
    protected User user;

    ... Other Properties specific to UserAboutSection
}

Here goes the UserServiceSection entity that derives from the UserSection entity. Hibernate uses the @DiscriminatorValue annotation to decide if a row in the database belongs to an instance of this class.

@Entity @DiscriminatorValue("SERVICE")
public class UserServiceSection extends UserSection {
    @ManyToOne 
    @JoinColumn(name="user_id",updatable=false,insertable=false,nullable=false)
    protected User user;

    ... Other Properties specific to UserServiceSection
}

Pretty straightforward… huh! When you try to retrieve an instance of User along with its aboutUs and services collections eagerly (or lazily – doesn’t matter), what do you expect?

I expected an instance of User with the aboutUs collection filled with only UserAboutSection instances and the services collection filled with only UserServiceSection instances corresponding to only the rows they represent in the database. And I believe this expectation is valid, because that is what the mapping looks like and hibernate also has all the information it needs to make this work.

But I got something different. Both the aboutUs and services collections had all the UserSection rows that belong to this User. I mean, aboutUs collection had all the UserSection instances including UserAboutSection and UserServiceSection instances. This was surprising because hibernate has all the information it needs to populate the right instances.

After quite a bit of debugging, googling and RTFM-ing I landed upon @ForceDiscriminator annotation. This annotation has to be applied to the base class in the Inheritance hierarchy for “Single Table Inheritance” strategy. In my case, I had to apply it to UserSection entity. The UserSection entity after applying this annotation is given below…

@Entity @Table(name = "user_section")
@Inheritance(strategy= InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="user_section_type", discriminatorType = STRING) 
@ForceDiscriminator
public class UserSection extends BaseEntity {
    
    @Column(name = "title")         
    protected String title;

    @Column(name = "description")   
    protected String description;

    ... Getters and Setters
}

Once I ask hibernate to Force Discriminiator, it is happy and populates the aboutUs and services collections with its respective instances.

Ok, Problem Solved! But why did I have to tell hibernate to Force Discriminator. Shouldn’t that be the default behaviour. Is it a bug in hibernate or is it a feature? Am I missing something? If any one of you hibernate fans have walked this path and know the answer, please feel free to drop in a comment. I sincerely hope this post will be a valuable time-saver for other hibernate developers who step on this Bug/Feature.

Happy Friendship Day!

Imagine you are attending a party along with your friend! He plays all kind of foolish pranks and cracks stupid jokes. All along you are with him, quite enjoying his playing the fool. You come home with not a thought troubling you. Now imagine the same scenario with your brother! Even as the party progresses, you ask yourself a hundred times, “why is he behaving so silly? Why can’t he behave a bit more mature? What will my friends think of me now?”

Today is a day that celebrates friendship. So it is only proper that we contemplate a little bit on this most special relationship and what makes it so special? Among one thousand reasons the above mentioned scenario explains it the best.

“In friendship there is no place for judgment and labelling.”

Most often a problem in relationship comes only when you label somebody as your ‘husband’, ‘mother,’ ‘father’, ‘sister’ etc and once labelled you try to squeeze the individual to live according to the label. And then when they do not fit the label since they have their own characteristics we feel pained and somehow cheated. In friendship you do not label the person. He is given the freedom to be a fool, a good for nothing fellow, carefree, irresponsible and so on. You enjoy him and give him the space and freedom to be what he is. That is why while all of life is relationships; the best form of relationship is friendship.

The family in which the husband is a friend to the wife, the parent is friend to the child and vice versa, that family is heaven. Where there is no friendship in families, the story of that family will be written in tears.

So to celebrate friendship day in its true spirit would be to resolve to relate like a friend to all the members of your family. To give them freedom!

Happy friendship day!