Tuesday, March 01, 2011

Seth Godin - Leadership philosophies




"Leadership is not practical and not every day"

"Leadership is about finding the right people, agreeing on where you want to go and getting out of the way. Leadership means embracing the failure of your people if it leads to growth. Leadership means not knowing what's going to happen tomorrow, just knowing is going to take you where you want to go."

Friday, February 18, 2011

Minimalistic to-do

Last month while browsing on net, I found blog post on how to create minimalist to-do list in bash shell. Code was simple, 3 lines in .bash_profile. Since I day spend considerable amount of time in iTerm2 (alternative to Terminal app on Mac OS X) and I hardly close iTerm2, I thought to give it a try and see how it works out for me. After using for around a month, I'm finding it easier to manage my to-do list. And with help of Dropbox on Mac and PlainText app on iPhone, I'm able to sync list between my Mac and iPhone. Unfortunately I lost the link to blog post, so pasting code here.

Add following in .bash_profile
# Todo start
# Store in PlainText iPhone app folder in Dropbox for sync
export TODO=~/Dropbox/PlainText/todo.txt
function todo() { if [ $# == "0" ]; then cat $TODO; else echo "* $@" >> $TODO; fi }
function todone() { sed -i "" -e "/$*/d" $TODO; }

Reload profile
$ source .bash_profile

Add task to to-do list
$ todo write test case of bug #345
$ todo refactor worker class
$ todo check 280slides.com

Display to-do list
$ todo
* write test case of bug #345
* refactor worker class
* check 280slides.com

Remove task from to-do
$ todone refactor

To remove to-do item, only part of description is required. This might sometime get messy if list is long, but hey, isn't goal is to keep getting things done in to-do list and try to keep it as small as possible?

I also used GeekTool to display to-do list on my desktop on second monitor.

Tuesday, February 08, 2011

Thursday, February 03, 2011

Calculate number of days between two dates

Computing number of days between two dates is simple mathematics. This is how it is done.

public int differenceInDays(Calendar start, Calendar end) {  
    long ms = Math.abs(start.getTimeInMillis() - end.getTimeInMillis());
 
    return (int) (ms / (1000 * 3600 * 24));
}
But does this work in all cases? Not exactly. Take a look at this code:

public Calendar newDateInstance(int year, int month, int day) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, month - 1);
    cal.set(Calendar.DAY_OF_MONTH, day);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    return cal;
}

Calendar start = newDateInstance(2011, 3, 13);
Calendar end = newDateInstance(2011, 3, 14);
System.out.println(differenceInDays(start, end));

This code prints 0. Why? Because on 14th March morning Daylight Saving starts and an hour is lost. One solution I use is to add 1 hour to end date to avoid loosing a day. Here's how above code is rewritten.

private void resetTime(Calendar cal) {
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
}

public int differenceInDays(Calendar start, Calendar end) {  
    resetTime(start);
    resetTime(end);
 
    // This is to avoid loosing a day when daylight saving starts(14th March)
    end.set(Calendar.HOUR_OF_DAY, 1);
 
    long ms = Math.abs(start.getTimeInMillis() - end.getTimeInMillis());

    return (int) (ms / (1000 * 3600 * 24));
}

Friday, January 07, 2011

Saturday, January 01, 2011

Web: Year & Month selector

Three weekends back I started my weekend project ExpenseBook to track my personal expenses and was looking for jQuery plugin to select date for expense entries. Almost all of my google search ended up in calendar style plugins which are very common and I was not able to convince my self to use them. So I decided to design and code myself. Since I had lot of space to fit this piece, I came up with this design.



