Prajwal Tuladhar’s Blog
 
programming, life and some random thoughts

Jun 17 2009

Four Phases Test of Unit Testing

Published by Prajwal Tuladhar under Unit Testing

Gerald Meszaros has defined four phases to be included while structuring unit tests. The four phases are:

  • Setup is the first phase where test fixture is setup for the SUT (System under Test) to exhibit the expected behaviour as well as anything we need to put in place to be able to observe the actual outcome
  • Interact with the SUT or exercise
  • Verify / Determine if expected outcome is obtained
  • Tear Down the test fixture

Implementation

Account.rb


class Account
  MIN_BALANCE = 100
  attr_reader :balance

  def initialize
    @balance = MIN_BALANCE
  end
end

account_test.rb


class Account_Test < Test::Unit::TestCase
  def test_there_should_be_minium_balance_when_account_is_created
    #setup
    @account = Account.new
    #exercise
    balance = @account.balance
    #verify
    assert_operator balance, :>, 0
  end

  def teardown
    @account = nil
  end
end

You can get more information about this topic here.


Comments

May 31 2009

Damn! There is a difference between HTTP POST and HTTP PUT

Published by Prajwal Tuladhar under REST

HTTP 1.1 specifications has defined number of request methods like: GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, OPTIONS. But generally, GET and POST are two widely used and de-facto request methods due to the restrictions set by the server as well as client in most of the scenarios. As a web developer, I do know that these methods exist but like most of the web developers I had focused only on POST and GET because normally, other methods besides GET and POST are not supported by most web servers.

It’s been few sessions that I have started playing with document based storage technology, CouchDB which is *naturally* based on the REST philosophy. There is a really nice quote in CouchDB book site “Django may be built for the Web, but CouchDB is built of the Web”.

Everything was going fine until there was a command for creating database that utilizes HTTP PUT method:

$ curl -X PUT http://127.0.0.1:5984:/new_db

The response is: {"ok":true}

So, I was wondering what will happen if I use POST because my preception was that POST and PUT are really not so much different:
$ curl -X POST http://127.0.0.1:5984:/new_db

Response: {"error":"not_found", "reason": "missing"}

Booom! I was wrong!

As usual I google on the web and was pretty happy to find that it was not only me who was confused about PUT versus POST debate ;)

W3C has defined following functions of POST:

  • Annotation of existing resources;
  • Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
  • Providing a block of data, such as the result of submitting a form, to a data-handling process;
  • Extending a database through an append operation.

Let’s focus only on first function of POST for now. It clearly states that POST should be used for existing resources.

In my case, http://127.0.0.1:5984:/new_db has not existed yet so, using POST to create is against the specification.

But again trying to differentiate PUT and POST as: PUT for creating new resource and POST for updating existing one would be awful mistake. One can view PUT as a SQL insert operation. When a specified URI is defined, it will create resource there if the resource does not exist or replace the existing one.

But POST is quite flexible and can perform more operations as compared to PUT. POST sends data to the specified URI but how it will be processed is entirely dependent on the server. The action performed by the POST method might not result in a resource that can be identified by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on whether or not the response includes an entity that describes the result.

According to the HTTP 1.1 specification:

The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request — the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI, it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.

Examples:

  • PUT => http://mysocialapp/users/{username} => createUser
  • PUT => http://mysocialapp/users/{username} => updateUser
  • POST => http://mysocialapp/users/{username}/posts => createPost
  • PUT => http://mysocialapp/users/{username}/posts/{post_id} => updatePost

The URI and client will be ultimately responsible for handling above requests URI. If we look at the POST example, there is no way one can map the URI for every posts being created so, POST is idempotent and non-cacheable. While first and second example shows that PUT can be used not only to create resource but also to update it. But this solely depends on who is responsible for creating the new resource’s URI: client or the server. If client is responsible, then it should response 201 (”created”) when new resource is created and when the resource URI already exists, it should use POST method. If the server is responsible, it should respond 401 (”unauthorized”). If I try to create same database “new_db” using:

$ curl -X POST http://127.0.0.1:5984:/new_db then CouchDB returns {"error": "database_already_exists", "reason":"Database "another_test_db" already exists"}

