I'm working on a project that lets you create products in a database. It includes a form with an editable combo box so you can select a pre-existing manufacturer for the new product, or type in a name of a new manufacturer you want to create along with the product.
The combo box is populated with a collection of Manufacturer objects (they implement toString() so they display something meaningful).
The logic for dealing with the output from the combobox is currently implemented thus:
Object mfr = mfctrCombo.getSelectedItem ();
Product newPrd = new Product ();
// If the mfr is a string then we need to create a new Manufacturer
if (mfr instanceof String) {
Manufacturer newMfr = new Manufacturer ();
newMfr.setName ((String) mfr);
// Logic for persisting the new Manufacturer goes here
newPrd.setManufacturer (newMfr);
} else if (mfr instanceof Manufacturer) {
newPrd.setManufacturer ((Manufacturer) mfr);
}
// Logic for persisting the new Product goes here
This does work, but the need to cast the mfr object seems unnecessary to me. I'm doing an instanceof check at the start of the if block, so I know for a fact what type the object is inside the block. Is it really necessary to do the cast inside the block after doing the check at the start of it as well? It seems to me that it shouldn't be required.
While I'm new to Java I'm fairly sure that what I'm doing with the combo box isn't best practice, but as it's for a university project with a deadline set in concrete and because it appears to work sufficiently well for this purpose I'd rather leave discussing a better way of populating the combo box for another question.