the_real_jiub the_real_jiub - 7 months ago 5
Java Question

Only Allow Objects with Unique Name - Java

I am making an inventory system.

I want to ensure that objects I am creating (Ingredients) all have unique names. In other words, I want to make sure that there are never two Ingredients that have the same name in the whole program. Currently I have the following class:

package ingredient;

import java.util.HashSet;

public class Ingredient {

private final String name;
private final double price;

private static HashSet<String> names = new HashSet<String> ();

private Ingredient(String ingr_name, double ingr_price) {
name = ingr_name;
price = ingr_price;
}

public static Ingredient createIngredient(String ingr_name, double ingr_price) {
if (names.contains(ingr_name)) {
return null;
} else {
names.add(ingr_name);
return new Ingredient(ingr_name, ingr_price);
}
}

public String getName() {
return name;
}

public double getPrice() {
return price;
}


}

Then, when I go to actually make new ingredients, I make statements such as :

Ingredient egg = Ingredient.createIngredient("egg", 1);


Is this okay design? I suppose I am concerned because returning "NULL" might not be the best practice here.

Answer

I cant comment, but whatever... I would go about this by storing all of the Ingredients in a different class, then you wouldn't need all this static nonsense. In the class where you actually create a new Ingredient (Ingredient egg = Ingredient.createIngredient("egg", 1);) you could maybe create an ArrayList of ingredients like so:

ArrayList<Ingredient> ingredients = new ArrayList<>();

Then when you make a new Ingredient you would just have to make sure you add it to the ArrayListand when you do so, check that none of the ingredients are already there, maybe something like this:

createIngredient("egg", 1);

or

Ingredient egg = createIngredient("egg", 1);

...

private Ingredient createIngredient(String ingr_name, double ingr_price){
    for(Ingredient i : ingredients){
        if(i.getName().equals(ingr_name)){
            return null;
        }
    }
    Ingredient newing = new Ingredient(ingr_name, ingr_price);
    ingredients.add(newing);
    return newing;
}

Then the Ingredient class could be cut down to something like this:

package ingredient;

public class Ingredient {

    private final String name;
    private final double price;

    public Ingredient(String ingr_name, double ingr_price) {
        name = ingr_name;
        price = ingr_price;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }
}

And then you could access each individual Ingredientwith a method to run through the ArrayList and find the Ingredient with the name your looking for:

public Ingredient findIngredient(String name){
    for(Ingredient i : ingredients){
        if(i.getName().equals(name)){
            return i;
        }
    }
    return null;
}
Comments