Sometimes there's a fine line between being safe and running scared.
Does this code cross the line into scaredy-cat zone?
DuckbillPlatypusForm dbpf = null;
if (radioButtonUseExistingPlatypus.Checked) {
dbpf = new DuckbillPlatypusForm(DuckbillSetupUtils.DuckbillPlatypusState.Readonly, funnyMammalIDs);
} else if (radioButtonCreateNewFromExistingPlatypus.Checked) {
dbpf = new DuckbillPlatypusForm(DuckbillSetupUtils.DuckbillPlatypusState.Template, funnyMammalIDs);
} else if (radioButtonCreateNewPlatypus.Checked) {
dbpf = new DuckbillPlatypusForm(DuckbillSetupUtils.DuckbillPlatypusState.StartNew, funnyMammalIDs);
}
if (null != dbpf)
{
dbpf.Show();
}
After all, there are only three radio buttons, and one is checked at design time, so dbpf can never be null, right? Unless somehow all of the radio buttons become unchecked at design-time, or I add another radio button without updating this code, and that one gets selected, but at what point do I just "bite the bullet" and accept suchlike risks?
Checking for null is good in my opinion, because there is a chance that another radio button will be added in future. Maybe from another developer of your team (not yourself), and perhaps it's quite some time in the future.
Maybe it would be even better to handle it as an exception, if the variable is null, because that would certainly be an error in the code, and should be fixed.
Edit:
If you rearrange your code a little bit, the exception thing would become very natural. Just separate the reading from the GUI.
function DuckbillSetupUtils.DuckbillPlatypusState StateFromGui()
{
if (radioButtonUseExistingPlatypus.Checked)
return DuckbillSetupUtils.DuckbillPlatypusState.Readonly;
if (radioButtonCreateNewFromExistingPlatypus.Checked)
return DuckbillSetupUtils.DuckbillPlatypusState.Template;
if (radioButtonCreateNewPlatypus.Checked)
return DuckbillSetupUtils.DuckbillPlatypusState.StartNew;
else
return DuckbillSetupUtils.DuckbillPlatypusState.Undefined;
}
new DuckbillPlatypusForm(StateFromGui(), funnyMammalIDs);
Now if the constructor is called with State Undefined, you can throw an exception. This way, if you add another radiobutton, you have to update only this StateFromGui function, and you have a single point to test the state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With