I have a method that I want to call from two different places on the same class where in one it calls a dialog normally and on the other it calls the dialog with one disabled field on it.
I know that passing a flag on the call and making the test inside the method works but is there a more optmized way of doing it?
Is there any way to inside the method knowing where the call happened?
edit:
// The part where you call the method passing a flag.
showItemCustomDialog(true);
showItemCustomDialog(false);
// The dialog
public void showItemCustomDialog(boolean flag) {
customDialog = new Dialog(this));
field.setEnabled(flag);
}
Is that a good example?
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
booleanvalues, so the easiest way to get thatbooleanis 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
booleanvalue, 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
booleanfield instead of abooleanparameter, 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:
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 passfalse.