Clean Coding

Clean Coding

ยท

2 min read

๐—ง๐—ถ๐—ฝ๐˜€ ๐—ณ๐—ผ๐—ฟ ๐—–๐—น๐—ฒ๐—ฎ๐—ป ๐—–๐—ผ๐—ฑ๐—ฒ

When we code, we write it for others to read later on, not for ourselves. Even if a person is working on an individual project itโ€™s crucial that your code is readable to another developer.

๐Ÿญ. ๐—”๐˜ƒ๐—ผ๐—ถ๐—ฑ ๐—ฝ๐—ผ๐—ผ๐—ฟ ๐—ป๐—ฎ๐—บ๐—ถ๐—ป๐—ด

Variables should be meaningful, reveal intention, and should be chosen from the problem domain

๐Ÿฎ. ๐—™๐—ผ๐—น๐—น๐—ผ๐˜„ ๐—ฐ๐—ผ๐—ฟ๐—ฟ๐—ฒ๐—ฐ๐˜ ๐—ป๐—ฎ๐—บ๐—ถ๐—ป๐—ด ๐—ฐ๐—ผ๐—ป๐˜ƒ๐—ฒ๐—ป๐˜๐—ถ๐—ผ๐—ป๐˜€

Itโ€™s important that you follow the correct naming convention to avoid being a chaotic coder. Be consistent with the casing.

๐Ÿฏ. ๐—ž๐—ฒ๐—ฒ๐—ฝ ๐—ณ๐˜‚๐—ป๐—ฐ๐˜๐—ถ๐—ผ๐—ป ๐—ฝ๐—ฎ๐—ฟ๐—ฎ๐—บ๐—ฒ๐˜๐—ฒ๐—ฟ ๐—ฐ๐—ผ๐˜‚๐—ป๐˜ ๐˜๐—ผ ๐—ฎ ๐—บ๐—ถ๐—ป๐—ถ๐—บ๐˜‚๐—บ

The best practice is to keep your method to 3 or fewer parameters. While it can become hard sometimes when you look closely there are situations where you can split the method into different functions.

๐Ÿฐ. ๐——๐—ฒ๐—ฐ๐—น๐—ฎ๐—ฟ๐—ฒ ๐˜ƒ๐—ฎ๐—ฟ๐—ถ๐—ฎ๐—ฏ๐—น๐—ฒ๐˜€ ๐—ฎ๐˜ ๐˜๐—ต๐—ฒ ๐—ฝ๐—น๐—ฎ๐—ฐ๐—ฒ ๐—ผ๐—ณ ๐˜‚๐˜€๐—ฒ

Variables should be declared at the place where they are actually being used. That way you wonโ€™t have to scroll back and forth to understand your code.

๐Ÿฑ. ๐—”๐˜ƒ๐—ผ๐—ถ๐—ฑ ๐˜‚๐˜€๐—ถ๐—ป๐—ด ๐—ฐ๐—ผ๐—ป๐—ณ๐˜‚๐˜€๐—ถ๐—ป๐—ด ๐—บ๐—ฎ๐—ด๐—ถ๐—ฐ ๐—ป๐˜‚๐—บ๐—ฏ๐—ฒ๐—ฟ๐˜€

If you are using numbers in if-else-if conditional statements, declare constants to explain their meaning. Also, you can create an enumeration if the value is being used at multiple places.

๐Ÿฒ. ๐— ๐—ถ๐—ป๐—ถ๐—บ๐—ถ๐˜‡๐—ฒ ๐—ฒ๐˜…๐˜๐—ฒ๐—ป๐˜€๐—ถ๐˜ƒ๐—ฒ ๐—ป๐—ฒ๐˜€๐˜๐—ฒ๐—ฑ ๐—ฐ๐—ผ๐—ป๐—ฑ๐—ถ๐˜๐—ถ๐—ผ๐—ป๐˜€

Multiple nested conditions make it hard to read your code. Always try to simplify them. Hint: use the switch statement or combine them using conditional operators.

๐Ÿณ. ๐——๐—ผ๐—ปโ€™๐˜ ๐—ถ๐—บ๐—ฝ๐—น๐—ฒ๐—บ๐—ฒ๐—ป๐˜ ๐˜€๐˜‚๐—ฝ๐—ฒ๐—ฟ ๐—น๐—ผ๐—ป๐—ด ๐—ณ๐˜‚๐—ป๐—ฐ๐˜๐—ถ๐—ผ๐—ป๐˜€

The function should be short and do just 1 thing. Try to avoid creating long functions. Just because you can read it and understand that doesnโ€™t mean itโ€™s a good practice. Most of the time itโ€™s hard to understand, change and reuse.

๐Ÿด. ๐—”๐˜ƒ๐—ผ๐—ถ๐—ฑ ๐—ฐ๐—ผ๐—ฑ๐—ฒ ๐—ฑ๐˜‚๐—ฝ๐—น๐—ถ๐—ฐ๐—ฎ๐˜๐—ถ๐—ผ๐—ป Do you find yourself copy-pasting the same code to different places with small changes? Bad..Use the DRY principle instead

๐Ÿต. ๐— ๐—ฎ๐—ธ๐—ฒ ๐—ป๐—ฒ๐—ฐ๐—ฒ๐˜€๐˜€๐—ฎ๐—ฟ๐˜† ๐—ฐ๐—ผ๐—บ๐—บ๐—ฒ๐—ป๐˜๐˜€

Use your comments to explain the whys and hows. Never state the obvious using comments. Donโ€™t keep dead code in comments, use version control

ย