In Java, given a pair of public methods, enableFoo and disableFoo, that set a boolean field named isEnabledFoo to true or false, respectively, should the method check to see if Foo is already enabled before setting? If yes, should an exception be thrown? If yes, should it be checked or unchecked? If unchecked, what should it throw? IllegalStateException?
A twist: Although the current implementation simply sets a boolean field, I'm purposely not implementing it as one setFoo "setter" method with a boolean parameter because the implementation might be changed later on to include side effects (maybe even not setting a field at all). Keeping it as enableFoo/disableFoo seemed the best way to guarantee encapsulation.
Should I do this:
public void enableFoo() throws myCheckedException
{
if (! this.isEnabledFoo)
{
this.isEnabledFoo = true;
}
// Is this overkill?
else
{
// Foo is already enabled...Should a checked exception be thrown?
throw new myCheckedException ("Foo is already enabled.");
// What about an unchecked exception?
// throw new IllegalStateException ("Foo is already enabled.");
}
}
or simply like this:
public void enableFoo()
{
// I guess we don't care if foo is already enabled...
this.isEnabledFoo = true;
}
or even:
public void enableFoo()
{
// Is this just code bloat?
if (! this.isEnabledFoo)
{
this.isEnabledFoo = true;
}
}
I think that while the last two versions are simpler, they would hide a possible bug where the developer was calling enableFoo thinking that it was disabled, when in fact it was already enabled (but would that really matter?). What's the best design here?