Tuesday 15 September 2009

Covariant Return Types in Java 5

Covariant return types are one of the newly added features in Java 5. Using covariant return types, an overridden method in a derived class can return a type derived from the type returned by the base-class method.

For example in the Java versions prior to Java 5, the following would have thrown a compile time error.

class Vehicle
{
Vehicle myFunc(){return this;}
}

class Car extends Vehicle
{
// myFunc() returns Car, which is a subclass of Vehicle
Car myFunc(){return this;}
public void printMe(){ System.out.println("I am a Car");}
}

public class Covariant {

public static void main(String args[]) 
{
Car car = new Car();
car.myFunc().printMe();
}
}

CompileTime Error: The return type is incompatible with Vehicle.myFunc()

Prior to Java 1.5, to remove this error you had to make 2 changes.

1. Change the return type of derived class myFunc() to Vehicle and
2. Downcast Object being returned by car.myFunc() to Car

Java 5 lets you get away with that and makes the above code work just fine.

Thursday 6 August 2009

XP2010, Norway

All agile enthusiasts who missed out on, XP 2009, Tenth International Conference on Agile Processes and eXtreme Programming in Software Engineering, held in May 2009
at Sardinia, Italy could compensate for their loss by registering for XP2010, 11th National Conference on Agile Software Development to be hosted by the SINTEF research foundation in Trondheim, Norway.

Registration of the meet would begin in January 2010.

The conference, as per the official website, would focus specifically on theory, practical applications and implications of agile methods.

Deadlines
Dec 6th 2009     Research papers, experience reports
Dec 13th 2009     Lightning talks
Jan 7th 2010     Workshops, tutorials, posters and PhD symposium

You can find more information here XP2010

So start putting things in your boss's ears because it might take some time and some effort to make her approve the training budget.

Good luck.

Friday 17 July 2009

Tuesday 7 July 2009

Friday 19 June 2009

Germany Scrum Gathering - 2009

Though I would not be able to make it to this event, I thought of letting all of you know about it.

Date:
Monday, October 19, 2009 - Wednesday, October 21, 2009

Venue:
Hilton Munich City
Rosenheimer Strasse 15
Munich, Germany 81667

Speakers:
Ken Schwaber - Scrum Co-Founder
Jeff Sutherland - Scrum Co-Founder
Mike Cohn - Mountain Goat Software

plus many more industry speakers, authors, trainers, innovators
and special sessions too!

Early payment:
Scrum Alliance Members - 1,200 euros
Non-member - 1,400 euros
CST/CSC 900 - euros
Early discount rates available until August 1, 2009.

Regular rates:
Members - 1,600 euros
Non-members - 1,800 euros.

Registration & information:
http://www.scrumgathering.org

Tuesday 9 June 2009

PMP Tips: Standard vs Regulation

A Standard is a “document established by consensus and approved by a recognized body that provides, for common and repeated use, rules, guidelines or characteristics for activities or their results, aimed at achievement of the optimum degree of order in a given context.”

A Regulation is a government imposed requirement, which specifies product, process or service characteristics, including the applicable administrative provision, with which compliance is mandatory.

It's often seen that standards become so overly used, that with a widespread use, they take the form of a regulation.


Wednesday 20 May 2009

Java Tips - Always Override toString()

I am sure all of us at some point in time of our software development career, would have done an SOP on an object, expecting to see an interpretable string value but were displayed a string, which could not add much to our understanding.

Though java.lang.Object provides a default implementation of toString() method, I dont think its really informative. The returned string consists of the class name followed by an @ sign and an unsigned hexadecimal representation of the hash code, for example, Employee@235b92.

Actually The contract for the toString() method says that the returning string sould be concise, easily readable and also all the subclasses should override it. Though it can be argued that Employee@235b92 is concise and small enough to read, but it certainly is not very informative.

Joshua Bloch suggests to override toString() method so that a suitable string interpretation of your object can be returned. Providing a good string implementation makes your class much more pleasant to use. Overriding toString() appropriately not only is beneficial to instances of your class, but it is also useful for the objects containing instances of your class. For example if you want to print the contents of a hashmap containing instances of your class, I am sure anyday you would prefer to see a Employee@BillGates_CTO over Employee@235b92.

Ideally, the toString() method should contain all the interesting information about the object. But if the object is really large it might not be possible to include all the information in returning string. In that case you can make it return something which provides a small summary of the object.

I know that you are not really familiar with this approach and might not find it a value adding practice but I would still recommend that you start using it and I am sure that soon you would start appreciating it's benefits.

Monday 4 May 2009

Difference Between Software Architecture and Software Design

