Thursday, April 29, 2010

Improving your Code

In my experience, I've come across engineers of different calibre. Some who are natural engineers (developers or QA) and others who could do with a bit of help to get to the point of being great engineers. Being a developer I've always been on the look out for ways to improve the code that is produced. The other day I came across this presentation and it helped me to organise my thoughts on the subject. I've summarised the presentation here and added my opinions to too
Composed methods
Each method does one task. This makes it granular and easy to read and understand.
Within a method all operations are at the same level, functionally.
Smaller methods also are documented by the method name. In fact, working backwards will help you to identify methods that need to be refactored. After implementing the method, change the name to reflect what the method does. Instinctively, you'll identify that the method name is too long or it does not summarise the operation correctly. This means the method needs to be refactored!
Test Driven Development
Every engineer I've spoken to has heard this term and most aren't aware what it means and how to do it. The most common question I've heard is: "What's the use of unit-testing?". I'm not going to get into that discussion here, but will summarise the benefits.

  1. Think like a user. The code/implementation being delivered needs to be used.
  2. Aids in created composed methods, because smaller atomic methods are easier to test
  3. Improves reliability by providing an automated regression suite
Static Analysis
FindBugs and Checkstyle, are two tools that help in reducing common bad practices, bugs and code complexity.

Good citizenship
In other words, ensure all references have the right scope. This includes:
  1. Scope identifiers, viz., private, default, protected, public. My recommendation is make everything private and increase scope as and when required
  2. variable scope, viz., block, method, field, static. My recommendation again is to declare a variable as close as possible to it's point of usage and take it higher up only if required. Another recommendation is to rather pass values around using method parameters rather than increase a variable's scope.
With these two it implies that one should avoid using static references. This can further be extrapolated to avoiding SINGLETONS. Singletons combine responsibilities, making objects global and difficult (if not impossible) to test. Instead create a POJO to hold the data and a factory to create a single instance. This not only separates out responsibility and concerns but also make it easier to test.
KISS
Keep It Stupidly Simple! That also means, choose the simplest implementation for the current requirement. Don't go about indulging in speculative development. A lot of the times, simple things are cheap to throw away. If it gets complex you probably need a framework and should look at reusing existing ones rather than building a new one. Simple code is refactor-able and easy to change hence resulting in more agile and adaptable implementations.
Refactoring is not rework
Many times I've heard the complain:
"We had to change <insert your code here> and we wasted time in refactoring. If only we had done a little up front design we would have done it right the first time!"

But this is not true. You saved time the first time you did it without having to worry about complexity. Secondly, if you followed the principal correctly, you would have implemented something simple and hence cheap to throw away. And Thirdly, who ever got it right the first time!
If you are a Linux fan, even today there are new releases of Linux and if you are a Windows fan, Windows is at version 7.x No one got it right the first time, not even Einstein. So why do you expect yourself to be perfect. You will have to change whatever you do. If you come to terms with that, then why not be simple. Don't get attached to the code. And refactor. It's part of software engineering. It's part of implementation cost. It cannot be reduced! And hence it is not waste but part of the process.
This kind of thinking is usually triggered by managers asking: "How can we improve the process and reduce waste". Managers have to ask this. They control the budget and who doesn't want the best value for money? But we as engineers have to stop viewing refactoring as waste and something to be reduced. It is part of the software engineering process!
Ask Question
As simple as this sounds a lot of the time, questions aren't asked especially to authorities. This means you question suggestions, opinions, decisions, implementations, traditions, etc., etc. Questions will either lead to a change, hopefully for the better or will reaffirm that you've got the right implementation. So what's the harm in asking them? In today's world questions are no longer an indication that you don't know something. Quite the contrary, it's an indication whether you are paying attention and an indication of how much you've understood. I've always been of the opinion that 'There are no stupid questions, only stupid answers'. The only exception is when, you've not done your homework before asking the question or weren't paying attention. In which case, apologise for your bad behaviour' but still ask the question!


