Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation after initializing variables in a constructor: why not the other way?

Tags:

java

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?

like image 892
Jan Schultke Avatar asked Nov 25 '25 19:11

Jan Schultke


1 Answers

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.

like image 123
Aaron Davis Avatar answered Nov 27 '25 07:11

Aaron Davis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!