Software Architecture focuses more on the interaction between the externally visible components of the system where as the Design is about how the internal components of the system interact with each other.

Software Architecture is more about what we want the system to do and and Design is about how we want to achieve that.

Software architecture is at a higher level of abstraction than the Software Design.

Software Architecture is concerned with issues beyond the data structures and algorithms used in the system.

Friday 24 April 2009

Array Access Evaluation Order in Java

Consider the java program written below and then guess its output.
public class ArrayEvaluationOrder {
public static void main(String[] args) 
{

int[] aryA = { 10, 20, 30, 40, 50, 60 };
int[] aryB = { 1, 2, 3, 4, 5, 6 };

System.out.println(aryA[(aryA=aryB)[4]]); //1
System.out.println(aryA[(aryA=aryA)[4]]); //2
System.out.println(aryA[(aryA=aryB)[3]]); //3
}
}
The output is:
60
6
5

If you are scratching your head, let me be of some assistance and explain the reason behind this.

As per Array Access Evaluation Order in java, in case of an array access, the expression to the left of the brackets is fully evaluated before any part of the expression within the brackets is evaluated.

For example consider the following line of code:
System.out.println(aryA[(aryA=aryB)[4]]); 
The expression aryA is fully evaluated before the expression (aryA=aryB)[4] is evaluated. This means that the original value of aryA is fetched and remembered while the expression (aryA=aryB)[4] i.e. 5 is evaluated.

Since aryA still remembers its original value aryA[5] returns 60. But after the execution of this line, aryA and aryB both would be pointing to array pointed to by aryB.

I would leave figuring out the rest of the output to you.

Monday 20 April 2009

Scrum Vs XP

I keep on seeing people debating about the differences between Scrum and XP. It’s quite interesting to hear the different advantages people suggest of one approach over the other. I am listing down the differences as per my understanding of each methodology.

• Scrum concentrates more on project management aspects of software development where as XP is more focused towards the engineering disciplines. It’s very much possible to follow all the XP engineering practices in a Scrum project. I have heard a lot of people say that pair programming is not allowed in an XP project. I don’t particularly agree with that. Remember Agile is not about following something blindly, it’s about being proactive and deliver maximum value in each release. If a team thinks pair programming or for that matter any XP engineering practice helps them do that, I tell them to have a go.

• Each development life cycle in a Scrum is called a Sprint where as in XP it is referred to as Iteration.

• XP teams work in a strict priority order. All the features to be developed are prioritized by the customer or Product Owner and team works on the features in that order. In Scrum the team is free to pick up the features to be developed. Though the Product Owner does specify the priority of the features, it is up to the team to choose the sequence in which the features would be developed.

• Scrum sprints last from 1-4 weeks where as an XP iteration is generally 1-2 or maximum 3 weeks long.

• Scrum teams strictly do not allow a change in the sprint backlog once a sprint has started. If the change is really mandatory, the sprint is ended midway and a new sprint is started. XP teams are much more adaptable to change with in iterations. As long as team believes they can deliver an extra/changed story without hampering the quality of the rest of the features, a change can be accepted in the iteration plan. I favour Scrum more in this particular context as I don’t really admire allowing a change once the iteration as started. I believe the responsibility of convincing the Product Owner to not to come up with a change request or a new story, during an iteration, lies with the Project Manager or the Scrum Master.

• Scrum does not suggest any engineering practices. Scrum is more flexible that way and leaves it to the team to adopt and implement the engineering disciplines as per their project requirement and their comfort level with those practices. XP is very strict in terms of engineering practices. It forces the team to follow various engineering practices like Test driven development (TDD), Pair programming, Automated Testing, Continuous Integration, Refactoring etc.

All the content written above is as per my understanding of the two methodologies. If you think I am wrong or there is something which needs any amendment or you have any query please write to me at ravinder.rawat@gmail.com.

Wednesday 15 April 2009

Microsoft Cloud

Lately I have been reading articles on this new and promising technology phenomena called Cloud Computing and I came across this really good article on the Microsoft's new initiative on cloud computing called Microsoft Cloud. Its basically a synopsis of Microsoft Chief Software Architect, Ray Ozzie's speech at Microsoft's annual Financial Analyst Meeting (FAM). I would strongly recommend it to all who want to keep themselves abreast with emerging technologies or in particular cloud computing.
http://www.readwriteweb.com/archives/peering_into_microsofts_cloud.php

Tuesday 14 April 2009

A simple OOPS concept

In this post I am going to discuss a simple OOPS concept. Consider the code snippet below.
class Base{}



