Clean code

The Baseline

Code is clean if it can be understood clearly by everyone in the team, and code can also be changed easily to meet different needs in the future.

Readability

Changeability

Extensibility

Maintainability

The concept of technical debt is important, and by not creating clean code, there are long term ramifications for a business. By writing code that isn’t clean, it is the same as taking out a loan. Even if you take shortcuts and achieve something faster, the loan will attain interest and you will pay a higher cost later on. (quote I found from a random article).

Some of the basic stuff

Variable Naming

Choose descriptive unambiguous names

Use searchable names (so ctrl + f life is easier)

Don’t use random indexing and replace with named constants.

Functions

Keep it small

Try your best to make it do one thing

Fewer arguments

No side effects

Don’t alter a global variable.

Avoid logical dependencies

Concepts to remember

Be consistent when writing code. Generally this means following the standards set by the company you are working at.

DRY Code. Try no to repeat the same code. Generally I like to offset the repeated code into a shared utils file.

SOLID Code. The classic thing we learn in uni. A set of principles to look into (which I won’t explain here since it will take a while.

Things I’ve learnt from work

To be honest, the best code from what I’ve experienced is code that can be easily read by other people in your team. As long as your follow a company specific convention and your code is not ambiguous. Some of the things I’ve learnt from work that I need to remember are as follows

Always think about extensibility. Think about how in the future if a user were to add more options to a react component such as a button component. Make an enum of all the possible types to ensure type safety and make sure that it is easy to add in new button types for example.

Try to split into more components, our legacy code used to include 1000+ lines which could easily be reduced for readability (imagine reading through 1000 lines to find a specific function causing a bug!). I tend to try to limit a file size to 300 lines max (generally less than this)

Sort folders contextually (a lot of legacy code was a bit messy)

Some useful articles

https://gist.github.com/wojteklu/73c6914cc446146b8b533c0988cf8d29

https://moderatemisbehaviour.github.io/clean-code-smells-and-heuristics/

https://www.planetgeek.ch/wp-content/uploads/2014/11/Clean-Code-V2.4.pdf

https://github.com/ryanmcdermott/clean-code-javascript