I've recently seen some code similar to that outlined below.
public void someMethod() {
Lecture lect = createLecture();
...
lect.getLectureSeries().delete();
}
public Lecture createLecture() {
LectureSeries series = new Series();
Lecture lect = new Lecture(series);
...
return lect;
}
The point being that some object (in this case the LectureSeries) which needs to be deleted at the end of the call to someMethod() is actually created in the call to another method. I'm trying to explain why it should be created in the same scope it will eventually be deleted. ie
public void someMethod() {
LectureSeries series = new Series();
Lecture lect = createLecture(series);
...
series.delete();
}
public Lecture createLecture(LectureSeries series) {
Lecture lect = new Lecture(series);
...
return lect;
}
The original code has caused some complication tidying things up when things fail so hopefully the benefits will be evident, but has anyone got any ideas on how I can explain the more general principle behind this refactoring? or anyone want to explain to me why I'm wrong?
== Edit ==
The case in question was a test method so cleaning up anything which had been created during the execution of the test was important. I think though that the unwanted side effect of a LectureSeries being created as a result of the call to createLecture() is still something to try and avoid in most cases.