class Derived extends Base
{
public void func()
{
System.out.println(“Inside the Derived class”);
}
}


public class Test
{
public static void main (String args[])
{
Base b = new Derived();
b.func();
}
}

What would happen if I try to compile and run the above code?
There are a few who might say that it would print “Insider the derived class”. The reason – Since at runtime the object that is created is a derived class object, it can call the method func(). But actually the code would not even compile. I agree that if the code would have compiled fine it would have called the func() method of the derived class but the problem is the compiler would not allow you to proceed because it does not see a func() method in the base class and thus b.func() would give a compile time error.

I agree a lot of you already feel like shouting ‘Come on codeguru… even a person who learnt OOPS from ‘OOPS for Dummies’ knows that’. But actually I have been interviewing candidates for a while and one common mistake a lot of candidates make is around this concept. Though it seems to be a very basic concept of OOPS, I have seen candidates with more than 2-3 years of experience failing to give a suitable reply. So I thought of including this in my blog. Sorry if it looks like that I have doubted your PQ(Programming Quotient). Remember we all started from the first step of the ladder and there are still a lot of them trying to do so.

Monday 13 April 2009

Mocking

In this article I will explain a unit testing concept called Mocking. We will also discuss a couple of examples based on EasyMock library.

Unit testing is an integral part of any software development cycle. It is the process using, which a programmer makes sure that the piece of code he/she has developed does what it is supposed to do. In more specific terms a unit test can be defined as the test of a single isolated component that can be done repeatedly. There are various tools available for doing unit testing like Nunit, JUnit etc.

Testing units of code often is a problem because mostly, the components of a software application do not work in isolation but collaborate with other components to get the job done. But in unit testing we don’t want to test the depending objects, but the unit under test. Mocking provides a solution to this problem. All the collaborating objects which are not to be tested can be passed as the ’mock’ objects after setting up their behaviour for the life cycle of the test.
Mock objects are not to be confused with mocks or stubs, which is another library to facilitate the testing of a unit with dependencies.

The basic idea behind Mock Objects is that the dependencies are resolved on the fly with in the test itself. EasyMock provides Mock Objects for interfaces in JUnit tests by generating them on the fly using Java's proxy mechanism.

Let me explain this concept by a very basic example. I have used Easymock for mocking the objects. Consider the following class:
public class Employee 
{
public Employee(String fName, String lName)
{
firstName = fName;
lastName = lName; 
}
private String firstName = null;
private String lastName = null;

public String getFirstName()
{
return firstName;
}


public String getLastName()
{
return lastName;
}

public String displayNameWithDepartment(IDepartment dpt)
{
return firstName+” ”+lastName+” ”+dpt.getName();
}
}

There is an interface IDepartment which is used by our Employee class.
public class IDepartment 
{
public String getName();
public String getHODName();
}

Now let’s consider testing of Employee class. What do we want to test, and how do we go about it. We are mainly interested in the way that our implementation class collaborates with its dependencies. We need to make sure that our class behaves correctly, when interacting with these parameters. We want to make sure that the right methods are called in the right order with the right parameters, but it is not used.
Obviously, in order to test the Employee class’s behaviour we will have to pass it a IDepartment reference but which need not be an actual object.
Lets create an example JUnit test, which shows the EasyMock at work
import static org.easymock.EasyMock.*;
import junit.framework.*;
//other imports omitted

public class EasyMockTest extends TestCase
{
public void testWithMockObjects() throws Exception
{
// strict mock forces us to specify the correct order of method calls
IDepartment dpt = createStrictMock(IDepartment.class); //1

expect(dpt.getName()).andReturn("Development"); // 2

//unexpected method calls after this point will throw exceptions
replay(dpt); //3

Employee emp = new Employee(“Michael”, “Sheen”); //4

assert(emp.displayNameWithDepartment(dpt), “Michael Sheen Development”) //5
//check that the behaviour expected is actually
verify(request); //6
}
//more test methods omitted ...
}

EasyMockTest class tests the behaviour of the displayNameWithDepartment() method in a specific scenario.

Let’s walk through each line of code and find out what it is doing.
1. We ask EasyMock to create dynamic proxy implementing IDepartment, which starts in record mode.
2. Record a method call along with the expected result.
3. replay() call tells EasyMock to stop recording. If we don’t call replay(), a call to dpt.getName() would return null.
4. Create the Employee object that needs to be tested.
5. Call on the mock object returns the set value. If it gets a call it does not expects, it throws an exception.
6. Verifies that only the method calls which were recorded were played. If we make a method call which was not recorded, an ‘Unexpected method call’ error is thrown. Moreover all the method calls which were recorded need to be made.

