- Notifications
You must be signed in to change notification settings - Fork1.2k
Clean Code concepts adapted for TypeScript
License
labs42io/clean-code-typescript
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Clean Code concepts adapted for TypeScript.
Inspired fromclean-code-javascript.
- Introduction
- Variables
- Functions
- Objects and Data Structures
- Classes
- SOLID
- Testing
- Concurrency
- Error Handling
- Formatting
- Comments
- Translations
Software engineering principles, from Robert C. Martin's bookClean Code,adapted for TypeScript. This is not a style guide. It's a guide to producingreadable, reusable, and refactorable software in TypeScript.
Not every principle herein has to be strictly followed, and even fewer will beuniversally agreed upon. These are guidelines and nothing more, but they areones codified over many years of collective experience by the authors ofClean Code.
Our craft of software engineering is just a bit over 50 years old, and we arestill learning a lot. When software architecture is as old as architectureitself, maybe then we will have harder rules to follow. For now, let theseguidelines serve as a touchstone by which to assess the quality of theTypeScript code that you and your team produce.
One more thing: knowing these won't immediately make you a better softwaredeveloper, and working with them for many years doesn't mean you won't makemistakes. Every piece of code starts as a first draft, like wet clay gettingshaped into its final form. Finally, we chisel away the imperfections whenwe review it with our peers. Don't beat yourself up for first drafts that needimprovement. Beat up the code instead!
Distinguish names in such a way that the reader knows what the differences offer.
Bad:
functionbetween<T>(a1:T,a2:T,a3:T):boolean{returna2<=a1&&a1<=a3;}
Good:
functionbetween<T>(value:T,left:T,right:T):boolean{returnleft<=value&&value<=right;}
If you can’t pronounce it, you can’t discuss it without sounding like an idiot.
Bad:
typeDtaRcrd102={genymdhms:Date;modymdhms:Date;pszqint:number;}
Good:
typeCustomer={generationTimestamp:Date;modificationTimestamp:Date;recordId:number;}
Bad:
functiongetUserInfo():User;functiongetUserDetails():User;functiongetUserData():User;
Good:
functiongetUser():User;
We will read more code than we will ever write. It's important that the code we do write must be readable and searchable. Bynot naming variables that end up being meaningful for understanding our program, we hurt our readers. Make your names searchable. Tools likeESLint can help identify unnamed constants (also known as magic strings and magic numbers).
Bad:
// What the heck is 86400000 for?setTimeout(restart,86400000);
Good:
// Declare them as capitalized named constants.constMILLISECONDS_PER_DAY=24*60*60*1000;// 86400000setTimeout(restart,MILLISECONDS_PER_DAY);
Bad:
declareconstusers:Map<string,User>;for(constkeyValueofusers){// iterate through users map}
Good:
declareconstusers:Map<string,User>;for(const[id,user]ofusers){// iterate through users map}
Explicit is better than implicit.
Clarity is king.
Bad:
constu=getUser();consts=getSubscription();constt=charge(u,s);
Good:
constuser=getUser();constsubscription=getSubscription();consttransaction=charge(user,subscription);
If your class/type/object name tells you something, don't repeat that in your variable name.
Bad:
typeCar={carMake:string;carModel:string;carColor:string;}functionprint(car:Car):void{console.log(`${car.carMake}${car.carModel} (${car.carColor})`);}
Good:
typeCar={make:string;model:string;color:string;}functionprint(car:Car):void{console.log(`${car.make}${car.model} (${car.color})`);}
Default arguments are often cleaner than short circuiting.
Bad:
functionloadPages(count?:number){constloadCount=count!==undefined ?count :10;// ...}
Good:
functionloadPages(count:number=10){// ...}
Enums can help you document the intent of the code. For example when we are concerned about values beingdifferent rather than the exact value of those.
Bad:
constGENRE={ROMANTIC:'romantic',DRAMA:'drama',COMEDY:'comedy',DOCUMENTARY:'documentary',}projector.configureFilm(GENRE.COMEDY);classProjector{// declaration of ProjectorconfigureFilm(genre){switch(genre){caseGENRE.ROMANTIC:// some logic to be executed}}}
Good:
enumGENRE{ROMANTIC,DRAMA,COMEDY,DOCUMENTARY,}projector.configureFilm(GENRE.COMEDY);classProjector{// declaration of ProjectorconfigureFilm(genre){switch(genre){caseGENRE.ROMANTIC:// some logic to be executed}}}
Limiting the number of function parameters is incredibly important because it makes testing your function easier.Having more than three leads to a combinatorial explosion where you have to test tons of different cases with each separate argument.
One or two arguments is the ideal case, and three should be avoided if possible. Anything more than that should be consolidated.Usually, if you have more than two arguments then your function is trying to do too much.In cases where it's not, most of the time a higher-level object will suffice as an argument.
Consider using object literals if you are finding yourself needing a lot of arguments.
To make it obvious what properties the function expects, you can use thedestructuring syntax.This has a few advantages:
When someone looks at the function signature, it's immediately clear what properties are being used.
It can be used to simulate named parameters.
Destructuring also clones the specified primitive values of the argument object passed into the function. This can help prevent side effects. Note: objects and arrays that are destructured from the argument object are NOT cloned.
TypeScript warns you about unused properties, which would be impossible without destructuring.
Bad:
functioncreateMenu(title:string,body:string,buttonText:string,cancellable:boolean){// ...}createMenu('Foo','Bar','Baz',true);
Good:
functioncreateMenu(options:{title:string,body:string,buttonText:string,cancellable:boolean}){// ...}createMenu({title:'Foo',body:'Bar',buttonText:'Baz',cancellable:true});
You can further improve readability by usingtype aliases:
typeMenuOptions={title:string,body:string,buttonText:string,cancellable:boolean};functioncreateMenu(options:MenuOptions){// ...}createMenu({title:'Foo',body:'Bar',buttonText:'Baz',cancellable:true});
This is by far the most important rule in software engineering. When functions do more than one thing, they are harder to compose, test, and reason about. When you can isolate a function to just one action, it can be refactored easily and your code will read much cleaner. If you take nothing else away from this guide other than this, you'll be ahead of many developers.
Bad:
functionemailActiveClients(clients:Client[]){clients.forEach((client)=>{constclientRecord=database.lookup(client);if(clientRecord.isActive()){email(client);}});}
Good:
functionemailActiveClients(clients:Client[]){clients.filter(isActiveClient).forEach(email);}functionisActiveClient(client:Client){constclientRecord=database.lookup(client);returnclientRecord.isActive();}
Bad:
functionaddToDate(date:Date,month:number):Date{// ...}constdate=newDate();// It's hard to tell from the function name what is addedaddToDate(date,1);
Good:
functionaddMonthToDate(date:Date,month:number):Date{// ...}constdate=newDate();addMonthToDate(date,1);
When you have more than one level of abstraction your function is usually doing too much. Splitting up functions leads to reusability and easier testing.
Bad:
functionparseCode(code:string){constREGEXES=[/* ... */];conststatements=code.split(' ');consttokens=[];REGEXES.forEach((regex)=>{statements.forEach((statement)=>{// ...});});constast=[];tokens.forEach((token)=>{// lex...});ast.forEach((node)=>{// parse...});}
Good:
constREGEXES=[/* ... */];functionparseCode(code:string){consttokens=tokenize(code);constsyntaxTree=parse(tokens);syntaxTree.forEach((node)=>{// parse...});}functiontokenize(code:string):Token[]{conststatements=code.split(' ');consttokens:Token[]=[];REGEXES.forEach((regex)=>{statements.forEach((statement)=>{tokens.push(/* ... */);});});returntokens;}functionparse(tokens:Token[]):SyntaxTree{constsyntaxTree:SyntaxTree[]=[];tokens.forEach((token)=>{syntaxTree.push(/* ... */);});returnsyntaxTree;}
Do your absolute best to avoid duplicate code.Duplicate code is bad because it means that there's more than one place to alter something if you need to change some logic.
Imagine if you run a restaurant and you keep track of your inventory: all your tomatoes, onions, garlic, spices, etc.If you have multiple lists that you keep this on, then all have to be updated when you serve a dish with tomatoes in them.If you only have one list, there's only one place to update!
Oftentimes you have duplicate code because you have two or more slightly different things, that share a lot in common, but their differences force you to have two or more separate functions that do much of the same things. Removing duplicate code means creating an abstraction that can handle this set of different things with just one function/module/class.
Getting the abstraction right is critical, that's why you should follow theSOLID principles. Bad abstractions can be worse than duplicate code, so be careful! Having said this, if you can make a good abstraction, do it! Don't repeat yourself, otherwise, you'll find yourself updating multiple places anytime you want to change one thing.
Bad:
functionshowDeveloperList(developers:Developer[]){developers.forEach((developer)=>{constexpectedSalary=developer.calculateExpectedSalary();constexperience=developer.getExperience();constgithubLink=developer.getGithubLink();constdata={ expectedSalary, experience, githubLink};render(data);});}functionshowManagerList(managers:Manager[]){managers.forEach((manager)=>{constexpectedSalary=manager.calculateExpectedSalary();constexperience=manager.getExperience();constportfolio=manager.getMBAProjects();constdata={ expectedSalary, experience, portfolio};render(data);});}
Good:
classDeveloper{// ...getExtraDetails(){return{githubLink:this.githubLink,}}}classManager{// ...getExtraDetails(){return{portfolio:this.portfolio,}}}functionshowEmployeeList(employee:(Developer|Manager)[]){employee.forEach((employee)=>{constexpectedSalary=employee.calculateExpectedSalary();constexperience=employee.getExperience();constextra=employee.getExtraDetails();constdata={ expectedSalary, experience, extra,};render(data);});}
You may also consider adding a union type, or common parent class if it suits your abstraction.
classDeveloper{// ...}classManager{// ...}typeEmployee=Developer|ManagerfunctionshowEmployeeList(employee:Employee[]){// ...});}
You should be critical about code duplication. Sometimes there is a tradeoff between duplicated code and increased complexity by introducing unnecessary abstraction. When two implementations from two different modules look similar but live in different domains, duplication might be acceptable and preferred over extracting the common code. The extracted common code, in this case, introduces an indirect dependency between the two modules.
Bad:
typeMenuConfig={title?:string,body?:string,buttonText?:string,cancellable?:boolean};functioncreateMenu(config:MenuConfig){config.title=config.title||'Foo';config.body=config.body||'Bar';config.buttonText=config.buttonText||'Baz';config.cancellable=config.cancellable!==undefined ?config.cancellable :true;// ...}createMenu({body:'Bar'});
Good:
typeMenuConfig={title?:string,body?:string,buttonText?:string,cancellable?:boolean};functioncreateMenu(config:MenuConfig){constmenuConfig=Object.assign({title:'Foo',body:'Bar',buttonText:'Baz',cancellable:true},config);// ...}createMenu({body:'Bar'});
Or, you could use the spread operator:
functioncreateMenu(config:MenuConfig){constmenuConfig={title:'Foo',body:'Bar',buttonText:'Baz',cancellable:true, ...config,};// ...}
The spread operator andObject.assign()
are very similar.The main difference is that spreading defines new properties, whileObject.assign()
sets them. More detailed, the difference is explained inthis thread.
Alternatively, you can use destructuring with default values:
typeMenuConfig={title?:string,body?:string,buttonText?:string,cancellable?:boolean};functioncreateMenu({ title='Foo', body='Bar', buttonText='Baz', cancellable=true}:MenuConfig){// ...}createMenu({body:'Bar'});
To avoid any side effects and unexpected behavior by passing in explicitly theundefined
ornull
value, you can tell the TypeScript compiler to not allow it.See--strictNullChecks
option in TypeScript.
Flags tell your user that this function does more than one thing.Functions should do one thing. Split out your functions if they are following different code paths based on a boolean.
Bad:
functioncreateFile(name:string,temp:boolean){if(temp){fs.create(`./temp/${name}`);}else{fs.create(name);}}
Good:
functioncreateTempFile(name:string){createFile(`./temp/${name}`);}functioncreateFile(name:string){fs.create(name);}
A function produces a side effect if it does anything other than take a value in and return another value or values.A side effect could be writing to a file, modifying some global variable, or accidentally wiring all your money to a stranger.
Now, you do need to have side effects in a program on occasion. Like the previous example, you might need to write to a file.What you want to do is to centralize where you are doing this. Don't have several functions and classes that write to a particular file.Have one service that does it. One and only one.
The main point is to avoid common pitfalls like sharing state between objects without any structure, using mutable data types that can be written to by anything, and not centralizing where your side effects occur. If you can do this, you will be happier than the vast majority of other programmers.
Bad:
// Global variable referenced by following function.letname='Robert C. Martin';functiontoBase64(){name=btoa(name);}toBase64();// If we had another function that used this name, now it'd be a Base64 valueconsole.log(name);// expected to print 'Robert C. Martin' but instead 'Um9iZXJ0IEMuIE1hcnRpbg=='
Good:
constname='Robert C. Martin';functiontoBase64(text:string):string{returnbtoa(text);}constencodedName=toBase64(name);console.log(name);
Browsers and Node.js process only JavaScript, therefore any TypeScript code has to be compiled before running or debugging. In JavaScript, some values are unchangeable (immutable) and some are changeable (mutable). Objects and arrays are two kinds of mutable values so it's important to handle them carefully when they're passed as parameters to a function. A JavaScript function can change an object's properties or alter the contents of an array which could easily cause bugs elsewhere.
Suppose there's a function that accepts an array parameter representing a shopping cart. If the function makes a change in that shopping cart array - by adding an item to purchase, for example - then any other function that uses that samecart
array will be affected by this addition. That may be great, however it could also be bad. Let's imagine a bad situation:
The user clicks the "Purchase" button which calls apurchase
function that spawns a network request and sends thecart
array to the server. Because of a bad network connection, thepurchase
function has to keep retrying the request. Now, what if in the meantime the user accidentally clicks an "Add to Cart" button on an item they don't actually want before the network request begins? If that happens and the network request begins, then that purchase function will send the accidentally added item because thecart
array was modified.
A great solution would be for theaddItemToCart
function to always clone thecart
, edit it, and return the clone. This would ensure that functions that are still using the old shopping cart wouldn't be affected by the changes.
Two caveats to mention to this approach:
There might be cases where you actually want to modify the input object, but when you adopt this programming practice you will find that those cases are pretty rare. Most things can be refactored to have no side effects! (seepure function)
Cloning big objects can be very expensive in terms of performance. Luckily, this isn't a big issue in practice because there aregreat libraries that allow this kind of programming approach to be fast and not as memory intensive as it would be for you to manually clone objects and arrays.
Bad:
functionaddItemToCart(cart:CartItem[],item:Item):void{cart.push({ item,date:Date.now()});};
Good:
functionaddItemToCart(cart:CartItem[],item:Item):CartItem[]{return[...cart,{ item,date:Date.now()}];};
Polluting globals is a bad practice in JavaScript because you could clash with another library and the user of your API would be none-the-wiser until they get an exception in production. Let's think about an example: what if you wanted to extend JavaScript's native Array method to have adiff
method that could show the difference between two arrays? You could write your new function to theArray.prototype
, but it could clash with another library that tried to do the same thing. What if that other library was just usingdiff
to find the difference between the first and last elements of an array? This is why it would be much better to just use classes and simply extend theArray
global.
Bad:
declare global{interfaceArray<T>{diff(other:T[]):Array<T>;}}if(!Array.prototype.diff){Array.prototype.diff=function<T>(other:T[]):T[]{consthash=newSet(other);returnthis.filter(elem=>!hash.has(elem));};}
Good:
classMyArray<T>extendsArray<T>{diff(other:T[]):T[]{consthash=newSet(other);returnthis.filter(elem=>!hash.has(elem));};}
Favor this style of programming when you can.
Bad:
constcontributions=[{name:'Uncle Bobby',linesOfCode:500},{name:'Suzie Q',linesOfCode:1500},{name:'Jimmy Gosling',linesOfCode:150},{name:'Gracie Hopper',linesOfCode:1000}];lettotalOutput=0;for(leti=0;i<contributions.length;i++){totalOutput+=contributions[i].linesOfCode;}
Good:
constcontributions=[{name:'Uncle Bobby',linesOfCode:500},{name:'Suzie Q',linesOfCode:1500},{name:'Jimmy Gosling',linesOfCode:150},{name:'Gracie Hopper',linesOfCode:1000}];consttotalOutput=contributions.reduce((totalLines,output)=>totalLines+output.linesOfCode,0);
Bad:
if(subscription.isTrial||account.balance>0){// ...}
Good:
functioncanActivateService(subscription:Subscription,account:Account){returnsubscription.isTrial||account.balance>0;}if(canActivateService(subscription,account)){// ...}
Bad:
functionisEmailNotUsed(email:string):boolean{// ...}if(isEmailNotUsed(email)){// ...}
Good:
functionisEmailUsed(email:string):boolean{// ...}if(!isEmailUsed(email)){// ...}
This seems like an impossible task. Upon first hearing this, most people say, "how am I supposed to do anything without anif
statement?" The answer is that you can use polymorphism to achieve the same task in many cases. The second question is usually, "well that's great but why would I want to do that?" The answer is a previous clean code concept we learned: a function should only do one thing. When you have classes and functions that haveif
statements, you are telling your user that your function does more than one thing. Remember, just do one thing.
Bad:
classAirplane{privatetype:string;// ...getCruisingAltitude(){switch(this.type){case'777':returnthis.getMaxAltitude()-this.getPassengerCount();case'Air Force One':returnthis.getMaxAltitude();case'Cessna':returnthis.getMaxAltitude()-this.getFuelExpenditure();default:thrownewError('Unknown airplane type.');}}privategetMaxAltitude():number{// ...}}
Good:
abstractclassAirplane{protectedgetMaxAltitude():number{// shared logic with subclasses ...}// ...}classBoeing777extendsAirplane{// ...getCruisingAltitude(){returnthis.getMaxAltitude()-this.getPassengerCount();}}classAirForceOneextendsAirplane{// ...getCruisingAltitude(){returnthis.getMaxAltitude();}}classCessnaextendsAirplane{// ...getCruisingAltitude(){returnthis.getMaxAltitude()-this.getFuelExpenditure();}}
TypeScript is a strict syntactical superset of JavaScript and adds optional static type checking to the language.Always prefer to specify types of variables, parameters and return values to leverage the full power of TypeScript features.It makes refactoring more easier.
Bad:
functiontravelToTexas(vehicle:Bicycle|Car){if(vehicleinstanceofBicycle){vehicle.pedal(currentLocation,newLocation('texas'));}elseif(vehicleinstanceofCar){vehicle.drive(currentLocation,newLocation('texas'));}}
Good:
typeVehicle=Bicycle|Car;functiontravelToTexas(vehicle:Vehicle){vehicle.move(currentLocation,newLocation('texas'));}
Modern browsers do a lot of optimization under-the-hood at runtime. A lot of times, if you are optimizing then you are just wasting your time. There are goodresources for seeing where optimization is lacking. Target those in the meantime, until they are fixed if they can be.
Bad:
// On old browsers, each iteration with uncached `list.length` would be costly// because of `list.length` recomputation. In modern browsers, this is optimized.for(leti=0,len=list.length;i<len;i++){// ...}
Good:
for(leti=0;i<list.length;i++){// ...}
Dead code is just as bad as duplicate code. There's no reason to keep it in your codebase.If it's not being called, get rid of it! It will still be saved in your version history if you still need it.
Bad:
functionoldRequestModule(url:string){// ...}functionrequestModule(url:string){// ...}constreq=requestModule;inventoryTracker('apples',req,'www.inventory-awesome.io');
Good:
functionrequestModule(url:string){// ...}constreq=requestModule;inventoryTracker('apples',req,'www.inventory-awesome.io');
Use generators and iterables when working with collections of data used like a stream.
There are some good reasons:
- decouples the callee from the generator implementation in a sense that callee decides how manyitems to access
- lazy execution, items are streamed on-demand
- built-in support for iterating items using the
for-of
syntax - iterables allow implementing optimized iterator patterns
Bad:
functionfibonacci(n:number):number[]{if(n===1)return[0];if(n===2)return[0,1];constitems:number[]=[0,1];while(items.length<n){items.push(items[items.length-2]+items[items.length-1]);}returnitems;}functionprint(n:number){fibonacci(n).forEach(fib=>console.log(fib));}// Print first 10 Fibonacci numbers.print(10);
Good:
// Generates an infinite stream of Fibonacci numbers.// The generator doesn't keep the array of all numbers.function*fibonacci():IterableIterator<number>{let[a,b]=[0,1];while(true){yielda;[a,b]=[b,a+b];}}functionprint(n:number){leti=0;for(constfiboffibonacci()){if(i++===n)break;console.log(fib);}}// Print first 10 Fibonacci numbers.print(10);
There are libraries that allow working with iterables in a similar way as with native arrays, bychaining methods likemap
,slice
,forEach
etc. Seeitiriri foran example of advanced manipulation with iterables (oritiriri-async for manipulation of async iterables).
importitiririfrom'itiriri';function*fibonacci():IterableIterator<number>{let[a,b]=[0,1];while(true){yielda;[a,b]=[b,a+b];}}itiriri(fibonacci()).take(10).forEach(fib=>console.log(fib));
TypeScript supports getter/setter syntax.Using getters and setters to access data from objects that encapsulate behavior could be better than simply looking for a property on an object."Why?" you might ask. Well, here's a list of reasons:
- When you want to do more beyond getting an object property, you don't have to look up and change every accessor in your codebase.
- Makes adding validation simple when doing a
set
. - Encapsulates the internal representation.
- Easy to add logging and error handling when getting and setting.
- You can lazy load your object's properties, let's say getting it from a server.
Bad:
typeBankAccount={balance:number;// ...}constvalue=100;constaccount:BankAccount={balance:0,// ...};if(value<0){thrownewError('Cannot set negative balance.');}account.balance=value;
Good:
classBankAccount{privateaccountBalance:number=0;getbalance():number{returnthis.accountBalance;}setbalance(value:number){if(value<0){thrownewError('Cannot set negative balance.');}this.accountBalance=value;}// ...}// Now `BankAccount` encapsulates the validation logic.// If one day the specifications change, and we need extra validation rule,// we would have to alter only the `setter` implementation,// leaving all dependent code unchanged.constaccount=newBankAccount();account.balance=100;
TypeScript supportspublic
(default),protected
andprivate
accessors on class members.
Bad:
classCircle{radius:number;constructor(radius:number){this.radius=radius;}perimeter(){return2*Math.PI*this.radius;}surface(){returnMath.PI*this.radius*this.radius;}}
Good:
classCircle{constructor(privatereadonlyradius:number){}perimeter(){return2*Math.PI*this.radius;}surface(){returnMath.PI*this.radius*this.radius;}}
TypeScript's type system allows you to mark individual properties on an interface/class asreadonly. This allows you to work in a functional way (an unexpected mutation is bad).
For more advanced scenarios there is a built-in typeReadonly
that takes a typeT
and marks all of its properties as readonly using mapped types (seemapped types).
Bad:
interfaceConfig{host:string;port:string;db:string;}
Good:
interfaceConfig{readonlyhost:string;readonlyport:string;readonlydb:string;}
For arrays, you can create a read-only array by usingReadonlyArray<T>
.It doesn't allow changes such aspush()
andfill()
, but can use features such asconcat()
andslice()
that do not change the array's value.
Bad:
constarray:number[]=[1,3,5];array=[];// errorarray.push(100);// array will be updated
Good:
constarray:ReadonlyArray<number>=[1,3,5];array=[];// errorarray.push(100);// error
Declaring read-only arguments inTypeScript 3.4 is a bit easier.
functionhoge(args:readonlystring[]){args.push(1);// error}
Preferconst assertions for literal values.
Bad:
constconfig={hello:'world'};config.hello='world';// value is changedconstarray=[1,3,5];array[0]=10;// value is changed// writable objects is returnedfunctionreadonlyData(value:number){return{ value};}constresult=readonlyData(100);result.value=200;// value is changed
Good:
// read-only objectconstconfig={hello:'world'}asconst;config.hello='world';// error// read-only arrayconstarray=[1,3,5]asconst;array[0]=10;// error// You can return read-only objectsfunctionreadonlyData(value:number){return{ value}asconst;}constresult=readonlyData(100);result.value=200;// error
Use type when you might need a union or intersection. Use an interface when you wantextends
orimplements
. There is no strict rule, however, use the one that works for you.
For a more detailed explanation refer to thisanswer about the differences betweentype
andinterface
in TypeScript.
Bad:
interfaceEmailConfig{// ...}interfaceDbConfig{// ...}interfaceConfig{// ...}//...typeShape={// ...}
Good:
typeEmailConfig={// ...}typeDbConfig={// ...}typeConfig=EmailConfig|DbConfig;// ...interfaceShape{// ...}classCircleimplementsShape{// ...}classSquareimplementsShape{// ...}
The class' size is measured by its responsibility. Following theSingle Responsibility principle a class should be small.
Bad:
classDashboard{getLanguage():string{/* ... */}setLanguage(language:string):void{/* ... */}showProgress():void{/* ... */}hideProgress():void{/* ... */}isDirty():boolean{/* ... */}disable():void{/* ... */}enable():void{/* ... */}addSubscription(subscription:Subscription):void{/* ... */}removeSubscription(subscription:Subscription):void{/* ... */}addUser(user:User):void{/* ... */}removeUser(user:User):void{/* ... */}goToHomePage():void{/* ... */}updateProfile(details:UserDetails):void{/* ... */}getVersion():string{/* ... */}// ...}
Good:
classDashboard{disable():void{/* ... */}enable():void{/* ... */}getVersion():string{/* ... */}}// split the responsibilities by moving the remaining methods to other classes// ...
Cohesion defines the degree to which class members are related to each other. Ideally, all fields within a class should be used by each method.We then say that the class ismaximally cohesive. In practice, this, however, is not always possible, nor even advisable. You should however prefer cohesion to be high.
Coupling refers to how related or dependent are two classes toward each other. Classes are said to be low coupled if changes in one of them don't affect the other one.
Good software design hashigh cohesion andlow coupling.
Bad:
classUserManager{// Bad: each private variable is used by one or another group of methods.// It makes clear evidence that the class is holding more than a single responsibility.// If I need only to create the service to get the transactions for a user,// I'm still forced to pass and instance of `emailSender`.constructor(privatereadonlydb:Database,privatereadonlyemailSender:EmailSender){}asyncgetUser(id:number):Promise<User>{returnawaitdb.users.findOne({ id});}asyncgetTransactions(userId:number):Promise<Transaction[]>{returnawaitdb.transactions.find({ userId});}asyncsendGreeting():Promise<void>{awaitemailSender.send('Welcome!');}asyncsendNotification(text:string):Promise<void>{awaitemailSender.send(text);}asyncsendNewsletter():Promise<void>{// ...}}
Good:
classUserService{constructor(privatereadonlydb:Database){}asyncgetUser(id:number):Promise<User>{returnawaitthis.db.users.findOne({ id});}asyncgetTransactions(userId:number):Promise<Transaction[]>{returnawaitthis.db.transactions.find({ userId});}}classUserNotifier{constructor(privatereadonlyemailSender:EmailSender){}asyncsendGreeting():Promise<void>{awaitthis.emailSender.send('Welcome!');}asyncsendNotification(text:string):Promise<void>{awaitthis.emailSender.send(text);}asyncsendNewsletter():Promise<void>{// ...}}
As stated famously inDesign Patterns by the Gang of Four, you shouldprefer composition over inheritance where you can. There are lots of good reasons to use inheritance and lots of good reasons to use composition. The main point for this maxim is that if your mind instinctively goes for inheritance, try to think if composition could model your problem better. In some cases it can.
You might be wondering then, "when should I use inheritance?" It depends on your problem at hand, but this is a decent list of when inheritance makes more sense than composition:
Your inheritance represents an "is-a" relationship and not a "has-a" relationship (Human->Animal vs. User->UserDetails).
You can reuse code from the base classes (Humans can move like all animals).
You want to make global changes to derived classes by changing a base class. (Change the caloric expenditure of all animals when they move).
Bad:
classEmployee{constructor(privatereadonlyname:string,privatereadonlyemail:string){}// ...}// Bad because Employees "have" tax data. EmployeeTaxData is not a type of EmployeeclassEmployeeTaxDataextendsEmployee{constructor(name:string,email:string,privatereadonlyssn:string,privatereadonlysalary:number){super(name,email);}// ...}
Good:
classEmployee{privatetaxData:EmployeeTaxData;constructor(privatereadonlyname:string,privatereadonlyemail:string){}setTaxData(ssn:string,salary:number):Employee{this.taxData=newEmployeeTaxData(ssn,salary);returnthis;}// ...}classEmployeeTaxData{constructor(publicreadonlyssn:string,publicreadonlysalary:number){}// ...}
This pattern is very useful and commonly used in many libraries. It allows your code to be expressive, and less verbose. For that reason, use method chaining and take a look at how clean your code will be.
Bad:
classQueryBuilder{privatecollection:string;privatepageNumber:number=1;privateitemsPerPage:number=100;privateorderByFields:string[]=[];from(collection:string):void{this.collection=collection;}page(number:number,itemsPerPage:number=100):void{this.pageNumber=number;this.itemsPerPage=itemsPerPage;}orderBy(...fields:string[]):void{this.orderByFields=fields;}build():Query{// ...}}// ...constqueryBuilder=newQueryBuilder();queryBuilder.from('users');queryBuilder.page(1,100);queryBuilder.orderBy('firstName','lastName');constquery=queryBuilder.build();
Good:
classQueryBuilder{privatecollection:string;privatepageNumber:number=1;privateitemsPerPage:number=100;privateorderByFields:string[]=[];from(collection:string): this{this.collection=collection;returnthis;}page(number:number,itemsPerPage:number=100): this{this.pageNumber=number;this.itemsPerPage=itemsPerPage;returnthis;}orderBy(...fields:string[]): this{this.orderByFields=fields;returnthis;}build():Query{// ...}}// ...constquery=newQueryBuilder().from('users').page(1,100).orderBy('firstName','lastName').build();
As stated in Clean Code, "There should never be more than one reason for a class to change". It's tempting to jam-pack a class with a lot of functionality, like when you can only take one suitcase on your flight. The issue with this is that your class won't be conceptually cohesive and it will give it many reasons to change. Minimizing the amount of time you need to change a class is important. It's important because if too much functionality is in one class and you modify a piece of it, it can be difficult to understand how that will affect other dependent modules in your codebase.
Bad:
classUserSettings{constructor(privatereadonlyuser:User){}changeSettings(settings:UserSettings){if(this.verifyCredentials()){// ...}}verifyCredentials(){// ...}}
Good:
classUserAuth{constructor(privatereadonlyuser:User){}verifyCredentials(){// ...}}classUserSettings{privatereadonlyauth:UserAuth;constructor(privatereadonlyuser:User){this.auth=newUserAuth(user);}changeSettings(settings:UserSettings){if(this.auth.verifyCredentials()){// ...}}}
As stated by Bertrand Meyer, "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification." What does that mean though? This principle basically states that you should allow users to add new functionalities without changing existing code.
Bad:
classAjaxAdapterextendsAdapter{constructor(){super();}// ...}classNodeAdapterextendsAdapter{constructor(){super();}// ...}classHttpRequester{constructor(privatereadonlyadapter:Adapter){}asyncfetch<T>(url:string):Promise<T>{if(this.adapterinstanceofAjaxAdapter){constresponse=awaitmakeAjaxCall<T>(url);// transform response and return}elseif(this.adapterinstanceofNodeAdapter){constresponse=awaitmakeHttpCall<T>(url);// transform response and return}}}functionmakeAjaxCall<T>(url:string):Promise<T>{// request and return promise}functionmakeHttpCall<T>(url:string):Promise<T>{// request and return promise}
Good:
abstractclassAdapter{abstractasyncrequest<T>(url:string):Promise<T>;// code shared to subclasses ...}classAjaxAdapterextendsAdapter{constructor(){super();}asyncrequest<T>(url:string):Promise<T>{// request and return promise}// ...}classNodeAdapterextendsAdapter{constructor(){super();}asyncrequest<T>(url:string):Promise<T>{// request and return promise}// ...}classHttpRequester{constructor(privatereadonlyadapter:Adapter){}asyncfetch<T>(url:string):Promise<T>{constresponse=awaitthis.adapter.request<T>(url);// transform response and return}}
This is a scary term for a very simple concept. It's formally defined as "If S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.)." That's an even scarier definition.
The best explanation for this is if you have a parent class and a child class, then the parent class and child class can be used interchangeably without getting incorrect results. This might still be confusing, so let's take a look at the classic Square-Rectangle example. Mathematically, a square is a rectangle, but if you model it using the "is-a" relationship via inheritance, you quickly get into trouble.
Bad:
classRectangle{constructor(protectedwidth:number=0,protectedheight:number=0){}setColor(color:string): this{// ...}render(area:number){// ...}setWidth(width:number): this{this.width=width;returnthis;}setHeight(height:number): this{this.height=height;returnthis;}getArea():number{returnthis.width*this.height;}}classSquareextendsRectangle{setWidth(width:number): this{this.width=width;this.height=width;returnthis;}setHeight(height:number): this{this.width=height;this.height=height;returnthis;}}functionrenderLargeRectangles(rectangles:Rectangle[]){rectangles.forEach((rectangle)=>{constarea=rectangle.setWidth(4).setHeight(5).getArea();// BAD: Returns 25 for Square. Should be 20.rectangle.render(area);});}constrectangles=[newRectangle(),newRectangle(),newSquare()];renderLargeRectangles(rectangles);
Good:
abstractclassShape{setColor(color:string): this{// ...}render(area:number){// ...}abstractgetArea():number;}classRectangleextendsShape{constructor(privatereadonlywidth=0,privatereadonlyheight=0){super();}getArea():number{returnthis.width*this.height;}}classSquareextendsShape{constructor(privatereadonlylength:number){super();}getArea():number{returnthis.length*this.length;}}functionrenderLargeShapes(shapes:Shape[]){shapes.forEach((shape)=>{constarea=shape.getArea();shape.render(area);});}constshapes=[newRectangle(4,5),newRectangle(4,5),newSquare(5)];renderLargeShapes(shapes);
ISP states that "Clients should not be forced to depend upon interfaces that they do not use.". This principle is very much related to the Single Responsibility Principle.What it really means is that you should always design your abstractions in a way that the clients that are using the exposed methods do not get the whole pie instead. That also include imposing the clients with the burden of implementing methods that they don’t actually need.
Bad:
interfaceSmartPrinter{print();fax();scan();}classAllInOnePrinterimplementsSmartPrinter{print(){// ...}fax(){// ...}scan(){// ...}}classEconomicPrinterimplementsSmartPrinter{print(){// ...}fax(){thrownewError('Fax not supported.');}scan(){thrownewError('Scan not supported.');}}
Good:
interfacePrinter{print();}interfaceFax{fax();}interfaceScanner{scan();}classAllInOnePrinterimplementsPrinter,Fax,Scanner{print(){// ...}fax(){// ...}scan(){// ...}}classEconomicPrinterimplementsPrinter{print(){// ...}}
This principle states two essential things:
High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend upon details. Details should depend on abstractions.
This can be hard to understand at first, but if you've worked with Angular, you've seen an implementation of this principle in the form of Dependency Injection (DI). While they are not identical concepts, DIP keeps high-level modules from knowing the details of its low-level modules and setting them up. It can accomplish this through DI. A huge benefit of this is that it reduces the coupling between modules. Coupling is a very bad development pattern because it makes your code hard to refactor.
DIP is usually achieved by a using an inversion of control (IoC) container. An example of a powerful IoC container for TypeScript isInversifyJs
Bad:
import{readFileasreadFileCb}from'fs';import{promisify}from'util';constreadFile=promisify(readFileCb);typeReportData={// ..}classXmlFormatter{parse<T>(content:string):T{// Converts an XML string to an object T}}classReportReader{// BAD: We have created a dependency on a specific request implementation.// We should just have ReportReader depend on a parse method: `parse`privatereadonlyformatter=newXmlFormatter();asyncread(path:string):Promise<ReportData>{consttext=awaitreadFile(path,'UTF8');returnthis.formatter.parse<ReportData>(text);}}// ...constreader=newReportReader();constreport=awaitreader.read('report.xml');
Good:
import{readFileasreadFileCb}from'fs';import{promisify}from'util';constreadFile=promisify(readFileCb);typeReportData={// ..}interfaceFormatter{parse<T>(content:string):T;}classXmlFormatterimplementsFormatter{parse<T>(content:string):T{// Converts an XML string to an object T}}classJsonFormatterimplementsFormatter{parse<T>(content:string):T{// Converts a JSON string to an object T}}classReportReader{constructor(privatereadonlyformatter:Formatter){}asyncread(path:string):Promise<ReportData>{consttext=awaitreadFile(path,'UTF8');returnthis.formatter.parse<ReportData>(text);}}// ...constreader=newReportReader(newXmlFormatter());constreport=awaitreader.read('report.xml');// or if we had to read a json reportconstreader=newReportReader(newJsonFormatter());constreport=awaitreader.read('report.json');
Testing is more important than shipping. If you have no tests or an inadequate amount, then every time you ship code you won't be sure that you didn't break anything.Deciding on what constitutes an adequate amount is up to your team, but having 100% coverage (all statements and branches)is how you achieve very high confidence and developer peace of mind. This means that in addition to having a great testing framework, you also need to use a goodcoverage tool.
There's no excuse to not write tests. There areplenty of good JS test frameworks with typings support for TypeScript, so find one that your team prefers. When you find one that works for your team, then aim to always write tests for every new feature/module you introduce. If your preferred method is Test Driven Development (TDD), that is great, but the main point is to just make sure you are reaching your coverage goals before launching any feature, or refactoring an existing one.
You are not allowed to write any production code unless it is to make a failing unit test pass.
You are not allowed to write any more of a unit test than is sufficient to fail, and; compilation failures are failures.
You are not allowed to write any more production code than is sufficient to pass the one failing unit test.
Clean tests should follow the rules:
Fast tests should be fast because we want to run them frequently.
Independent tests should not depend on each other. They should provide same output whether run independently or all together in any order.
Repeatable tests should be repeatable in any environment and there should be no excuse for why they fail.
Self-Validating a test should answer with eitherPassed orFailed. You don't need to compare log files to answer if a test passed.
Timely unit tests should be written before the production code. If you write tests after the production code, you might find writing tests too hard.
Tests should also follow theSingle Responsibility Principle. Make only one assert per unit test.
Bad:
import{assert}from'chai';describe('AwesomeDate',()=>{it('handles date boundaries',()=>{letdate:AwesomeDate;date=newAwesomeDate('1/1/2015');assert.equal('1/31/2015',date.addDays(30));date=newAwesomeDate('2/1/2016');assert.equal('2/29/2016',date.addDays(28));date=newAwesomeDate('2/1/2015');assert.equal('3/1/2015',date.addDays(28));});});
Good:
import{assert}from'chai';describe('AwesomeDate',()=>{it('handles 30-day months',()=>{constdate=newAwesomeDate('1/1/2015');assert.equal('1/31/2015',date.addDays(30));});it('handles leap year',()=>{constdate=newAwesomeDate('2/1/2016');assert.equal('2/29/2016',date.addDays(28));});it('handles non-leap year',()=>{constdate=newAwesomeDate('2/1/2015');assert.equal('3/1/2015',date.addDays(28));});});
When a test fails, its name is the first indication of what may have gone wrong.
Bad:
describe('Calendar',()=>{it('2/29/2020',()=>{// ...});it('throws',()=>{// ...});});
Good:
describe('Calendar',()=>{it('should handle leap year',()=>{// ...});it('should throw when format is invalid',()=>{// ...});});
Callbacks aren't clean, and they cause excessive amounts of nesting(the callback hell).
There are utilities that transform existing functions using the callback style to a version that returns promises(for Node.js seeutil.promisify
, for general purpose seepify,es6-promisify)
Bad:
import{get}from'request';import{writeFile}from'fs';functiondownloadPage(url:string,saveTo:string,callback:(error:Error,content?:string)=>void){get(url,(error,response)=>{if(error){callback(error);}else{writeFile(saveTo,response.body,(error)=>{if(error){callback(error);}else{callback(null,response.body);}});}});}downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin','article.html',(error,content)=>{if(error){console.error(error);}else{console.log(content);}});
Good:
import{get}from'request';import{writeFile}from'fs';import{promisify}from'util';constwrite=promisify(writeFile);functiondownloadPage(url:string,saveTo:string):Promise<string>{returnget(url).then(response=>write(saveTo,response));}downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin','article.html').then(content=>console.log(content)).catch(error=>console.error(error));
Promises supports a few helper methods that help make code more concise:
Pattern | Description |
---|---|
Promise.resolve(value) | Convert a value into a resolved promise. |
Promise.reject(error) | Convert an error into a rejected promise. |
Promise.all(promises) | Returns a new promise which is fulfilled with an array of fulfillment values for the passed promises or rejects with the reason of the first promise that rejects. |
Promise.race(promises) | Returns a new promise which is fulfilled/rejected with the result/error of the first settled promise from the array of passed promises. |
Promise.all
is especially useful when there is a need to run tasks in parallel.Promise.race
makes it easier to implement things like timeouts for promises.
Withasync
/await
syntax you can write code that is far cleaner and more understandable than chained promises. Within a function prefixed withasync
keyword, you have a way to tell the JavaScript runtime to pause the execution of code on theawait
keyword (when used on a promise).
Bad:
import{get}from'request';import{writeFile}from'fs';import{promisify}from'util';constwrite=util.promisify(writeFile);functiondownloadPage(url:string,saveTo:string):Promise<string>{returnget(url).then(response=>write(saveTo,response));}downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin','article.html').then(content=>console.log(content)).catch(error=>console.error(error));
Good:
import{get}from'request';import{writeFile}from'fs';import{promisify}from'util';constwrite=promisify(writeFile);asyncfunctiondownloadPage(url:string):Promise<string>{constresponse=awaitget(url);returnresponse;}// somewhere in an async functiontry{constcontent=awaitdownloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin');awaitwrite('article.html',content);console.log(content);}catch(error){console.error(error);}
Thrown errors are a good thing! They mean the runtime has successfully identified when something in your program has gone wrong and it's letting you know by stopping functionexecution on the current stack, killing the process (in Node), and notifying you in the console with a stack trace.
JavaScript as well as TypeScript allow you tothrow
any object. A Promise can also be rejected with any reason object.
It is advisable to use thethrow
syntax with anError
type. This is because your error might be caught in higher level code with acatch
syntax.It would be very confusing to catch a string message there and would makedebugging more painful.
For the same reason you should reject promises withError
types.
Bad:
functioncalculateTotal(items:Item[]):number{throw'Not implemented.';}functionget():Promise<Item[]>{returnPromise.reject('Not implemented.');}
Good:
functioncalculateTotal(items:Item[]):number{thrownewError('Not implemented.');}functionget():Promise<Item[]>{returnPromise.reject(newError('Not implemented.'));}// or equivalent to:asyncfunctionget():Promise<Item[]>{thrownewError('Not implemented.');}
The benefit of usingError
types is that it is supported by the syntaxtry/catch/finally
and implicitly all errors have thestack
property whichis very powerful for debugging.
There are also other alternatives, not to use thethrow
syntax and instead always return custom error objects. TypeScript makes this even easier.Consider the following example:
typeResult<R>={isError:false,value:R};typeFailure<E>={isError:true,error:E};typeFailable<R,E>=Result<R>|Failure<E>;functioncalculateTotal(items:Item[]):Failable<number,'empty'>{if(items.length===0){return{isError:true,error:'empty'};}// ...return{isError:false,value:42};}
For the detailed explanation of this idea refer to theoriginal post.
Doing nothing with a caught error doesn't give you the ability to ever fix or react to said error. Logging the error to the console (console.log
) isn't much better as often it can get lost in a sea of things printed to the console. If you wrap any bit of code in atry/catch
it means you think an error may occur there and therefore you should have a plan, or create a code path, for when it occurs.
Bad:
try{functionThatMightThrow();}catch(error){console.log(error);}// or even worsetry{functionThatMightThrow();}catch(error){// ignore error}
Good:
import{logger}from'./logging'try{functionThatMightThrow();}catch(error){logger.log(error);}
For the same reason you shouldn't ignore caught errors fromtry/catch
.
Bad:
getUser().then((user:User)=>{returnsendEmail(user.email,'Welcome!');}).catch((error)=>{console.log(error);});
Good:
import{logger}from'./logging'getUser().then((user:User)=>{returnsendEmail(user.email,'Welcome!');}).catch((error)=>{logger.log(error);});// or using the async/await syntax:try{constuser=awaitgetUser();awaitsendEmail(user.email,'Welcome!');}catch(error){logger.log(error);}
Formatting is subjective. Like many rules herein, there is no hard and fast rule that you must follow. The main point isDO NOT ARGUE over formatting. There are tons of tools to automate this. Use one! It's a waste of time and money for engineers to argue over formatting. The general rule to follow iskeep consistent formatting rules.
For TypeScript there is a powerful tool calledESLint. It's a static analysis tool that can help you improve dramatically the readability and maintainability of your code. There are ready to use ESLint configurations that you can reference in your projects:
ESLint Config Airbnb - Airbnb style guide
ESLint Base Style Config - a Set of Essential ESLint rules for JS, TS and React
ESLint + Prettier - lint rules forPrettier code formatter
Refer also to this greatTypeScript StyleGuide and Coding Conventions source.
If you are looking for help in migrating from TSLint to ESLint, you can check out this project:https://github.com/typescript-eslint/tslint-to-eslint-config
Capitalization tells you a lot about your variables, functions, etc. These rules are subjective, so your team can choose whatever they want. The point is, no matter what you all choose, justbe consistent.
Bad:
constDAYS_IN_WEEK=7;constdaysInMonth=30;constsongs=['Back In Black','Stairway to Heaven','Hey Jude'];constArtists=['ACDC','Led Zeppelin','The Beatles'];functioneraseDatabase(){}functionrestore_database(){}typeanimal={/* ... */}typeContainer={/* ... */}
Good:
constDAYS_IN_WEEK=7;constDAYS_IN_MONTH=30;constSONGS=['Back In Black','Stairway to Heaven','Hey Jude'];constARTISTS=['ACDC','Led Zeppelin','The Beatles'];constdiscography=getArtistDiscography('ACDC');constbeatlesSongs=SONGS.filter((song)=>isBeatlesSong(song));functioneraseDatabase(){}functionrestoreDatabase(){}typeAnimal={/* ... */}typeContainer={/* ... */}
Prefer usingPascalCase
for class, interface, type and namespace names.
Prefer usingcamelCase
for variables, functions and class members.Prefer using capitalizedSNAKE_CASE
for constants.
If a function calls another, keep those functions vertically close in the source file. Ideally, keep the caller right above the callee.We tend to read code from top-to-bottom, like a newspaper. Because of this, make your code read that way.
Bad:
classPerformanceReview{constructor(privatereadonlyemployee:Employee){}privatelookupPeers(){returndb.lookup(this.employee.id,'peers');}privatelookupManager(){returndb.lookup(this.employee,'manager');}privategetPeerReviews(){constpeers=this.lookupPeers();// ...}review(){this.getPeerReviews();this.getManagerReview();this.getSelfReview();// ...}privategetManagerReview(){constmanager=this.lookupManager();}privategetSelfReview(){// ...}}constreview=newPerformanceReview(employee);review.review();
Good:
classPerformanceReview{constructor(privatereadonlyemployee:Employee){}review(){this.getPeerReviews();this.getManagerReview();this.getSelfReview();// ...}privategetPeerReviews(){constpeers=this.lookupPeers();// ...}privatelookupPeers(){returndb.lookup(this.employee.id,'peers');}privategetManagerReview(){constmanager=this.lookupManager();}privatelookupManager(){returndb.lookup(this.employee,'manager');}privategetSelfReview(){// ...}}constreview=newPerformanceReview(employee);review.review();
With clean and easy to read import statements you can quickly see the dependencies of current code. Make sure you apply following good practices forimport
statements:
- Import statements should be alphabetized and grouped.
- Unused imports should be removed.
- Named imports must be alphabetized (i.e.
import {A, B, C} from 'foo';
) - Import sources must be alphabetized within groups, i.e.:
import * as foo from 'a'; import * as bar from 'b';
- Prefer using
import type
instead ofimport
when importing only types from a file to avoid dependency cycles, as these imports are erased at runtime - Groups of imports are delineated by blank lines.
- Groups must respect following order:
- Polyfills (i.e.
import 'reflect-metadata';
) - Node builtin modules (i.e.
import fs from 'fs';
) - external modules (i.e.
import { query } from 'itiriri';
) - internal modules (i.e
import { UserService } from 'src/services/userService';
) - modules from a parent directory (i.e.
import foo from '../foo'; import qux from '../../foo/qux';
) - modules from the same or a sibling's directory (i.e.
import bar from './bar'; import baz from './bar/baz';
)
- Polyfills (i.e.
Bad:
import{TypeDefinition}from'../types/typeDefinition';import{AttributeTypes}from'../model/attribute';import{Customer,Credentials}from'../model/types';import{ApiCredentials,Adapters}from'./common/api/authorization';importfsfrom'fs';import{ConfigPlugin}from'./plugins/config/configPlugin';import{BindingScopeEnum,Container}from'inversify';import'reflect-metadata';
Good:
import'reflect-metadata';importfsfrom'fs';import{BindingScopeEnum,Container}from'inversify';import{AttributeTypes}from'../model/attribute';import{TypeDefinition}from'../types/typeDefinition';importtype{Customer,Credentials}from'../model/types';import{ApiCredentials,Adapters}from'./common/api/authorization';import{ConfigPlugin}from'./plugins/config/configPlugin';
Create prettier imports by defining the paths and baseUrl properties in the compilerOptions section in thetsconfig.json
This will avoid long relative paths when doing imports.
Bad:
import{UserService}from'../../../services/UserService';
Good:
import{UserService}from'@services/UserService';
// tsconfig.json..."compilerOptions":{ ..."baseUrl":"src","paths":{"@services":["services/*"]}...}...
The use of a comments is an indication of failure to express without them. Code should be the only source of truth.
Don’t comment bad code—rewrite it.
—Brian W. Kernighan and P. J. Plaugher
Comments are an apology, not a requirement. Good codemostly documents itself.
Bad:
// Check if subscription is active.if(subscription.endDate>Date.now){}
Good:
constisSubscriptionActive=subscription.endDate>Date.now;if(isSubscriptionActive){/* ... */}
Version control exists for a reason. Leave old code in your history.
Bad:
typeUser={name:string;email:string;// age: number;// jobPosition: string;}
Good:
typeUser={name:string;email:string;}
Remember, use version control! There's no need for dead code, commented code, and especially journal comments. Usegit log
to get history!
Bad:
/** * 2016-12-20: Removed monads, didn't understand them (RM) * 2016-10-01: Improved using special monads (JP) * 2016-02-03: Added type-checking (LI) * 2015-03-14: Implemented combine (JR) */functioncombine(a:number,b:number):number{returna+b;}
Good:
functioncombine(a:number,b:number):number{returna+b;}
They usually just add noise. Let the functions and variable names along with the proper indentation and formatting give the visual structure to your code.
Most IDE support code folding feature that allows you to collapse/expand blocks of code (see Visual Studio Codefolding regions).
Bad:
////////////////////////////////////////////////////////////////////////////////// Client class////////////////////////////////////////////////////////////////////////////////classClient{id:number;name:string;address:Address;contact:Contact;////////////////////////////////////////////////////////////////////////////////// public methods////////////////////////////////////////////////////////////////////////////////publicdescribe():string{// ...}////////////////////////////////////////////////////////////////////////////////// private methods////////////////////////////////////////////////////////////////////////////////privatedescribeAddress():string{// ...}privatedescribeContact():string{// ...}};
Good:
classClient{id:number;name:string;address:Address;contact:Contact;publicdescribe():string{// ...}privatedescribeAddress():string{// ...}privatedescribeContact():string{// ...}};
When you find yourself that you need to leave notes in the code for some later improvements,do that using// TODO
comments. Most IDE have special support for those kinds of comments so thatyou can quickly go over the entire list of todos.
Keep in mind however that aTODO comment is not an excuse for bad code.
Bad:
functiongetActiveSubscriptions():Promise<Subscription[]>{// ensure `dueDate` is indexed.returndb.subscriptions.find({dueDate:{$lte:newDate()}});}
Good:
functiongetActiveSubscriptions():Promise<Subscription[]>{// TODO: ensure `dueDate` is indexed.returndb.subscriptions.find({dueDate:{$lte:newDate()}});}
This is also available in other languages:
Brazilian Portuguese:vitorfreitas/clean-code-typescript
Chinese:
French:ralflorent/clean-code-typescript
German:mheob/clean-code-typescript
Japanese:MSakamaki/clean-code-typescript
Korean:738/clean-code-typescript
Russian:Real001/clean-code-typescript
Spanish:3xp1o1t/clean-code-typescript
Turkish:ozanhonamlioglu/clean-code-typescript
Ukrainian:KirillPd/clean-code-typescript
Vietnamese:hoangsetup/clean-code-typescript
References will be added once translations are completed.
Check thisdiscussion for more details and progress.You can make an indispensable contribution toClean Code community by translating this to your language.
About
Clean Code concepts adapted for TypeScript