I have 0..n objects, each of which requires a unique identifier, that are created in this way:
public class Squirrel {
private static numSquirrels = 0;
private String id = null;
public Squirrel() {
this(String.valueOf(numSquirrels++);
}
public Squirrel(String id) {
this.id = id;
}
}
This is a problem in a few ways but I'll give one:
When unit testing, the numSquirrels variable carries over between tests, even though I may be working with a different population of squirrels. That means that their IDs continue to increment when I'd like to start fresh.
- Is this the correct time to use a SquirrelFactory (the ones the kids are raving about)?
- Should I pass the Factory into the Squirrel object using dependency injection, or should the Squirrel class be contained inside the Squirrel Factory which has an interface to the outside world?
- How do I ensure uniqueness if I want the user to be able to set the ID (or at least suggest IDs)?