Introduction
About TypeScript
What Is It?
TypeScript is a superset of JavaScript. That is, it’s JavaScript with a bunch of additional features. After you’ve written your code, it compiles into JavaScript.
It was created by Microsoft and lead by Anders Hejlsberg (who was a core member of forming the C# programming language, among others).
TypeScript’s primary features and benefits include:
- A fairly advanced type system
- Support for future and bleeding-edge JavaScript features
- Fantastic support for developer tooling inside IDEs
What’s All The Fuss About?
TypeScript has gained a lot of traction in the past few years. In the 2019 Stack Overflow Developer Survey, TypeScript was rated as the #3 top loved programming language!
Why do developers love it so much?
From my own experience, it’s because JavaScript (due to its dynamic nature) can allow for some strange kinds of code. Also, because it’s compiled at run-time, most bugs are discovered at run-time (in certain production scenarios this can be too late to catch bugs!)
With TypeScript, on the other hand, you can define solid contracts by using types (classes, interfaces, types, implicit method return types, etc.). This enables the IDE you are using to immediately detect certain kinds of bugs as you type your code! It also makes your code more predictable and less error-prone since you have guaranteed method return types, for example.
I remember the first time that I introduced TypeScript into a real-world project - it increased my productivity tons! I discovered bugs that I had no idea existed too.
TypeScript Vs. JavaScript
I’d like to do a quick comparison between some vanilla JavaScript and TypeScript to give you an idea of what I’ve been talking about.
Let’s take some valid code in JavaScript:
1 const myData = getMyData();
How do I know what the getMyData
method will return? Will it return an object? A boolean?
If it does return an object, how can I know what the properties of the object are?
Other than digging into the source code for that method, I can’t.
Inside that method we could even do something strange like this:
1 function getMyData(kind) {2 if(!kind)3 return false;4 else5 return { data: "hi" };6 }
So… sometimes this function returns a boolean and other times it returns an object?
I’ve seen code like this in real-world production code-bases. And yes - it’s very hard to understand, debug, test and is very prone to errors.
Using TypeScript, you can “lock-down” the return type explicitly:
1 function getMyData(kind) : object {2 if(!kind)3 return false;4 else5 return { data: "hi" };6 }
This would not compile since the method signature says that the method should always return an object but the code can return a boolean and an object.
Take another example:
1 const user = {2 emailAddress: "test@test.com"3 };4 5 emailUser(user.emailAddress);6 7 user.emailAddress = 2;8 9 emailUser(user.emailAddress);
The second time we call emailUser
we are passing it a number instead of a string. That’s what I mean by “strange code.”
In TypeScript, this would throw an error at compilation time (and in your IDE as you type).
You would find this issue out immediately as you type. However, in JavaScript, you wouldn’t know about this until you tried to send an email to a user at run-time.
What if this bug ended-up only happening in certain production scenarios? In this case, using TypeScript could avoid this error before you even commit code in the first place!
Why I Chose TypeScript For This Book
I chose TypeScript as the language to use for this book because it has much in common with dynamic languages like JavaScript yet also has common features from object-oriented type-safe languages like Java and C#.
It has a good blend of object-oriented tools, functional tools and the ability to still harness the dynamic nature of JavaScript if needed.
Most of the techniques in this book are generic and can be applied to most other programming languages. TypeScript just happens to be a good middle ground to use to showcase these problems and solutions!
What Is Refactoring?
Let’s Define It
Refactoring is just a fancy term that means improving your code without changing how it behaves.
If improving the quality of your code introduces more bugs or changes how the system worked before, then is it really improving your code? Nope!
With refactoring, the best approach is to apply small targeted changes to a codebase. Instead of doing a huge sweeping change to your code, refactoring is better as a long-term and continuous enterprise.
Why? Applying larger changes all-at-once presents more risk and more time to implement.
We don’t want that.
We want to improve the health of our code while maintaining control of our code/software.
It’s important to have your code under test (unit, integration, etc.) which will give you a safety net to ensure any code changes won’t also change the behavior and cause bugs.
While we won’t look at building tests in this book, it’s important to remember the importance of having tests.
Our Approach
I’ve found that many refactoring resources are hard to follow and easily overwhelming. They also tend to start on the wrong end by telling you what a pattern is before explaining what problem it solves.
Each category/section in this book represents some kind of “code smell”. A code smell is some indication that a part of your code is rotting and becoming unhealthy.
The first chapter of each category will introduce how to identify a specific code smell and why it is considered unhealthy. Then, we’ll look at techniques that can be used to address the code issue - after we’ve explored the problem first!
Design Patterns
When learning about design patterns, it’s important to realize that these patterns are actually a form of refactoring tools.
Design patterns are meant to address issues around the fact that your code is not flexible enough, hard to maintain, etc.
As you move through this book, the emphasis will be on looking at and solving specific code issues. Some of those issues just happen to be solvable using design patterns!
Why Refactor At All?
Slow Development?
Ever work in a software system where your business asked you to build a new feature - but once you started digging into the existing code you discovered that it’s not going to be so easy to implement?
Many times, this is because our existing code is not flexible enough to handle new behaviors the business wants to include in your application.
Why?
Well, sometimes we take shortcuts and hack stuff in.
Perhaps we don’t have the knowledge and skills to know how to write healthy code (this book will help!).
Other times, timelines need to be met at the cost of introducing these shortcuts.
This is why refactoring is so important:
Refactoring can help your currently restrictive code to become flexible and able/easy to extend once again.
Code is like a living organism. Like a garden. Sometimes you just need to get rid of the weeds!
I’ve been in a software project where adding a checkbox to a screen was not possible given the system’s set up at the time! Adding a button to a screen took days to figure out! And this was as a senior developer with a good number of years under my belt. Sadly, some systems are just very convoluted and hacked together.
This is what happens when we don’t keep our code healthy!
Saving Money
It’s a practical reality that you need to meet deadlines and get a functioning product out to customers. This could mean having to take shortcuts from time-to-time, depending on the context. Bringing value to your customers is what makes money for your company after-all.
Long-term, however, these “quick-fixes” or shortcuts lead to code that can be rigid, hard to understand, more prone to contain bugs, etc.
Improving and keeping code quality high leads to:
- Fewer bugs
- Ability to add new features faster
- Able to keep changes to existing code isolated
- Code that’s easier to reason about
All of these benefits lead to less time spent on debugging, fixing problems, developers trying to understand how the code works, etc.
E.g. It saves your company real money!
Navy SEALS Get It
There’s an adage that comes from the Navy SEALs which many have noticed also applies to creating software:
Slow is smooth. Smooth is fast.
Taking time to build quality code upfront will help your company move faster in the long-term. But even then, we don’t anticipate all future changes to the code and still need to refactor from time-to-time.
Being A Craftsman
Software development is a critical part of our society.
Developers build code that controls:
- Vehicles
- Power Grids
- Government Secrets
- Home Security
- Weapons
- Banking Accounts
- Etc.
I’m sure you can think of more cases where the software a developer creates is tied to the security and well-being of an individual or group of people.
Would you expect your doctor to haphazardly prescribe you medications without carefully ensuring that he/she knows what your medical condition is?
Wouldn’t you want to have a vehicle mechanic who takes the time to ensure your vehicle’s tires won’t fall off while you are driving?
Being a craftsman is just another way to say that we should be professional and care about our craft.
We should value quality software that will work as intended!
I’ve had it happen before that my car’s axel was replaced and, while I was driving away, the new axel fell right out of my car! Is that the kind of mechanic I can trust my business to? Nope!
Likewise, the quality of software that we build can directly impact people’s lives in real ways.
Case Study #1
You might be familiar with an incident from 2018 where a Boeing 737 crashed and killed all people on board.
It was found that Boeing had outsourced its software development to developers who were not experienced in this particular industry:
Increasingly, the iconic American planemaker and its subcontractors have relied on temporary workers making as little as $9 an hour to develop and test software, often from countries lacking a deep background in aerospace.
Also, these developers were having to redo improperly written code over and over again:
The coders from HCL were typically designing to specifications set by Boeing. Still, “it was controversial because it was far less efficient than Boeing engineers just writing the code,” Rabin said. Frequently, he recalled, “it took many rounds going back and forth because the code was not done correctly.”
One former software engineer with Boeing is quoted as saying:
I was shocked that in a room full of a couple hundred mostly senior engineers we were being told that we weren’t needed.
While I have no beef with software developers from particular countries, it does concern me when a group of developers are lacking the knowledge or tools to build quality software in such critical systems.
For Boeing in general, what did this overall lack of quality and craftsmanship lead to?
The company’s stocks took a huge dip a couple of days after the crash.
Oh, and don’t forget - people died. No one can undo or fix this.
After it’s all said and done, Boeing did not benefit from cutting costs, trying to rush their software development and focus on speed rather than quality.
As software development professionals, we should seek to do our part and value being software craftsmen and craftswomen who focus on creating quality software.
Case Study #2
Do you still think that because airplanes can potentially kill people that the software built is going to be quality? Nope.
Here’s another example of software quality issues in the aviation field: $300 million Airbus software bug solved by “turning it off and on again every 149 hours.”
Sound’s kind of like a memory leak? You know, when you have a web application that starts getting slow and clunky after keeping it opened for a while. Just refresh the page and voila! Everything’s fine again!
Sadly, we are building airplanes like that too…
Quoting the article:
Airlines who haven’t performed a recent software update on certain models of the Airbus A350 are being told they must completely power cycle the aircraft every 149 hours or risk “…partial or total loss of some avionics systems or functions,” according to the EASA.
Do you want to fly on those planes?
Quality matters. And the fact is, many developers are not writing quality software.
I hope that this book will help developers get just a little bit better at building quality software.
When Should I Refactor?
It’s already been mentioned that refactoring is best done in smaller chunks rather than in big sweeping changes.
Again, this avoids riskier and error-prone changes. You can also ship your product to your customers in a more iterative way and get feedback from your users earlier.
The question then arises: “When should I refactor?”
The Boy Scout Rule
There’s a programming principle called “The Boy Scout Rule” which states:
Leave the code cleaner than you found it.
This applies whether you are fixing a bug, adding a new feature, etc. Just do something that improves the code you are working with.
It could be as simple as adjusting the name of an ambiguous variable name.
It could be re-organizing the structure of your code’s files.
It could be introducing design patterns to solve specific issues.
Repetitive Work
Ever run into a situation where you need to write code that you’ve already written before? Maybe the same code already exists somewhere else in the system?
If you find that you’ve had to write the same (exact) code over-and-over, then you might want to consider consolidating that code into a shareable resource.
This way, you don’t have to change 12 different files to fix a bug or add a new piece of logic.
Difficulty Adding Features
As mentioned before, sometimes you are faced with the task of adding new features to your code. But, the existing code makes it really difficult to “just add” that new feature or behavior.
In these cases, refactoring can help you to mould the existing code into a place where it is easy to add new behaviors!
This also applies to architectural issues. But, this book will focus on more code-based issues.
In The End
In the end, refactoring should be a continuous and habitual activity that you have chosen to engage in.
Martin Fowler, on the topic of refactoring, said:
Refactoring isn’t a special task that would show up in a project plan. Done well, it’s a regular part of programming activity.
You shouldn’t have to “ask” to refactor. Just do it when it makes sense.