If the client could access the public field in your question before it had a value assigned to it (i.e., without calling the constructor), there would be an obvious issue. Specifically, this field could not have an expected/proper value when a client tried to access it. Nonetheless, as has been pointed out in the comments, you have not declared Test.MY_INT
with a static
identifier, making it essentially impossible for the value of this constant to be retrieved without first calling the constructor.
Therefore, it would appear sensible (in terms of immutability) to do what you are doing. However, in terms of "good code," you are (as others have said) forcing yourself and your clients to refer to this value explicitly by name. If you were using a getter, though, and needed to change the name of MY_INT
while keeping the purpose of the constant the same, neither you nor your client would be forced to change anything beyond the implementation in Test
.
To be more explicit, I provide your class with a getter and privatized constant.
public class Test {
private final int MY_INT;
public Test(int myInt) {
MY_INT = myInt;
}
public int getAssignedIntValue() {
return MY_INT;
}
}
I would get the assigned integer value like so:
Test test = new Test(1);
// with your class
test.MY_INT;
// with the above class
test.getAssignedIntValue();
Now, say I rename MY_INT
to myInt
to match naming conventions. In both cases, I have to change all occurrences of MY_INT
in the Test
class. But, the difference between the two implementations becomes clear when I need to get the value with the new constant name:
// if this is the old code from above
Test test = new Test(1);
// I need to change this to test.myInt, or I get an ERROR!
test.MY_INT;
// since I didn't change the name of the getter, all is well
test.getAssignedIntValue();
Note: while this may have been an acceptable answer, it does not necessarily have the most applicable reasoning. Please see this answer for reasoning given in a more general context.