my question is all about to write nice and clean Java code. Let's say that I have this method:
public static int getRealPosY() {
realPosY = (matrix.length -1) - pos.getPosY();
return realPosY;
}
and I call:
matrix[posX][getRealPosY()] = 1;
Is this nice and clean for you?? I know that my method return me an Int but...I don't know why....to call a method like this seems "weird" for me. I just want to learn the right way to write this....
I can also write:
int y = getRealPosY();
matrix[posX][y] = 1;
But like this seems to have a useless access to a variable.
Or I can use the same variable "private static int realPosY;":
realPosY = getRealPosY();
matrix[posX][realPosY] = 1;
But, again, it seems weird to use exactly the same variable of the get method.
I'm quite new of Java so of course I'm a bit confuse. BTW if someone want to teach me it would be great. Thank you very much.
In my opinion
public static int getRealPosY() {
realPosY = (matrix.length -1) - pos.getPosY();
return realPosY;
}
Is bad because it it isn't just getting some value, it has a side effect of changing the value of the global variable realPosY
. This is ok in your own small program, but if you are working with other people (or on a big code base), then it can make the code harder to debug and maintain.
The "normal" solution is probably one calculateRealPosY()
method that just sets the global, and then use the global directly (we won't open the can-o-worms about why you have globals in the first place ;-)
If it really does make your calling code easier, then calculateRealPosY()
can return the new value of realPosY
- it's still slightly ambiguous, but it's a lot better than completely hidden side effects in a getter!