Note: Methods on the mock object would return the result in the same order in which the expectations were recorded/set on them. If the order does not match our test case is going to fail.
For example if our test case contains following lines of code, it’s going to fail:
expect(dpt.getName()).andReturn("Development"); //Development first
expect(dpt.getName()).andReturn("HR"); //HR second  
replay(dpt);
Employee emp = new Employee("Michael", "Sheen");
assertEquals(emp.displayNameWithDepartment(dpt), "Michael Sheen HR"); //HR first
assertEquals(emp.displayNameWithDepartment(dpt), "Michael Sheen Development");
verify(dpt);

Multiple calls
If a method on a mock object is to be called multiple times, we can use times() method. So if in the above example, I want to set multiple expectations with same arguments, I can use following the following line of code
expect(dpt.getName()).andReturn("Development").times(2);

reset method()
In the above example, the test method has a single replay() and verify() call with single expectation setting and verification phases. Sometimes it is convenient to reuse the same mock object over multiple expectation setting, replay and verification cycles. But the problem is once a mock object has been verified, it cannot record a method call. If we try to do that, an ‘Unexpected method call name’ error is thrown.
reset() method is used to set the mock object back to the expectation setting mode.
For example consider the following two scenarios:
Without reset()
expect(dpt.getName()).andReturn("Development");
replay(dpt);
Employee emp = new Employee("Michael", "Sheen");
assertEquals(emp.displayNameWithDepartment(dpt), " Michael Sheen Development");
verify(dpt);
expect(dpt.getName()).andReturn("Development");  //Error
replay(dpt);
assertEquals(emp.displayNameWithDepartment(dpt), "Michael Sheen Development");
verify(dpt);
With reset()
expect(dpt.getName()).andReturn("Development");
replay(dpt);
Employee emp = new Employee("Michael", "Sheen");
assertEquals(emp.displayNameWithDepartment(dpt), "Michael Sheen Development");
verify(dpt);
reset(dpt); //resetting the mock object back to the recording mode
expect(dpt.getName()).andReturn("Development");
replay(dpt);
assertEquals(emp.displayNameWithDepartment(dpt), "Michael Sheen Development");
verify(dpt);
Nice mocks and Strict mocks
You may have observed we used createStrictMock() to create the Mock objects. There are two other ways to create mock objects.
  • Nice mock
  • Default mock object
All these mocking strategies basically differ in two ways

Optionality
Nice mock allows you to omit expected method calls. If a method is called, but no expectation has been set, then the nice mock simply returns the default value for the type, if the invoked method returns a primitive, or null for an object.
For example, if we change our DepartmentImpl to look like this
public class DepartmentImpl implements IDepartment{
private String name = null;
private String HOD = null;
public String getName() 
{
return name;
}

public String getHODName() 
{
return HOD;
}
}
and change the testWithMockObjects to following
public void testWithMockObjects() throws Exception
{
IDepartment dpt = createNiceMock(IDepartment.class);
replay(dpt);
Employee emp = new Employee(“Michael”, “Sheen”);
assert(emp.displayNameWithDepartment(dpt), “Michael Sheen”)
verify(request);
}
Ordering
Expected invocations on strict mocks need to be specified in the correct order, that is, in the same order that they are executed. In the case of default and nice mocks its not mandatory.

Stubs
Strict mocks are great for defining rigorous tests, but at times applying them can lead to overkill. For example our mock objects contain a bunch of methods, with only some of these of interest. So how can we stop our tests from failing as a result of unexpected behaviour of these "other" methods? This is where Stubs are used.
Consider the code snippet below.
expect(dpt.getName()).andStubReturn("Development"); 
replay(dpt);
Employee emp = new Employee("Michael", "Sheen");
assertEquals(emp.displayNameWithDepartment(dpt), "Michael Sheen A");
...
...
...
...
verify(dpt);
The first line says, if dpt.getName(...) is called one or more times, then each time simply return the String "Development". However, if the method is not called, then don't throw an error. This gives us a lot of flexibility in stubbing out interaction with the mock objects which are irrelevant to the test in consideration.

Summary
Mocking is a powerful technique for helping to obtain high levels of test coverage for our code without worrying much about resolving the associated dependencies. It allows us to specify the behaviour of objects collaborating with our classes under test with a great deal of ease and with a lot more control.
The aim of this article is provide a brief overview of Mocking and overcome the hurdles faced in putting EasyMock to work in their applications.

If you find any problem in the code, or disagree with anything I have mentioned please write to me at ravinder.rawat@gmail.com. You might help me in becoming a more learned person.

Sunday 29 March 2009

