loading...

HOW TO WRITE MAINTAINABLE CODE

oyelowo profile image Ye ・2 min read

Frontend guidelines

Prefer small, simpler functions and components over longer ones. Bigger functions and components can always be decomposed into smaller parts.
Why? Bigger Functions/components are harder to follow/read. They can also introduce complexities into your type declarations and testing.

Ideally, Functions should hardly be longer than 20 lines (humans have short attention spans) and keeping things more focused can help keep others reading your code engaged. When it’s getting longer than that, start thinking of how you could break down the complexity and abstract more specific logics out into other functions, inline with Single Responsibility of the SOLID principle.

It is okay not to know every underlying implementation details of each sub-function just the same way we utilize helpers from third party libraries and not worry about their implementation details. Testing increases the confidence of a codebase and smaller functions enable easier testing.

React Components should hardly be longer than 100 - 200 lines. Rather than having several logics in a component, abstract the logic into normal helper functions or hooks if the logic relies on other hooks.

Prefer at most 5-10 custom properties for your react component. Having more custom properties might be a sign that you need to break down the component into smaller parts and group them into a logical shared folder

Avoid passing props beyond one level. Prop drilling can often make debugging harder and also make it difficult for others to follow your code. When you need to pass props beyond one level, prefer using Context API with hooks. This combined with typescript greatly simplifies things

Be mindful of premature optimizations with React’s memoizing functionalities as React is quite fast. Memoizing introduces complexities into your codebase, hence, you want to be sure that you are reaping the benefits

Use more specific descriptive names for variables, functions, components and types e.g getEntireStudentsSummerData over getData

Prefer pure functions whenever possible

Avoid big reducers as they are just like every other function. Reducers can always be split into subReducers.
The React ecosystem has moved from HOC/Props towards more functional hooks, hence, we should try to move towards that as they are simpler, easier to type and debug

Posted on by:

Discussion

pic
Editor guide