We are using Java as a backend development language.
We are using a List variable as
method() {
List recordsList = new ArrayList<Record>();
.
.
recordsList.add(records);
.
.
recordsList.flush();
.
.
recordsList.add(new Record());
}
Should we consider Split Temporary Variable refactoring pattern in this case, thus creating a new List as
method() {
List recordsList = new ArrayList<Record>();
.
.
recordsList.add(records);
.
.
recordsList.flush();
.
.
List newRecordList = new ArrayList<Record>();
newRecordList.add(new Record());
}
1 Answer 1
Yes. There are three reasons to do this:
it prevents confusion where someone reading the code might think an operation performed on the second group of items was performed on the first or vice versa, because they didn't notice the list being cleared
it encourages you to come up with more specific variable names - you'll have to rename one of them and hopefully you will find a useful way of designating the difference between the two lists
at least in Java, the ArrayList implementation doesn't shrink its backing array when you clear the list, which could result in memory being wasted while the second half of your operation is ongoing.
Furthermore, I would examine your method closely in terms of size and complexity. If your operation generates a list, uses it, then empties and generates a new one, I would question whether it might be wise to split it into two methods encapsulating these two separable phases of the operation.