Saturday, July 23, 2011

The story of the ArrayList imposter

Each and everyone of us, undoubtedly has had used Array lists in our lives as programmers. This story is about an imposter who lives among us, unnoticed, undetected until WHAM you are presented with a bug that makes no sense. Let me give you an example to reveal this imposter :). I have a hypothetical system that stores information on games and their ratings. A glimpse of the DTO i would use is as follow;

 * A class to hold basic data about game titles
 * @author dinuka
public class Game  {

	 * The name of the game
	private String title;
	 * The rating users have given the game
	private int rating;
	public Game(String title,int rating){
		this.title = title;
		this.rating = rating;

	public String getTitle() {
		return title;

	public void setTitle(String title) {
		this.title = title;

	public int getRating() {
		return rating;

	public void setRating(int rating) {
		this.rating = rating;

	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + rating;
		result = prime * result + ((title == null) ? 0 : title.hashCode());
		return result;

	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Game other = (Game) obj;
		if (rating != other.rating)
			return false;
		if (title == null) {
			if (other.title != null)
				return false;
		} else if (!title.equals(other.title))
			return false;
		return true;

	public String toString() {
		return "Game [title=" + title + ", rating=" + rating + "]";

Nothing fancy. Just a plain old data holder value object with customary getter/setter methods. I have overriden equals,hashcode and tostring methods because i usually do that as a principal :). Ok moving on to reveal the culprit i will present you with a sample code and run the code and show you the problem at hand;

import java.util.Arrays;
import java.util.List;

public class Test {

	public static void main(String[] args) {

		Game[]gameArr = new Game[3];
		gameArr[0] = new Game("Metal gear solid 4",8);
		gameArr[1] = new Game("Unchartered 2",6);
		gameArr[2] = new Game("NFS Underground",2);
		Game[]newGameList = manipulateGames(gameArr);
	 * Here we delete low rating games
	 * and add new game titles in place of those games
	 * @param gameArr
	private static Game[] manipulateGames(Game[]gameArr){
		List<Game>gameList = Arrays.asList(gameArr);
		for(int i=0;i<gameList.size();i++){
			Game game = gameList.get(i);
				Game newGame = new Game("NFS Hot pursuit 2",7);
		Game[]newArr = new Game[gameList.size()];
		return gameList.toArray(newArr);

Ok these are my personal ratings i have given for the few of the games i love. Hopefully no one will take them personally because i do not want you to get off the topic here ;). So what we are doing here is, we have an array of games which we pass into a method which looks at the games with ratings lower than 5 and removes them and adds new games as substitutes. Do not consider implementation details as that is not my intention. My intention is to show you the problem at hand. So lets run this code and see what we get.

Ok what just happened? We get this really awkward error saying Unsupported exception. When i first got this i was thinking that maybe a previous version of java did not support removing from list given the object because i was at work using JDK 1.4 for work related things. But jdeclipse came to my help. If anyone has not used it, i can guarantee that it is one of the most useful plugins and a faithful companion in my eclipse workbench. Its a java decompiler which can decompile class files. Its much easier than downloading the JDK source and linking it.

I wanted to see the implementation of the Arrays.asList() method. This is where i found our little ArrayList imposter.....

public static <T> List<T> asList(T[] paramArrayOfT)
    return new ArrayList(paramArrayOfT);

By the looks of it, there is nothing implicitly wrong with this implementation. So most probably it should be a problem with the ArrayList. Lets see whats happening there;

private static class ArrayList<E> extends AbstractList<E>
    implements RandomAccess, Serializable
    private static final long serialVersionUID = -2764017481108945198L;
    private final E[] a;

    ArrayList(E[] paramArrayOfE)
      if (paramArrayOfE == null)
        throw new NullPointerException();
      this.a = paramArrayOfE;

    public int size()
      return this.a.length;

    public Object[] toArray()
      return ((Object[])this.a.clone());

    public <T> T[] toArray(T[] paramArrayOfT)
      int i = size();
      if (paramArrayOfT.length < i)
        return Arrays.copyOf(this.a, i, paramArrayOfT.getClass());
      System.arraycopy(this.a, 0, paramArrayOfT, 0, i);
      if (paramArrayOfT.length > i)
        paramArrayOfT[i] = null;
      return paramArrayOfT;

    public E get(int paramInt)
      return this.a[paramInt];

    public E set(int paramInt, E paramE)
      Object localObject = this.a[paramInt];
      this.a[paramInt] = paramE;
      return localObject;

    public int indexOf(Object paramObject)
      int i;
      if (paramObject == null)
        for (i = 0; i < this.a.length; ++i)
          if (this.a[i] == null)
            return i;
        for (i = 0; i < this.a.length; ++i)
          if (paramObject.equals(this.a[i]))
            return i;
      return -1;

    public boolean contains(Object paramObject)
      return (indexOf(paramObject) != -1);

Huh what is that?? Its an inner class extending the AbtractList class,residing within the Arrays class baring the name ArrayList. The problem here is that it does not override all methods available within AbtractList thus throwing the UnsupportedException as defined within the class AbtractList .

Why they have done this im not really sure. It maybe because they are syncing the Array you passed initially and what ever update you do, is done to the original Array you passed in. But why chose such an implementation is a question mark for me.

So if you ever want to remove elements when using an ArrayList composed using Arrays.asList make sure to wrap it with a call such as newArrayList(Array.asList(myArr)); This will guarantee that you will use the concrete ArrayList implementation and not our imposter we just discovered.

So that ends the story of the ArrayList imposter that bothered me last week at work :)

Thank you for reading and hope you guys have a peaceful day of coding!!!

Wednesday, July 6, 2011

The MBA Riddle

So its been a while since i started working. 4 years to be exact. And i decided it is time i pondered on what kind of higher studies i should pursue. For me learning is not about having a piece of paper nicely laminated,framed and hanged in your house. Its about the learning outcome and the value i get from it. You feel this more when you have to self sponsor your studies and not depend on your parents to fund you. After all i believe they spent more than enough for my undergraduate studies and i do not want to burden them again.

Most people have the propensity to think that your post graduate studies should be inline with your undergraduate studies. Whilst there is some truth to this belief let me say that it shouldnt be a one to one match of your undergraduate studies. At least that is the case with my choice. I had two choices. MSc vs MBA.

I read for my BSc in  Computing and Information Systems as my undergraduate studies, as computers were my passion from younger days. Most people will and actually did suggest that i should read for an MSc in Computer Science saying it will propel my career to new heights. I never disregard anyone's thoughts as a principal so i thought about it long and hard. Here is my analysis on it.

If i were to do an MSc i first would see the available options for me. Coming from an average family the financial feasibility of funding for a foreign education was not realistic. I sure do wish i could have done a degree at MIT. But hey that is life, we do not always get what we want, but i believe God guides us through various paths so that we realize our true potential in ways we could not comprehend at first.

So anyhow moving on, i looked at a few opportunities locally. I must say in Sri Lanka there are quite a few reputed local universities offering recognized post graduate degrees in Computer Science. So my next step was to see what areas are covered within those courses.

Going along each, some were more inclined towards Software Architecture whilst others were more into artificial intelligence, Data mining etc. My passion was Software Architecture so i looked at the course content of those post graduate degrees. Going through it in detail i was amazed to see that most of what it covers had already been covered within my work experience. So i was left with the question as to what possible advantage this will give me. If i were to do a SWOT analysis i would come up with a negative response for sure.

As i stated before i am not a person to do degree just to get the mental satisfaction that i have achieved something great. I would actually want something that would enable me to challenge my self and help to me reach new heights.

An MBA has always been my choice of post graduate studies. I did my research on MSc because various people suggested that option to me and i really wanted to assess that option. So why an MBA you might ask. I am not going to give you obvious answers many people give such as;

  1. I want to start my own business someday
  2. I want to be a manager in my work place
and many more.

For me the world of entrepreneurship has been an interesting phenomena. From my younger days i have been a fan of The Apprentice, following most seasons up-to-date. Some may not like the way Mr. Trump handles business, but i can see his point of view in most cases.Though some may seem harsh, at the end of the day as he says its business and nothing personal.

An MBA for me is a source which will enable me to view the world in a different perspective and to think differently. Take for example what happened with Coca Cola and Pepsi. They were rivals going head on against each other. Though the rivalry exist still, its not as much as before. Its because they identified their true foe which is WATER. So they came up with various stalls on the road to promote the idea that if your thirsty you should drink Coca cola/Pepsi. This is a concept called Game Theory. For me this is a great idea. In the world of business so many interesting cases exists. That thinking pattern amazes me. Though an MBA will not directly provide me the ability to come up with amazing ideas as such, it will surely change my thinking pattern to see things differently at to let go of the limited scope thinking pattern.

Being able to grab hold of all aspects of the business world is very important as i see with the increased propelling of the economies of countries. So rather than limiting my knowledge to one particular field i would like to have the option of widening my knowledge in the business world. Of course one might say that you can learn all that is taught in MBA schools by reading a few books. Of course the theoretical knowledge you can acquire my reading a few good books, but the practical experience that you are taught my visiting lecturers and the various experiences you obtain with outbound training, team work activities etc those you cannot gain by your own as those are experiences you have to live out.

Im not stating that everyone in the field of IT should do an MBA after the undergraduate studies. For me its a passion driven by various aspects as i highlighted above. An MSc will stand you in good stead too given that the course content fits what you are looking for.

And that is how i solved my MBA riddle :) ... I know many will have alot of different views on the same. So pls leave by your view which is highly appreciated.

And to others who are contemplating on their higher studies i hope i shed some light on the subject and i wish each and everyone of you the best in everything.

God Bless....

Sunday, July 3, 2011

My two cents on Scrum

Scrum is an agile methodology which helps companies iterate through a product/project development to successful completion. Back in the days we all know that we were limited to the water fall model which was later extended to be known as the V-Model. Gantt charts and the like were included with these methodologies.

The practices defined within these traditional methods were concise and precise. We start off with gathering of requirements from the client, document it which usually goes as the Software Requirement Document (Known as SRS), which is later signed off by the client after user acceptance testing is done. Afterwards we have the design phase where all our class diagrams come into play as well as use case diagrams, ER diagrams and the like. Then it’s time to implement this well designed product with technologies that fit the choice. Testing and product release follows the implementation phase.

Though there were no intrinsic problems with this methodology, the problem lied in the fact that we humans are involved in every phase. In a perfect world (such as what skynet once planned) this methodology would work seamlessly and we would have picture perfect product releases. But alas, with us humans nothing is guaranteed. We all know how hard it is for us to make a decision on something at certain times. In terms of a company, when they approach a software company to build a piece of software for them, they might not know what they exactly want early on. As time goes on as they see the product they might and most usually do want something radically different to what they wanted earlier.

The problem posed by the traditional methodologies as everyone knows is that it’s very hard to go back from once phase to a previous phase as the cost and time involved in the process is of great monetary value to the company. We can’t coerce the customer to agree on our basis as client’s request are always dynamic and we as a company should have the processes in place to adapt to such changes.
This is where Scrum shines as I see. I’m quite new to the scrum process. In scrum what is usually done is that we start off with a base Product backlog which has feature tasks that the client requested. There are a few entities that are involved within the process of Scrum such as;

The Product Owner(PO) – The product owner is the one who gathers requirements from the client and creates and maintains the product backlog. Also he/she is responsible in assigning a priority to each task defined within the product backlog.
The Scrum Master(SM) – The scrum master does not involve with anything specific to the project, but acts as a supervisor helping the team and the product owner to adhere to scrum practices whenever he/she sees that they are deviating from proper processes.
The Team  – is that development team involved in the development as well as the testing of the project features.

Ok now that we have met the people involved in the Scrum, let’s see why it is so awesome. One of the eye catching points of Scrum is the fact that the team decides on the time lines rather than your project manager deciding it for you. I have been any many meetings where the developers stand there like deaf or dumb people and watch as their Project manger do the estimation giving unrealistic deadlines. In scrum the practice is that the team decides along with the PO which tasks they can take on. Usually in Scrum features are taken to fit into one sprint which is more less a month of time. This is the most efficient time as proposed by Scrum. So the team decides what they can achieve within the month and take on the tasks that fit the timeline.

The key feature to note is that they do not make the estimation based on the high level task defined within the Product backlog. They break it down to meaningful development tasks and estimate based on that. If a feature has work for more than one sprint, some features are pushed to the next release. This is a very efficient way of estimating as I see because you do not leave anything out in your estimate and are able to give credible estimates to your Product owner.

Also Scrum is dynamic in which if a customer wants a new feature added on whilst a spring is going on, though they can’t achieve it within this sprint they can always push it to the next sprint  and the wait time of the customer is minimized to just a month.

Also usually whilst a Sprint is coming to an end, the team gets together with the PO to estimate on the upcoming spring to. In scrum momentum is key, which allows teams and companies achieve its development goals in a timely manner without pressurizing the developers with unrealistic deadlines. So the team is aware of upcoming work load as well whilst within the current spring. This is a great feature of scrum the scrum practice. Planning ahead, but not too far ahead.

And also if for any reason they are unable to deliver a feature within the current Sprint they can always push it to the next Sprint and finish off.

As a couple or so Sprints go on, the team gets the feeling of the kind of work it can achieve within a particular sprint which allows them to make timely, accurate estimates on future tasks.
All in all, I believe these agile practices is the way ahead for all companies big or small as the benefits it brings along supersedes the switching costs involved with moving away from your current practices.
What are your thoughts on Scrum? Pls do leave a comment with your own thoughts on the same.

God Bless 

Font resizing and IE

Font Size mishaps

When it comes to declaring font size we know we have a variety of methods in order to achieve it. Few of them are as below;

1.    px – the size in number of pixels
2.    em – the size relative to the parent element
3.    in – the size in inches
4.    cm – the size in centi-meters
And a few others are there as well. On top of these there are a few keywords available to define text size such as;
1.    xx-small
2.    x-small
3.    small
4.    medium
5.    large
6.    x-large
7.    xx-large
In general I have seen many people using px(pixel) definition to markup your text size. Of course this works well out of the box but one caveat it brings along with it is a small scalability issue that I am going to touch upon this article.
To start off lets vamp up a test html plus a css file to go along with it.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 <html xmlns="" xml:lang="en" lang="en" id="vista"> 
 <title>Test my font size</title>
 <link rel="stylesheet" href="style.css" type="text/css" media="screen" />

<h1>My Awesome Article</h1>
		Though i started the heading as my awesome article i do not actually know
		what to write about that simply could be awesome.


font-family:"Times New Roman",Georgia,Serif;

Nothing special as you can see. It’s just a simple definition of a header and a paragraph element. And within our style sheet we have defined a font-size attribute specifying it to by 15px which will be the default size on which elements will base on. Now let’s run this and see how this looks like;

Ok looks fine to me. How about you guys? So what is the problem you might ask? You probably must be thinking I’m nuts to assume something was going to be wrong.  Though there is nothing wrong implicitly in this markup it fails in one area where if for an instance a person with bad eye sight wants to increase the default text size through the browser by going to View->Text size in Internet explorer and selecting a text size, the text in our site won’t budge. It will always stay on the default 15px size we defined.

Not what you want for your site right? A website should be accessible, readable no matter if you have a disability or not. So in this instance how are we going to fix this problem with our sites text? We want it to scale according to the user preference.

In order to do that we first need to specify the size in any one of the keywords I mentioned earlier. Afterwards any subsequent element you want to increase/decrease the size, we use percentages to define the size based on the base keyword size we defined. Ok enough words; let’s put this into action shall we?

font-family:"Times New Roman",Georgia,Serif;

So now if we try to resize again we will see this time our text within the page will scale according to the user’s need. Following is a screen shot of the same;

One thing before i forget, for this to work in IE 5 you need to apply something called the Box model hack which was developed by Tantek Celik. . You need this hack because in IE 5 it displays the text one step larger than the font size keyword we define.This is the short version of the same hack defined in the site;

* html body{
font-size:x-small;/* for IE5*/
f\ont-size:small;/* for all other IE versions*/

That’s it guys. Most of you might already know this. So for you guys this is just a revision, for all others I hope this helped you in anyway. Comments are as usual always welcome.

God Bless