I was asked a question a while back over IM. The question and my subsequent answer made me think about my coding style, decision making process and evolution over the years and I decided that I would share those thoughts with you (aren’t you lucky).
The initial conversation went something like this, I’m paraphrasing here (but at least I’m not filling it with “dude”’s):
M: I was thinking about the
event.setArg()method, and thought it would be nice if you could have it set the variable to session or cookies within the same call, e.g.
event.setArg('name','value',true,true), what do you think?
Me: I see what you’re thinking, but I don’t like it. I think that your code should be clear to you and others what it is doing and those true arguments don’t give you much insight into what they’re doing.
You’ve got to think about someone else coming to maintain your code, would they be able to see what it was doing without digging through to find the definition of
Also how many times will you use it, and if not many, will you have to check the definition yourself to remind you which one is setting the cookie and which the session next time you see it?
So in the end I proposed 3 methods, the original setArg() method and two for setting cookie values & session values, basically a couple of cookie and session façade, and I think that’s what he went for in the end.
In my view the few times you’d want to set the same value to cookie and or session is very rare and the following example shows the worst case scenario where you want the value in all 3 places:
event.setArg( 'myArg', myVal );
cookie.set( 'myArg', myVal );
session.set( 'myArg', myVal );
It’s not the driest piece of code, but in my opinion much better than being presented with
event.setArg('myArg', myVal, false, true).
So that brings me to the title of this post, “Coding Clarity Over Cleverness”, the example with the extra façade for the session & cookie can’t really be any clearer in my opinion, it’s not the cleverest or driest solution but as far as readability and future maintenance in my opinion it’s much better. Presented with that code you probably wouldn’t even dig into the documentation or code to see what cookie.set() and session.set() are doing as it’s pretty clear.
The clarity over cleverness argument goes for any coding situation, you might hide some really clever code behind a method or function, but it’s name and signature should clearly show what it’s doing.
So the next time you come up with a clever solution, ask yourself if it’s clear what the code is doing if not then re-factor it so that it is.