Refactoring Replace Array with Object
This refactoring technique is a special case of Replace Data Value with Object.
ProblemYou have an array that contains various types of data.
SolutionReplace the array with an object that will have separate fields for each element.
String row = new String; row = "Liverpool"; row = "15";
Performance row = new Performance(); row.setName("Liverpool"); row.setWins("15");
string row = new string; row = "Liverpool"; row = "15";
Performance row = new Performance(); row.SetName("Liverpool"); row.SetWins("15");
$row = array(); $row = "Liverpool"; $row = 15;
$row = new Performance(); $row->setName("Liverpool"); $row->setWins(15);
row = [None * 2] row = "Liverpool" row = "15"
row = Performance(); row.setName("Liverpool") row.setWins("15")
Arrays are an excellent tool for storing data and collections of a single type. But if you use an array like post office boxes, storing the username in box 1 and the user's address in box 14, you will someday be very unhappy that you did. This approach leads to catastrophic failures when somebody puts something in the wrong "box" and also requires your time for figuring out which data is stored where.
In the resulting class, you can place all associated behaviors that had been previously stored in the main class or elsewhere.
The fields of a class are much easier to document than the elements of an array.
How to Refactor
Create the new class that will contain the data from the array. Place the array itself in the class as a public field.
Create a field for storing the object of this class in the original class. Do not forget to also create the object itself in the place where you initiated the data array.
In the new class, create access methods one by one for each of the array elements. Give them self-explanatory names that indicate what they do. At the same time, replace each use of an array element in the main code with the corresponding access method.
When access methods have been created for all elements, make the array private.
For each element of the array, create a private method in the class and then change the access methods so that they use this field instead of the array.
When all data has been moved, delete the array.
Tired of reading?
No wonder, there are 7 hours worth of the text on this website.
Try out something different. We've just launched the interactive learning course on refactoring. It has more content and much more fun than a boring text.Learn more...
Everything is quite simple. This example is like video (but much cooler):
- After pressing the Play button, you will see floating messages, which will guide you through the example. You can proceed by clicking on them.
- You can fast-forward or return to previous steps by pressing arrow buttons on the left.
- Also, you can take a look at the code diff window, which will show what has changed in code during the example ()
- To check the code for errors, you can press "Compile and test" button ()