Lastly, it would be better if Roy T. Fielding’s response on PUT is also considered:

FWIW, PUT does not mean store.  I must have repeated that a million times in webdav and related lists.  HTTP defines the intended semantics of the communication — the expectations of each party. The protocol does not define how either side fulfills those expectations, and it makes damn sure it doesn’t prevent a server from having absolute authority over its own resources.  Also, resources are known to change over time, so if a server accepts an invalid Atom entry via PUT one second and then immediately thereafter decides to change it to a valid entry for later GETs, life is grand.

Some useful links + resources:

Please do correct me if I am wrong :)


Comments

May 27 2009

There gotta be correction

Published by Prajwal Tuladhar under iSpeak

No doubt that smart phones are the next PC and their use will grow at exponential rate iPhone along with its innovative AppStore has changed the dynamism of this industry. Apple has rejuvenated once boring mobile platform with the introduction of platform that lets third party developers to write applications and eventually make money. With the success of AppStore, others like Microsoft, Nokia, RIM, Palm and Google are following or have taken some similar steps. So, one can expect do-or-die battle for the dominance of yet to grow and lucrative smart phone industry.

If we analyze the current events that have been taking place in this industry with the pre-mature phase of PC industry, we can find some similarities. The PC industry flourished with the introduction of GUI computers from Apple with the ability for 3rd party developers to write an application for. Prior to as well as after introduction of Apple OS, there were various vendors including Microsoft, IBM, DEC and so on offering similar services. But at last, as it normally happens in the information economy, only one emerged as the dominant force, it was Microsoft at that time. The success of Microsoft during PC battle was not just because of Microsoft Windows and/or DOS was superior to other available platforms, but Microsoft had and still have support of  wide array of hardware and software vendors. Apple and other vendors lost the PC war because of that particular reason.

Now lets come to current smart phone war. There are so many vendors offering or soon to be offering their own OS along with application platforms like Apple iPhone + AppStore, Google Android + MarketPlace, Palm Pre, Windows Mobile + Windows Marketplace, RIM + AppWorld, Nokia + Ovi and may be we will hear more in the near future. For now, as a developer it’s much easier to choose a smart phone platform to develop for (most in the US choose iPhone with Android trailing by long margin). Just imagine what will happen once all major vendors provide similar platforms after sometime. Which platform will you choose and what about interoperability? Certainly for large companies this won’t be a big issue as they have and they can afford to provide their applications for respective platforms. But what about those small developers and entrepreneurs and even for someone trying to get into mobile phone development? It will be just be crazy and/or practically impossible to offer certain services in all platforms.

I think we are going in somewhat wrong direction. With so much hype of iPhone and Android, along with other upcoming platforms especially Palm Pre, developers are forgetting about interoperability that the Internet and WWW have taught us and what Web 2.0 have delivered us. We are again going back to same PC era and writing applications for vendor specific platforms. Smart phone and as a whole mobile industry should focus providing their APIs respecting the concept of WWW. It’s true that browsers are available in almost all smart phones but which application will you choose when one is offered as a native one and while other being offered pointing to some URL like htpp://m.time.com or m.cnn.com and so on. In most of the cases, users will rightly choose former.

I am not saying platforms that enable developers to write vendor specific application is wrong but  one needs to fear that after sometime, it will be quite hard to offer applications for each and every platforms. But I am optimistic that one dominant player will emerge as victorious in the current smart phone battle and it will be the next Microsoft for PC and/or Google for Internet search.

My Bet: certainly not Apple even though iPhone + AppStore  provide the most superior platform for now ;)


Comments

May 09 2009

What Killed Smalltalk could also kill Ruby – Nice Keynote by Bob Martin

Published by Prajwal Tuladhar under Links, Programming, iSpeak

This is an interesting keynote presentation by Robert Martin delivered during RailsConf 2009. According to Robert Martin, Smalltalk was the most superior language of its time and even with such unique features and even being the epicenter for introducing Pattern based development, Test Driven approach and various OO principles we are following, Smalltalk was never successful with mainstream developers and eventually extinct with the popularity of JAVA in early mid 1990s. He believes that failure of Smalltalk users to ignore problems commonly faced by enterprises and attitude of Smalltalk users in being more superior than other platform developers were one of the crucial reasons that killed SmallTalk. He further expressed during the keynote that if Ruby and Rails community fail and/or ignore problems faced by enterprises then, there is a chance what happened to Smalltalk could also happen to Ruby.