What I liked about this design is:

  1. jumping between months is much quicker: single click or single tap on my iPhone (unless I don't want to change year)
  2. entering day of month is much quicker by typing on keyboard than clicking and selecting.
  3. it fits nicely in overall page design.

Below is html, css and jQuery code to make this working. (Note: Years and months in html are hard coded for this post. In real application, they are auto generated.)

Nicole Sullivan: "The Top 5 Mistakes of Massive CSS"

Tuesday, December 07, 2010

Convert time to EST

Code to convert given time in UTC milliseconds to EST, irrespective of timezone of environment in which code executes.

Mockito: verify order of invocations

Sometimes there is need to verify the order of invocations happened on mock object. Take a look at below RequestProcessor class. This class reads request from input stream, does some processing, write response to output stream and closes the connection.

public class RequestProcessor {
    private Socket socket;

    public RequestProcessor(Socket socket) {
        this.socket = socket;
    }

    public void process() {
        try {
            InputStream is = socket.getInputStream();
            String response = processRequest(is);

            PrintWriter pw = new PrintWriter(socket.getOutputStream());
            pw.append(response);
            pw.flush();
        } catch (IOException e) {
            // catch exception
        } finally {
            try {
                socket.close();
            } catch (IOException e) {}
        }
    }
  
    private String processRequest(InputStream is) {
        // process request and send response
    }
}

Here, we want to verify that in ideal case RequestProcessor should first read request from socket.getInputStream() and then after processing request, write response in socket.getOutputStream(). One way that comes in mind is to write test as:

@Test public void socketClosedInIdealCase() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ByteArrayInputStream bais = new ByteArrayInputStream("a=b+c".getBytes());
  
    when(socketMock.getInputStream()).thenReturn(bais);
    when(socketMock.getOutputStream()).thenReturn(baos);

    RequestProcessor request = new RequestProcessor(socketMock);  
    request.process();

    // verify method invocations
    verify(socketMock).getInputStream();
    verify(socketMock).getOutputStream();  
}

At first this test seems to be verifying what is suppose to, but unfortunately this test will not detect if socket.getOutputStream() is moved before socket.getInputStream() as done in below code.

public void process() {
    try {
        OutputStream os = socket.getOutputStream()
        InputStream is = socket.getInputStream();
        String response = processRequest(is);
 
        // rest of the code
        } catch (IOException e) {
            // catch exception
        } finally {
            try {
                socket.close();
            } catch (IOException e) {}
        }
    }
}

This is because Mockito.verify() static method only verifies whether any invocation happened on mock object. It does not verifies order of invocation.

To make test verify invocation order, Mockito provides Mockito.inOrder static method. Using this method above test can be rewritten as:

@Test public void socketClosedInIdealCase() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ByteArrayInputStream bais = new ByteArrayInputStream("a=b+c".getBytes());
  
    when(socketMock.getInputStream()).thenReturn(bais);
    when(socketMock.getOutputStream()).thenReturn(baos);

    RequestProcessor request = new RequestProcessor(socketMock);  
    request.process();

    // verify method invocations
    InOrder order = inOrder(socketMock);
    order.verify(socketMock).getInputStream();
    order.verify(socketMock).getOutputStream();
}

If the order of invocation is changed in RequestProcessor.process() method, this test will fail.

Below is complete code.



Thursday, December 02, 2010

Mockito: Two simple ways to create mock

Mockito is the simplest, cleanest and easiest to start with among other mocking frameworks present in java world. Being so simple, it still tries to make our test more cleaner and readable by providing two simple ways to create mocks depending upon the need. Let's look into those.

1. Using static mock method

Socket socketMock = mock(Socket.class);

This is most common way to create mock. But what if mock is to be created and used in each test method in test class? One way to do is declare it as field and initialize it before test method is called. Something like this:

public class RequestProcessorTest {
    private Socket socketMock;

    @Before public void init() {
        socketMock = mock(Socket.class);
    }
}

This looks simple and clean, but what if there are more than one field to be mocked? Create mock for each in init(). It's simple. But is there more simpler way to combine declaration and initialization process? Yes! that takes us to second point.

2. Using @Mock annotation

@Mock annotation is shorthand for creating mock. This code shows how to create mocks using annotation.

public class RequestProcessorTest {
    @Mock private Socket socketMock;

    @Before public void initMock() {
        MockitoAnnotations.initMocks(this);
    }
}

