Simplified a little, I have this code:
public class TaskProcessCases{
private Assessment assessment ;
public void execute() { // the actual name
for (Case case : cases) {
assessment = new Assessment();
// some more code (which a.o. sets 'id')
retrieveData(id); // the actual name
if (assessment.getMyField() == null) {
reopen();
}
// some more code
}
}
private void retrieveData(int id) {
// some more code which uses 'id'
assessment.setMyField(Integer.valueOf(42)); // just example
}
}
public class Assessment {
Integer myField;
public Integer getMyField() { return myField; }
public void setMyField(Integer myField) { this.myField = myField; }
}
My problem with this is that reading execute
, I have to check all methods called (like retrieveData
) to know where assessment
is changed.
Is this the right way to write this?
Should I pass assessment
to retrieveData
like retrieveData(assessment )
to make it more explicit? Should retrieveData
be a method of assessment
? With help I thought I might initialize everything in the constructor and make the class immutable, which is great, but rather intrusive.
EDIT: My aim is to have code that is readable to a typical programmer, which does not invite the making of wrong assumptions and which has few ways to be used/changed incorrectly. Small differences in performance don't matter here.
EDIT: I made the code more specific. Here is the old version which the first answers were based on:
class Alpha {
Beta inst;
void doThing() {
inst = new Beta();
// some more code
fill();
// some more code
inst.getMyField();
}
void fill() {
// some more code
inst.setMyField(Integer.valueOf(42));
}
}
class Beta {
Integer myField;
public Integer getMyField() { return myField; }
public void setMyField(Integer myField) { this.myField = myField; }
}
fill
can be renamed to "initMyFieldOfBeta", then it should be clear what it does, but does this make sense in context of the other abstractions? Impossible to say.