Is it bad practice to directly manipulate data like:
Sorter.mergeSort(testData); //(testData is now sorted)
Or should I create A copy of the data and then manipulate and return that like:
sortedData = Sorter.mergeSort(testData); // (sortedData is now sorted and testData remains unsorted)?
I have several sorting methods and I want to be consistent in the way they manipulate data. With my insertionSort method I can directly work on the unsorted data. However, if I want to leave the unsorted data untouched then I would have to create a copy of the unsorted data in the insertionSort method and manipulate and return that (which seems rather unnecessary). On the other hand in my mergeSort method I need to create a copy of the unsorted data one way or another so I ended up doing something that also seems rather unnecessary as a work around to returning a new sortedList:
List <Comparable> sorted = mergeSortHelper(target);
target.clear();
target.addAll(sorted);`
Please let me know which is the better practice, thanks!
The best practice is to be consistent.
Personally I prefer my methods to not modify the input parameters since it might not be appropriate in all situations (you're pushing the responsibility onto the end user to make a copy if they need to preserve the original ordering).
That being said, there are clear performance benefits of modifying the input (especially for large lists). So this might be appropriate for your application.
As long as the functionality is clear to the end user you're covered either way!
It depends whether you're optimising for performance or functional purity. Generally in Java functional purity is not emphasised, for example Collections.Sort sorts the list you give it (even though it's implemented by making an array copy first).
I would optimise for performance here, as that seems more like typical Java, and anyone who wants to can always copy the collection first, like Sorter.mergeSort(new ArrayList(testData));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With