Ultimately you're going to need to do some kind of test to know whether or not you need to disable the field, and you test on boolean
values, so the easiest way to get that boolean
is to simply pass it. Parameter passing of any kind, primitives, objects, etc., is relatively cheap, so performance wise, there isn't really any issue with this.
In terms of design, it makes sense to use the parameter since this is indeed the purpose of a boolean
value, to indicate to do one thing or another whether it's true or false.
Any other solution you come up with is going to be either nasty or slow (I'm looking at you, Thread.currentThread().getStackTrace()
people) and is going to require you to test some value, but you'll have to calculate that value first, which takes time.
If you really don't want to pass the parameter, then maybe you can use some kind of state within the object to decide this, but ultimately that will just be a boolean
field instead of a boolean
parameter, so really, you're just doing the same thing. Plus, if you run that code in any kind of concurrent system, then you'll have to add synchronization, which just further increases code complexity you could have avoided by passing it as a parameter.
I guess, long story short, just use a parameter. It's sensible, readable, and anyone who reads your code will immediately understand what you did. Don't do things in your code that are vague, that will hinder readability, etc. just because it will "do something cool" like make it so you don't have to pass a parameter. Think of it like this: if someone wanted to call that method from some other method besides the ones you added, how long would it take them to figure out how to call it?
Edit: One other option would be overloading. You could provide some common default-valued method and a method with the parameter. If you find that you enable the field more often than you disable it:
public void showDialog() {
showDialog(true);
}
public void showDialog(boolean fieldEnabled) {
// Show the dialog
}
Then everywhere that opens the dialog with it enabled will call the first method (or the second with true
), and the ones that want it to be disabled call the second one and have to pass false
.