How to safeguard your career in recession

A couple of strategies for making sure that your job is safe in the recession-hit corporate world.

Be a money-spinner
Share client leads or ideas to generate revenue even if that's not part of your responsibilities. The most important resources for any organization are the people who bring/generate business.

Stand out and step up
Make sure people know you, by solving problems and taking on high-profile and critical projects.

Move around in safe zone
Dont keep the company of the people who are not rated very highly by your bosses. Hang out with the people, the boss respects most. The aura of their good reputation may extend to you.

Go beyond your job scope
Look for problem spots that you can help fix and step in whenever extra hands are needed.

Make a sacrifice
Volunteering to take a salary cut during an industrywide downturn can make you look like a hero. This one is a little bit risky but may put you in the good books of your higher management very quickly.

Increase your market value
Enroll for some certification course to add value to your resume. Its really great if you can manage your organization to sponsor otherwise spend out of your pocket. Don't think of it as an expenditure, it is an investment.

Monday 23 March 2009

KISS, DRY and YAGNI

I am mentioning a few programming philosophies, which seem so obvious yet so difficult to follow. Only after spending a few years in software industry I could realize that the beginners write the complicated code and experts write the simple code and not the vice versa. I believe all these strategies can never be mastered; they can just be bettered.

KISS - Keep It Simple Stupid
I am sure all of us have heard this advice quite often and it still holds its ground. A lot of times we over complicate the solution to make our, otherwise boring, life a little fun. This happens a lot of times in the corporate software development world, where the boredom of routine jobs can be relieved by implementing an intellectual but not required solution. It feels great when we do it but if someone needs to fix, maintain or modify it, I am sure we would be up for a few cuss words. It is quite possible that when even we ourselves go back to our code, we start scratching our heads to figure out what exactly the code is doing. I am sure none of us would want to feel stupid looking at our own code. So just follow the words of the wise - KISS.

DRY - Don’t Repeat Yourself
Try not to repeat your code at a lot of places. Repetition is always a maintenance nightmare. If you need to repeat your code probably its time to refactor your code down to one use. You can refer it from multiple places. If you know your code is going to be used only once, then you are better off with the cut-and-paste approach rather than looking for a more general and thoughtful DRY solution. But if thats not the case, be more thoughtful before you commit the sin of duplication.

YAGNI - You Ain’t Gonna Need It
Don’t build something now because you think you might need it later on. Don’t over plan things. Don’t try to look too far. You might not need to travel that far at all. Try being a minimalist. Don’t try to gold plate things when its not needed. A time might come when the new functionality would not fit in the current code and a redesign would be needed but don’t factor that in too early.

Thursday 19 March 2009

How to view Hibernate query?

If you want to see the Hibernate generated SQL statements on console, what should you do?

In Hibernate configuration file set as follows:
<session-factory >
...
<property name="show_sql">true</property>
...
</session-factory >

Is little knowledge really harmful?

knowledge is always good, and certainly always better than ignorance. - Sergey Brin (CoFounder, Google)

Method overloading in Java 1.5

This post discusses the behaviour of method overloading in Java 1.5.

Suppose you have a class, which has a method void print(Integer x) and you call print(5) then Autoboxing will come into play and print will be called.

Another case is, if you have a method void print(long x) and you call print(5) then the primitive integer 5 will be widened to long and method print will be called.

Now suppose you have overloaded print method in your class

public class OverLoaded
{
public static void print(Integer i)
{
System.out.println("Integer");
}
public static void print(long l)
{
System.out.println("long")
}
public static void main(String args[])
{
int i = 10;
print(i)
}
}

There can be two possible outputs:
If you think "Autoboxing" will be done, then "Ineger" would be printed.
If you think "Widening" will be done, then "long" would be printed

Since both the method exists, which one will be used? Autoboxing or Widening?
In such situtations compiler uses the following order of priority:
  • Widening
  • Autoboxing
  • Var-args
Next question is what if there is a combination of these operations required.
When there is a combination of the above operations exists, the compiler will perform BoxingAndWidening but it will not perform WideningAndBoxing.

Class WidenNBox
{
static void print(Long x)
{
System.out.println("This is from long");
}
public static void main(String args[])
{
byte b = 10;
print(10);
}
}

In the above case, Compiler needs to widen byte to long first and then it should be boxed to Long which is not allowed.

Now consider this class

Class BoxNWiden
{
static void print(Object x)
{
System.out.println("This is from Object");
}
public static void main(String args[])
{
byte b = 10;
print(10);
}
}

Here compiler would autobox it to Byte first and then it can be widened to an Object.
 
Technology