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 JavaScript

License

NotificationsYou must be signed in to change notification settings

Boying14/clean-code-javascript

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 

Repository files navigation

Table of Contents

  1. Introduction
  2. Variables
  3. Functions
  4. Objects and Data Structures
  5. Classes
  6. SOLID
  7. Testing
  8. Concurrency
  9. Error Handling
  10. Formatting
  11. Comments
  12. Translation

Introduction

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

Software engineering principles, from Robert C. Martin's bookClean Code,adapted for JavaScript. This is not a style guide. It's a guide to producingreadable, reusable, and refactorable software in JavaScript.

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 theJavaScript 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!

Variables

Use meaningful and pronounceable variable names

Bad:

constyyyymmdstr=moment().format("YYYY/MM/DD");

Good:

constcurrentDate=moment().format("YYYY/MM/DD");

⬆ back to top

Use the same vocabulary for the same type of variable

Bad:

getUserInfo();getClientData();getCustomerRecord();

Good:

getUser();

⬆ back to top

Use searchable names

We will read more code than we will ever write. It's important that the code wedo write is readable and searchable. Bynot naming variables that end upbeing meaningful for understanding our program, we hurt our readers.Make your names searchable. Tools likebuddy.js andESLintcan help identify unnamed constants.

Bad:

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

Good:

// Declare them as capitalized named constants.constMILLISECONDS_IN_A_DAY=86400000;setTimeout(blastOff,MILLISECONDS_IN_A_DAY);

⬆ back to top

Use explanatory variables

Bad:

constaddress="One Infinite Loop, Cupertino 95014";constcityZipCodeRegex=/^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;saveCityZipCode(address.match(cityZipCodeRegex)[1],address.match(cityZipCodeRegex)[2]);

Good:

constaddress="One Infinite Loop, Cupertino 95014";constcityZipCodeRegex=/^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;const[,city,zipCode]=address.match(cityZipCodeRegex)||[];saveCityZipCode(city,zipCode);

⬆ back to top

Avoid Mental Mapping

Explicit is better than implicit.

Bad:

constlocations=["Austin","New York","San Francisco"];locations.forEach(l=>{doStuff();doSomeOtherStuff();// ...// ...// ...// Wait, what is `l` for again?dispatch(l);});

Good:

constlocations=["Austin","New York","San Francisco"];locations.forEach(location=>{doStuff();doSomeOtherStuff();// ...// ...// ...dispatch(location);});

⬆ back to top

Don't add unneeded context

If your class/object name tells you something, don't repeat that in yourvariable name.

Bad:

constCar={carMake:"Honda",carModel:"Accord",carColor:"Blue"};functionpaintCar(car){car.carColor="Red";}

Good:

constCar={make:"Honda",model:"Accord",color:"Blue"};functionpaintCar(car){car.color="Red";}

⬆ back to top

Use default arguments instead of short circuiting or conditionals

Default arguments are often cleaner than short circuiting. Be aware that if youuse them, your function will only provide default values forundefinedarguments. Other "falsy" values such as'',"",false,null,0, andNaN, will not be replaced by a default value.

Bad:

functioncreateMicrobrewery(name){constbreweryName=name||"Hipster Brew Co.";// ...}

Good:

functioncreateMicrobrewery(name="Hipster Brew Co."){// ...}

⬆ back to top

Functions

Function arguments (2 or fewer ideally)

Limiting the amount of function parameters is incredibly important because itmakes testing your function easier. Having more than three leads to acombinatorial explosion where you have to test tons of different cases witheach 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 havemore than two arguments then your function is trying to do too much. In caseswhere it's not, most of the time a higher-level object will suffice as anargument.

Since JavaScript allows you to make objects on the fly, without a lot of classboilerplate, you can use an object if you are finding yourself needing alot of arguments.

To make it obvious what properties the function expects, you can use the ES2015/ES6destructuring syntax. This has a few advantages:

  1. When someone looks at the function signature, it's immediately clear whatproperties are being used.
  2. Destructuring also clones the specified primitive values of the argumentobject passed into the function. This can help prevent side effects. Note:objects and arrays that are destructured from the argument object are NOTcloned.
  3. Linters can warn you about unused properties, which would be impossiblewithout destructuring.

Bad:

functioncreateMenu(title,body,buttonText,cancellable){// ...}

Good:

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

⬆ back to top

Functions should do one thing

This is by far the most important rule in software engineering. When functionsdo 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 refactoredeasily and your code will read much cleaner. If you take nothing else away fromthis guide other than this, you'll be ahead of many developers.

Bad:

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

Good:

functionemailActiveClients(clients){clients.filter(isActiveClient).forEach(email);}functionisActiveClient(client){constclientRecord=database.lookup(client);returnclientRecord.isActive();}

⬆ back to top

Function names should say what they do

Bad:

functionaddToDate(date,month){// ...}constdate=newDate();// It's hard to tell from the function name what is addedaddToDate(date,1);

Good:

functionaddMonthToDate(month,date){// ...}constdate=newDate();addMonthToDate(1,date);

⬆ back to top

Functions should only be one level of abstraction

When you have more than one level of abstraction your function is usuallydoing too much. Splitting up functions leads to reusability and easiertesting.

Bad:

functionparseBetterJSAlternative(code){constREGEXES=[// ...];conststatements=code.split(" ");consttokens=[];REGEXES.forEach(REGEX=>{statements.forEach(statement=>{// ...});});constast=[];tokens.forEach(token=>{// lex...});ast.forEach(node=>{// parse...});}

Good:

functionparseBetterJSAlternative(code){consttokens=tokenize(code);constsyntaxTree=parse(tokens);syntaxTree.forEach(node=>{// parse...});}functiontokenize(code){constREGEXES=[// ...];conststatements=code.split(" ");consttokens=[];REGEXES.forEach(REGEX=>{statements.forEach(statement=>{tokens.push(/* ... */);});});returntokens;}functionparse(tokens){constsyntaxTree=[];tokens.forEach(token=>{syntaxTree.push(/* ... */);});returnsyntaxTree;}

⬆ back to top

Remove duplicate code

Do your absolute best to avoid duplicate code. Duplicate code is bad because itmeans that there's more than one place to alter something if you need to changesome logic.

Imagine if you run a restaurant and you keep track of your inventory: all yourtomatoes, onions, garlic, spices, etc. If you have multiple lists thatyou keep this on, then all have to be updated when you serve a dish withtomatoes 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 slightlydifferent things, that share a lot in common, but their differences force youto have two or more separate functions that do much of the same things. Removingduplicate code means creating an abstraction that can handle this set ofdifferent things with just one function/module/class.

Getting the abstraction right is critical, that's why you should follow theSOLID principles laid out in theClasses section. Bad abstractions can beworse than duplicate code, so be careful! Having said this, if you can makea good abstraction, do it! Don't repeat yourself, otherwise you'll find yourselfupdating multiple places anytime you want to change one thing.

Bad:

functionshowDeveloperList(developers){developers.forEach(developer=>{constexpectedSalary=developer.calculateExpectedSalary();constexperience=developer.getExperience();constgithubLink=developer.getGithubLink();constdata={      expectedSalary,      experience,      githubLink};render(data);});}functionshowManagerList(managers){managers.forEach(manager=>{constexpectedSalary=manager.calculateExpectedSalary();constexperience=manager.getExperience();constportfolio=manager.getMBAProjects();constdata={      expectedSalary,      experience,      portfolio};render(data);});}

Good:

functionshowEmployeeList(employees){employees.forEach(employee=>{constexpectedSalary=employee.calculateExpectedSalary();constexperience=employee.getExperience();constdata={      expectedSalary,      experience};switch(employee.type){case"manager":data.portfolio=employee.getMBAProjects();break;case"developer":data.githubLink=employee.getGithubLink();break;}render(data);});}

⬆ back to top

Set default objects with Object.assign

Bad:

constmenuConfig={title:null,body:"Bar",buttonText:null,cancellable:true};functioncreateMenu(config){config.title=config.title||"Foo";config.body=config.body||"Bar";config.buttonText=config.buttonText||"Baz";config.cancellable=config.cancellable!==undefined ?config.cancellable :true;}createMenu(menuConfig);

Good:

constmenuConfig={title:"Order",// User did not include 'body' keybuttonText:"Send",cancellable:true};functioncreateMenu(config){config=Object.assign({title:"Foo",body:"Bar",buttonText:"Baz",cancellable:true},config);// config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true}// ...}createMenu(menuConfig);

⬆ back to top

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,temp){if(temp){fs.create(`./temp/${name}`);}else{fs.create(name);}}

Good:

functioncreateFile(name){fs.create(name);}functioncreateTempFile(name){createFile(`./temp/${name}`);}

⬆ back to top

Avoid Side Effects (part 1)

A function produces a side effect if it does anything other than take a value inand 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 astranger.

Now, you do need to have side effects in a program on occasion. Like the previousexample, you might need to write to a file. What you want to do is tocentralize where you are doing this. Don't have several functions and classesthat 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 objectswithout 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 willbe happier than the vast majority of other programmers.

Bad:

// Global variable referenced by following function.// If we had another function that used this name, now it'd be an array and it could break it.letname="Ryan McDermott";functionsplitIntoFirstAndLastName(){name=name.split(" ");}splitIntoFirstAndLastName();console.log(name);// ['Ryan', 'McDermott'];

Good:

functionsplitIntoFirstAndLastName(name){returnname.split(" ");}constname="Ryan McDermott";constnewName=splitIntoFirstAndLastName(name);console.log(name);// 'Ryan McDermott';console.log(newName);// ['Ryan', 'McDermott'];

⬆ back to top

Avoid Side Effects (part 2)

In JavaScript, primitives are passed by value and objects/arrays are passed byreference. In the case of objects and arrays, if your function makes a changein a shopping cart array, for example, by adding an item to purchase,then any other function that uses thatcart array will be affected by thisaddition. That may be great, however it can be bad too. Let's imagine a badsituation:

The user clicks the "Purchase", button which calls apurchase function thatspawns a network request and sends thecart array to the server. Becauseof a bad network connection, thepurchase function has to keep retrying therequest. 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 functionwill send the accidentally added item because it has a reference to a shoppingcart array that theaddItemToCart function modified by adding an unwanteditem.

A great solution would be for theaddItemToCart to always clone thecart,edit it, and return the clone. This ensures that no other functions that areholding 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 casesare pretty rare. Most things can be refactored to have no side effects!

  2. 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 allowthis kind of programming approach to be fast and not as memory intensive asit would be for you to manually clone objects and arrays.

Bad:

constaddItemToCart=(cart,item)=>{cart.push({ item,date:Date.now()});};

Good:

constaddItemToCart=(cart,item)=>{return[...cart,{ item,date:Date.now()}];};

⬆ back to top

Don't write to global functions

Polluting globals is a bad practice in JavaScript because you could clash with anotherlibrary and the user of your API would be none-the-wiser until they get anexception in production. Let's think about an example: what if you wanted toextend JavaScript's native Array method to have adiff method that couldshow the difference between two arrays? You could write your new functionto theArray.prototype, but it could clash with another library that triedto do the same thing. What if that other library was just usingdiff to findthe difference between the first and last elements of an array? This is why itwould be much better to just use ES2015/ES6 classes and simply extend theArray global.

Bad:

Array.prototype.diff=functiondiff(comparisonArray){consthash=newSet(comparisonArray);returnthis.filter(elem=>!hash.has(elem));};

Good:

classSuperArrayextendsArray{diff(comparisonArray){consthash=newSet(comparisonArray);returnthis.filter(elem=>!hash.has(elem));}}

⬆ back to top

Favor functional programming over imperative programming

JavaScript isn't a functional language in the way that Haskell is, but it hasa functional flavor to it. Functional languages can be cleaner and easier to test.Favor this style of programming when you can.

Bad:

constprogrammerOutput=[{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<programmerOutput.length;i++){totalOutput+=programmerOutput[i].linesOfCode;}

Good:

constprogrammerOutput=[{name:"Uncle Bobby",linesOfCode:500},{name:"Suzie Q",linesOfCode:1500},{name:"Jimmy Gosling",linesOfCode:150},{name:"Gracie Hopper",linesOfCode:1000}];consttotalOutput=programmerOutput.reduce((totalLines,output)=>totalLines+output.linesOfCode,0);

⬆ back to top

Encapsulate conditionals

Bad:

if(fsm.state==="fetching"&&isEmpty(listNode)){// ...}

Good:

functionshouldShowSpinner(fsm,listNode){returnfsm.state==="fetching"&&isEmpty(listNode);}if(shouldShowSpinner(fsmInstance,listNodeInstance)){// ...}

⬆ back to top

Avoid negative conditionals

Bad:

functionisDOMNodeNotPresent(node){// ...}if(!isDOMNodeNotPresent(node)){// ...}

Good:

functionisDOMNodePresent(node){// ...}if(isDOMNodePresent(node)){// ...}

⬆ back to top

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 thatyou can use polymorphism to achieve the same task in many cases. The secondquestion is usually, "well that's great but why would I want to do that?" Theanswer is a previous clean code concept we learned: a function should only doone thing. When you have classes and functions that haveif statements, youare telling your user that your function does more than one thing. Remember,just do one thing.

Bad:

classAirplane{// ...getCruisingAltitude(){switch(this.type){case"777":returnthis.getMaxAltitude()-this.getPassengerCount();case"Air Force One":returnthis.getMaxAltitude();case"Cessna":returnthis.getMaxAltitude()-this.getFuelExpenditure();}}}

Good:

classAirplane{// ...}classBoeing777extendsAirplane{// ...getCruisingAltitude(){returnthis.getMaxAltitude()-this.getPassengerCount();}}classAirForceOneextendsAirplane{// ...getCruisingAltitude(){returnthis.getMaxAltitude();}}classCessnaextendsAirplane{// ...getCruisingAltitude(){returnthis.getMaxAltitude()-this.getFuelExpenditure();}}

⬆ back to top

Avoid type-checking (part 1)

JavaScript is untyped, which means your functions can take any type of argument.Sometimes you are bitten by this freedom and it becomes tempting to dotype-checking in your functions. There are many ways to avoid having to do this.The first thing to consider is consistent APIs.

Bad:

functiontravelToTexas(vehicle){if(vehicleinstanceofBicycle){vehicle.pedal(this.currentLocation,newLocation("texas"));}elseif(vehicleinstanceofCar){vehicle.drive(this.currentLocation,newLocation("texas"));}}

Good:

functiontravelToTexas(vehicle){vehicle.move(this.currentLocation,newLocation("texas"));}

⬆ back to top

Avoid type-checking (part 2)

If you are working with basic primitive values like strings and integers,and you can't use polymorphism but you still feel the need to type-check,you should consider using TypeScript. It is an excellent alternative to normalJavaScript, as it provides you with static typing on top of standard JavaScriptsyntax. The problem with manually type-checking normal JavaScript is thatdoing it well requires so much extra verbiage that the faux "type-safety" you getdoesn't make up for the lost readability. Keep your JavaScript clean, writegood tests, and have good code reviews. Otherwise, do all of that but withTypeScript (which, like I said, is a great alternative!).

Bad:

functioncombine(val1,val2){if((typeofval1==="number"&&typeofval2==="number")||(typeofval1==="string"&&typeofval2==="string")){returnval1+val2;}thrownewError("Must be of type String or Number");}

Good:

functioncombine(val1,val2){returnval1+val2;}

⬆ back to top

Don't over-optimize

Modern browsers do a lot of optimization under-the-hood at runtime. A lot oftimes, if you are optimizing then you are just wasting your time.There are goodresourcesfor seeing where optimization is lacking. Target those in the meantime, untilthey 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++){// ...}

⬆ back to top

Remove dead code

Dead code is just as bad as duplicate code. There's no reason to keep it inyour codebase. If it's not being called, get rid of it! It will still be safein your version history if you still need it.

Bad:

functionoldRequestModule(url){// ...}functionnewRequestModule(url){// ...}constreq=newRequestModule;inventoryTracker("apples",req,"www.inventory-awesome.io");

Good:

functionnewRequestModule(url){// ...}constreq=newRequestModule;inventoryTracker("apples",req,"www.inventory-awesome.io");

⬆ back to top

Objects and Data Structures

Use getters and setters

Using getters and setters to access data on objects could be better than simplylooking for a property on an object. "Why?" you might ask. Well, here's anunorganized list of reasons why:

  • When you want to do more beyond getting an object property, you don't haveto 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 aserver.

Bad:

functionmakeBankAccount(){// ...return{balance:0// ...};}constaccount=makeBankAccount();account.balance=100;

Good:

functionmakeBankAccount(){// this one is privateletbalance=0;// a "getter", made public via the returned object belowfunctiongetBalance(){returnbalance;}// a "setter", made public via the returned object belowfunctionsetBalance(amount){// ... validate before updating the balancebalance=amount;}return{// ...    getBalance,    setBalance};}constaccount=makeBankAccount();account.setBalance(100);

⬆ back to top

Make objects have private members

This can be accomplished through closures (for ES5 and below).

Bad:

constEmployee=function(name){this.name=name;};Employee.prototype.getName=functiongetName(){returnthis.name;};constemployee=newEmployee("John Doe");console.log(`Employee name:${employee.getName()}`);// Employee name: John Doedeleteemployee.name;console.log(`Employee name:${employee.getName()}`);// Employee name: undefined

Good:

functionmakeEmployee(name){return{getName(){returnname;}};}constemployee=makeEmployee("John Doe");console.log(`Employee name:${employee.getName()}`);// Employee name: John Doedeleteemployee.name;console.log(`Employee name:${employee.getName()}`);// Employee name: John Doe

⬆ back to top

Classes

Prefer ES2015/ES6 classes over ES5 plain functions

It's very difficult to get readable class inheritance, construction, and methoddefinitions for classical ES5 classes. If you need inheritance (and be awarethat you might not), then prefer ES2015/ES6 classes. However, prefer small functions overclasses until you find yourself needing larger and more complex objects.

Bad:

constAnimal=function(age){if(!(thisinstanceofAnimal)){thrownewError("Instantiate Animal with `new`");}this.age=age;};Animal.prototype.move=functionmove(){};constMammal=function(age,furColor){if(!(thisinstanceofMammal)){thrownewError("Instantiate Mammal with `new`");}Animal.call(this,age);this.furColor=furColor;};Mammal.prototype=Object.create(Animal.prototype);Mammal.prototype.constructor=Mammal;Mammal.prototype.liveBirth=functionliveBirth(){};constHuman=function(age,furColor,languageSpoken){if(!(thisinstanceofHuman)){thrownewError("Instantiate Human with `new`");}Mammal.call(this,age,furColor);this.languageSpoken=languageSpoken;};Human.prototype=Object.create(Mammal.prototype);Human.prototype.constructor=Human;Human.prototype.speak=functionspeak(){};

Good:

classAnimal{constructor(age){this.age=age;}move(){/* ... */}}classMammalextendsAnimal{constructor(age,furColor){super(age);this.furColor=furColor;}liveBirth(){/* ... */}}classHumanextendsMammal{constructor(age,furColor,languageSpoken){super(age,furColor);this.languageSpoken=languageSpoken;}speak(){/* ... */}}

⬆ back to top

Use method chaining

This pattern is very useful in JavaScript and you see it in many libraries suchas jQuery and Lodash. It allows your code to be expressive, and less verbose.For that reason, I say, use method chaining and take a look at how clean your codewill be. In your class functions, simply returnthis at the end of every function,and you can chain further class methods onto it.

Bad:

classCar{constructor(make,model,color){this.make=make;this.model=model;this.color=color;}setMake(make){this.make=make;}setModel(model){this.model=model;}setColor(color){this.color=color;}save(){console.log(this.make,this.model,this.color);}}constcar=newCar("Ford","F-150","red");car.setColor("pink");car.save();

Good:

classCar{constructor(make,model,color){this.make=make;this.model=model;this.color=color;}setMake(make){this.make=make;// NOTE: Returning this for chainingreturnthis;}setModel(model){this.model=model;// NOTE: Returning this for chainingreturnthis;}setColor(color){this.color=color;// NOTE: Returning this for chainingreturnthis;}save(){console.log(this.make,this.model,this.color);// NOTE: Returning this for chainingreturnthis;}}constcar=newCar("Ford","F-150","red").setColor("pink").save();

⬆ back to top

Prefer composition over inheritance

As stated famously inDesign Patterns by the Gang of Four,you should prefer composition over inheritance where you can. There are lots ofgood 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 forinheritance, try to think if composition could model your problem better. In somecases it can.

You might be wondering then, "when should I use inheritance?" Itdepends on your problem at hand, but this is a decent list of when inheritancemakes 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(name,email){this.name=name;this.email=email;}// ...}// Bad because Employees "have" tax data. EmployeeTaxData is not a type of EmployeeclassEmployeeTaxDataextendsEmployee{constructor(ssn,salary){super();this.ssn=ssn;this.salary=salary;}// ...}

Good:

classEmployeeTaxData{constructor(ssn,salary){this.ssn=ssn;this.salary=salary;}// ...}classEmployee{constructor(name,email){this.name=name;this.email=email;}setTaxData(ssn,salary){this.taxData=newEmployeeTaxData(ssn,salary);}// ...}

⬆ back to top

SOLID

Single Responsibility Principle (SRP)

As stated in Clean Code, "There should never be more than one reason for a classto change". It's tempting to jam-pack a class with a lot of functionality, likewhen you can only take one suitcase on your flight. The issue with this isthat your class won't be conceptually cohesive and it will give it many reasonsto 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 modifya piece of it, it can be difficult to understand how that will affect otherdependent modules in your codebase.

Bad:

classUserSettings{constructor(user){this.user=user;}changeSettings(settings){if(this.verifyCredentials()){// ...}}verifyCredentials(){// ...}}

Good:

classUserAuth{constructor(user){this.user=user;}verifyCredentials(){// ...}}classUserSettings{constructor(user){this.user=user;this.auth=newUserAuth(user);}changeSettings(settings){if(this.auth.verifyCredentials()){// ...}}}

⬆ back to top

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 thatmean though? This principle basically states that you should allow users toadd new functionalities without changing existing code.

Bad:

classAjaxAdapterextendsAdapter{constructor(){super();this.name="ajaxAdapter";}}classNodeAdapterextendsAdapter{constructor(){super();this.name="nodeAdapter";}}classHttpRequester{constructor(adapter){this.adapter=adapter;}fetch(url){if(this.adapter.name==="ajaxAdapter"){returnmakeAjaxCall(url).then(response=>{// transform response and return});}elseif(this.adapter.name==="nodeAdapter"){returnmakeHttpCall(url).then(response=>{// transform response and return});}}}functionmakeAjaxCall(url){// request and return promise}functionmakeHttpCall(url){// request and return promise}

Good:

classAjaxAdapterextendsAdapter{constructor(){super();this.name="ajaxAdapter";}request(url){// request and return promise}}classNodeAdapterextendsAdapter{constructor(){super();this.name="nodeAdapter";}request(url){// request and return promise}}classHttpRequester{constructor(adapter){this.adapter=adapter;}fetch(url){returnthis.adapter.request(url).then(response=>{// transform response and return});}}

⬆ back to top

Liskov Substitution Principle (LSP)

This is a scary term for a very simple concept. It's formally defined as "If Sis 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 anyof 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 base class and child class can be used interchangeably without gettingincorrect results. This might still be confusing, so let's take a look at theclassic Square-Rectangle example. Mathematically, a square is a rectangle, butif you model it using the "is-a" relationship via inheritance, you quicklyget into trouble.

Bad:

classRectangle{constructor(){this.width=0;this.height=0;}setColor(color){// ...}render(area){// ...}setWidth(width){this.width=width;}setHeight(height){this.height=height;}getArea(){returnthis.width*this.height;}}classSquareextendsRectangle{setWidth(width){this.width=width;this.height=width;}setHeight(height){this.width=height;this.height=height;}}functionrenderLargeRectangles(rectangles){rectangles.forEach(rectangle=>{rectangle.setWidth(4);rectangle.setHeight(5);constarea=rectangle.getArea();// BAD: Returns 25 for Square. Should be 20.rectangle.render(area);});}constrectangles=[newRectangle(),newRectangle(),newSquare()];renderLargeRectangles(rectangles);

Good:

classShape{setColor(color){// ...}render(area){// ...}}classRectangleextendsShape{constructor(width,height){super();this.width=width;this.height=height;}getArea(){returnthis.width*this.height;}}classSquareextendsShape{constructor(length){super();this.length=length;}getArea(){returnthis.length*this.length;}}functionrenderLargeShapes(shapes){shapes.forEach(shape=>{constarea=shape.getArea();shape.render(area);});}constshapes=[newRectangle(4,5),newRectangle(4,5),newSquare(5)];renderLargeShapes(shapes);

⬆ back to top

Interface Segregation Principle (ISP)

JavaScript doesn't have interfaces so this principle doesn't apply as strictlyas others. However, it's important and relevant even with JavaScript's lack oftype system.

ISP states that "Clients should not be forced to depend upon interfaces thatthey do not use." Interfaces are implicit contracts in JavaScript because ofduck typing.

A good example to look at that demonstrates this principle in JavaScript is forclasses that require large settings objects. Not requiring clients to setuphuge amounts of options is beneficial, because most of the time they won't needall of the settings. Making them optional helps prevent having a"fat interface".

Bad:

classDOMTraverser{constructor(settings){this.settings=settings;this.setup();}setup(){this.rootNode=this.settings.rootNode;this.animationModule.setup();}traverse(){// ...}}const$=newDOMTraverser({rootNode:document.getElementsByTagName("body"),animationModule(){}// Most of the time, we won't need to animate when traversing.// ...});

Good:

classDOMTraverser{constructor(settings){this.settings=settings;this.options=settings.options;this.setup();}setup(){this.rootNode=this.settings.rootNode;this.setupOptions();}setupOptions(){if(this.options.animationModule){// ...}}traverse(){// ...}}const$=newDOMTraverser({rootNode:document.getElementsByTagName("body"),options:{animationModule(){}}});

⬆ back to top

Dependency Inversion Principle (DIP)

This principle states two essential things:

  1. High-level modules should not depend on low-level modules. Both shoulddepend on abstractions.
  2. Abstractions should not depend upon details. Details should depend onabstractions.

This can be hard to understand at first, but if you've worked with AngularJS,you've seen an implementation of this principle in the form of DependencyInjection (DI). While they are not identical concepts, DIP keeps high-levelmodules 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 reducesthe coupling between modules. Coupling is a very bad development pattern becauseit makes your code hard to refactor.

As stated previously, JavaScript doesn't have interfaces so the abstractionsthat are depended upon are implicit contracts. That is to say, the methodsand properties that an object/class exposes to another object/class. In theexample below, the implicit contract is that any Request module for anInventoryTracker will have arequestItems method.

Bad:

classInventoryRequester{constructor(){this.REQ_METHODS=["HTTP"];}requestItem(item){// ...}}classInventoryTracker{constructor(items){this.items=items;// BAD: We have created a dependency on a specific request implementation.// We should just have requestItems depend on a request method: `request`this.requester=newInventoryRequester();}requestItems(){this.items.forEach(item=>{this.requester.requestItem(item);});}}constinventoryTracker=newInventoryTracker(["apples","bananas"]);inventoryTracker.requestItems();

Good:

classInventoryTracker{constructor(items,requester){this.items=items;this.requester=requester;}requestItems(){this.items.forEach(item=>{this.requester.requestItem(item);});}}classInventoryRequesterV1{constructor(){this.REQ_METHODS=["HTTP"];}requestItem(item){// ...}}classInventoryRequesterV2{constructor(){this.REQ_METHODS=["WS"];}requestItem(item){// ...}}// By constructing our dependencies externally and injecting them, we can easily// substitute our request module for a fancy new one that uses WebSockets.constinventoryTracker=newInventoryTracker(["apples","bananas"],newInventoryRequesterV2());inventoryTracker.requestItems();

⬆ back to top

Testing

Testing is more important than shipping. If you have no tests or aninadequate amount, then every time you ship code you won't be sure that youdidn't break anything. Deciding on what constitutes an adequate amount is upto your team, but having 100% coverage (all statements and branches) is howyou achieve very high confidence and developer peace of mind. This means thatin addition to having a great testing framework, you also need to use agood coverage tool.

There's no excuse to not write tests. There areplenty of good JS test frameworks, so find one that your team prefers.When you find one that works for your team, then aim to always write testsfor every new feature/module you introduce. If your preferred method isTest Driven Development (TDD), that is great, but the main point is to justmake sure you are reaching your coverage goals before launching any feature,or refactoring an existing one.

Single concept per test

Bad:

importassertfrom"assert";describe("MomentJS",()=>{it("handles date boundaries",()=>{letdate;date=newMomentJS("1/1/2015");date.addDays(30);assert.equal("1/31/2015",date);date=newMomentJS("2/1/2016");date.addDays(28);assert.equal("02/29/2016",date);date=newMomentJS("2/1/2015");date.addDays(28);assert.equal("03/01/2015",date);});});

Good:

importassertfrom"assert";describe("MomentJS",()=>{it("handles 30-day months",()=>{constdate=newMomentJS("1/1/2015");date.addDays(30);assert.equal("1/31/2015",date);});it("handles leap year",()=>{constdate=newMomentJS("2/1/2016");date.addDays(28);assert.equal("02/29/2016",date);});it("handles non-leap year",()=>{constdate=newMomentJS("2/1/2015");date.addDays(28);assert.equal("03/01/2015",date);});});

⬆ back to top

Concurrency

Use Promises, not callbacks

Callbacks aren't clean, and they cause excessive amounts of nesting. With ES2015/ES6,Promises are a built-in global type. Use them!

Bad:

import{get}from"request";import{writeFile}from"fs";get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin",(requestErr,response)=>{if(requestErr){console.error(requestErr);}else{writeFile("article.html",response.body,writeErr=>{if(writeErr){console.error(writeErr);}else{console.log("File written");}});}});

Good:

import{get}from"request";import{writeFile}from"fs";get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin").then(response=>{returnwriteFile("article.html",response);}).then(()=>{console.log("File written");}).catch(err=>{console.error(err);});

⬆ back to top

Async/Await are even cleaner than Promises

Promises are a very clean alternative to callbacks, but ES2017/ES8 brings async and awaitwhich offer an even cleaner solution. All you need is a function that is prefixedin anasync keyword, and then you can write your logic imperatively withoutathen chain of functions. Use this if you can take advantage of ES2017/ES8 featurestoday!

Bad:

import{get}from"request-promise";import{writeFile}from"fs-promise";get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin").then(response=>{returnwriteFile("article.html",response);}).then(()=>{console.log("File written");}).catch(err=>{console.error(err);});

Good:

import{get}from"request-promise";import{writeFile}from"fs-promise";asyncfunctiongetCleanCodeArticle(){try{constresponse=awaitget("https://en.wikipedia.org/wiki/Robert_Cecil_Martin");awaitwriteFile("article.html",response);console.log("File written");}catch(err){console.error(err);}}

⬆ back to top

Error Handling

Thrown errors are a good thing! They mean the runtime has successfullyidentified when something in your program has gone wrong and it's lettingyou know by stopping function execution on the current stack, killing theprocess (in Node), and notifying you in the console with a stack trace.

Don't ignore caught errors

Doing nothing with a caught error doesn't give you the ability to ever fixor 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 printedto the console. If you wrap any bit of code in atry/catch it means youthink 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);}

Good:

try{functionThatMightThrow();}catch(error){// One option (more noisy than console.log):console.error(error);// Another option:notifyUserOfError(error);// Another option:reportErrorToService(error);// OR do all three!}

Don't ignore rejected promises

For the same reason you shouldn't ignore caught errorsfromtry/catch.

Bad:

getdata().then(data=>{functionThatMightThrow(data);}).catch(error=>{console.log(error);});

Good:

getdata().then(data=>{functionThatMightThrow(data);}).catch(error=>{// One option (more noisy than console.log):console.error(error);// Another option:notifyUserOfError(error);// Another option:reportErrorToService(error);// OR do all three!});

⬆ back to top

Formatting

Formatting is subjective. Like many rules herein, there is no hard and fastrule that you must follow. The main point is DO NOT ARGUE over formatting.There aretons of tools to automate this.Use one! It's a waste of time and money for engineers to argue over formatting.

For things that don't fall under the purview of automatic formatting(indentation, tabs vs. spaces, double vs. single quotes, etc.) look herefor some guidance.

Use consistent capitalization

JavaScript is untyped, so capitalization tells you a lot about your variables,functions, etc. These rules are subjective, so your team can choose whateverthey want. The point is, no matter what you all choose, just be 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(){}classanimal{}classAlpaca{}

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(){}classAnimal{}classAlpaca{}

⬆ back to top

Function callers and callees should be close

If a function calls another, keep those functions vertically close in the sourcefile. Ideally, keep the caller right above the callee. We tend to read code fromtop-to-bottom, like a newspaper. Because of this, make your code read that way.

Bad:

classPerformanceReview{constructor(employee){this.employee=employee;}lookupPeers(){returndb.lookup(this.employee,"peers");}lookupManager(){returndb.lookup(this.employee,"manager");}getPeerReviews(){constpeers=this.lookupPeers();// ...}perfReview(){this.getPeerReviews();this.getManagerReview();this.getSelfReview();}getManagerReview(){constmanager=this.lookupManager();}getSelfReview(){// ...}}constreview=newPerformanceReview(employee);review.perfReview();

Good:

classPerformanceReview{constructor(employee){this.employee=employee;}perfReview(){this.getPeerReviews();this.getManagerReview();this.getSelfReview();}getPeerReviews(){constpeers=this.lookupPeers();// ...}lookupPeers(){returndb.lookup(this.employee,"peers");}getManagerReview(){constmanager=this.lookupManager();}lookupManager(){returndb.lookup(this.employee,"manager");}getSelfReview(){// ...}}constreview=newPerformanceReview(employee);review.perfReview();

⬆ back to top

Comments

Only comment things that have business logic complexity.

Comments are an apology, not a requirement. Good codemostly documents itself.

Bad:

functionhashIt(data){// The hashlethash=0;// Length of stringconstlength=data.length;// Loop through every character in datafor(leti=0;i<length;i++){// Get character code.constchar=data.charCodeAt(i);// Make the hashhash=(hash<<5)-hash+char;// Convert to 32-bit integerhash&=hash;}}

Good:

functionhashIt(data){lethash=0;constlength=data.length;for(leti=0;i<length;i++){constchar=data.charCodeAt(i);hash=(hash<<5)-hash+char;// Convert to 32-bit integerhash&=hash;}}

⬆ back to top

Don't leave commented out code in your codebase

Version control exists for a reason. Leave old code in your history.

Bad:

doStuff();// doOtherStuff();// doSomeMoreStuff();// doSoMuchStuff();

Good:

doStuff();

⬆ back to top

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: Removed type-checking (LI) * 2015-03-14: Added combine with type-checking (JR) */functioncombine(a,b){returna+b;}

Good:

functioncombine(a,b){returna+b;}

⬆ back to top

Avoid positional markers

They usually just add noise. Let the functions and variable names along with theproper indentation and formatting give the visual structure to your code.

Bad:

////////////////////////////////////////////////////////////////////////////////// Scope Model Instantiation////////////////////////////////////////////////////////////////////////////////$scope.model={menu:"foo",nav:"bar"};////////////////////////////////////////////////////////////////////////////////// Action setup////////////////////////////////////////////////////////////////////////////////constactions=function(){// ...};

Good:

$scope.model={menu:"foo",nav:"bar"};constactions=function(){// ...};

⬆ back to top

Translation

This is also available in other languages:

⬆ back to top

About

🛁 Clean Code concepts adapted for JavaScript

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript100.0%

[8]ページ先頭

©2009-2025 Movatter.jp