Coding for Understandability

Often I have a number of options in how to code a particular piece of functionality. I’m constantly balancing between brevity, simplicity, speed, size, and readability. I often find that if I put a little more focus on simplicity and readability, I save myself time and headaches, in addition to making my code more readable, more object oriented, and more accessible to other coders.

I’m going to provide some examples in ECMAScript, but I know that similar problems exist in other languages, as well.

I recently ran across some code that was coded for brevity:

var userdefined:Object = (_model.partner || {}).userdefined || {},
bsb:BannerShownBeacon = new BannerShownBeacon(
		? userdefined.dims
		: userdefined.width && userdefined.height
			? userdefined.width + 'x' + userdefined.height
			: 'fixed_bottom'

Now, this is fully valid, well-written code, and it’s also tabbed and line-broken for readability, but what exactly is it doing? What is the purpose of this code?

The difficulty I find is that when someone is trying to determine whether their particular implementation is going to be executed — lets say we have dims, width, and height in our userdefined param, and we’re looking at this the first time. Since coding standards aren’t set for how to structure ? : style if statements, it’s difficult to go through this by instinct and take a guess at what it’s doing. Every language has if/else statements and most coders are intimately familiar with them.

First, we look to see if _model.partner exists and if it doesn’t, we create it, then we check to see if _model.partner.userdefined exists and if not, we create it and assign that to a variable.
Then, we create a second variable called bsb that expects a BannerShownBeacon;
If userdefined has a dims param, we use it, otherwise, we check if it has width and height params, and if it does, we combine them with an x in between, otherwise, we just use the term “fixed_bottom” and make a BannerShownBeacon out of that.

The final option is to include large amounts of comments (which is excellent for non-compiled languages like JS), but in compiled languages, this often doesn’t save any time or lines of code.

I’ve rewritten this here using if/else statements

var bsbText:String = "fixed_bottom";
		var userdefined:Object = _model.partner.userdefined;
			bsbText = userdefined.dims;
		else if(userdefined.hasOwnProperty("width") && userdefined.hasOwnProperty("height"))
			bsbText = userdefined.width + "x" + userdefined.height;
var bsb:BannerShownBeacon = new BannerShownBeacon(bsbText);

Leave a Reply

Your email address will not be published. Required fields are marked *