Monday, September 14, 2009

AIR on FC 11

YAY!!! Got AIR installed on my laptop!!! It's strange that Adobe refuses to publish a 64 bit version of AIR. Had to do a lot of R&D (another word for googling ;-) ) to find out the hacks required to get it working.

Adobe's official site has instructions on how to install it on FC-11 From this site got the hint to replace all *i386* packages with *i586*.

It's wierd that you need 32 packages to run AIR. What a pain!!! But it works. I got the Yammer client working, and will now once again try to get Tweetdeck working!

Update:

Tweet deck is working too! :-)

Tuesday, February 17, 2009

handling the apparent slowdown

Recently an ex-co-colleague put in an email questions that I do believe are on the minds of a number of people and that I've been asked a couple of times already...

  • How do you see the current market scenario?
  • Is there any opening in java/j2ee?
  • Also is it advisable to switch in this time frame, when companies are doing employee cuts?
 Good questions.And below is my Rs. 0.02...
 
In any scenario, it best to be where you know there is a need for your particular skills. In the current scenario of a slowdown, I'd suggest looking at it as an opportunity. This is the time to do the tihings you always wanted to do but were unable to find the time for it.
 
So as a few examples
  • this is the time to get that certification you've always been putting off
  • this is the time to do that bit of R & D on the new technologies you've been dying to give a spin
  • this is the time to join that open source project and contribute to it, not only with code, but maybe with feature suggestions, bug reports, reviews, etc.
On the job front, I wouldn't say that the market is down, quite the opposite! The market is hot but it's very choosy. Hiring takes place only if you match 80%-90% unlike earlier where even a 20% match was enough to hire a person. While it makes landing a job a little time consuming, it does mean that a job is more secure, as once hired there is a genuine need you statisfy and hence less likely to be laid off!
 
So my advice would be, do not panic and use this as an opportunity! And whatever you do, create a report. A simple blog, or a one page word doc which will be the additional proof that you've done something constructive. This will help not only you but also the organisation you work in.
 
What do you think?
 

Sunday, February 1, 2009

Design Patterns - Creational Patterns

I finally began a long overdue task of upgrading my design skills by reading the book Design Java. During this process I'll start another series to summarise my readings.

The book is based on another well know book by the Gang of Four but with a focus on implementing the original 23 design patterns in Java. Very rightly, it starts by highlighting the importance of design patterns today as:
  1. Design patterns describes the communication between objects
  2. They are recurring solutions to recurring problems, thus enabling reuse of solutions to common problems
Design patterns are divided into three categories, viz.,
  1. Creational Patterns: Cover the cases for object creation
  2. Structural Patterns: Compose groups of objects into larger structures
  3. Behavioural Patterns: Defines communication and data flow between objects in a system
Another thing I liked is the way the book highlights the learning pattern for design patterns.
  1. Acceptance: You accept that it is an important part of your work. I'm past this point and that's why I'm here! ;-)
  2. Recognition: This is the learning stage where you begin to recognise the patterns, both the problem and solution patterns
  3. Internalization: This is where you apply your knowledge.
These three steps aren't specific to the learning of design patterns but in fact are the general steps to learn anything and everything. It's an internalised process but knowing the explicit steps helps in understanding the process.

Two things to remember when using any design patterns are:
  1. Program to an interface and not an implementation: This principle is the at core for reducing dependence on an implementation. Programming to an interface allows implementation to change with time for any reasons, e.g., better algorithms, newer technologies, newer frameworks, etc.
  2. Favour Composition over inheritance: While this is not what we are taught in the OO theory, in reality favouring composition over inheritance eases up decoupling many a time. When I was first told this by one of my previous team leads (Irfan Mohammed), I thought he did not know what he was talking about! However, now I'm older (and hopefully wiser) and have realised the wisdom in his words then. I now go on preaching the same thing to everyone I meet!
Creational Patterns:
Creational Patterns are used when we need to handle special cases while creating new objects. The simplest way to create objects in Java is to use the new operator. However, many a time, special cases need to be considered and Creational Patterns may be used to solve them.