MockitoAnnotations.initMocks() is important here. It initializes all fields with @Mock annotation. In above code it creates mock of Socket and assigns it to socketMock. Using @Mock annotation has below listed advantages( as specified in mockito java docs):

  • Minimizes repetitive mock creation code.
  • Makes the test class more readable.
  • Makes the verification error easier to read because the field name is used to identify the mock.

So when to use #1 and #2? As listed in java docs of @Mock annotation, if mock creation code is repetitive, I prefer to use #2 otherwise #1.

Wednesday, December 01, 2010

Why Ruby?

I don't completely agree with the presenter on monkey patching and Java, but was an interesting presentation.

Sunday, November 28, 2010

dup and clone: What's the difference?

dup and clone are used in ruby to create duplicate/clone of an object. So what's the difference between them? They differ in how they operate on frozen object. When frozen object is cloned using clone, the cloned object remains frozen, while when frozen object is duplicated using dup, the duplicated object is not frozen.

Saturday, November 27, 2010

Ruby: freezing your object

Before diving in, lets look into what are mutable and immutable objects.

Mutable object is object that can be modified anytime during its life time. Immutable object is object that cannot be modified after it is created.

In ruby object can be made immutable anytime using freeze method. Once the object is frozen, it cannot be modified further in its life time. Any attempt to modify frozen object results in TypeError. Let's take a look at simple example of freezing a string object.


Once str is frozen there is no way it can be unfrozen.

Ruby also provides frozen? method to check whether object is frozen or not.


One important point to take a note about freeze method here is that freeze makes object immutable and not object reference variable. Take a look at below code.


obj1 and obj3 points to one instance of FreezeTest and obj2 points to another instance of FreezeTest. Once obj1.freeze is invoked, instance of FreezeTest to which obj1 and obj3 are pointing is frozen and not obj1 and obj3 variables. Both these variables can be modified to point to any other instance as seen in above code.


So where can freeze method be useful? Two places I can think of

  1. Creating a true constant object: By true constant, I mean constant variable that refer to immutable object. Lets take example from rails. request.rb defines LOCALHOST constant as

    LOCALHOST = [/^127\.0\.0\.\d{1,3}$/, "::1", /^0:0:0:0:0:0:0:1(%.*)?$/].freeze

    By freezing array to which LOCALHOST points, rails makes sure that no one should be able to modify definition of localhost by removing and adding elements to array.

  2. Using object as hash key: Once object is used as hash key, we want to make sure that it's hash is not changed otherwise it will be difficult to find value associated with it. One of the way to achieve this is by freezing object and then using it as hash key.

What All Rubyist Should Know About Threads

Tuesday, November 23, 2010

Google App Engine, things to know

Goodbye Google App Engine (GAE) provides some details one should be aware before starting using GAE as platform for new killer web app.

Sunday, November 21, 2010

Using ActiveRecord without Rails

Following ruby code shows how to use active record in non rails environment.



Contents of database.yml:

Friday, February 04, 2005

Encapsulation is not information hiding

Excellent article describing the difference between Encapsulation and Information hiding with real life example. Read it.

Saturday, January 15, 2005

ROWNUM Pseudocolumn with ORDER BY

In Oracle to limit the number of rows return we use ROWNUM in the WHERE clause. Suppose if we want first 10 rows of emp table, then the sql query will be something like

SELECT id, name FROM emp WHERE ROWNUM < = 10


And if we want sorted result then might be ( as i thought for first time)

SELECT id, name FROM emp WHERE ROWNUM < = 10 ORDER BY name

The above query does not work as we want. The WHERE clause is applied before the ORDER BY clause. Oracle picks the first 10 rows and then applies ORDER BY on them. We need to first sort the data and then select the first 10 rows. Here is the query:

SELECT id, name FROM (SELECT id, name FROM emp ORDER BY name) WHERE ROWNUM<=10


You have to do this if the column in ORDER BY clause is non-primary key. If the column is primary key then simple query will do. Look at the below sql query

SELECT id, name FROM emp WHERE ROWNUM < = 10 ORDER BY id DESC

here id is primary key.

Also one more thing i noticed that we cannot use greater than(>) operator with ROWNUM. The query returns zero rows.