Article thumbnail

Improving code that was not written by us

5m
patterns
code improvements

Intro

We'll check how developers can avoid bugs with facade pattern. Let's understand the power of this simple pattern and use it.

Prelude

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.

Loading

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.

Loading

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.

Loading

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.

Loading

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.

Loading

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.

Loading

Full example

Summary

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!

I create content regularly!

I hope you found my post interesting. If so, maybe you'll take a peek at my LinkedIn, where I publish posts daily.

Comments

Add your honest opinion about this article and help us improve the content.

created: 03-05-2022
updated: 02-07-2022