Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Clean Code concepts adapted for TypeScript

License

NotificationsYou must be signed in to change notification settings

ozanhonamlioglu/clean-code-typescript

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

60 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Temiz Kod konseptleri TypeScript için uyarlandı.
clean-code-javascript'den ilham alındı.

İçindekiler

  1. Giriş
  2. Değişkenler
  3. Fonksiyonlar
  4. Obje ve Veri Yapısı
  5. Claslar
  6. SOLID
  7. Test
  8. Eşzamanlılık
  9. Hata İşleme
  10. Biçimlendirme
  11. Yorum Satırları
  12. Dil Çevirmeleri

Giriş

Humorous image of software quality estimation as a count of how many expletives you shout when reading code

TypeScript için uyarlanmış yazılım mühendisliği ilkeleri. Robert C. Martin'inClean Code adlı kitabından.
Bu makale bir stil rehberi değildir. Bu makale; TypeScript ileokunabilir, tekrar kullanılabilir, ve geliştirilebilir yazılım üretebilmenin rehberidir.

Buradaki her ilkenin kesinlikle takip edilmesi gerekmiyor ve hatta daha az bir kısmı evrensel olarak kabul edilecektir.
Buradaki bilgiler sadece bir klavuz niteliği taşımaktadır ve bundan daha fazlası değildir ancak önemi;Clean Code yazarlarının yıllarca süren kod yazma tecrübelerinin sonucu ortaya çıkmış olmasıdır.

Yazılım mühendisliği sanatımız 50 yaşından biraz daha fazla ve hâlâ sürekli öğreniyoruz. Yazılım mimarisi, mimarinin kendisi kadar yaşlı olduğunda belki o zaman takip etmesi zor kurallarımız olabilir ama şimdilik bu kılavuzu; sizin ve ekibinizin TypeScript kodlarını değerlendirebileceği bir mihenk taşı niteliğinde kabul edebilirsiniz.

Birşey daha: Bu bilgileri bilmek sizi hemencecik daha iyi bir yazılımcı yapmayacak, hatta bu bilgilerle yıllarca çalışmak da hata yapmayacağınız anlamına gelmiyor.
Her bir kod parçası hayatına, ıslak bir kilin son şeklini alırcasına, taslak olarak başlar, en sonunda kusurlar, ekip ile beraber gözden geçirilerek onarılır. Asla zamanının hepsini ilk taslakların daha iyi geliştirilmesi gerektiğini düşünerek harcama, bunun yerine önce koda ve genel yapıya odaklan.

⬆ sayfanın başına git

Değişkenler

Anlamlı değişken isimleri kullanın

Değişken isimlerini öyle bir şekilde ayırt edin ki, okuyan kişi değişken isimlerinin neyi ifade ettiğini anlayabilsin.

Kötü:

functionbetween<T>(a1:T,a2:T,a3:T):boolean{returna2<=a1&&a1<=a3;}

İyi:

functionbetween<T>(value:T,left:T,right:T):boolean{returnleft<=value&&value<=right;}

⬆ sayfanın başına git

Telaffuzu rahat değişken isimleri kullanın

Eğer isimleri telaffuz edemezseniz, bir aptal gibi konuşmadan tartışamazsınız.

Kötü:

typeDtaRcrd102={genymdhms:Date;modymdhms:Date;pszqint:number;};

İyi:

typeCustomer={generationTimestamp:Date;modificationTimestamp:Date;recordId:number;};

⬆ sayfanın başına git

Aynı değişkenler için aynı isimleri kullanmaya çalışın

Kötü:

functiongetUserInfo():User;functiongetUserDetails():User;functiongetUserData():User;

İyi:

functiongetUser():User;

⬆ sayfanın başına git

Aranması kolay isimler kullanın

Kodumuzu yazmaktan çok okumak için vakit ayıracağız, bu yüzden yazacağımız kodların anlaşılabilir ve istediğimiz zaman kolayca bulunabilir olması çok önemli.
Anlamlı bir şekilde isimlendirmesi yapılmamış kodlar, kodları okuyacak kişiler için çok zor bir hâl alacaktır.
TSLint gibi araçlar adsız sabitleri tanımlamaya yardımcı olurlar. Örneğin, "86400000" değerininTSLint sayesinde adlandırılması gerektiğini farkedebilirsiniz.

Kötü:

// What the heck is 86400000 for?setTimeout(restart,86400000);

İyi:

// Declare them as capitalized named constants.constMILLISECONDS_IN_A_DAY=24*60*60*1000;setTimeout(restart,MILLISECONDS_IN_A_DAY);

