I have an object instantiated and I would like to call a function of this object that going to initialize an attribute of it.
class Player {
private String sex;
public void born(){
this.sex = randomSex();
}
//Getters & Setters
}
Is this accepted ? Or we prefer to return a value from the function and initialize it manually outside the object ?
class Player {
private String sex;
public String born(){
return randomSex();
}
//Getters & Setters
}
class Test {
Player p = new Player();
p.setSex(p.born());
}
For more information, I try to instantiate an object representing a Crontab:
public class Crontab {
private Path path;
private boolean isPresent;
private List<Cron> crons;
public Crontab(Path path) {
this.path = path;
if (Files.exists(path) && !Files.isDirectory(path)) {
this.isPresent = true;
} else {
this.isPresent = false;
}
}
public void extractCronsFromFile() throws IOException {
ArrayList<Cron> crons = new ArrayList<Cron>();
Pattern p = Pattern.compile("^#? ?[* \d]* default:fr.default.cron.CronExecute \w*");
if (this.isPresent == false)
throw new IllegalStateException(
"Le fichier crontab n'existe pas pour le chemin:" + this.path);
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(this.path.toFile()));
String line = reader.readLine();
while (line != null) {
Matcher m = p.matcher(line);
if (m.find()) {
String s = m.group();
String[] cronArray = s.split(" java:fr.default.cron.CronExecute ");
boolean isActive = false;
if (cronArray[0].indexOf('#') != -1) {
isActive = true;
cronArray[0] = cronArray[0].split("#")[1];
}
crons.add(new Cron(isActive, cronArray[0], cronArray[1]));
}
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
throw e;
}
this.crons = crons;
}
}
Does it make sense to do that in the constructor here ?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…