Friday, December 21, 2012

Coding tip: readability first!

In this 'Coding tip' I'll introduce you to one of the most sustainable coding tip of mine IMO. You may or may not agree with me but this has proven to be a valuable tip for me in terms of coding maintainability.

This one tip is was I call 'put material where the work needs to be done'. It is the opposite of offshoring :)


Rule:

Put the code where it is needed. If a code is needed in more than one place put it in a reusable form (function/method/...). Use code-folding to un-clutter when needed.

Example in ObjC not applying this rule:

- (void)viewDidLoad {
   [super viewDidLoad];

   [self setupImageView];

   [self setupTitleView];

   [self setupButton];
}

Example in ObjC applying this rule:

- (void)viewDidLoad {
   [super viewDidLoad];

   // Setup the ImageView
   UIImageView *imageView = [[[UIImageView alloc]init]autorelease];
   /*
         ...
         configure the imageView
         ...
   */
   [self.view addSubview:imageView];
 
 
   // Setup the TitleView
   UILabel *titleView = [[[UILabel alloc]init]autorelease];
   /*
         ...
         configure the titleView
         ...
   */
   [self.view addSubview:titleView];
 

   // Setup the Button
   UIButton *button = [[[UIButton alloc]init]autorelease];

   /*
         ...
         configure the button
         ...
   */

   [self.view addSubview:button];

}

Discussion:

You may find the first solution more readable but it is only because it hides most of the work in secondary methods.

The point of this tip is to avoid the creation of sub methods/functions just to tidy up a long block. In fact this will complicate the reading and will also clutter the namespace.

The second example (which use this tip) is what I prefer since it allows one to find everything it needs in one place. It is even possible to get the same level of low verbosity as in the first example with the use of code folding that most code editors provide. To do so, I usually put each sub-parts inside its own block (using curly brackets in C)

Example of foldable sub-part code (notice the curly brackets):

// Setup the ImageView
{
   UIImageView *imageView = [[[UIImageView alloc]init]autorelease];
   /*
         ...
         configure the imageView
         ...
   */
   [self.view addSubview:imageView];
}

Folded code result:

- (void)viewDidLoad {
   [super viewDidLoad];

   // Setup the ImageView
   {...}
 
   // Setup the TitleView
   {...}    

   // Setup the Button
   {...}    

}


Now you see how readable your code can be. At any moment you may see the whole code or if you wish you can fold every blocks and unfold just one to get inside a specific part.

My personal rating for this tip is:

Performance 2/5
Readability 5/5
Sustainability 4/5

No comments:

Post a Comment