Keeping your code clean

17 11 2008

Quite often we are in a situation where we have to work on a code that was written a few months (or years) back by self or someone else. Sounds a little scary? To ensure that reworking on a code is not as difficult as mining a coal mine I always try and keep my code clean. Now, what is clean? There can be a lot of ways to keep your code clean, but two thumb rules that I follow are:

1. One responsibility per class: For example, I’m working on building a media player in Flash that will run audio and video files. I’ve kept the code for playing the video and audio in separate classes that are sub-classes of one common MediaPlayer class. VideoPlayer class carries the responsibility of playing the video, and AudioPlayer class encapsulates properties and methods for playing audio only. Then, I also have a separate class called VideoUI for laying out the user interface for the video player and a AudioUI class for building the audio player UI.

2. One task per method: In the above example of VideoPlayer class, there’s a separate method for each of the tasks that it needs to perform – playVideo(), pauseVideo(), stopVideo(), and so on. In some cases, it means that you make a separate method for even a one line code. 

Following the above two principles really help in keeping my code clean, readable,  scalable, and reusable.