Design Pattern and Refactoring

Michael Sudirman
Moodah POS
Published in
2 min readNov 14, 2019
Making things look better

With the ever growing lines of codes that we write into our project everyday, we tend to get messy and do not even know how to add features anymore. Yes, it might be a running code, but it will not be soon if we do not do something about it. Having techniques such as refactoring will sure guide you in making the best structured codes.

“I’m not a great programmer; I’m just a good programmer with great habits.”
Martin Fowler, Refactoring: Improving the Design of Existing Code

React JavaScript: HOC (Higher Order Component) Design Pattern

React JS revolves around states and props, and these properties can be messy when you are working under variety of functions. With the use of HOC pattern, we can implement a “habit” so that simple components can reuse the same codes.

Enhancing component by giving it additional functionality or data

To put it in words, HOC is a JavaScript function that takes a component, inject or add additional data and functionality and return the new component with those additional data.

To go deeper, lets look at the codes below:

const newComponent = (BaseComponent) => {
class HOC extends React.Component {
render() {
return <BaseComponent />;
}
}

return HOC;
};const updatedComponent = newComponent(oldComponent);

We can see that updatedComponent is a baseComponent that is enhanced by a function called newComponent. ThenewComponent will give additional functionality or data from baseComponent adding them before/during the render() function.

How Moodah POS use HOC

During our project development of Moodah POS, we are asked to use HOC pattern for Front-end. It is reasonable to use HOC design pattern because the project will have pages with similar characteristics(e.g: list display, forms, etc).

Table Display on POS Category(left) and POS partner(right)

Both tables uses different

React HOC example, and how base component can be altered differently

With the use of HOC, each models can have have a same base component, yet have a different “added value”. In our case, we use added filters, offset, and limit for our posConfigs table. In the code above, both posConfigs and ResPartner will give the same additional property; filters,offset,limit. However, we can choose to delete any of those variables if not needed(because there can and will be table that does not need limit/offset/filters feature) for a table in the future! pretty neat huh.

Now that we know the importance of design pattern, hopefully we can do better in structuring our codes! yay~

--

--