Writing Readable and Maintainable Code in TypeScript.

Writing Readable and Maintainable Code in TypeScript.

How to make it easier for other people to understand your code.

Freek MenckeBlockedUnblockFollowFollowingMay 14Photo by Carles Rabada on UnsplashThe thing I hate most about programming is when I have to read code that I don’t immediately understand.

I’m sure those of you who’ve worked in a team know what I mean.

Take this code for example:export function chunk(arr, size) { const R = []; for (var i = 0, len = arr.

length; i < len; i += size) R.

push(arr.

slice(i, i + size)); return R;}This code is not easy to read.

Sure, you can understand it, but you’d have to focus.

You may have to read it twice, or more, to fully understand what’s happening here.

There is also zero typing going on, so when using this function, it’s not even clear what’s supposed to happen.

Now take the following code:export class ArrayUtils { static chunk<T>(array: T[], chunkSize: number): T[][] { const chunks: T[] = []; let index = 0; while(index < array.

length){ chunks.

push(array.

slice(index, index + chunkSize); index += chunkSize } return chunks; }}We can immediately see that this is a function for splitting arrays into chunks.

If we were to use this function, our IDE would show exactly what parameters are requested and what we should expect as output.

When we want to look at the implementation, logically named variables and whitespace make it easy for us to understand this code.

You could say that it would take longer to write the code in the second example, compared to the first.

That’s probably true.

You will save that time, however, by making the function easier to use.

You won’t have to look that function up because you know what it will do.

The typings will make it easier to use that function because your IDE’s Intellisense will tell you how to use it.

You can also easier locate bugs because it’s much easier to read the code, causing you to understand it more quickly and more deeply.

The chunk array function might be a trivial example, but for more complex code the same logic will apply.

5 Tips to improve you and your team’s codeI’m going to share some of the things I’ve learned working on TypeScript projects as part of a team.

These are all things that, in my experience, made it easier to read and maintain our code.

It also reduced the time for new team members to become productive because they could quickly understand the code.

Don’t write code for yourself, write code for others.

What I‘m trying to say is that you always have to consider that other people will read your code.

It might not be today or even next week, but it will happen.

1.

Make you tsconfig as strict as possibleThis is probably the most important tip I’m going to give you in this article.

Let TypeScript do what it’s meant to do, it’s made to prevent human errors.

The best way to do this is by enabling TypeScript options that will force you to follow certain rules.

Don’t just enable all TypeScript features though, carefully consider what options would be an improvement for your team.

In some situations, it could be counterproductive to enable certain features.

Strict optionsThere are a couple of strict options in TypeScript that I highly recommend you to use:–noImplicitAnyRaise error on expressions and declarations with an implied any type.

–noImplicitThisRaise error on “this” expressions with an implied any type.

–alwaysStrictParse in strict mode and emit “use strict” for each source file.

–strictNullChecksIn strict null checking mode, the null and undefined values are not in the domain of every type and are only assignable to themselves and any (the one exception being that undefined is also assignable to void).

–strictFunctionTypesDisable bivariant parameter checking for function types.

I call these strict options because they are all set when you use the –strict flag.

There are a few more options that would be set, but they can be bothersome to use depending on what framework you’re using.

For example, using –strictPropertyInitialization with Angular clashes a bit with the @Input, @Output and @ViewChild(ren) decorators.

Non-strict optionsThere are a lot more options available that improve code quality, and I highly suggest you take a look.

You can find all of the options available in the TypeScript handbook: https://www.

typescriptlang.

org/docs/handbook/compiler-options.

html2.

Prefer readability over performanceVariable and function namesDon’t be that guy who always uses single letter variables.

Sure you might save a few milliseconds.

A few lines even.

But it’s all at the cost of your readability.

Always ask yourself the following question: “Would someone understand this code the first time they read it?”.

If the answer is yes, you give yourself a pat on the back.

If the answer is no, think of a good name that makes the purpose of this variable clear.

It can really make your code easier to understand.

The same goes for your function names.

If you see the name of a function, it’s parameters and the class it belongs to, you should know what the function does.

If you don’t, then it doesn’t have a proper name.

PerformanceIt all depends on the kind of project you’re working on, but in most cases, it’s not worth to save a millisecond if it makes your code that much harder to understand.

Code that’s hard to understand can easily cause bugs.

First focus on correctness, then clarity, and finally, if needed, performance.

If you do need the performance, make sure you use proper naming and to add some clarifying comments.

This way you will prevent your teammates from wasting their time trying to understand your complex code.

3.

LintingIf you don’t enforce a code style, everyone will code the way they prefer.

Some will use trailing comma’s, some will use 4 space indents, others will prefix their private variables with an underscore… In short, every file will look different.

With tools like TSLint and/or Prettier, you can make rules for the way you want the code to look.

Try to make your linting as strict as possible.

Sure it can bothersome if you miss a trailing comma or a semi-colon, but it will be easier to read other peoples code because you will know what to expect.

4.

Project structureAnother thing that can be time-consuming is to have a project structure that doesn’t make sense.

It can be really annoying when you’re trying to solve a bug, but you can’t find the file that handles that specific logic.

I can’t suggest a project structure for you.

What I can suggest is that you think before you randomly start creating folders and files.

Maybe even sit together with your team and try to create a project structure where everyone will be able to find what they’re looking for.

If you don’t, who knows what you’ll end up with.

5.

Pair programmingSometimes when you’re solving complex problems, it can be useful to do this in pair.

Working in pair has several advantages over working alone.

The first being that not one, but two people will understand this complex problem.

The second advantage is that four eyes will detect bugs faster than two eyes will.

The other person could also have a different solution in mind.

Perhaps combining your solutions could create an even better solution than either of you would have made if you worked alone.

Don’t always work in pair though.

You also have to able to program independently.

You can’t always rely on someone else.

TL;DRMake your tsconfig as strict as possible.

First focus on correctness, then clarity, and finally, if needed, performance.

Enforce a code style using TSLint and/or Prettier.

Make it easy to find relevant files in your project structure.

It can be useful to program in pair for complex problems.

Final noteThese are all things I’ve learned from my own experience.

Don’t underestimate the benefit of having a high-quality code base.

.

. More details

Leave a Reply