⬆ sayfanın başına git

Açıklayıcı değişkenler kullanın

Örnekte görüldüğü üzere, döngü çıktılarını "keyValue" diyerek tek değişkende toplamak yerine, çıktıların neler olabileceğini "[id, user]" en başta belirtmek kodun anlaşılabilirliği için önemli rol oynayacaktır.

Kötü:

declareconstusers:Map<string,User>;for(constkeyValueofusers){// iterate through users map}

İyi:

declareconstusers:Map<string,User>;for(const[id,user]ofusers){// iterate through users map}

⬆ sayfanın başına git

Zihninizde canlanabileceğini düşündüğünüz harf haritalaması yapmaktan kaçının

Açıklayıcı olmak kısaltma yapmaktan her zaman iyidir.
Berraklık en iyisidir.

Kötü:

constu=getUser();consts=getSubscription();constt=charge(u,s);

İyi:

constuser=getUser();constsubscription=getSubscription();consttransaction=charge(user,subscription);

⬆ sayfanın başına git

İsimlerde gereksiz uzatmalar yapmayın

Eğer zaten oluşturduğunuz class/type/object isimleri size kendileri hakkında açıklayıcı oluyorlar ise, onlara bağlı olan değişken isimlerinde aynısını tekrar etmeyin, saf değişken isimleri oluşturun.

Kötü:

typeCar={carMake:string;carModel:string;carColor:string;};functionprint(car:Car):void{console.log(`${car.carMake}${car.carModel} (${car.carColor})`);}

İyi:

typeCar={make:string;model:string;color:string;};functionprint(car:Car):void{console.log(`${car.make}${car.model} (${car.color})`);}

⬆ sayfanın başına git

Şartlandırmalar yerine varsayılan değerler kullanın

Varsayılan değerler, kısa şartlandırmalardan daha temiz bir yapı oluştururlar.

Kötü:

functionloadPages(count?:number){constloadCount=count!==undefined ?count :10;// ...}

İyi:

functionloadPages(count:number=10){// ...}

⬆ sayfanın başına git

Amacı belgelemek için enum kullanın

Enum kullanımı kodun amacını belgelemek için size yardımcı olur. Örneğin, girilen değerlerin kesin değerlerinden farklı olacağından endişelendiğimiz bir durumda, enumlar bu endişeyi ortadan kaldırırlar. Aynı şeyi "Kötü" örnekte olduğu gibi yaparsak, "İyi" koda göre fazla tanımlama yapıp okunaklılığı azaltmış oluruz.

Kötü:

constGENRE={ROMANTIC:'romantic',DRAMA:'drama',COMEDY:'comedy',DOCUMENTARY:'documentary'};projector.configureFilm(GENRE.COMEDY);classProjector{// delactation of ProjectorconfigureFilm(genre){switch(genre){caseGENRE.ROMANTIC:// some logic to be executed}}}

İyi:

enumGENRE{ROMANTIC,DRAMA,COMEDY,DOCUMENTARY}projector.configureFilm(GENRE.COMEDY);classProjector{// delactation of ProjectorconfigureFilm(genre){switch(genre){caseGENRE.ROMANTIC:// some logic to be executed}}}

⬆ sayfanın başına git

Fonksiyonlar

Fonksiyon parametreleri (ideali 2 ya da daha az)

Fonksiyon parametrelerini limitlemek çok önemlidir, çünkü bu iş, fonksyionların testlerini kolaylaştıracaktır.
Bir fonksiyona üçten fazla parametre eklemek, birçok kombinasyonlu durumu test etmenizi gerektirecektir, bu da testlerin zorlaşması anlamına geliyor.

Mümkünse bir ya da iki parametre en ideal seçim olacaktır.
Bundan daha fazlası için, kod içerisinde sağlamlaştırma yapılmalıdır.
Genellikle iki den fazla parametre fonksiyonlarınızın ağır çalışmasına sebep olacaktır. Aksi durumlarda, yüksek seviye bir fonksiyon parametre olarak kullanılabilir.

Eğer birden fazla parametreye ihityacınız var ise, alternatif olarak object literallerini kullanmaya çalışın.

Fonksiyonların ne tür parametreler beklediğini belirtmek için,destructuring sentakslarını kullanabilirsiniz ve hatta bunun avantajlarından da bahsedelim.

  1. Herhangi biri, fonksiyon satırına baktığı zaman, hangi parametrelerin kullandığını apaçık görecektir.

  2. Destructuring işlemi, fonksiyonda belirtilen basit parametrelerin kopyasını oluşturacağından dolayı side effect sorununu önleyecektir.
    NOT: Destruct yapılan objeler ve arraylar kopyalanmazlar.

  3. TypeScript, sizi kullanılmayan değişekenler için uyaracaktır ki bu destructing işlemi yapmadan imkansızdır.

Kötü:

functioncreateMenu(title:string,body:string,buttonText:string,cancellable:boolean){// ...}createMenu('Foo','Bar','Baz',true);

İyi:

functioncreateMenu(options:{title:string;body:string;buttonText:string;cancellable:boolean;}){// ...}createMenu({title:'Foo',body:'Bar',buttonText:'Baz',cancellable:true});

Okunabilirliği artırmak içintype aliases kullanabilirsiniz:

typeMenuOptions={title:string;body:string;buttonText:string;cancellable:boolean;};functioncreateMenu(options:MenuOptions){// ...}createMenu({title:'Foo',body:'Bar',buttonText:'Baz',cancellable:true});

⬆ sayfanın başına git

Fonksiyonlar tek bir iş yapmalıdır

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, they 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:

functionemailClients(clients:Client[]){clients.forEach(client=>{constclientRecord=database.lookup(client);if(clientRecord.isActive()){email(client);}});}

Good:

functionemailClients(clients:Client[]){clients.filter(isActiveClient).forEach(email);}functionisActiveClient(client:Client){constclientRecord=database.lookup(client);returnclientRecord.isActive();}

⬆ sayfanın başına git

Function names should say what they do

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);

⬆ sayfanın başına git

Functions should only be one level of abstraction

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;}

⬆ sayfanın başına git

Remove duplicate code

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 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.

⬆ sayfanın başına git

Set default objects with Object.assign or destructuring

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'});

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.

⬆ sayfanın başına git

Don't use flags as function parameters

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);}

⬆ sayfanın başına git

Avoid Side Effects (part 1)

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);

⬆ sayfanın başına git

Avoid Side Effects (part 2)

In JavaScript, primitives are passed by value and objects/arrays are passed by reference. In the case of objects and arrays, if your function makes a change in a shopping cart array, for example, by adding an item to purchase, then any other function that uses thatcart array will be affected by this addition. That may be great, however it can be bad too. 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, the purchase function has to keep retrying the request. Now, what if in the meantime the user accidentally clicks "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 it has a reference to a shopping cart array that theaddItemToCart function modified by adding an unwanted item.

A great solution would be for theaddItemToCart to always clone thecart, edit it, and return the clone. This ensures that no other functions that are holding onto a reference of the shopping cart will be affected by any changes.

Two caveats to mention to this approach:

  1. 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)

  2. Cloning big objects can be very expensive in terms of performance. Luckily, this isn't a big issue in practice because there are great 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()}];}

⬆ sayfanın başına git

Don't write to global functions

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));}}

