The question to ask yourself is what is the job or responsibility of the People
class (or the Person1
class - you seem to have used different names) and how much external resource, coordination and time will it need? These questions should also lead you to examine: will your class need to preserve state of the name or anything else? In other words, is generating the name expensive? Will you only need the name once? Will you need to share one single name, or will you need different names for different users or threads or whatever?
For example, if your method creates a random name by simply iterating and a few calls to Math.random()
, and you want a different name each time, this sounds suited to a static utility class:
public final NameUtils {
private final NameUtils() {} // only allow access to static methods
// 2 consecutive calls will give different results
public static String generateName() {
StringBuilder name = new StringBuilder();
// do stuff to generate name
return name.toString();
}
}
Alternatively, if your name generation involves lookups and fetches to a database, a library of xml files and/or some external website or service (be it SOAP or REST or whatever) or even just parsing a flat file with a list of common names in it, then you need something more involved, but which involvement is hidden from the calling code.
public interface NameGenerator {
// 2 consecutive calls should give same result for a given instance
String getName();
// Might take a while (30 seconds or more) consider wrapping in a thread and using a `Future`
void generateName() throws NameGenerationException;
}
public class NameGeneratorImpl implements NameGenerator {
private String name = null;
public String getName() { return this.name; }
public void generateName() {
Resource resource = // for example database connection
try {
// this might even be broken down into multiple private methods
// a. access resource
StringBuilder nameBuilder = new StringBuilder();
// b. get data from resource
// c. use data in name formula
this.name = nameBuilder.toString();
} catch(ResourceException e) {
throw new NameGenerationException(e);
} finally {
// free expensive resource
}
}
}