Validation after initialization of variables in a constructor: why not the opposite?

advertisements

When looking through Java libraries, specifically constructors, I've noticed that fields are usually being initialized and validated afterwards for some reason:

public java.awt.Color(int r, int g, int b, int a) {
    value = ((a & 0xFF) << 24) |
            ((r & 0xFF) << 16) |
            ((g & 0xFF) << 8)  |
            ((b & 0xFF) << 0);
    testColorValueRange(r,g,b,a);
}

What is the point of first initializing the fields and validating the method parameters afterwards? Shouldn't it be the other way around? Is it just a coding convention or does it have any practical use?


In general parameters should be checked before the rest of the method body in both methods or constructors. This is mentioned in the book Effective Java by Joshua Bloch. The section in question is available at the following link:

http://www.informit.com/articles/article.aspx?p=31551

There are a few exceptions but none of them apply in this case. My guess for why the java.awt.Color class does the check at the end is that some of the core Java classes don't follow what is considered best practice, especially really old ones like java.awt.Color. There are a number of examples of Java language classes that violate certain rules in a detrimental way. I'd highly recommend reading that book if you haven't had a chance to do so.