⬆ sayfanın başına git

Favor functional programming over imperative programming

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);

⬆ sayfanın başına git

Encapsulate conditionals

Bad:

if(subscription.isTrial||account.balance>0){// ...}

Good:

functioncanActivateService(subscription:Subscription,account:Account){returnsubscription.isTrial||account.balance>0;}if(canActivateService(subscription,account)){// ...}

⬆ sayfanın başına git

Avoid negative conditionals

Bad:

functionisEmailNotUsed(email:string):boolean{// ...}if(isEmailNotUsed(email)){// ...}

Good:

functionisEmailUsed(email):boolean{// ...}if(!isEmailUsed(node)){// ...}

⬆ sayfanın başına git

Avoid conditionals

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();}}

⬆ sayfanın başına git

Avoid type checking

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'));}

⬆ sayfanın başına git

Don't over-optimize

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++){// ...}

⬆ sayfanın başına git

Remove dead code

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 safe 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');

⬆ sayfanın başına git

Use iterators and generators

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 thefor-of syntax
  • iterables allow to implement 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));

⬆ sayfanın başına git

Objects and Data Structures

Use getters and setters

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 aset.
  • 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;

⬆ sayfanın başına git

Make objects have private/protected members

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;}}

⬆ sayfanın başına git

Prefer immutability

TypeScript's type system allows you to mark individual properties on an interface / class asreadonly. This allows you to work in a functional way (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;}

Case of Array, you can create a read-only array by usingReadonlyArray<T>.do not allow changes such aspush() andfill(), but can use features such asconcat() andslice() that do not change the value.

