Archive for April, 2006

Arcane Java Operators

Friday, April 21st, 2006

I previously posted about the nifty ?: Java operator that I personally love, but that I never see in the code. And then I realized that there are quite a few instances of Java specific stuff that no one really knows or cares about. It seems that most Java instructors these days are C++ people who read a Java book - and thus they rely heavily on their C++ experience.

And that’s fine, you can really survive in Java world with a C++ like mindset (as long as you don’t try to pass integers by reference). But you miss out on all nifty little language nuggets and syntactic sugar that Java has to offer.

For example, Let’s say you have an ArrayList, a Vector or another Collection class. At some point you want to extract something out of it. Since you populate your collection class you know what should be in it. But what happens if someone sticks in an Integer into a Vector that should contain only Strings?

You can always do this:

try
{
    Sting foo = (String) vector.get(i);
}
catch(ClassCastException e)
{
    // error handling
}

This is IMHO a PITA. Of course Java has a much more elegant solution to a problem like that. It is the instanceof operator:

if(vector.get(i) instanceof String)
    // do something
else
    // error handling

Java will gladly let you know, what type of object you are dealing with, as long as you ask it the right way. Granted that this example is trivial, but in the long run, instanceof can save you allot of catching and handling runtime exceptions.

Operators such as instanceof or ?: do not exist in C like languages. So most C oriented Java instructors ignore them completely.

Allot of programmers do not understand the this keyword. For example most people do this:

public class Foobar
{
    private int foo, bar;
    public Foobar(int a, int b) { foo = a; bar = b; }
    public Foobar(int a) { foo = a; bar = 0; }
    public Foobar() { foo = 0; bar = 0; }
}

This is an ok code, but imagine having 5 or 8 fields to handle. It becomes real messy, really quick. What if you have 12 constructors need to change the name of bar to something else? What if you decide to initialize values to 1 instead of 0?

What you shour really do is this:

public class Foobar
{
    private final DEFAULT =0;
    private int foo, bar;
    public Foobar(int a, int b) { foo = a; bar = b; }
    public Foobar(int a) { this(a, DEFAULT); }
    public Foobar() { this(DEFAULT); }
}

This is a good coding practice from the get-go. If you ever rename your fields, or change the default initialization value, all you need to do is to edit the top constructor. If your code is written well, you rarely need ractoring tools for minor stuff like this.

I think there is simply a fundamental issue with teaching the students to use the correct tools for the right job.

I cannot tell you how many times I have seen people implementing XOR like so:

if(foo)
    foobar();
else if(bar)
    foobar();
else
    barfoo();

But Java has a perfectly good boolean exclusive or operator:

if(foo ^ bar)
    foobar();
else
    barfoo();

There is a xor operator in C, so I just see no reason why most college level programmers only use && and ||.

This is kinda like using the break on the default case of the switch statement. Code that is not wrong, but obviously redundant, or unnecessarily convoluted annoys me.

Tags: , , ,

Java ?: operator

Friday, April 21st, 2006

One of the least understood, and most underestimated Java language constructs is the ?: operator. Most people never even seen it in action. And those who did, never actually used it to do anything meaningful. Imagine something like this:

public generateFoo(int threshold)
{
    if(threshold > MIN_THRESHOLD)
       return new Foo();
    else
       return null;
}

In this snippet of code we have a function which generates a new Foo object if the passed argument is greater than some minimal threshold. If it is below threshold we return null. This is not an uncommon scenario… But with the ?: operator we could accomplish all of this on a single line.

public generateFoo(in threshold)
{
    return (threshold > MIN_THRESHOLD) ? new Foo() : null;
}

If you didn’t catch that let me show you something simpler:

int foo = bar ? a : b;

Java expects to a boolean or an expression evaluating to a boolean before the question mark. If that expression is true, then the whole statement evaluates to a. Else it evaluates to b.

