23 Apr 2019 • 3 min read
I've been reviewing a lot of code lately and have seen some good and not-so-good practices. There is code that works, and then there is code that works and reads well. Here are three easy ways to write cleaner, more readable code.
Almost every language has specific naming conventions. Functions and variables in Python are snake_cased
. Javascript functions are camelCased
. If you're writing a CSS class it will probably be spinal-cased
. Go with the grain of the language.
Never mix case unless there is absolutely no other choice. Mixing case makes the developer experience worse because then your mind has to juggle "is this a function? a variable? a constant?".
In addition to language conventions, follow codebase conventions. There are cases where previous developers have made deliberate decisions about naming things. For example:
snake_cased
. You might make the conscious choice to use snake casing with data that comes back from the API for consistency.Many languages let you be liberal with whitespace (even whitespace delimited languages like Python). Before making a pull request, look at your code and see if a little spacing could make it easier to read. For example, the code that renders my "TH" top left link:
<Button href={Routes.home()} className={classnames(styles.Brand, 'global-brand')} noStyling={true}>
TH
</Button>
I wouldn't say that code is bad, but depending on how wide your editor is, it could be difficult to read. Let's add a little bit of whitespace:
<Button
href={Routes.home()}
className={classnames(styles.Brand, 'global-brand')}
noStyling={true}
>
TH
</Button>
When rereading both snippets, the second is easier to scan and see what props I'm passing to Button
.
I have found that by the time I finish writing a piece of code, the variable and function names I initially started with no longer accurately describe what is happening in the code. So before comitting any new changes to master, revisit your variable and function names and ask yourself:
If you decide that a variable or function needs to be renamed, always choose clarity over brevity. Tickets
might be shorter, but NewTicketsWithoutAnId
will make your code easier to understand.
None of these tips are groundbreaking, but it's surprising how these simple practices can really make a big impact on the readability and maintainability of the code you write.
Get my posts in your feed of choice. Opt-out any time.
If you enjoyed this article, you might enjoy one of these: