本篇同步發文於個人網站: Organizing Data
This article references the chapter 9 ” Organizing Data ” of Refactoring: Improving the Design of Existing Code (2nd Edition). Author had highlighted many important refactorings in this chapter.
I use .NET C# to practice with these refactorings and upload to Github.
(Photo from Pixabay: https://pixabay.com/photos/cabinet-drawer-wood-catalogue-3283536/)
Split Variable
Tips
- Loop variable and collecting variable are special. They are assigned value many times.
- Other variable is responsible for one thing. It should be assigned value one time.
- If some variable is assigned many times, we should split it into different variables.
Examples:
- A simple example
- Assigning to an Input Parameter
Github
Rename Field
Tips
- A field with good naming makes the developer clever about what the code does.
- Field and accessors (getter/setter) namings are important.
- If a record is still not encapsulated, use Encapsulate Record.
Examples:
Github
Replace Derived Variable with Query
Tips
- We should minimize the scope of mutable data at much as possible.
- Use this skill to avoid “We update the source data but we forget to update the derived variable”
Examples:
- A simple example
- More Than One Source
Github
Change Reference to Value
Tips
- A value object is immutable. We can transfer this object into other logic without caring about modifying the object’s data.
- If an object can be shared between many objects and they can see its modification, it should be a reference object.
- Value object usually implements equals function.
Examples:
- A simple example
- More Than One Source
Github
Change Reference to Value
Tips
- If a shared Value Object data needs update, we need to find all data copies and update them. Change it to Reference Object and the object’s update reflects on all clients.
- Build a Repository to manage the reference object. All clients find the reference objects by the repository.
Examples:
Github
Conclusion
This chapter introduces me how to organize data. In ASP.NET MVC development, I have used Service/Repository pattern to manage my data source. And I used the LINQ to perform Replace Derived Variable with Query. I have grown up to write better code when I study this refactoring chapter. If you want to learn detailed motivation and mechanics, study the chapter 9 ” Organizing Data ” of Refactoring: Improving the Design of Existing Code (2nd Edition). and it improves our programmer’s ability.