It is elegant, produces a lean code and saves you one return statement. It is a good coding practice to have one return statement per method when possible. I think more Java programmers should embrace this little syntactic sugar. It saves you allot of typing when used appropriately.

Tags: , ,

Barefoot Shoemaker

Wednesday, April 19th, 2006

The keyboard on my laptop is fucked. Up and Left arrow keys simply do not work. I figured it might have been a software glitch, but they do not work at the bootloader either. It is annoying as hell, but if I hit down at the GRUB screen, I cannot go back up at all…

My solution? I figured I xmodmap some other, rarely used keys to up and left. I use an external kyboard and monitor most of the time anyway. This is my problem - they pay me for fixing other people’s computers, but my own laptop is a pile of junk.

I have a broken pointer knob that sometimes short-circuits and sends signals without being touched (causing wandering mouse movements on the screen). I have a bad display that sometimes cuts off, or blooms out into multi colored jumble. And now two dead keys… But this does not bother me that much, because I know how to route around these problems. An average technophobe on the other hand, has a shit-fit every time their screen as much as blinks the wrong way P

I should get this fixed though. It’s really annoying. I just don’t have fucking time to sit on the phone with Dell for 3 hours explaining to them that I just need a new keyboard. I can’t figure out why don’t they sell laptop keyboards on their website. The only way you can get a new keyboard is to call their parts department. And you better have a valid part number, or an open service call…

Tags: , , , , ,

The case of the switch

Wednesday, April 19th, 2006

Please look at the following code snippet and tell me what is wrong with it. No it contains no errors, just something really dumb that shows that the programmer does not understand the switch construct:

switch(foo)
{
     case 1:
     // do something
     break;
 
     case 2:
     // do something
     break;
 
     default:
     // do something
     break;
}

Do you see what I’m talking about? Come on, look at it!

If you couldn’t spot it, shame on you. Look at the default block. Why do we have a break there? The break statement is only there to prevent rolling down the the next case. If you are in the default case, which also happens to be the last case of the switch you are done. There is nothing below default it that can be executed. There is no need to put that break there!

And yet every book, online tutorial, and example I see put it there. Who the hell stated it? Why is everyone blindly copying this pattern? Is it for consistency?

Putting a break on a default statement is not wrong. It is syntactically correct. But that does not mean it does not look dumb as hell when you do it P

Tags: , , ,

No chanel switching during commercials.

Wednesday, April 19th, 2006

Holy Jesus Jumping Christ! WTF is this world comming to?

Philips suggests adding flags to commercial breaks to stop a viewer from changing channels until the adverts are over. The flags could also be recognised by digital video recorders, which would then disable the fast forward control while the ads are playing. via New Scientist Tech

The day they start doing this, is the day I stop paying for cable. This is the stupidest fucking thing I have seen since the unskipable DVD previews bullshit, and the broadcast flag. WTF! What if I accidentally switch to an infomercial channel? You just going to keep me there forever?

This is not going to fly with the consumers dude. You may be able to sell the broadcast flag to retarded idiots using that “pirates steal our content” joke. And hey, average Joe will not know about the broadcast flag until he tries to tape a show, or points a camcorder at the screen. But this? Hell, you don’t mess with people’s TV. That’s just plain stupid! If a Philips device would do that to me one day, I would fucking take a hammer to it in 5 seconds flat and then I would cancel my cable subscription.

Hell, they will have to modify the Nielsen rating system stuff to accommodate this. Cause, you know - you may really want to watch Lost or 24 but you are stuck on a channel running a 20 minute infomercial that can’t be skipped. To bad…

Implementation of this would be the beginning of the end of American TV industry. People would watch less TV, and download more TV shows with commercials edited out. Less and less people would get cable legally, because the a hacked illegal cable box would probably strip the “no-commercial-skip” flags off the signal.

The only winers would probably be the paid subscription channels like HBO - because this bullshit would make them even more appealing than before. They don’t have commercials AND you can flip to a different channel whenever you want P

Tags: , , , , , ,