Jul 30

I couldn’t post for about 3 weeks, due to a number of things that have been happening since my last post…

First it was Lal Masjid (Red Mosque) Massacre that left me deeply tense. I was against (like many others) the views of Lal Masjid Molanas and the way they were trying to implement their home made Sharia. But no matter how hard Mush’s government tries, they can never justify the massacre that happened in Lal Masjid. Shame on “Mush” and Shame on his supporters.

The good news is CJ’s restoration. I hope it is a step forward towards a free Pakistan (in real sense)

I had to visit my native village (Mianwali) for some family business. Have spent there around 2 weeks. Am about to leave for Lahore, going back to work from tomorrow…

By the way, I am planning to do some refinements to the blog gradually, first installment is here, it’s a new theme. I saw this on www.pkpolitics.com, it’s simple and elegant. May be I’ll make some more improvements this weekend.

written by ishaq

Jul 10

Currently I am working on a project that has been under development for almost 6 years now, so it contains a lot code written by a lot of people.

A couple of days ago, I was modifying a module in which We had a function like:

public ResponseObject perfromTask(/* params */)  {

  ResponseObject response;

  try {
  // — My Changes Start Here –

  //….

  //some statements

  //….

  // all done, return the object

  return response; // this response object is perfectly valid

  // — My Changes End Here –

  }

  catch(SomeException ex)  {  // handle exception

  }  finally {

  // some resource cleaning

  return response; // BOOM!!!!! I didn’t notice this statement at first

  }

}

and there was another method that was calling the above method like this:

public void callerMethod(/* params */) {

  // irrelevant code

  ResponseObject response = performTask( /* params */); // the response object received here was always null

  // irrelevant code

}

But strangely, I was always getting NullPointerException when the callerMethod tried to get response from perfromTask. So I placed a breakpoint at the line where I was returning the response in the performTask (the line that has a “this response is perfectly valid” comment) and another just after the line where performTask is called in the callerMethod. And when it interrupted the execution inside perfromTask, I could see that the response object was the one that should have been expected, so I just “resume” to jump to the next break point and OUCH! the response object received in the caller is indeed null.

After single stepping through performTask, I noticed that finally block had a return statement itself, I don’t know why it was returning null (since it had the same reference as the try block) but it, while at the same time being surprising, was quiet annoying because the code ran into an error when in fact there was no error (in the changes I made I mean). Anyway, removing return statement from finally block and making sure that try block was returning in every case it was supposed to return solved the problem.

I never thought of returning inside finally block before, but now that I have seen it, I know it is something mysterious and might get you into problems. Don’t know what java specs have to say about it.

written by ishaq

Jul 09

Long Long Time Ago (that is about 6 months) when I was still a university student, I was a fan of Microsoft Technologies and a frequent visitor to Chad Hower aka Kudzu’s blogs (I have listened to him, and He is a very good speaker). Then, a paradigm shift occurred and I moved to open source…

The other day I saw a link to a Google Tech Talk by Josh Bloch on reddit and Boy! he is by no means a less addictive speaker than Kudzu.

Anyway, his talk was on How to Design an API, and the following roughly summarizes what I remember from his talk.

1. Why An API is important:

A good API is an asset to the programmer and the company. An API that is flexible and easy to evolve does not only maximize software reuse but also the testing time (since APIs code does not need to be extensively tested).

2. Why is it important to You (Or Me for that matter):

Because anyone who programs is an API Designer. Good Programs are usually modular and the inter-modular boundaries are APIs themselves. Good APIs tend to be reused, and if an API is being used by a couple dozens of people, it is important that You code it right the first time, once it is out in the public, Changes cannot be made at your will.

Also, thinking in terms of API Desin tends to make you write good independent units, instead of just hacking a solution.

3. Characteristics of a Good API

  1. Easy to use even without Documentation
  2. Hard to misuse
  3. “sufficient”ly powerful to satisfy requirements (a powerful API doesn’t necessarily make it a good API, If an API satisfies the requirements, it’s good)

Rest was blah blah blah.

4. Requirements Gathering:

Mostly people suggest solutions instead of stating their problems, it’s upto the API designer to determine the requirements. For Example, a requirement might be to clean the server cache every 2 hours, where the real requirement could be to improve server’s performance in terms of memory utilization. A good tip to reach the actual requirement from the suggested requirement may be to ask “Why do you want it?”

5. Start with a short specification:

Long specifications are hard to maintain. Expand the specs as you gain confidence through coding. Write code to the API even before writing the API.

6. Maintain Realistic Expectations:

You cannot please everyone, so you should try to displease everyone equally i.e. the API should be written in such a way that Everyone can find use for it, it may not excite everyone, but it should be good enough to make everyone consider it.