These are the five Creational patterns.
Factory Pattern
Creates different implementations for an abstract class or interface based on the input parameter(s). The client is unaware of the implementation being returned. If the implementation is changed, only the factory needs to be changed and the remaining part of the client is not affected.


From a previous post, I've also highlighted the benefits of using a static factory instead of calling the constructor directly. This is a variation on the Factory Pattern and I'd like to re-iterate to use the new operator only inside a Factory.

Abstract Factory Method
The Factory pattern applied to the Factory! Creates different factories that in turn provide different implementations for an abstract class or interface based on the input parameters.

Singleton Pattern
The Singleton Pattern is probably the most well know pattern. It's aim is to create a single object for a given class. There are a number of ways to do this in Java of which I favour the following:
  • Creating a static implementation
Use a private constructor to prevent object creation.
The methods and data within the class are static

This pattern doesn't create a single instance and can still fulfill the requirement of having a single point within the system.

The downside to this is that the object is not dynamic, meaning it cannot be passed around nor can it implement any interfaces. It is best suited for utility classes.
  • Factory that ensures only a single instance is returned
This has two flavours. An external factory or an internal static factory method. In both cases the factory ensures that an object instance is created only if one doesn't exist or returning the already created instance.

I favour the factory pattern over using static implementations because it is a bit more flexible and reduces the static coupling that the first method mandates. The additional benefit of the latter is that it can easily be extended to provide a pool of objects or to remove the singleton requirement if found necessary later.

Builder Pattern
From what I understand, the builder pattern and the factory pattern are different parts of the same coin.

The Factory or Director is used to create the Builder objects.

When the factory creates instances that are more complex in nature and which in turn build different implementations even though the interface implemented is the same. In terms of a UI, the builder is responsible for constructing different views or different UI to represent similar data in different representation based on a slight difference in the data. The book gives an example of using the Builder Pattern to create multi-select list of items a group of checkboxes if the number of items are three or less or a multi-select listbox if there are more than three items. The Factory decides which builder is to be created based on the data sent to it.

Prototype Pattern
The Prototype Pattern is largely used to create copies of an object. This is useful when the object creation is expensive. For example a database lookup or network call is required to populate and create an object. However, the same data in the object may be required to be manipulated or represented in different ways. Again an example from the book is of creating the prototype object after a database file lookup. Then creating a copy of the data a sorted list.

The book also talks about the default Java method for creating object copies, i.e., the clone method, and rightly highlights the common pitfalls of the clone method. IMO, the first rule for the clone, method is don't use it! But there are times you can't avoid it, and one has to be extremely careful in implementing an override.

Secondly, just overriding the clone method results in a shallow copy, i.e., all mutable referenced objects are common to both the prototype and the clone. If this is not desired and one needs a deep-clone Java does not really help you and you have to implement it yourself. Up until I read this book, this meant going through the complete object graph and recursively calling clone on every referenced object. But, the book highlight a simple cheat, use serialisation! It's so neat and elegant. Use a ByteArray to serialise the prototype using the ObjectOutputStream and then deserialise the object to create a deep-clone using the ObjectInputStream. Simple! Neat! Few lines of code! But it does have it downside, viz., every object in the graph must be Serializable.

The caveats for the prototype pattern is mainly it's impact on performance. While creating the copies of the prototype relatively cheaper than creating instances of the prototypes, there still is an expense of doing a deep- pr shallow-copy. Every instance retrieved of the prototype is always a copy which in turn will have a hit on performance.

My 2 paise here, especially in cases where read-only information is required, it would make sense to return an immutable interface to the object or an immutable clone if possible. But then this is a creational pattern and the reason one would use it is to create mutable instances of objects that are expensive to create from scratch. But I couldn't resist documenting my thoughts... (after all it is my Blog...uh... Blikki) :-D

