A friend on mine pointed me in the direction of Stack Overflow the other day. It is a great resource for developers, and just a little bit addictive. Go check it out if your a developer and haven’t already.
Archive for September, 2008
Stack Overflow
Sep 24
Conditionals
Sep 8
Conditionals when used correctly can make verbose code concise and readable. However, there are enough examples of them being used incorrectly that can scare most people away from them completely.
That is one of the most unreadable conditionals I have ever seen. It returns true of false depending on whether or not $year is a leap year. However this is a bit of an extreme example. Just because something can be used badly doesn’t mean we cannot use it well. If that was the case then most Hollywood actors would be out of work.
The following code sample does a very simple thing. It calls a sort method with a sort direction depending on a flag.
if (flag) {
sort(SORT_ASC);
} else {
sort(SORT_DESC);
}
This is quite verbose, but it does not use conditionals. It can be modified to be even more readable with the use of a simple conditional:
The benefit of doing it this way is that the logic of the sort direction is contained in the function call. There is no need to look at its surrounding lines to figure out what is going in. This means less work, and a win from my point of view.
Sometimes when you are trying to create a custom tag for JSPs you come across the strangest problems.
For example, I was creating a JSP custom tag for generating JavaScript. The generated code is responsible for filling a JavaScript associative array with values so that they can be used later on in the JSP. Here is the kicker — the JSP can optionally create a variable with the same name before using the tag and fill it with its own values. In that case the custom tag has to append its own values to it instead of creating a new array. This means the the generated code cannot simply declare a new object, since this would erase any of the values that the JSP inserted into it. You have to love requirements sometimes.
After a bit of experimenting I discovered that all the variables (and functions for that matter) for the page was stored in the window object.
if (typeof(window['varName']) == "undefined") {
window['varName'] = new Object();
}
Voila. The above checks to see whether or not the variable has been defined, and creates it if it’s not.
The Stonemaker Argument
Sep 3
I love it when I find a new source of humour on the web. I came across The Stonemaker Argument today and had a good laugh.