7. Make API as small as possible:

Only provide the necessary functionality and specifically “When in doubt, leave it out

8. API should be tied to a particular implementation:

This is specially true in case of return values and exceptions that are thrown. Make sure that your return values (and exceptions) are at the same level of abstraction as the API e.g. returning a HashMap is tying the method to a particular implementation.

9. Minimize Accessibility of Everything.

The more access you provide, the more difficult it is to change the API later. In fact, unless there are reasons for a class to be sub-classed, declare the class as final, and if the class can be sub-classed, clearly mention (in the comments) the expected ways to do so. Don’t make this serialization, you are potentially provide access to the data.

10. Names and Documentation Matters:

API is like a language, use good names, and document rigorously.

11. Rules for Documentation:

  • Class: Describe what an instance is
  • Method: Contract between the client and the method, preconditions and postconditions and any potential side effects
  • Parameters: Describe the unit of parameters (e.g. time), form (e.g. xml) and ownership (whether the caller still has it) of the parameters

12. Design decisions can affect the performance:

True that Premature optimization is root of all evil, but thoughtful decisions at design time can save a lot of optimization later.

13. API must coexist with the platform:

14. While translating an API, DO NOT Transliterate:

i.e. don’t just translate the code line by line from one language to another, instead write the code that provides same functionality on the target platform.

15. Class Design:

  • Minimize mutability (that’s a general rule anyway)
  • Sub-class only when there’s a need for it

16. Method Design:

Don’t make the client do what the API can do” e.g. boiler plate code in Win32 API. Such code is normally copy-pasted and is error prone. Do such house keeping in your own API.

Follow the principle of Least Astonishment, A method should do what its name suggests it does and nothing else e.g. in java, thread’s “interrupted()” method does not only return the interrupted status of a thread by it also clears it. it is BAD

Fail Fast, If something has gone wrong, tell the client as soon as you can. Throwing an exception 20 function calls later that the expected parameter was a String which could be parsed to a valid integer will only make debugging a mess…

Provide programmatic access to the data that is available in string form e.g. java’s Exception doesn’t only provide “printStackTrace()” (which returns a string) but also “getStackTrace()” which provides programatic access…

and finally use a consistent parameter order through the system i.e. if the first string to string manipulation method is source string, it should be so through out the system.

That’s a lot of stuff I have recalled, and before writing this post I didn’t think I would remember this much :). However, according to Josh, if you remember two things from his talk, you have gained very much, and these two things are:

  1. When in doubt, leave it out
  2. Don’t make the client do something that the API can do

Need to leave the office, next post will most probably be a strange return value bug in a module today. Although, it was found quickly, but it was something quiet surprising. more on it later…

written by ishaq

Jul 04

I came across a very good blog article today at http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/. It’s about Singleton Pattern.

I was not surprised at the title “Why I hate: Patterns” since like any man made creation, they have their own share of weaknesses. The author has made five points in support of his argument, he says:

  1. Singleton hides dependencies.
  2. Singletons are hard to test
  3. Singleton can’t be sub-classed (easily)
  4. Singleton is a lie (from Java Perspective)
  5. The system might evolve to need more instances of an object, whose only one instance is needed in current perspective.

Alright, first three points are fair. But are they really problems? I don’t think so, Singletons are meant to encapsulate the objects that are needed through out the system (e.g. a database connection). So it should be understood that (almost) all of the classes in the system would be using this resource.

About hard to test, well I am confused about it. The author says that singletons hide coupling and therefore make it hard to run tests. Well, may be, but I have not run into such a situation yet (and I immediately admit that I consider myself a beginner with patterns).

Well, yeah Singletons are hard to subclass. This is a genuine problem.

The last two points are not fair. If a platform sucks at supporting patterns, it’s not the pattern’s fault. (No offense to Java, but that seems as if MS were to blame JavaScript for having buggy implementation in their browser, would that have been fair.?)

Lastly, if I don’t foresee how the system would evolve and have used a Singleton where it should not have been, it’s a fault that I am responsible for. I should not have used singleton in first place. It’s the architects job to use the patterns right.

Conclusion:

Singleton pattern, as I said earlier, is meant to encapsulate global resources. It has become a convention to use Singletons for (at least) logging and DB Connections, which is, what Singletons are meant for. Having a couple of Singletons (for global resources) in the system won’t do any harm. But if you have stuffed your system with them, then there’s trouble and I guess that’s what Miller’s (author’s) article is addressing, but may be it’s not appropriately named.

————

[EDIT] The post was originally titled “Singletons are Evil? But why?”, however, it has been changed based on the discussion below…

written by ishaq