I think the video is a must watch if you a Ruby developer and/or want to jump to Ruby/Rails band wagon. There’s no doubt that Rails is one of the leading web frameworks that have embed the concept of test driven development at its core and Ruby developers have always been in the fore front adopting agile development strategies. But whenever I read some blog posts/articles and writings by Ruby enthusiasts and developers, I feel some kind of rebel and attitude of superiority in their expression which is somewhat same as mentioned in the keynote. Ironically, most of the Ruby syntax is also inspired from Smalltlk with small blend of C; that’s why Ruby is also called reincarnation of Smalltalk but lets hope Ruby won’t be next Smalltalk and as Microsoft new initiative Make Web Not War.


Comments

May 01 2009

Book Review: House of Cards - A Tale of Hubris and Wretched Excess on Wall

Published by Prajwal Tuladhar under iSpeak

 

Finally, I completed reading House of Cards - A Tale of Hubris and Wretched Excess on Wall Street by William D. Cohan :) I accept that I may not have enough background knowledge for understanding each and every terms mentioned in this book and even for writing book review but I am petty sure that now I have general knowing about the state of Wall Street and financial mess they have nurtured in the form of sub prime mortgages and other complicated financial instruments like derivatives (I swear I don’t know what the fuck is this).

Cohan is a former senior Wall Street investment banker, author of The Last Tycoons and as a whole a respected writer and/or journalist.  I am really impressed by the way this book is written. The sequence of the events and excitement of consequences produced by them is what let me to complete this book in such a short time interval.

The book describes about the whole life cycle (from the birth and impressive rise to the dramatic collapse) of once proud investment bank Bear Stearns that became the first major casualty of the global financial crisis or credit crunch and consequently triggering the global financial system in the edge of collapse. Bear Stearns was eventually acquired by JPMorgan Chase in the fire sale price for just $2, later adjusted to $10 after shareholder lawsuit (Just a month or so ago it was trading above $100).

Here are some of the major events / points from the book:

  • Bear Stearns had had leverage ratio of nearly 40 times i.e. it was borrowing $40 by showing liquid asset of $1. Not only Bear Stearns, AIG (Always Investing Garbage Hmm..Did I write something wrong:) ), Lehman Brothers and most financial institutions and investment banks were leveraged in the same way.
  • Confident is the name of the game in the Wall Street. Just couple of weeks before the collapse of Bear Stearns, it had $18 Billion cash in hand. But once news about its potential survival and toxic assets in its balance sheet began to leak, there was run for money by its clients and no one was ready to do business with Bear.
  • Though Bear Stearns was a public company, its management and overall control was in the hand of few people namely Ace Greenberg, Jimmy Cayne and Alan D. Schwart. The failure of Bear was not only due to its business model but managerial missteps and personal rivalry about controlling the firm were also one of the causes.
  • Its quite shocking to know that most of the investment banks rely on over night funding for their daily transactions.
  • The rating agencies like Standard & Poor’s, Moody’s and Fitch Ratings are the bitch of Wall Street firms and also one of the major villains of this crisis.
  • Ironically, the executives of the failed firms like Bear Stearns and Lehman brothers were highest paid. But overall, all Wall Street executives normally were make millions even after the crisis (Remember AIG bonus saga). Wall Street has always be known for its excessive pay and risky investments especially after the de-regulation initiated during Clinton Administration.

Certainly the above list do not fully capitalize what this book explains. I have to say, I never thought it would be so interesting to read a book about finance world. But I believe that every person in the world is being directly or indirectly affected by the current crisis should have at least rough idea about how crisis of such magnitude completely took the world by surprise. As currently I am living in New York, which being the home of Wall Street can be considered as the epicenter of the current mess and one of the most affected state so, getting to know about the financial crisis is always nice.

 

 

 

And I can conclude what I learn in just one statement:

Investment banking is an unregulated black magic that let you to believe you are making chunk of profit that is kinda NULL in reality.


Comments

Next »

RSS Feed
Subscribe by email
Follow me @ Twitter