Summary
To summarise this blog entry, I've gone through the first section of the book and looked at the creational design patterns, viz.,
  1. Factory
  2. Abstract Factory
  3. Builder
  4. Singleton
  5. Prototype
Of these I think Factory is the basis for all creational patterns and the rest are really subtle extensions of it. And this is how I'll remember them:

Factory creates objects. If the objects created are factories in their own right then the top factroy is an Abstract Factory.If the objects construct something like UI etc., then the objects are Builders. A Singleton is a Factory returning only one instance of the object while a Prototype would be one that creates copies of an object.

Five creational patterns all linked with the core pattern The Factory!

Sunday, December 14, 2008

Savio's Notes: Java Book: Effective Java - Chapter 2 - Item 1

The first in a series of notes about the book Effective Java by Joshua Bloch will cover Chapter 2 - Item 1. Some sharp readers would be wondering why not Chapter 1. Those who have read the book will be aware that Chapter 1 is more of an introduction to the book and it also will explain why I didn't make any notes for it. So worry not, you haven't missed anything yet!

Item 1

Use static factories instead of constructors
I never thought of it in these terms, but I had always felt uneasy whenever I used the new operator in code. I always tried to never to use the new operator and have either a third utility class that returned a newly minted instance or have a static method that did the same.

But Joshua Bloch puts it more eloquently and convincingly and here are his reasons:
  1. Static factories unlike constructors can have more meaningful names which in turn help code readability
  2. Static factories unlike constuctors do need to create a new object every time. They could implement some kind of caching mechanism to enable reuse of instances
  3. Static factories unlike constuctors can return sub-types of their return types
The book also lists disadvantages of this item as:
  1. Classes without public or protected constructors cannot be sub-classed. But he goes on to state that this may be an advantage as it forces the use of composition over inheritance which is further elaborated in Item 14
  2. Besides the use of naming conventions there is no way to distinguish a static factory from other static methods in the class
In conclusion the book recommends using static factories unless you are convinced that it dooesn't suit your needs. Alternatively if you are confused go with constructors as they are the norm.

From my part, I will now be trying this pattern more often to put in private constructors and use static factories. Maybe the convention to use would be to have the static factory name as getInstanceUsingXxxx(...)

Savio's Notes: An introduction to a blogging series

I recently got my hands on a copy of Effective Java - Programming Language Guide by Joshua Bloch. I've been meaning to read this book for quite a while now as I've heard nothing but praise from most people I know who have read it. Also, having read Effective C and absolutely loving that book, I'm a little biased because of the title of this book.

So I began reading it and got through the first three chapters and thought to my self: "Hey this is common sense stuff and still there are some common mistakes pointed out too!"

It's always great when someone else (a more famous person than oneself) confirms what one is thinking. Now I'm not trying to say that I've known everything that I've read so far. Quite the contrary I've also learnt a quite a bit of new stuff. Which is exactly why, given my terrible memory I though I should make notes for the same.

Now had I been in the office, I'd have Wiki-ed this. So rather than that, I thought let's start a kind-of series on my blog called Savio's Notes that will track these notes of mine on this and various topics.

As the title of the series suggests, the series is not one that is polished and proper. It is an aid to a quick reference and a summary of sorts of the things I'd like to remember.

I'll use the following convention for the title of the post when I create one that belongs to the series: Savio's Notes: Sub-series: Post title

With that introduction I'll now move to the first post in the series, viz., Savio's Notes: Java Book: Effective Java - Chapter 2 - Item 1 to Item 6

FC 10 - A good distribution that can get better

While helping the Sword CTSpace to set up the office during their transition out of Symphony, I had the opportunity to experiment with FC 10, i.e., Fedora Core's latest release, viz., Version 10.

First impression were excellent. This is a release that just great in terms of ease of use and hardware detection. In fact, up until this release, whenever I installed a version of FC on a laptop, I always ended up removing it because the laptop would never work as it was designed to work.

