1

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());
}
asked Dec 29, 2015 at 18:16

1 Answer 1

4

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.

answered Dec 29, 2015 at 18:56

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.