Skip to content
Advertisement

A global variable as a method argument in the same java class: Is this bad programming practice?

Below code works just fine. But as a newbie I’m not sure if it’s bad practice to pass the global variables into the private method as an argument in the same java class. Is this acceptable? Is there a better or more acceptable way to do it, in case this is bad programming?

JavaScript

Advertisement

Answer

If the expectancy is that the setboolean method will change the value of the canExecute field, then that’s unfortunately not correct.

So when you call this line

JavaScript

It will actually take the current value of this.canExecute and will pass it in. The method setboolean does not know where that value comes from.

So when setboolean updates the value of the parameter, it won’t have any effect outside the scope of that function.

So, in your case, what would make more sense is:

JavaScript

And then use the function like this.canExecute = setboolean(...); Just using the return value of the function.

There is another way. You may want to look at BooleanHolder, which acts like a wrapper around a primitive boolean. The advantage is that you can pass it around and change the content of the holder. That’s close to what you attempted to do.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement