- code improvements
How to unify code written by programmers? How to add additional methods? How to hide what is not needed and how to simply make your life easier with facade pattern.
During a project you will most likely cooperate with other developers. Each of them has a slightly different writing style. In addition, you might encounter situations where the code is duplicated or specific methods are missing.
What if you had something to unify the API, add the missing methods and force developers to write consistent code?
We will implement the List class using the facade pattern to create code which solves above problems.
1. API design
We want our List class to have additional functionality - tracking a specific list item and reading this item at any time. Plus, we need a method that will allow us to replace a specific element.
In addition, we need a method that will allow us to replace a specific element.
2. Mock implementation
Let’s create class which implements previously created interface. In TDD, throwing exceptions is a standard practice to indicate that they are not yet implemented.
3. Creation of test scenarios
Before starting the implementation, think about exactly how your methods should behave. We’re going write our test scenario. Thanks to this approach it is possible to locate more edge cases in the code.
4. Implementing tests
Time for tests implementation. After this step, all tests are read. We created some helper functions and test user data which you can check inside mocks directory.
5. Making tests green
Having the correct implementation, we can go to refactor later. In this article we skip this step.
In the constructor, we assign initial values and set the pointer. Then we implement specific methods that will move the pointer and return a new instance of the List. Additionally, we add a method to replace an element with an identifier or a pointer / index.
6. Usage in React
No spread operators, no anonymous functions for data management, 100% immutability, separation of concerns, encapsulation and readable / consistent code as benefits of facade pattern.
I hope you enjoyed this quick win 🙂.
Of course this is simple example but as you see sky is the limit and you can create your own facade for everything in your application.
Feel free to contact me if you have any questions/proposals. Have a nice day and good health!