But this time, I had a new laptop, an Acer Extensa 4620 upgraded to 4 GB of RAM which came with Windows Vista Home Basic, 32 bit edition. The 32 bit edition of Vista refused to recognise all 4 GB and a bit of googling, revealed that this is an inherit limitation of the 32 bit OS.

So the alternative was to get a 64 bit OS on the laptop. Since FC-10 was freshly released I thought of using that and also because a 64 bit Vista required me to shell out more cash.

Well sufficient to say, I've tried it for a fortnight now, and I'm so happy I made the decision. Of course, there are a few things that annoy me, but I can live with them. For the record, here is a list of my failures (only because I gave up) with FC10:
  1. Dual display support: I failed with this both on the desktop and the laptop. No amount of R&D and trials & errors seemed successful. Finally from most of what I found on the net was that FC had changed the display related architecture from FC9 onwards and it was still in development.
  2. Webcam: The webcam doesn't work, but to be fair, I've not really tried to get it to work. (Now working as per update 3)
  3. Acer Keys: Some of them worked, like the sound, brightness while others (application quick launches) don't. Most of those that don't I rarely ever used even if I were on Windows. So not a big issue for me.
  4. Bluetooth: This works sometimes and not the rest of the time. When it does work, it's only for file transfers. I still can't get my Nokia to synch my calendar and contacts. I really miss the way Nokia PC Suite works on Windows and wish that Nokia would get a Linux version of PC suite out. ( (Now working consistently as per update 3)
  5. Opera: My biggest miss is that I couldn't get Opera for FC10-x64. It just refused to work. And I'm a BIG fan of the browser. I really miss it and currently get by using Firefox. (Now working as per update 1)
But I still think FC10-86x64 is GREAT! I couldn't think of using something else. Well... Maybe Ubuntu, but I've just gotten used to the way FC works I don't think I'll really shift. And of course there's Puppy Linux. Now that's a distribution that so very cool! I wish, we could have something like that for all our Linux distributions. But till that time comes, I'll stick with FC for my larger computers and keep Puppy as part of my the Emergency Rescue kit as well as for my older hardware and basic browsing needs.

However, my final verdict is still is to say with FC8 if you need stability and don't want to be hassled with cutting edge technology issues. But if your willing to rough it out a bit and learn a lot along the way I'd suggest going for FC-10 and you won't be dissappointed.

Update 1

I finally got Opera to work on FC 10. Yippee!!! Well for the record here's what I did to get it to work.

After a bit of a browse through the forums, I realised that there were a few who go it to work and that there is a special 64 bit version that needed to be downloaded. So back to the Opera download web-site. Unfortunately, the site doesn't recognise 64 bit version of linux correctly and hence I had to manually navigate and select the right version to download. Once done, this would not install because of a dependancy on libXt. When I checked, I had libXt installed and the latest version. Then, why???? Few more tries and it dawned on me... Opera wanted the 32 bit version, not the 64 bit version that I had installed!!! Duh!!! That was strange. So after a yum install libXt.i386 I tried installing opera again and success!!!

A bit strange that opera required the 32 bit library, but I won't complain, because I now have my favorite browser working on my favorite OS!!!

Update 2

Found some good stuff at http://www.mjmwired.net/resources/mjm-fedora-f10.html to help in the setup of FC-10. When used with caution and it is quite helpful.

Update 3

I'm not sure what I did but the webcam has begun to work. I do know that I did a yum update and also installed GYachE Improved an improved client for the Yahoo Messenger. After installing the new client I thought I'll check if it supports the webcam and it worked! I then tried Cheese the Webcam Booth, which I had installed earlier. And it worked this time. So another success on FC-10. Yipeee!!!

I also figured out to get the bluetooth to work consistently. I had earlier set the bluetooth applet for gnome to be visible always. After I changed this to be displayed only when bluetooth was active, everything worked well and consistently!

Update 4

I just managed to get Virtual box to recognize the attached USB devices. However to achieve this I needed to run VirtualBox as root. Which is not what I really want to do. Till I figure out on which file(s) I've not got the permissions on I'll make do with having to run it as root.