Bad:

constarray:number[]=[1,3,5];array=[];// errorarray.push(100);// array will 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

⬆ sayfanın başına git

type vs. interface

Use type when you might need a union or intersection. Use 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{// ...}

⬆ sayfanın başına git

Classes

Classes should be small

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// ...

⬆ sayfanın başına git

High cohesion and low coupling

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 doesn'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>{// ...}}

⬆ sayfanın başına git

Prefer composition over inheritance

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:

  1. Your inheritance represents an "is-a" relationship and not a "has-a" relationship (Human->Animal vs. User->UserDetails).

  2. You can reuse code from the base classes (Humans can move like all animals).

  3. 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){}// ...}

⬆ sayfanın başına git

Use method chaining

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();

⬆ sayfanın başına git

SOLID

Single Responsibility Principle (SRP)

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 times 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()){// ...}}}

⬆ sayfanın başına git

Open/Closed Principle (OCP)

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}}

⬆ sayfanın başına git

Liskov Substitution Principle (LSP)

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);

⬆ sayfanın başına git

Interface Segregation Principle (ISP)

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(){// ...}}

⬆ sayfanın başına git

Dependency Inversion Principle (DIP)

This principle states two essential things:

  1. High-level modules should not depend on low-level modules. Both should depend on abstractions.

  2. 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();awaitreport=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());awaitreport=awaitreader.read('report.xml');// or if we had to read a json reportconstreader=newReportReader(newJsonFormatter());awaitreport=awaitreader.read('report.json');

⬆ sayfanın başına git

Testing

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.

The three laws of TDD

  1. You are not allowed to write any production code unless it is to make a failing unit test pass.

  2. You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.

  3. You are not allowed to write any more production code than is sufficient to pass the one failing unit test.

⬆ sayfanın başına git

F.I.R.S.T. rules

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.

⬆ sayfanın başına git

Single concept per test

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));});});

⬆ sayfanın başına git

The name of the test should reveal its intention

When a test fail, 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',()=>{// ...});});

⬆ sayfanın başına git

Concurrency

Prefer promises vs callbacks

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 conscise:

PatternDescription
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.

⬆ sayfanın başına git

Async/Await are even cleaner than 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,saveTo:string):Promise<string>{constresponse=awaitget(url);awaitwrite(saveTo,response);returnresponse;}// somewhere in an async functiontry{constcontent=awaitdownloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin','article.html');console.log(content);}catch(error){console.error(error);}

⬆ sayfanın başına git

Error Handling

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.

Always use Error for throwing or rejecting

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 another alternatives, not to use thethrow syntax and instead always return custom error objects. TypeScript makes this even easier.Consider 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.

⬆ sayfanın başına git

Don't ignore caught errors

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 times 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);}

⬆ sayfanın başına git

Don't ignore rejected promises

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);}

⬆ sayfanın başına git

Formatting

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 calledTSLint. It's a static analysis tool that can help you improve dramatically the readability and maintainability of your code. There are ready to use TSLint configurations that you can reference in your projects:

Refer also to this greatTypeScript StyleGuide and Coding Conventions source.

Use consistent capitalization

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'];functioneraseDatabase(){}functionrestoreDatabase(){}typeAnimal={/* ... */};typeContainer={/* ... */};

Prefer usingPascalCase for class, interface, type and namespace names.
Prefer usingcamelCase for variables, functions and class members.

⬆ sayfanın başına git

Function callers and callees should be close

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();

⬆ sayfanın başına git

Organize imports

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';
  • 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.eimport { 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';)

Bad:

import{TypeDefinition}from'../types/typeDefinition';import{AttributeTypes}from'../model/attribute';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';import{ApiCredentials,Adapters}from'./common/api/authorization';import{ConfigPlugin}from'./plugins/config/configPlugin';

⬆ sayfanın başına git

Use typescript aliases

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/*"]}...}...

⬆ sayfanın başına git

Comments

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

Prefer self explanatory code instead of comments

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){/* ... */}

⬆ sayfanın başına git

Don't leave commented out code in your codebase

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;};

⬆ sayfanın başına git

Don't have journal comments

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;}

⬆ sayfanın başına git

Avoid positional markers

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{// ...}}

⬆ sayfanın başına git

TODO comments

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 kind 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()}});}

⬆ sayfanın başına git

Translations

This is also available in other languages:

There is work in progress for translating this to other languages:

  • kr Korean

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

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript100.0%

[8]ページ先頭

©2009-2025 Movatter.jp