Tuesday 17 April 2012

Coding WTF

I got asked to help on a small PHP project that has already been started by another coder.

The very first thing I was confronted with was this;



if($variable == false)
{
}
else
{
      //do something
}




Ummm, WTF?

4 comments:

VeldMuijz said...

Did you ever use code before?
I only learn java at school but it goes like this.

If the variable let's say x has the condition false it will execute the code between the first brackets.
If the variable doesn't match the condition false then it will execute the else portion of the code.


I don't know if this helps...

Brett said...

Well golly veldmuijz, thanks for the unasked for coding lesson.

Now you can explain to me why that code is more readable or efficient than;

if($variable)
//do something

or, if you prefer a more readable style;

if($variable == true)
{
/do something
}

But thanks for your input, when I posted this I wondered if someone would chip in with an epic logic fail like you did and I wasn't disappointed.

That and your condescending attitude really made my day.

Anonymous said...

I have seen some people do this because they are opposed to using negative constructs in boolean statements; they want to express the code flow in terms of what something is rather than is not. I tend to agree with that philosophy but not to this degree. Or it could be the fact that it was a stub for anticipated code.

Brett said...

I agree anonymous, except for using a negative construct was exactly that this coder did;

if false do else do something

I also considered that it may be a place holder for future code but even that doesn't hold water because if that were the intent then this would be cleaner;

if true do something else do nothing

I asked the guy why he wrote it that way. He said "what do you mean" I explained that the logic was back to front and could be better and his response was " yeah, you could do it that way too I suppose"

Well yes, yes you could.