clean-code-javascript
clean code JavaScript(æ¥æ¬èªèš³)
Table of Contents
- Introduction
- Variables
- Functions
- Objects and Data Structures
- Classes
- SOLID
- Testing
- Concurrency
- Error Handling
- Formatting
- Comments
- Translation
Introduction
ã¯ããã«

Software engineering principles, from Robert C. Martinâs book Clean Code, adapted for JavaScript. This is not a style guide. Itâs a guide to producing readable, reusable, and refactorable JavaScript software.
Robert C. Martin ã®èæž Clean Code ã«èšèŒããããœãããŠã§ã¢ãšã³ãžãã¢ãªã³ã°ã®ååããJavaScript åãã«é©çšãããã®ã§ãã ããã¯ã¹ã¿ã€ã«ã¬ã€ãã§ã¯ãããŸãããå¯èªæ§ãé«ããåå©çšã§ãããªãã¡ã¯ã¿ãªã³ã°ãããã JavaScript ãæžãããã®ã¬ã€ãã§ãã
Not every principle herein has to be strictly followed, and even fewer will be universally agreed upon. These are guidelinesâcodified over many years of collective experience.
ããã«æžãããååãã¹ãŠã«å³å¯ã«åŸãå¿ èŠã¯ãããŸãããããã¹ãŠãæ®éçã«åæãããŠããããã§ããããŸããã ããã¯ã¬ã€ãã©ã€ã³ã§ãããé·å¹Žã®çµéšãããŸãšããããç¥èŠã§ãã
Software engineering is only about 50 years oldâwe are still learning. Perhaps in the future weâll have harder rules, but for now let these guidelines serve as a touchstone for your teamâs JavaScript quality.
ãœãããŠã§ã¢ãšã³ãžãã¢ãªã³ã°ã¯ãŸã 50 幎ã»ã©ã®æŽå²ãããªããç§ãã¡ã¯åžžã«åŠã³ç¶ããŠããŸãã ãã€ã峿 Œãªã«ãŒã«ã確ç«ããããããããŸããããä»ã®ãšãã㯠ããªããšããªãã®ããŒã ã JavaScript ã®å質ã倿ããããã®æé ãšããŠåœ¹ç«ãŠãŠãã ããã
One more thing: knowing these wonât instantly make you a better developer. Every piece of code starts as a first draftâlike wet clay that will be shaped later. Donât beat yourself up for imperfect drafts. Beat up the code instead!
ãã 1 ã€å€§åãªããšããããŸãã ãããã®ç¥èãèŠãããããšãã£ãŠãããã«åªããéçºè ã«ãªããããã§ã¯ãããŸããã ãã¹ãŠã®ã³ãŒãã¯æåã¯ãæªå®æã®ãããå°ãã§ãã æ¹åãå¿ èŠãªåçš¿ã«å¯ŸããŠèªåã責ããªãã§ãã ããã責ããã¹ãã¯ã³ãŒããã®ãã®ã§ãïŒ
Variables
Use meaningful and pronounceable variable names
æå³ããããçºé³ãããã倿°åã䜿ãããš
Bad:
const yyyymmdstr = moment().format("YYYY/MM/DD");
Good:
const currentDate = moment().format("YYYY/MM/DD");
Use the same vocabulary for the same type of variable
åãçš®é¡ã®å€æ°ã«ã¯åãèªåœã䜿ãããš
Bad:
getUserInfo();
getClientData();
getCustomerRecord();
Good:
getUser();
Use searchable names
æ€çŽ¢å¯èœãªååã䜿ãããš
We will read more code than we will ever write. Itâs important that the code we do write is readable and searchable. By not naming variables that end up being meaningful for understanding our program, we hurt our readers. Make your names searchable. Tools like buddy.js and ESLint can help identify unnamed constants.
ç§ãã¡ã¯ã³ãŒããæžãããããèªãã»ãããã£ãšå€ãã§ãã ãã®ãããæžãã³ãŒããèªã¿ããããæ€çŽ¢ããããããšã¯éåžžã«éèŠã§ãã ããã°ã©ã ã®çè§£ã«ãšã£ãŠæå³ãæã€å€æ°ã«ååãä»ããªããšãèªè ãèŠãããããšã«ãªããŸãã
ååã¯æ€çŽ¢å¯èœã«ããŠãã ããã buddy.js ã ESLint ãšãã£ãããŒã«ã¯ãååãä»ããŠããªã宿°ãæ€åºããã®ã«åœ¹ç«ã¡ãŸãã
Bad:
// What the heck is 86400000 for?
// äžäœããªãã®ããã®86400000ãªãã ãïŒ
setTimeout(blastOff, 86400000);
Good:
// Declare them as capitalized named constants.
// ãããã倧æåã®ååä»ã宿°ãšããŠå®£èšããŠãã ããã
const MILLISECONDS_PER_DAY = 60 * 60 * 24 * 1000;
setTimeout(blastOff, MILLISECONDS_PER_DAY);
Use explanatory variables
説æçãªå€æ°ãå©çšããããš
Bad:
const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
saveCityZipCode(
address.match(cityZipCodeRegex)[1],
address.match(cityZipCodeRegex)[2]
);
Good:
const address = "One Infinite Loop, Cupertino 95014";
const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/;
const [_, city, zipCode] = address.match(cityZipCodeRegex) || [];
saveCityZipCode(city, zipCode);
Avoid Mental Mapping
ã¡ã³ã¿ã«ãããïŒæé»çãªèªã¿æ¿ãïŒãé¿ãã
Explicit is better than implicit.
æç€ºã¯æé»ããåªããŠããã
Bad:
const locations = ["Austin", "New York", "San Francisco"];
locations.forEach((l) => {
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
// Wait, what is `l` for again?
// ã¡ãã£ãšåŸ
ã£ãŠãããäžåºŠ`l`ã£ãŠãªãã ã£ãïŒ
dispatch(l);
});
Good:
const locations = ["Austin", "New York", "San Francisco"];
locations.forEach((location) => {
doStuff();
doSomeOtherStuff();
// ...
// ...
// ...
dispatch(location);
});
Donât add unneeded context
äžå¿ èŠãªã³ã³ããã¹ãã远å ããªã
If your class/object name tells you something, donât repeat that in your variable name.
ããã¯ã©ã¹åããªããžã§ã¯ãåããã§ã«äœãã衚ããŠããã®ã§ããã°ã倿°åã®äžã§åãæ å ±ãç¹°ãè¿ããŠã¯ãããŸããã
Bad:
const Car = {
carMake: "Honda",
carModel: "Accord",
carColor: "Blue",
};
function paintCar(car, color) {
car.carColor = color;
}
Good:
const Car = {
make: "Honda",
model: "Accord",
color: "Blue",
};
function paintCar(car, color) {
car.color = color;
}
Use default parameters instead of short circuiting or conditionals
ç絡è©äŸ¡ãæ¡ä»¶åå²ã®ä»£ããã«ããã©ã«ãåŒæ°ã䜿ã
Default parameters are often cleaner than short circuiting. Be aware that if you use them, your function will only provide default values for undefined arguments. Other âfalsyâ values such as '', "", false, null, 0, and NaN, will not be replaced by a default value.
ããã©ã«ãåŒæ°ã®ã»ãããã³ãŒããããæç¢ºã§èªã¿ããããªããŸãã
ãã ãæ³šæç¹ãšããŠãããã©ã«ãåŒæ°ãé©çšãããã®ã¯ undefined ã®å Žåã ã ã§ãã
''ã""ãfalseãnullã0ãNaN ãšãã£ã âfalsyâ ãªå€ã¯ãããã©ã«ãå€ã§ã¯çœ®ãæããããŸããã
Bad:
function createMicrobrewery(name) {
const breweryName = name || "Hipster Brew Co.";
// ...
}
Good:
function createMicrobrewery(name = "Hipster Brew Co.") {
// ...
}
Functions
Function arguments (2 or fewer ideally)
颿°ã®åŒæ°ïŒçæ³ã¯ 2 ã€ä»¥äžïŒ
Limiting the amount of function parameters is incredibly important because it makes testing your function easier. Having more than three leads to a combinatorial explosion where you have to test tons of different cases with each separate argument.
颿°ã®åŒæ°ã®æ°ãå¶éããããšã¯éåžžã«éèŠã§ããåŒæ°ãå°ãªããã°ã颿°ããã¹ããããããªãããã§ãã åŒæ°ã 3 ã€ãè¶ ãããšãçµã¿åãããççºããããããã®åŒæ°ã«ã€ããŠèšå€§ãªã±ãŒã¹ããã¹ãããªããã°ãªããªããªããŸãã
One or two arguments is the ideal case, and three should be avoided if possible. Anything more than that should be consolidated. Usually, if you have more than two arguments then your function is trying to do too much. In cases where itâs not, most of the time a higher-level object will suffice as an argument.
çæ³çãªã®ã¯ 1ã2 åã®åŒæ° ã§ãããå¯èœã§ããã° 3 åãé¿ããã¹ã ã§ãã ãã以äžã®åŒæ°ãå¿ èŠã«ãªãå Žåã¯ããŸãšãããããæ€èšããŠãã ããã äžè¬çã«ã¯ãåŒæ°ã 2 åãè¶ ãã颿°ã¯ãããããããŠããããšãå€ãã§ãã ããã§ãªãå Žåã§ãããããŠãã¯ããé«ã¬ãã«ã®ãªããžã§ã¯ããåŒæ°ãšããŠæž¡ãããšã§ååã§ãã
Since JavaScript allows you to make objects on the fly, without a lot of class boilerplate, you can use an object if you are finding yourself needing a lot of arguments.
JavaScript ã§ã¯ã¯ã©ã¹ã®ãããªé¢åãªæºåãªãã«ãã®å Žã§ãªããžã§ã¯ããäœãããããåŒæ°ãå€ããªããããªãšãã¯ãªããžã§ã¯ãã䜿ãã®ãæå¹ã§ãã
To make it obvious what properties the function expects, you can use the ES2015/ES6 destructuring syntax. This has a few advantages:
- When someone looks at the function signature, itâs immediately clear what properties are being used.
- It can be used to simulate named parameters.
- Destructuring also clones the specified primitive values of the argument object passed into the function. This can help prevent side effects. Note: objects and arrays that are destructured from the argument object are NOT cloned.
- Linters can warn you about unused properties, which would be impossible without destructuring.
颿°ãã©ã®ããããã£ãæåŸ ããŠãããæç¢ºã«ããããã«ãES2015/ES6 ã®åå²ä»£å ¥ïŒdestructuringïŒæ§æ ã䜿ããšããã§ãããã ããã«ã¯æ¬¡ã®ã¡ãªããããããŸãïŒ
- 颿°ã·ã°ããã£ãèŠãã ãã§ãã©ã®ããããã£ã䜿ãããŠãããããã«åããã
- ååä»ããã©ã¡ãŒã¿ã®ããã«äœ¿ããã
- åå²ä»£å ¥ããã ããªããã£ãå€ ã¯è€è£œããããããå¯äœçšãé²ãå©ãã«ãªããâ»ãã ããåå²ä»£å ¥ããã ãªããžã§ã¯ããé åã¯è€è£œãããªã ç¹ã«æ³šæã
- Linter ã«ãããæªäœ¿çšããããã£ãã®èŠåãå¹ãããã«ãªããåå²ä»£å ¥ããªããã°ããã¯äžå¯èœã
Bad:
function createMenu(title, body, buttonText, cancellable) {
// ...
}
createMenu("Foo", "Bar", "Baz", true);
Good:
function createMenu({ title, body, buttonText, cancellable }) {
// ...
}
createMenu({
title: "Foo",
body: "Bar",
buttonText: "Baz",
cancellable: true,
});
Functions should do one thing
颿°ã¯ 1 ã€ã®ããšã ããè¡ãã¹ã
This is by far the most important rule in software engineering. When functions do more than one thing, they are harder to compose, test, and reason about. When you can isolate a function to just one action, it can be refactored easily and your code will read much cleaner. If you take nothing else away from this guide other than this, youâll be ahead of many developers.
ããã¯ãœãããŠã§ã¢ãšã³ãžãã¢ãªã³ã°ã«ããããã£ãšãéèŠãªã«ãŒã«ã§ãã 颿°ãè€æ°ã®ããšãè¡ããšãæ§æãã«ãããªãããã¹ãããã«ãããªããçè§£ããã¥ãããªããŸãã
颿°ã 1 ã€ã®åäœã«åãåããããšãã§ããã°ããªãã¡ã¯ã¿ãªã³ã°ãæ Œæ®µã«å®¹æã«ãªããã³ãŒãã®èªã¿ãããã倧ããåäžããŸãã
ãã®ã¬ã€ãããä»ã®ããšãäœãèŠããªããŠãããã®ã«ãŒã«ã ããå®ããã°ãå€ãã®éçºè ããäžæ©å ã«é²ããŸãã
Bad:
function emailClients(clients) {
clients.forEach((client) => {
const clientRecord = database.lookup(client);
if (clientRecord.isActive()) {
email(client);
}
});
}
Good:
function emailActiveClients(clients) {
clients.filter(isActiveClient).forEach(email);
}
function isActiveClient(client) {
const clientRecord = database.lookup(client);
return clientRecord.isActive();
}
Function names should say what they do
颿°åã¯ãã®é¢æ°ãäœãããã®ããæç¢ºã«è¡šãã¹ã
Bad:
function addToDate(date, month) {
// ...
}
const date = new Date();
// It's hard to tell from the function name what is added
// 颿°åããã¯äœã远å ãããŠããã®ãåããã«ããã
addToDate(date, 1);
Good:
function addMonthToDate(month, date) {
// ...
}
const date = new Date();
addMonthToDate(1, date);
Functions should only be one level of abstraction
颿°ã¯ 1 ã€ã®æœè±¡ã¬ãã«ã ããæ±ãã¹ã
When you have more than one level of abstraction your function is usually doing too much. Splitting up functions leads to reusability and easier testing.
è€æ°ã®æœè±¡ã¬ãã«ã 1 ã€ã®é¢æ°ã«æ··åšãããŠããŸããšããã®é¢æ°ã¯ãããŠãããããããŠãããç¶æ ã«ãªããŸãã 颿°ãé©åã«åå²ããã°ãåå©çšãããããªãããã¹ãããããããªããŸãã
Bad:
function parseBetterJSAlternative(code) {
const REGEXES = [
// ...
];
const statements = code.split(" ");
const tokens = [];
REGEXES.forEach((REGEX) => {
statements.forEach((statement) => {
// ...
});
});
const ast = [];
tokens.forEach((token) => {
// lex...
});
ast.forEach((node) => {
// parse...
});
}
Good:
function parseBetterJSAlternative(code) {
const tokens = tokenize(code);
const syntaxTree = parse(tokens);
syntaxTree.forEach((node) => {
// parse...
});
}
function tokenize(code) {
const REGEXES = [
// ...
];
const statements = code.split(" ");
const tokens = [];
REGEXES.forEach((REGEX) => {
statements.forEach((statement) => {
tokens.push(/* ... */);
});
});
return tokens;
}
function parse(tokens) {
const syntaxTree = [];
tokens.forEach((token) => {
syntaxTree.push(/* ... */);
});
return syntaxTree;
}
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!
ããšãã°ãããªããã¬ã¹ãã©ã³ãçµå¶ããŠããŠããããã»çããã»ã«ãã«ãã»ã¹ãã€ã¹ãªã©ã®åšåº«ã管çããŠãããšããŸãã ããåšåº«ãèšé²ãããªã¹ããè€æ°ããã°ããããã䜿ã£ãæçãåºããã³ã« ãã¹ãŠã®ãªã¹ããæŽæ°ããªããã°ãªããªããªããŸãã ããããªã¹ãã 1 ã€ã ããªããæŽæ°ãã¹ãå Žæã 1 ã€ã ãã§æžã¿ãŸãã
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.
éè€ã³ãŒããçãŸããå žåçãªçç±ã¯ãããšãŠããã䌌ãŠããããå°ãã ãéããåŠçãè€æ°ååšããããã«ã䌌ããããªé¢æ°ãè€æ°ã€ãã£ãŠããŸã ããã§ãã éè€ã³ãŒãããªãããšããããšã¯ããããããå°ãéãã ãã®è€æ°ã®åŠçãã 1 ã€ã®é¢æ°ã»ã¢ãžã¥ãŒã«ã»ã¯ã©ã¹ã«æœè±¡åãã ãšããããšã§ãã
Getting the abstraction right is critical, thatâs why you should follow the SOLID principles laid out in the Classes section. 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.
ãã ãããã®ãæœè±¡åããæ£ããè¡ãããšã¯éåžžã«éèŠã§ãã ãããé£ããçç±ã§ããããClasses ã»ã¯ã·ã§ã³ã§èª¬æãã SOLID åå ã«åŸãã¹ãçç±ã§ããããŸãã æªãæœè±¡åã¯éè€ã³ãŒããããæªåœ±é¿ãåãŒãã®ã§æ³šæããŠãã ããã
ãããããã è¯ãæœè±¡å ãã€ããããªããè¿·ãããããã¹ãã§ãã ãåãããšãç¹°ãè¿ããªãïŒDonât repeat yourselfïŒãã培åºããªããšãããªã㯠1 ç®æã®å€æŽãè¡ãããã« è€æ°ç®æãæŽæ°ãç¶ããæªæ¥ ã«çŽé¢ããããšã«ãªããŸãã
Bad:
function showDeveloperList(developers) {
developers.forEach((developer) => {
const expectedSalary = developer.calculateExpectedSalary();
const experience = developer.getExperience();
const githubLink = developer.getGithubLink();
const data = {
expectedSalary,
experience,
githubLink,
};
render(data);
});
}
function showManagerList(managers) {
managers.forEach((manager) => {
const expectedSalary = manager.calculateExpectedSalary();
const experience = manager.getExperience();
const portfolio = manager.getMBAProjects();
const data = {
expectedSalary,
experience,
portfolio,
};
render(data);
});
}
Good:
function showEmployeeList(employees) {
employees.forEach((employee) => {
const expectedSalary = employee.calculateExpectedSalary();
const experience = employee.getExperience();
const data = {
expectedSalary,
experience,
};
switch (employee.type) {
case "manager":
data.portfolio = employee.getMBAProjects();
break;
case "developer":
data.githubLink = employee.getGithubLink();
break;
}
render(data);
});
}
Set default objects with Object.assign
Object.assign ã䜿ã£ãŠããã©ã«ãã®ãªããžã§ã¯ããèšå®ãã
Bad:
const menuConfig = {
title: null,
body: "Bar",
buttonText: null,
cancellable: true,
};
function createMenu(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:
const menuConfig = {
title: "Order",
// User did not include 'body' key
// ãŠãŒã¶ãŒã¯ body ããŒãå«ããŠããªã
buttonText: "Send",
cancellable: true,
};
function createMenu(config) {
let finalConfig = Object.assign(
{
title: "Foo",
body: "Bar",
buttonText: "Baz",
cancellable: true,
},
config
);
return finalConfig;
// config now equals: {title: "Order", body: "Bar", buttonText: "Send", cancellable: true}
// config ã¯æ¬¡ã®ããã«ãªããŸãïŒ{ title: "Order", body: "Bar", buttonText: "Send", cancellable: true }
// ...
}
createMenu(menuConfig);
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.
ãã©ã°ãå¿ èŠã«ãªããšããããšã¯ããã®é¢æ°ãè€æ°ã®ããšãããŠãããšãããµã€ã³ã§ãã 颿°ã¯ 1 ã€ã®ããšã ããè¡ãã¹ãã§ãã
ããçåœå€ã«ãã£ãŠåŠçãåå²ããã®ã§ããã°ã颿°ãåå²ããŠããããå¥ã®åŠçãšããŠå®çŸ©ããŠãã ããã
Bad:
function createFile(name, temp) {
if (temp) {
fs.create(`./temp/${name}`);
} else {
fs.create(name);
}
}
Good:
function createFile(name) {
fs.create(name);
}
function createTempFile(name) {
createFile(`./temp/${name}`);
}
Avoid Side Effects (part 1)
å¯äœçšãé¿ããïŒ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.
éèŠãªã®ã¯ãå¯äœçšã®çºçå Žæã 1 ã€ã«éäžãããããš ã§ãã ç¹å®ã®ãã¡ã€ã«ã«æžã蟌ãåŠçããè€æ°ã®é¢æ°ãã¯ã©ã¹ã«æ£åšãããŠã¯ãããŸããã ãã®åœ¹å²ãæ ã åäžã®ãµãŒãã¹ã 1 ã€ã ãçšæããŠãã ããã
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.
// If we had another function that used this name, now it'd be an array and it could break it.
// ã°ããŒãã«å€æ°ããã®ããšã«ç¶ã颿°ããåç
§ãããŠããã
// ããåãååãå¥ã®é¢æ°ã§ã䜿ã£ãŠããå Žåãä»ããã®å€ã¯é
åã«ãªã£ãŠããŸããåäœãå£ããå¯èœæ§ãããã
let name = "Ryan McDermott";
function splitIntoFirstAndLastName() {
name = name.split(" ");
}
splitIntoFirstAndLastName();
console.log(name); // ['Ryan', 'McDermott'];
Good:
function splitIntoFirstAndLastName(name) {
return name.split(" ");
}
const name = "Ryan McDermott";
const newName = splitIntoFirstAndLastName(name);
console.log(name); // 'Ryan McDermott';
console.log(newName); // ['Ryan', 'McDermott'];
Avoid Side Effects (part 2)
å¯äœçšãé¿ããïŒpart 2ïŒ
In JavaScript, some values are unchangeable (immutable) and some are changeable (mutable). Objects and arrays are two kinds of mutable values so itâs important to handle them carefully when theyâre passed as parameters to a function. A JavaScript function can change an objectâs properties or alter the contents of an array which could easily cause bugs elsewhere.
JavaScript ã§ã¯ã倿Žã§ããªãå€ïŒimmutableïŒãšå€æŽã§ããå€ïŒmutableïŒããããŸãã ãªããžã§ã¯ããšé å㯠mutable ãªå€ ã«åé¡ãããããã颿°ã«æž¡ãéã«ã¯ç¹ã«æ³šæãå¿ èŠã§ãã JavaScript ã®é¢æ°ã¯ããªããžã§ã¯ãã®ããããã£ã倿Žããããé åã®å 容ã倿Žãããããããšãã§ãããã®çµæãæãã¬ç®æã§ãã°ãåŒãèµ·ããå¯èœæ§ããããŸãã
Suppose thereâs a function that accepts an array parameter representing a shopping cart. If the function makes a change in that shopping cart array - by adding an item to purchase, for example - then any other function that uses that same cart array will be affected by this addition. That may be great, however it could also be bad. Letâs imagine a bad situation:
ããšãã°ãã·ã§ããã³ã°ã«ãŒãã衚ãé åãåãåã颿°ããããšããŸãã ãããã®é¢æ°ãã«ãŒãã®é åã倿ŽïŒè³Œå ¥äºå®ã®ååã远å ããããªã©ïŒãããšãåãé åã䜿ã£ãŠããå¥ã®é¢æ°ã«ããã®å€æŽã圱é¿ããŸãã ãããæãŸããå ŽåããããŸãããæªåœ±é¿ã«ãªãã±ãŒã¹ããããŸãã
æªãã±ãŒã¹ãæ³åããŠã¿ãŸãããã
The user clicks the âPurchaseâ button which calls a purchase function that spawns a network request and sends the cart 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 an âAdd to Cartâ button on an item they donât actually want before the network request begins? If that happens and the network request begins, then that purchase function will send the accidentally added item because the cart array was modified.
ãŠãŒã¶ãŒããè³Œå ¥ããã¿ã³ãæŒããšãpurchase 颿°ãåŒã°ãããããã¯ãŒã¯ãªã¯ãšã¹ããçºè¡ããŠã«ãŒãã®é åããµãŒããŒã«éä¿¡ããŸãã ããããããã¯ãŒã¯ãäžå®å®ã§ããã®ãªã¯ãšã¹ããç¹°ãè¿ãå詊è¡ããããšããŸãã
ãã®éã«ããŠãŒã¶ãŒã誀ã£ãŠãã«ãŒãã«è¿œå ããã¿ã³ãæŒããæ¬åœã¯è³Œå
¥ããããªãååã远å ããŠããŸããããããŸããã
ãããã®ã¿ã€ãã³ã°ã§ãªã¯ãšã¹ããå詊è¡ããããšãpurchase 颿°ã¯èª€ã£ãŠè¿œå ãããååãŸã§éä¿¡ããŠããŸããŸãã
ããã¯ãã«ãŒãé
åã倿ŽãããŠããŸã£ãããã«èµ·ãããŸãã
A great solution would be for the addItemToCart function to always clone the cart, edit it, and return the clone. This would ensure that functions that are still using the old shopping cart wouldnât be affected by the changes.
ãã®åé¡ã®åªãã解決çã¯ãaddItemToCart 颿°ã åžžã«ã«ãŒãã cloneïŒè€è£œïŒããè€è£œãç·šéããŠè¿ãããšã§ãã
Two caveats to mention to this approach:
- There might be cases where you actually want to modify the input object, but when you adopt this programming practice you will find that those cases are pretty rare. Most things can be refactored to have no side effects!
- 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.
ãã®ã¢ãããŒãã«ã¯ 2 ã€ã®æ³šæç¹ããããŸãïŒ
- å ¥åãªããžã§ã¯ããå®éã«å€æŽãããã±ãŒã¹ããŸãã«ãããããã®ææ³ãæ¡çšãããšããã®ãããªã±ãŒã¹ã¯éåžžã«å°ãªãããšã«æ°ã¥ãã§ããããå€ãã®åŠçã¯ãå¯äœçšãªãã«ãªãã¡ã¯ã¿ãªã³ã°ã§ããŸãã
- 倧ããªãªããžã§ã¯ããè€è£œããã®ã¯ãããã©ãŒãã³ã¹é¢ã§é«ã³ã¹ãã§ãããã ãçŸå®çã«ã¯ããŸãåé¡ã«ãªããŸããããªããªããæåã§è€è£œããããé«éã§ã¡ã¢ãªå¹çãè¯ãåªããã©ã€ãã©ãªãååšããããã§ãã
Bad:
const addItemToCart = (cart, item) => {
cart.push({ item, date: Date.now() });
};
Good:
const addItemToCart = (cart, item) => {
return [...cart, { item, date: Date.now() }];
};
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 a diff method that could show the difference between two arrays? You could write your new function to the Array.prototype, but it could clash with another library that tried to do the same thing. What if that other library was just using diff to find the difference between the first and last elements of an array? This is why it would be much better to just use ES2015/ES6 classes and simply extend the Array global.
ã°ããŒãã«ãæ±æããããšã¯ãJavaScript ã«ãããæªããã©ã¯ãã£ã¹ã§ãã ãªããªããä»ã®ã©ã€ãã©ãªãšè¡çªããå¯èœæ§ããããããªãã® API ã®å©çšè ã¯æ¬çªç°å¢ã§äŸå€ãçºçãããŸã§ãã®åé¡ã«æ°ã¥ããªãããã§ãã
äŸãèããŠã¿ãŸãããã
JavaScript ã®ãã€ãã£ã㪠Array ã« diff ã¡ãœããã远å ããŠã2 ã€ã®é
åã®å·®åãååŸã§ããããã«ããããšããŸãã
Array.prototype ã«æ°ããã¡ãœãããæžã蟌ãããšã¯ã§ããŸãããåãååã® diff ã远å ããããšããŠããä»ã®ã©ã€ãã©ãªãšè¡çªããå¯èœæ§ ããããŸãã
ãããã®å¥ã®ã©ã€ãã©ãªã diff ããé
åã®æåãšæåŸã®èŠçŽ ã®å·®åãæ±ãã颿°ããšããŠå®è£
ããŠãããã©ããªãã§ããããïŒ
äºãã®å®è£
ãäžæžããããã©ã¡ãããæ£åžžã«åäœããªããªãå¯èœæ§ããããŸãã
ãã®ãããªçç±ãããArray.prototype ãæ±æããã®ã§ã¯ãªããES2015/ES6 ã®ã¯ã©ã¹æ§æã䜿ã£ãŠ Array ãæ¡åŒµããã»ãããã£ãšå®å
šã§ãã
Bad:
Array.prototype.diff = function diff(comparisonArray) {
const hash = new Set(comparisonArray);
return this.filter((elem) => !hash.has(elem));
};
Good:
class SuperArray extends Array {
diff(comparisonArray) {
const hash = new Set(comparisonArray);
return this.filter((elem) => !hash.has(elem));
}
}
Favor functional programming over imperative programming
æç¶ãåããã°ã©ãã³ã°ããã颿°åããã°ã©ãã³ã°ãåªå ãã
JavaScript isnât a functional language in the way that Haskell is, but it has a functional flavor to it. Functional languages can be cleaner and easier to test. Favor this style of programming when you can.
JavaScript 㯠Haskell ã®ãããªçŽç²ãªé¢æ°åèšèªã§ã¯ãããŸãããã颿°åã®ç¹åŸŽãããçšåºŠåããŠããŸãã 颿°åèšèªã¯ãããã¯ãªãŒã³ã§ãã¹ãããããåŸåããããŸãã
å¯èœãªå Žé¢ã§ã¯ããã®ã¹ã¿ã€ã«ã®ããã°ã©ãã³ã°ãåªå ããŸãããã
Bad:
const programmerOutput = [
{
name: "Uncle Bobby",
linesOfCode: 500,
},
{
name: "Suzie Q",
linesOfCode: 1500,
},
{
name: "Jimmy Gosling",
linesOfCode: 150,
},
{
name: "Gracie Hopper",
linesOfCode: 1000,
},
];
let totalOutput = 0;
for (let i = 0; i < programmerOutput.length; i++) {
totalOutput += programmerOutput[i].linesOfCode;
}
Good:
const programmerOutput = [
{
name: "Uncle Bobby",
linesOfCode: 500,
},
{
name: "Suzie Q",
linesOfCode: 1500,
},
{
name: "Jimmy Gosling",
linesOfCode: 150,
},
{
name: "Gracie Hopper",
linesOfCode: 1000,
},
];
const totalOutput = programmerOutput.reduce(
(totalLines, output) => totalLines + output.linesOfCode,
0
);
Encapsulate conditionals
æ¡ä»¶åŒãã«ãã»ã«åãã
Bad:
if (fsm.state === "fetching" && isEmpty(listNode)) {
// ...
}
Good:
function shouldShowSpinner(fsm, listNode) {
return fsm.state === "fetching" && isEmpty(listNode);
}
if (shouldShowSpinner(fsmInstance, listNodeInstance)) {
// ...
}
Avoid negative conditionals
åŠå®åœ¢ã®æ¡ä»¶åŒãé¿ãã
Bad:
function isDOMNodeNotPresent(node) {
// ...
}
if (!isDOMNodeNotPresent(node)) {
// ...
}
Good:
function isDOMNodePresent(node) {
// ...
}
if (isDOMNodePresent(node)) {
// ...
}
Avoid conditionals
æ¡ä»¶æãé¿ãã
This seems like an impossible task. Upon first hearing this, most people say, âhow am I supposed to do anything without an if 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 have if statements, you are telling your user that your function does more than one thing. Remember, just do one thing.
ããã¯äžèŠãäžå¯èœãªããšã®ããã«æãããããããŸããã
ãã®è©±ãèããšãå€ãã®äººã¯ãif æãªãã§ã©ããã£ãŠåŠçãæžãã®ïŒããšèšããŸãã
çãã¯ãå€ãã®å Žåãããªã¢ãŒãã£ãºã ïŒå€æ æ§ïŒã䜿ãããšã§åãããšãå®çŸã§ãã ãšããããšã§ãã æ¬¡ã«ããåºãŠãã質åã¯ãããã¯è¯ãããã ãã©ããªãããããããããå¿ èŠãããã®ïŒããšãããã®ã§ãã
ãã®çãã¯ã以ååºãŠããã¯ãªãŒã³ã³ãŒãã®åºæ¬ååãâ颿°ã¯ 1 ã€ã®ããšã ããè¡ãã¹ãâ ã«ãããŸãã
ã¯ã©ã¹ã颿°ã®äžã« if æããããšããããšã¯ããã®é¢æ°ã è€æ°ã®ããšãè¡ã£ãŠãã ããšãæå³ããŸãã
åžžã«æãåºããŠãã ããã 颿°ã¯ 1 ã€ã®ããšã ããè¡ãã¹ãã§ãã
Bad:
class Airplane {
// ...
getCruisingAltitude() {
switch (this.type) {
case "777":
return this.getMaxAltitude() - this.getPassengerCount();
case "Air Force One":
return this.getMaxAltitude();
case "Cessna":
return this.getMaxAltitude() - this.getFuelExpenditure();
}
}
}
Good:
class Airplane {
// ...
}
class Boeing777 extends Airplane {
// ...
getCruisingAltitude() {
return this.getMaxAltitude() - this.getPassengerCount();
}
}
class AirForceOne extends Airplane {
// ...
getCruisingAltitude() {
return this.getMaxAltitude();
}
}
class Cessna extends Airplane {
// ...
getCruisingAltitude() {
return this.getMaxAltitude() - this.getFuelExpenditure();
}
}
Avoid type-checking (part 1)
åãã§ãã¯ãé¿ããïŒ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 do type-checking in your functions. There are many ways to avoid having to do this. The first thing to consider is consistent APIs.
JavaScript ã«ã¯åããªãããã颿°ã¯ã©ããªåã®åŒæ°ã§ãåãåããŠããŸããŸãã ãã®èªç±ããè£ç®ã«åºãŠã颿°ã®äžã§åãã§ãã¯ãããããªãèªæãçãŸããããšããããŸãã
ãããããããé¿ããæ¹æ³ã¯ãããããããŸãã ãŸãæåã«èããã¹ãããšã¯ãAPI ã®äžè²«æ§ãä¿ã€ããš ã§ãã
Bad:
function travelToTexas(vehicle) {
if (vehicle instanceof Bicycle) {
vehicle.pedal(this.currentLocation, new Location("texas"));
} else if (vehicle instanceof Car) {
vehicle.drive(this.currentLocation, new Location("texas"));
}
}
Good:
function travelToTexas(vehicle) {
vehicle.move(this.currentLocation, new Location("texas"));
}
Avoid type-checking (part 2)
åãã§ãã¯ãé¿ããïŒ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 normal JavaScript, as it provides you with static typing on top of standard JavaScript syntax. The problem with manually type-checking normal JavaScript is that doing it well requires so much extra verbiage that the faux âtype-safetyâ you get doesnât make up for the lost readability. Keep your JavaScript clean, write good tests, and have good code reviews. Otherwise, do all of that but with TypeScript (which, like I said, is a great alternative!).
ãããæååãæ°å€ã®ãããªåºæ¬çãªããªããã£ãå€ãæ±ã£ãŠããŠãããªã¢ãŒãã£ãºã ã䜿ããªãã«ããããããåãã§ãã¯ãã©ãããŠãå¿ èŠã ãšæãã ã®ã§ããã°ãTypeScript ã䜿ãããšãæ€èšãã¹ãã§ãã
TypeScript ã¯æšæºã® JavaScript æ§æã®äžã« éçåä»ã ãæäŸããŠããããããéåžžã® JavaScript ã®åªããä»£æ¿ææ®µã§ãã
éåžžã® JavaScript ã§æåã®åãã§ãã¯ãããããšãããšããã¡ããšããã«ã¯å€§éã®äœåãªèšè¿°ãå¿ èŠã«ãªãããã£ããåŸãããããªãã¡ãã£ãŠåå®å šæ§ããããã倱ãããå¯èªæ§ã®ãã¡ãªããã®æ¹ã倧ãããªã£ãŠããŸããŸãã
JavaScript ãã¯ãªãŒã³ã«ä¿ã¡ãè¯ããã¹ããæžããè¯ãã³ãŒãã¬ãã¥ãŒãè¡ã£ãŠãã ããã
ããããã§äžååã ãšæãããªããããããã¹ãŠã TypeScript ã§è¡ãã°ãã ã®ã§ãã ïŒå ã»ã©èšã£ãããã«ãTypeScript ã¯æ¬åœã«åªããéžæè¢ã§ãïŒïŒ
Bad:
function combine(val1, val2) {
if (
(typeof val1 === "number" && typeof val2 === "number") ||
(typeof val1 === "string" && typeof val2 === "string")
) {
return val1 + val2;
}
throw new Error("Must be of type String or Number");
}
Good:
function combine(val1, val2) {
return val1 + val2;
}
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 good resources 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.
// å€ããã©ãŠã¶ã§ã¯ããã£ãã·ã¥ããŠããªã `list.length` ãã«ãŒãããšã«åç
§ãããš `list.length` ã®åèšç®ãè¡ãããããã³ã¹ããé«ãã£ãã
// ãããã¢ãã³ãã©ãŠã¶ã§ã¯ããã®éšåã¯æé©åãããŠããã
for (let i = 0, len = list.length; i < len; i++) {
// ...
}
Good:
for (let i = 0; i < list.length; i++) {
// ...
}
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:
function oldRequestModule(url) {
// ...
}
function newRequestModule(url) {
// ...
}
const req = newRequestModule;
inventoryTracker("apples", req, "www.inventory-awesome.io");
Good:
function newRequestModule(url) {
// ...
}
const req = newRequestModule;
inventoryTracker("apples", req, "www.inventory-awesome.io");
Objects and Data Structures
ãªããžã§ã¯ããšããŒã¿æ§é
Use getters and setters
getters ãš setters ã䜿ãããš
Using getters and setters to access data on objects could be better than simply looking for a property on an object. âWhy?â you might ask. Well, hereâs an unorganized list of reasons why:
- When you want to do more beyond getting an object property, you donât have to look up and change every accessor in your codebase.
- Makes adding validation simple when doing a
set. - Encapsulates the internal representation.
- Easy to add logging and error handling when getting and setting.
- You can lazy load your objectâs properties, letâs say getting it from a server.
ãªããžã§ã¯ãã®ããããã£ã«çŽæ¥ã¢ã¯ã»ã¹ããããããgetter ãš setter ã䜿ã£ãŠã¢ã¯ã»ã¹ããæ¹ãè¯ãå ŽåããããŸãã ããªãïŒããšæããããããŸããããçç±ã¯ããã€ããããŸãïŒ
- ãªããžã§ã¯ãã®ããããã£ååŸä»¥äžã®åŠçãããããªã£ãå Žåã§ãããã¹ãŠã®ã¢ã¯ã»ã¹ç®æãæ¢ããŠæžãæããå¿ èŠããªããªãã
- setter ã䜿ãã°ãå€ãèšå®ããéã«ç°¡åã«ããªããŒã·ã§ã³ã远å ã§ããã
- ãªããžã§ã¯ãã®å éšè¡šçŸïŒå éšç¶æ ïŒã ã«ãã»ã«å ã§ããã
- å€ååŸã»èšå®æã« ãã°èšé²ããšã©ãŒãã³ããªã³ã° ãç°¡åã«è¿œå ã§ããã
- ãªããžã§ã¯ãã®ããããã£ãé å»¶ããŒãã§ããïŒäŸïŒãµãŒããŒããååŸãããªã©ïŒã
Bad:
function makeBankAccount() {
// this one is private
// ããã¯ãã©ã€ããŒããªå€
let balance = 0;
// a "getter", made public via the returned object below
// getterãè¿ãå€ã®ãªããžã§ã¯ããéã㊠public ã«ãã
function getBalance() {
return balance;
}
// a "setter", made public via the returned object below
// setterãè¿ãå€ã®ãªããžã§ã¯ããéã㊠public ã«ãã
function setBalance(amount) {
// ... validate before updating the balance
// ... balance ãæŽæ°ããåã«ããªããŒã·ã§ã³ãè¡ã
balance = amount;
}
return {
// ...
getBalance,
setBalance,
};
}
const account = makeBankAccount();
account.setBalance(100);
Make objects have private members
ãªããžã§ã¯ãã¯ãã©ã€ããŒããªã¡ã³ããŒãæã€ããã«ãã
This can be accomplished through closures (for ES5 and below).
ããã¯ïŒES5 以åã§ã¯ïŒã¯ããŒãžã£ã䜿ãããšã§å®çŸã§ããŸãã
Bad:
const Employee = function (name) {
this.name = name;
};
Employee.prototype.getName = function getName() {
return this.name;
};
const employee = new Employee("John Doe");
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: undefined
Good:
function makeEmployee(name) {
return {
getName() {
return name;
},
};
}
const employee = makeEmployee("John Doe");
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
delete employee.name;
console.log(`Employee name: ${employee.getName()}`); // Employee name: John Doe
Classes
Prefer ES2015/ES6 classes over ES5 plain functions
ES5 ã®åãªã颿°ãããES2015/ES6 ã®ã¯ã©ã¹æ§æãåªå ãã
Itâs very difficult to get readable class inheritance, construction, and method definitions for classical ES5 classes. If you need inheritance (and be aware that you might not), then prefer ES2015/ES6 classes. However, prefer small functions over classes until you find yourself needing larger and more complex objects.
å€å žç㪠ES5 ã®ã¯ã©ã¹æ§æã§ã¯ãèªã¿ãããã¯ã©ã¹ç¶æ¿ã»ã³ã³ã¹ãã©ã¯ã¿ã»ã¡ãœããå®çŸ©ãå®çŸããã®ãéåžžã«é£ãã ã§ãã
ããç¶æ¿ãå¿ èŠã§ããã°ïŒå®éã«ã¯å¿ èŠã§ã¯ãªãããšãå€ãã§ããïŒãES2015/ES6 ã®ã¯ã©ã¹ãäœ¿ãæ¹ãåªå ããŠãã ããã
ãã ãã倧ããè€éãªãªããžã§ã¯ããå¿ èŠã ãšå€æã§ãããŸã§ã¯ãã¯ã©ã¹ãããå°ããªé¢æ°ãåªå ããããšãããããããŸãã
Bad:
javascript
const Animal = function(age) {
if (!(this instanceof Animal)) {
throw new Error("Instantiate Animal with `new`");
}
this.age = age;
};
Animal.prototype.move = function move() {};
const Mammal = function(age, furColor) {
if (!(this instanceof Mammal)) {
throw new Error("Instantiate Mammal with `new`");
}
Animal.call(this, age);
this.furColor = furColor;
};
Mammal.prototype = Object.create(Animal.prototype);
Mammal.prototype.constructor = Mammal;
Mammal.prototype.liveBirth = function liveBirth() {};
const Human = function(age, furColor, languageSpoken) {
if (!(this instanceof Human)) {
throw new Error("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 = function speak() {};
Good:
class Animal {
constructor(age) {
this.age = age;
}
move() {
/* ... */
}
}
class Mammal extends Animal {
constructor(age, furColor) {
super(age);
this.furColor = furColor;
}
liveBirth() {
/* ... */
}
}
class Human extends Mammal {
constructor(age, furColor, languageSpoken) {
super(age, furColor);
this.languageSpoken = languageSpoken;
}
speak() {
/* ... */
}
}
Use method chaining
ã¡ãœãããã§ãŒã³ãå©çšãã
This pattern is very useful in JavaScript and you see it in many libraries such as 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 code will be. In your class functions, simply return this at the end of every function, and you can chain further class methods onto it.
ãã®ãã¿ãŒã³ã¯ JavaScript ã§ãšãŠãæçšã§ãjQuery ã Lodash ãªã©å€ãã®ã©ã€ãã©ãªã§ãå©çšãããŠããŸãã
ã¡ãœãããã§ãŒã³ã䜿ãããšã§ãã³ãŒãããã衚çŸåè±ãã«ããåé·ããæžããããšãã§ããŸãã
ãã®ããç§ã¯ããèšããŸãïŒ ã¡ãœãããã§ãŒã³ã䜿ã£ãŠã¿ãŠãã ãããã©ãã ãã³ãŒããã¯ãªãŒã³ã«ãªãã宿ã§ããã¯ãã§ãã
ã¯ã©ã¹ã®ã¡ãœããã§ã¯ãåã¡ãœããã®æåŸã§ this ãè¿ãã ãã§ãåŸç¶ã®ã¯ã©ã¹ã¡ãœããããã§ãŒã³ãããããšãã§ããŸãã
Bad:
class Car {
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);
}
}
const car = new Car("Ford", "F-150", "red");
car.setColor("pink");
car.save();
Good:
class Car {
constructor(make, model, color) {
this.make = make;
this.model = model;
this.color = color;
}
setMake(make) {
this.make = make;
// NOTE: Returning this for chaining
return this;
}
setModel(model) {
this.model = model;
// NOTE: Returning this for chaining
return this;
}
setColor(color) {
this.color = color;
// NOTE: Returning this for chaining
return this;
}
save() {
console.log(this.make, this.model, this.color);
// NOTE: Returning this for chaining
return this;
}
}
const car = new Car("Ford", "F-150", "red").setColor("pink").save();
Prefer composition over inheritance
ç¶æ¿ããã³ã³ããžã·ã§ã³ïŒçµã¿åããïŒã奜ã
As stated famously in Design Patterns by the Gang of Four, you should prefer 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.
Gang of Four ã«ããæåãªæžç±Design Patterns ã§ãè¿°ã¹ãããŠããããã«ãå¯èœãªéãç¶æ¿ããã³ã³ããžã·ã§ã³ãåªå ãã¹ãã§ãã
ãã¡ãããç¶æ¿ã䜿ãã¹ãè¯ãçç±ãããã°ãã³ã³ããžã·ã§ã³ã䜿ãã¹ãè¯ãçç±ããããŸãã
ãã®æ Œèšã®ãã€ã³ãã¯ãããªãã®æèããç¶æ¿ã䜿ãã¹ãã ããšæ¬èœçã«åãããšããäžåºŠç«ã¡æ¢ãŸããã³ã³ããžã·ã§ã³ã®æ¹ãåé¡ãããé©åã«è¡šçŸã§ããªããïŒããšèããŠã¿ãã¹ããšããããšã§ãã
å®éãå€ãã®å Žåã§ã³ã³ããžã·ã§ã³ã®æ¹ãé©ããŠããŸãã
You might be wondering then, âwhen should I use inheritance?â It depends on your problem at hand, but this is a decent list of when inheritance makes more sense than composition:
- Your inheritance represents an âis-aâ relationship and not a âhas-aâ relationship (Human->Animal vs. User->UserDetails).
- You can reuse code from the base classes (Humans can move like all animals).
- You want to make global changes to derived classes by changing a base class. (Change the caloric expenditure of all animals when they move).
ã§ã¯ããã©ããªãšãã«ç¶æ¿ã䜿ãã¹ããªã®ãïŒã 以äžã¯ãã³ã³ããžã·ã§ã³ããç¶æ¿ã®ã»ããé©ããŠããå žåçãªã±ãŒã¹ã§ãïŒ
- ç¶æ¿é¢ä¿ã âhas-aïŒããæã£ãŠããïŒâ ã§ã¯ãªã âis-aïŒãã§ããïŒâ ã衚ããŠããå ŽåïŒHuman â Animal 㯠â人éã¯åç©ã§ããâãUser â UserDetails 㯠âãŠãŒã¶ãŒã¯ãŠãŒã¶ãŒæ å ±ã§ããâ ãšã¯èšããªãïŒ
- åºåºã¯ã©ã¹ã®ã³ãŒããåå©çšãããå ŽåïŒäŸïŒãã¹ãŠã®åç©ã¯ç§»åã§ãããã®ããžãã¯ã人éãåå©çšã§ããïŒ
- åºåºã¯ã©ã¹ã®å€æŽã掟çã¯ã©ã¹å šäœã«åæ ããããå ŽåïŒäŸïŒåç©ã®ç§»åæã®æ¶è²»ã«ããªãŒèšç®ãåºåºã¯ã©ã¹ã§å€ããã°ãå šãŠã®åç©ã¯ã©ã¹ã«å€æŽãåæ ãããïŒ
Bad:
class Employee {
constructor(name, email) {
this.name = name;
this.email = email;
}
// ...
}
// Bad because Employees "have" tax data. EmployeeTaxData is not a type of Employee
// ãããªãäŸããªããªãåŸæ¥å¡ïŒEmployeeïŒã¯çšæ
å ±ããæã£ãŠãããã ãã§ããã
// EmployeeTaxData 㯠Employee ã®äžçš®ïŒåïŒã§ã¯ãªãã
class EmployeeTaxData extends Employee {
constructor(ssn, salary) {
super();
this.ssn = ssn;
this.salary = salary;
}
// ...
}
Good:
class EmployeeTaxData {
constructor(ssn, salary) {
this.ssn = ssn;
this.salary = salary;
}
// ...
}
class Employee {
constructor(name, email) {
this.name = name;
this.email = email;
}
setTaxData(ssn, salary) {
this.taxData = new EmployeeTaxData(ssn, salary);
}
// ...
}
SOLID
Single Responsibility Principle (SRP)
åäžè²¬ä»»ã®åå(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.
Clean Code ã§ãè¿°ã¹ãããŠããããã«ããã¯ã©ã¹ã倿Žãããçç±ã¯ 1 ã€ã ãã§ããã¹ãã ã§ãã
ã¯ã©ã¹ã«å€ãã®æ©èœãè©°ã蟌ãã®ã¯ãäžèŠäŸ¿å©ã«æãããããããŸããã ããšãã°ãé£è¡æ©ã«ã¹ãŒãã±ãŒã¹ã 1 ã€ããæã¡èŸŒããªããšãã®ããã«ãã§ããéãè©°ã蟌ã¿ãããªããã®ã§ãã
ãããããã®ããã«æ©èœãè©°ã蟌ã¿ããããšãã¯ã©ã¹ã®æŠå¿µçãªãŸãšãŸãã倱ããã倿Žçç±ãå¢ããããŠããŸããŸãã
ã¯ã©ã¹ã倿Žããªããã°ãªããªãåæ°ãã§ããã ãå°ãªãããããšã¯éåžžã«éèŠã§ãã ãªããªãã1 ã€ã®ã¯ã©ã¹ã«å€§éã®åœ¹å²ãæŒã蟌ãã§ããŸããšããã®äžéšã倿Žããã ãã§ã³ãŒãããŒã¹å ã®ä»ã®äŸåã¢ãžã¥ãŒã«ãžã©ã®ãããªåœ±é¿ãåã¶ã®ããåããã«ãããªãããã§ãã
Bad:
class UserSettings {
constructor(user) {
this.user = user;
}
changeSettings(settings) {
if (this.verifyCredentials()) {
// ...
}
}
verifyCredentials() {
// ...
}
}
Good:
class UserAuth {
constructor(user) {
this.user = user;
}
verifyCredentials() {
// ...
}
}
class UserSettings {
constructor(user) {
this.user = user;
this.auth = new UserAuth(user);
}
changeSettings(settings) {
if (this.auth.verifyCredentials()) {
// ...
}
}
}
Open/Closed Principle (OCP)
ãªãŒãã³ã»ã¯ããŒãºãã®åå(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.
Bertrand Meyer ãè¿°ã¹ãŠããããã«ãããœãããŠã§ã¢ã®æ§æèŠçŽ ïŒã¯ã©ã¹ãã¢ãžã¥ãŒã«ã颿°ãªã©ïŒã¯ãæ¡åŒµã«å¯ŸããŠã¯éãããŠããã倿Žã«å¯ŸããŠã¯éããŠããã¹ãã§ããããšãããã®ã§ãã
ããã¯ã©ãããæå³ã§ããããïŒ
ãã®ååãæ¬è³ªçã«èšã£ãŠããã®ã¯ãæ¢åã®ã³ãŒãã倿Žããããšãªããæ°ããæ©èœã远å ã§ããããã«èšèšãã¹ãã§ãããšããããšã§ãã
Bad:
class AjaxAdapter extends Adapter {
constructor() {
super();
this.name = "ajaxAdapter";
}
}
class NodeAdapter extends Adapter {
constructor() {
super();
this.name = "nodeAdapter";
}
}
class HttpRequester {
constructor(adapter) {
this.adapter = adapter;
}
fetch(url) {
if (this.adapter.name === "ajaxAdapter") {
return makeAjaxCall(url).then((response) => {
// transform response and return
});
} else if (this.adapter.name === "nodeAdapter") {
return makeHttpCall(url).then((response) => {
// transform response and return
});
}
}
}
function makeAjaxCall(url) {
// request and return promise
}
function makeHttpCall(url) {
// request and return promise
}
Good:
class AjaxAdapter extends Adapter {
constructor() {
super();
this.name = "ajaxAdapter";
}
request(url) {
// request and return promise
}
}
class NodeAdapter extends Adapter {
constructor() {
super();
this.name = "nodeAdapter";
}
request(url) {
// request and return promise
}
}
class HttpRequester {
constructor(adapter) {
this.adapter = adapter;
}
fetch(url) {
return this.adapter.request(url).then((response) => {
// transform response and return
});
}
}
Liskov Substitution Principle (LSP)
ãªã¹ã³ãã®çœ®æåå (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.
ååã¯é£ãããã§ãããæŠå¿µèªäœã¯ãšãŠãã·ã³ãã«ã§ãã
æ£åŒãªå®çŸ©ã¯æ¬¡ã®ãšããã§ãïŒ
ããã S ã T ã®ãµãã¿ã€ãã§ãããªããããã°ã©ã ã®æãŸããæ§è³ªïŒæ£ããã»å®è¡çµæãªã©ïŒãæãªãããšãªããT åã®ãªããžã§ã¯ãã S åã®ãªããžã§ã¯ãã§çœ®ãæããããšãã§ããªããã°ãªããªããã
âŠâŠããã ãèªããšãããã«é£ããæãããããããŸããã
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 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.
ãã£ãšåãããããèšããšã芪ã¯ã©ã¹ãšåã¯ã©ã¹ããããåã¯ã©ã¹ã芪ã¯ã©ã¹ã®ä»£ãããšããŠåé¡ãªãæ±ããããšã ããã LSP ã®æ¬è³ªã§ãã
ãŸã å°ãåããã¥ãããããããªãã®ã§ãæåãªãæ£æ¹åœ¢ãšé·æ¹åœ¢ãã®äŸã§èããŠã¿ãŸãããã
æ°åŠçã«ã¯ãæ£æ¹åœ¢ã¯é·æ¹åœ¢ã®äžçš®ã§ãã ãããç¶æ¿ã䜿ã£ãŠ âæ£æ¹åœ¢ ã¯ é·æ¹åœ¢ ã§ããïŒis-aïŒâ ãšã¢ãã«åãããšãããã«åé¡ãçããŸãã
Bad:
class Rectangle {
constructor() {
this.width = 0;
this.height = 0;
}
setColor(color) {
// ...
}
render(area) {
// ...
}
setWidth(width) {
this.width = width;
}
setHeight(height) {
this.height = height;
}
getArea() {
return this.width * this.height;
}
}
class Square extends Rectangle {
setWidth(width) {
this.width = width;
this.height = width;
}
setHeight(height) {
this.width = height;
this.height = height;
}
}
function renderLargeRectangles(rectangles) {
rectangles.forEach((rectangle) => {
rectangle.setWidth(4);
rectangle.setHeight(5);
// BAD: Returns 25 for Square. Should be 20.
// ã ãïŒSquareïŒæ£æ¹åœ¢ïŒã®å Žå 25 ãè¿ã£ãŠããŸããæ¬æ¥ã¯ 20 ã§ããã¹ãã
const area = rectangle.getArea();
rectangle.render(area);
});
}
const rectangles = [new Rectangle(), new Rectangle(), new Square()];
renderLargeRectangles(rectangles);
Good:
class Shape {
setColor(color) {
// ...
}
render(area) {
// ...
}
}
class Rectangle extends Shape {
constructor(width, height) {
super();
this.width = width;
this.height = height;
}
getArea() {
return this.width * this.height;
}
}
class Square extends Shape {
constructor(length) {
super();
this.length = length;
}
getArea() {
return this.length * this.length;
}
}
function renderLargeShapes(shapes) {
shapes.forEach((shape) => {
const area = shape.getArea();
shape.render(area);
});
}
const shapes = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)];
renderLargeShapes(shapes);
Interface Segregation Principle (ISP)
ã€ã³ã¿ãŒãã§ã€ã¹åé¢ã®åå (ISP)
JavaScript doesnât have interfaces so this principle doesnât apply as strictly as others. However, itâs important and relevant even with JavaScriptâs lack of type system.
JavaScript ã«ã¯ã€ã³ã¿ãŒãã§ã€ã¹ãšããä»çµã¿ããªãããããã®ååã¯ä»ã®èšèªã»ã©å³å¯ã«é©çšããããã®ã§ã¯ãããŸããã ããããJavaScript ã«åã·ã¹ãã ããªãããšãèžãŸããŠãããã®ååã¯éåžžã«éèŠã§ãé¢é£æ§ã®é«ããã®ã§ãã
ISP states that âClients should not be forced to depend upon interfaces that they do not use.â Interfaces are implicit contracts in JavaScript because of duck typing.
ISP ãè¿°ã¹ãŠããã®ã¯ããã¯ã©ã€ã¢ã³ãïŒå©çšè ïŒã¯ã䜿ããªãã€ã³ã¿ãŒãã§ã€ã¹ã«äŸåãããããã¹ãã§ã¯ãªãããšããããšã§ãã
JavaScript ã§ã¯ããã¯ã¿ã€ãã³ã°ã«ããããã€ã³ã¿ãŒãã§ã€ã¹ãã¯æé»çãªå¥çŽãšããŠæ±ãããŸãã
A good example to look at that demonstrates this principle in JavaScript is for classes that require large settings objects. Not requiring clients to setup huge amounts of options is beneficial, because most of the time they wonât need all of the settings. Making them optional helps prevent having a âfat interfaceâ.
ãã®ååã JavaScript ã§ç€ºãè¯ãäŸã¯ã倧éã®èšå®ãªãã·ã§ã³ãå¿ èŠãšããã¯ã©ã¹ ã§ãã
ã¯ã©ã€ã¢ã³ãã«èšå€§ãªèšå®é ç®ã®å ¥åã匷ããã®ã¯è¯ããããŸããã ãªããªããå€ãã®å Žåããããã¹ãŠãå¿ èŠãšããªãããã§ãã
èšå®ã ä»»æïŒãªãã·ã§ã³ïŒ ã«ããããšã§ã䜿ãããªãããããã£ã ããã®ã倪ã£ãã€ã³ã¿ãŒãã§ã€ã¹ããé¿ããããšãã§ããŸãã
Bad:
class DOMTraverser {
constructor(settings) {
this.settings = settings;
this.setup();
}
setup() {
this.rootNode = this.settings.rootNode;
this.settings.animationModule.setup();
}
traverse() {
// ...
}
}
const $ = new DOMTraverser({
rootNode: document.getElementsByTagName("body"),
// Most of the time, we won't need to animate when traversing.
// ã»ãšãã©ã®å ŽåãããªãŒãèµ°æ»ãããšãã«ã¢ãã¡ãŒã·ã§ã³ã¯å¿
èŠãªãã
animationModule() {},
// ...
});
Good:
class DOMTraverser {
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 $ = new DOMTraverser({
rootNode: document.getElementsByTagName("body"),
options: {
animationModule() {},
},
});
Dependency Inversion Principle (DIP)
äŸåæ§é転ã®åå (DIP)
This principle states two essential things:
- High-level modules should not depend on low-level modules. Both should depend on abstractions.
- Abstractions should not depend upon details. Details should depend on abstractions.
ãã®ååã¯ã次㮠2 ã€ã®éèŠãªç¹ãè¿°ã¹ãŠããŸãïŒ
- äžäœã¬ãã«ã®ã¢ãžã¥ãŒã«ã¯äžäœã¬ãã«ã®ã¢ãžã¥ãŒã«ã«äŸåããŠã¯ãªããªããäž¡è ãšããæœè±¡ãã«äŸåãã¹ãã§ããã
- æœè±¡ã¯è©³çްïŒå®è£ ïŒã«äŸåããŠã¯ãªãããè©³çŽ°ãæœè±¡ã«äŸåãã¹ãã§ããã
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 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.
æåã¯åããã¥ãããããããŸããããããããªãã AngularJS ã䜿ã£ãããšããããªããäŸåæ§æ³šå ¥ïŒDIïŒãšãã圢ã§ãã®ååãå®è£ ãããŠããã®ãèŠãããšãããã§ãããã
DIP ãš DI ã¯å®å šã«åãæŠå¿µã§ã¯ãããŸããããDIP ã«åŸãããšã§ãäžäœã®ã¢ãžã¥ãŒã«ãäžäœã¢ãžã¥ãŒã«ã®è©³çްãç¥ããã«æžãããã«ãã ããšãã§ããŸãã ãã®ããã®ææ®µãšã㊠DI ãå©çšã§ããŸãã
ãã®ååã®å€§ããªå©ç¹ã¯ãã¢ãžã¥ãŒã«å士ã®çµå床ãäžãããã ããšã§ãã çµå床ãé«ããšãã³ãŒãã¯æ¥µããŠãªãã¡ã¯ã¿ãªã³ã°ãã«ãããªããæªãèšèšã®å žåäŸãšèšããŸãã
As stated previously, JavaScript doesnât have interfaces so the abstractions that are depended upon are implicit contracts. That is to say, the methods and properties that an object/class exposes to another object/class. In the example below, the implicit contract is that any Request module for an InventoryTracker will have a requestItems method.
å ã»ã©è¿°ã¹ãããã«ãJavaScript ã«ã¯ã€ã³ã¿ãŒãã§ã€ã¹ããªãããããæœè±¡ã㯠æé»ã®å¥çŽïŒã€ã³ã¿ãŒãã§ã€ã¹ã«çžåœããã¡ãœããæ§æïŒ ãšããŠæ±ãããŸãã
ã€ãŸãããããªããžã§ã¯ãïŒã¯ã©ã¹ãå¥ã®ãªããžã§ã¯ãïŒã¯ã©ã¹ã«æäŸãã ã¡ãœãããããããã£ããæœè±¡ãã«çžåœããŸãã
以äžã®äŸã§ã¯ãInventoryTracker ãäŸåãããã¹ãŠã® Request ã¢ãžã¥ãŒã«ã¯ requestItems ã¡ãœãããæã£ãŠãã ãšããæé»ã®å¥çŽãåæã«ãªã£ãŠããŸãã
Bad:
class InventoryRequester {
constructor() {
this.REQ_METHODS = ["HTTP"];
}
requestItem(item) {
// ...
}
}
class InventoryTracker {
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`
// ã ãïŒç¹å®ã®ãªã¯ãšã¹ãå®è£
ã«äŸåããŠããŸã£ãŠããã
// requestItems ã¯ã`request` ãšãããªã¯ãšã¹ãã¡ãœããã ãã«äŸåãã¹ãã§ããã
this.requester = new InventoryRequester();
}
requestItems() {
this.items.forEach((item) => {
this.requester.requestItem(item);
});
}
}
const inventoryTracker = new InventoryTracker(["apples", "bananas"]);
inventoryTracker.requestItems();
Good:
class InventoryTracker {
constructor(items, requester) {
this.items = items;
this.requester = requester;
}
requestItems() {
this.items.forEach((item) => {
this.requester.requestItem(item);
});
}
}
class InventoryRequesterV1 {
constructor() {
this.REQ_METHODS = ["HTTP"];
}
requestItem(item) {
// ...
}
}
class InventoryRequesterV2 {
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.
// äŸåé¢ä¿ãå€éšã§æ§ç¯ãããããæ³šå
¥ããããšã§ã
// WebSocket ãäœ¿ãæ°ãããªã¯ãšã¹ãã¢ãžã¥ãŒã«ãªã©ã«ç°¡åã«çœ®ãæããããã
const inventoryTracker = new InventoryTracker(
["apples", "bananas"],
new InventoryRequesterV2()
);
inventoryTracker.requestItems();
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 good coverage tool.
ãã¹ãã¯ãªãªãŒã¹ãããéèŠã§ãã ãã¹ãããªãã£ããéãäžååã§ããã°ãã³ãŒãããªãªãŒã¹ãããã³ã«ããªã«ãå£ããŠããªãã ãããïŒããšããäžå®ãã€ããŸãšããŸãã
ã©ããããã®ãã¹ãéããååããªã®ãã¯ããŒã ã«ãã£ãŠç°ãªããŸããã100% ã®ã«ãã¬ããžïŒãã¹ãŠã®æãšåå²ïŒ ãéæããããšã¯ãéåžžã«é«ãå®å¿æãšéçºè ã®å¿ã®å¹³ç©ããããããŸãã
ããã¯ãåªãããã¹ããã¬ãŒã ã¯ãŒã¯ãçšæããã ãã§ãªããè¯ãã«ãã¬ããžæž¬å®ããŒã«ã䜿ãå¿ èŠãããããšãæå³ããŸãã
Thereâs no excuse to not write tests. There are plenty 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 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.
ãã¹ããæžããªãèšãèš³ã¯ååšããŸããã åªããJavaScript ã®ãã¹ããã¬ãŒã ã¯ãŒã¯ã¯ããããããã®ã§ãããŒã ã«æé©ãªãã®ãéžãã§ãã ããã
ããŒã ã«åãããŒã«ãèŠã€ãã£ãããæ°ããæ©èœãã¢ãžã¥ãŒã«ã远å ãããã³ã«å¿ ããã¹ããæžãããšãç®æãã¹ãã§ãã
ããããªãããã¹ãé§åéçºïŒTDDïŒã奜ããªããããã¯çŽ æŽãããããšã§ãã ãããæãéèŠãªã®ã¯ãæ°ããæ©èœããªãªãŒã¹ããããæ¢åã³ãŒãããªãã¡ã¯ã¿ãªã³ã°ããåã«ã«ãã¬ããžã®ç®æšããã¡ããšæºãããŠããããšã確èªããããšã§ãã
Single concept per test
ãã¹ãããšã«åäžã®æŠå¿µã ãæ±ã
Bad:
import assert from "assert";
describe("MomentJS", () => {
it("handles date boundaries", () => {
let date;
date = new MomentJS("1/1/2015");
date.addDays(30);
assert.equal("1/31/2015", date);
date = new MomentJS("2/1/2016");
date.addDays(28);
assert.equal("02/29/2016", date);
date = new MomentJS("2/1/2015");
date.addDays(28);
assert.equal("03/01/2015", date);
});
});
Good:
import assert from "assert";
describe("MomentJS", () => {
it("handles 30-day months", () => {
const date = new MomentJS("1/1/2015");
date.addDays(30);
assert.equal("1/31/2015", date);
});
it("handles leap year", () => {
const date = new MomentJS("2/1/2016");
date.addDays(28);
assert.equal("02/29/2016", date);
});
it("handles non-leap year", () => {
const date = new MomentJS("2/1/2015");
date.addDays(28);
assert.equal("03/01/2015", date);
});
});
Concurrency
éåæåŠç
Use Promises, not callbacks
Promise ã䜿ããã³ãŒã«ããã¯ã¯äœ¿ããªãããš
Callbacks arenât clean, and they cause excessive amounts of nesting. With ES2015/ES6, Promises are a built-in global type. Use them!
ã³ãŒã«ããã¯ã¯ã³ãŒããç ©éã«ãªããæ·±ããã¹ããæãããã¯ãªãŒã³ã§ã¯ãããŸããã
ES2015/ES6 ã§ã¯ Promise ãã°ããŒãã«ã§å©çšã§ããæšæºæ©èœ ãªã®ã§ãç©æ¥µçã« Promise ã䜿ããŸãããïŒ
Bad:
import { get } from "request";
import { writeFile } from "fs";
get(
"https://en.wikipedia.org/wiki/Robert_Cecil_Martin",
(requestErr, response, body) => {
if (requestErr) {
console.error(requestErr);
} else {
writeFile("article.html", body, (writeErr) => {
if (writeErr) {
console.error(writeErr);
} else {
console.log("File written");
}
});
}
}
);
Good:
import { get } from "request-promise";
import { writeFile } from "fs-extra";
get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin")
.then((body) => {
return writeFile("article.html", body);
})
.then(() => {
console.log("File written");
})
.catch((err) => {
console.error(err);
});
Async/Await are even cleaner than Promises
Async/Await 㯠Promise ããããã«ã¯ãªãŒã³
Promises are a very clean alternative to callbacks, but ES2017/ES8 brings async and await which offer an even cleaner solution. All you need is a function that is prefixed in an async keyword, and then you can write your logic imperatively without a then chain of functions. Use this if you can take advantage of ES2017/ES8 features today!
Promise ã¯ã³ãŒã«ããã¯ã«å¯Ÿããéåžžã«ã¯ãªãŒã³ãªä»£æ¿ææ®µã§ãããES2017/ES8 ã§å°å ¥ããã async ãš await ã¯ãããã«èªã¿ããã解決çãæäŸããŸãã
颿°ã®å é ã« async ããŒã¯ãŒããä»ããã ãã§ãthen ãé£ããå¿ èŠã®ãªã ããèªç¶ãªåœä»€çãªæžãæ¹ ãã§ããããã«ãªããŸãã
ãã ES2017/ES8 ã®æ©èœãå©çšã§ããç°å¢ã§ããã°ããã² async/await ã䜿ããŸãããã
Bad:
import { get } from "request-promise";
import { writeFile } from "fs-extra";
get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin")
.then((body) => {
return writeFile("article.html", body);
})
.then(() => {
console.log("File written");
})
.catch((err) => {
console.error(err);
});
Good:
import { get } from "request-promise";
import { writeFile } from "fs-extra";
async function getCleanCodeArticle() {
try {
const body = await get("https://en.wikipedia.org/wiki/Robert_Cecil_Martin");
await writeFile("article.html", body);
console.log("File written");
} catch (err) {
console.error(err);
}
}
getCleanCodeArticle();
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 function execution on the current stack, killing the process (in Node), and notifying you in the console with a stack trace.
ãšã©ãŒãæããããããšã¯è¯ãããšã§ãïŒ ããã¯ãã©ã³ã¿ã€ã ã ããªãã®ããã°ã©ã ã§äœãåé¡ãèµ·ããããšãæ£ããæ€åºããçŸåšã®ã¹ã¿ãã¯ã§é¢æ°ã®å®è¡ã忢ããïŒNode ã§ã¯ïŒããã»ã¹ãçµäºããã¹ã¿ãã¯ãã¬ãŒã¹ä»ãã§ã³ã³ãœãŒã«ã«ç¥ãããŠãããŠãããšããæå³ã§ãã
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 a try/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.
ãšã©ãŒãææããŠãäœãããªãã®ã¯ææªã§ãã ãã®ãšã©ãŒã«å¯ŸããŠä¿®æ£ã察å¿ãã§ããªããªããŸãã
console.log ã§ãšã©ãŒãåºåããã ãã§ã¯æ¹åã«ã¯ãªããŸããã
ãã°ãä»ã®ã¡ãã»ãŒãžã«åãããæ°ã¥ããªãå¯èœæ§ãé«ãããã§ãã
try/catch ã§ã³ãŒããå²ããšããããšã¯ããã®å Žæã§ãšã©ãŒãèµ·ããåŸããšããªãèªèº«ãèªèããŠãã ãšããããšã§ãã
ãªãã°ããšã©ãŒãèµ·ãããšãã«ã©ãããããšããå¯ŸåŠæ¹æ³ãåå²ãçšæãã¹ãã§ãã
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
倱æãã PromiseïŒrejectïŒãç¡èŠããªãããš
For the same reason you shouldnât ignore caught errors from try/catch.
ãã㯠try/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!
});
Formatting
ãã©ãŒããã
Formatting is subjective. Like many rules herein, there is no hard and fast rule that you must follow. The main point is DO 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.
ãã©ãŒãããã¯äž»èгçãªãã®ã§ãã ããã«ããä»ã®ã«ãŒã«ãšåæ§ã絶察ã«åŸããªããã°ãªããªã峿 Œãªã«ãŒã«ã¯ãããŸããã
éèŠãªã®ã¯ããã©ãŒãããã«ã€ããŠè°è«ããªãããš ã§ãã ãã®äœæ¥ã¯èªååããŒã«ã倧éã«ååšããŸãã ãããã䜿ããŸãããïŒ ãšã³ãžãã¢ããã©ãŒããããå·¡ã£ãŠè°è«ããã®ã¯ãæéãšãéã®ç¡é§ã§ãã
For things that donât fall under the purview of automatic formatting (indentation, tabs vs. spaces, double vs. single quotes, etc.) look here for some guidance.
èªåãã©ãŒãããã®å¯Ÿè±¡ã«ãªããªãéšåïŒã€ã³ãã³ããã¿ããã¹ããŒã¹ããããã«ã¯ã©ãŒããã·ã³ã°ã«ã¯ã©ãŒããããªã©ïŒã«ã€ããŠã¯ãããã«ããã€ãã¬ã€ãã©ã€ã³ããããŸãã
Use consistent capitalization
äžè²«æ§ã®ãã倧æåã»å°æåïŒcapitalizationïŒã䜿ãããš
JavaScript is untyped, so 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, just be consistent.
JavaScript ã¯åããªãããã倿°åã颿°åãªã©ã®å€§æåã»å°æåã«ã¯å€ãã®æå³ãå«ãŸããŸãã ãããã®ã«ãŒã«ã¯äž»èгçãªã®ã§ãããŒã ã§å¥œããªã«ãŒã«ãéžã¹ã°æ§ããŸããã
éèŠãªã®ã¯ã©ã®ã«ãŒã«ãéžãã§ããå¿ ãäžè²«æ§ãä¿ã€ãšããããšã§ãã
Bad:
const DAYS_IN_WEEK = 7;
const daysInMonth = 30;
const songs = ["Back In Black", "Stairway to Heaven", "Hey Jude"];
const Artists = ["ACDC", "Led Zeppelin", "The Beatles"];
function eraseDatabase() {}
function restore_database() {}
class animal {}
class Alpaca {}
Good:
const DAYS_IN_WEEK = 7;
const DAYS_IN_MONTH = 30;
const SONGS = ["Back In Black", "Stairway to Heaven", "Hey Jude"];
const ARTISTS = ["ACDC", "Led Zeppelin", "The Beatles"];
function eraseDatabase() {}
function restoreDatabase() {}
class Animal {}
class Alpaca {}
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.
ãã颿°ãå¥ã®é¢æ°ãåŒã³åºãå Žåããããã®é¢æ°ã¯ãœãŒã¹ã³ãŒãäžã§çžŠæ¹åã«è¿ãäœçœ®ã«çœ®ãã¹ãã§ãã
çæ³çã«ã¯ãåŒã³åºãå ïŒcallerïŒãåŒã³åºãå ïŒcalleeïŒã® ããäž ã«é 眮ããŸãã
ç§ãã¡ã¯æ°èã®ããã«ãã³ãŒããäžããäžãžãšèªãåŸåããããŸãã ã ãããããã³ãŒãããã®æµãã§èªç¶ã«èªããããã«äžŠã¹ãã¹ããªã®ã§ãã
Bad:
class PerformanceReview {
constructor(employee) {
this.employee = employee;
}
lookupPeers() {
return db.lookup(this.employee, "peers");
}
lookupManager() {
return db.lookup(this.employee, "manager");
}
getPeerReviews() {
const peers = this.lookupPeers();
// ...
}
perfReview() {
this.getPeerReviews();
this.getManagerReview();
this.getSelfReview();
}
getManagerReview() {
const manager = this.lookupManager();
}
getSelfReview() {
// ...
}
}
const review = new PerformanceReview(employee);
review.perfReview();
Good:
class PerformanceReview {
constructor(employee) {
this.employee = employee;
}
perfReview() {
this.getPeerReviews();
this.getManagerReview();
this.getSelfReview();
}
getPeerReviews() {
const peers = this.lookupPeers();
// ...
}
lookupPeers() {
return db.lookup(this.employee, "peers");
}
getManagerReview() {
const manager = this.lookupManager();
}
lookupManager() {
return db.lookup(this.employee, "manager");
}
getSelfReview() {
// ...
}
}
const review = new PerformanceReview(employee);
review.perfReview();
Comments
ã³ã¡ã³ã
Only comment things that have business logic complexity.
ããžãã¹ããžãã¯ãè€éãªéšåã«ã®ã¿ã³ã¡ã³ããæžã
Comments are an apology, not a requirement. Good code mostly documents itself.
ã³ã¡ã³ãã¯ãèšãèš³ãã§ãã£ãŠãå¿ é ãã§ã¯ãããŸãããè¯ãã³ãŒãã¯ãã»ãšãã©ãã³ãŒãèªäœã§èª¬æã§ãããã®ã§ãã
Bad:
function hashIt(data) {
// The hash
let hash = 0;
// Length of string
const length = data.length;
// Loop through every character in data
for (let i = 0; i < length; i++) {
// Get character code.
const char = data.charCodeAt(i);
// Make the hash
hash = (hash << 5) - hash + char;
// Convert to 32-bit integer
hash &= hash;
}
}
Good:
function hashIt(data) {
let hash = 0;
const length = data.length;
for (let i = 0; i < length; i++) {
const char = data.charCodeAt(i);
hash = (hash << 5) - hash + char;
// Convert to 32-bit integer
hash &= hash;
}
}
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();
Donât have journal comments
æ¥èšã®ãããªã³ã¡ã³ããæžããªã
Remember, use version control! Thereâs no need for dead code, commented code, and especially journal comments. Use git log to get history!
ããŒãžã§ã³ç®¡çã䜿ãããšãå¿ããªãã§ãã ããïŒ äœ¿ãããŠããªãã³ãŒããã³ã¡ã³ãã¢ãŠããããã³ãŒãããããŠç¹ã«æ¥èšã®ãããªã³ã¡ã³ãã¯äžèŠã§ãã
å±¥æŽãå¿
èŠãªããgit log ã䜿ãã°ååã§ãã
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)
*/
function combine(a, b) {
return a + b;
}
Good:
function combine(a, b) {
return a + b;
}
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.
ãããã¯ãããŠã ãã ã®ãã€ãº ãå¢ããã ãã§ãã
ã³ãŒãã®èŠèŠçãªæ§é ã¯ã颿°åã»å€æ°åã»é©åãªã€ã³ãã³ãã»ãã©ãŒãããã«ãã£ãŠååã«è¡šçŸã§ããŸãã
Bad:
////////////////////////////////////////////////////////////////////////////////
// Scope Model Instantiation
////////////////////////////////////////////////////////////////////////////////
$scope.model = {
menu: "foo",
nav: "bar",
};
////////////////////////////////////////////////////////////////////////////////
// Action setup
////////////////////////////////////////////////////////////////////////////////
const actions = function () {
// ...
};
Good:
$scope.model = {
menu: "foo",
nav: "bar",
};
const actions = function () {
// ...
};
Translation
翻蚳
This is also available in other languages:
æ¬ã¬ã€ãã¯ä»¥äžã®èšèªã«ã翻蚳ãããŠããŸãïŒ
- ðŠð² Armenian: https://github.com/hanumanum/clean-code-javascript
- ð§ð© Bangla: https://github.com/InsomniacSabbir/clean-code-javascript/
- ð§ð· Brazilian Portuguese: https://github.com/fesnt/clean-code-javascript
- ðšð³ Simplified Chinese:
- https://github.com/alivebao/clean-code-js
- https://github.com/beginor/clean-code-javascript
- ð¹ðŒ Traditional Chinese: https://github.com/AllJointTW/clean-code-javascript
- ð«ð· French: https://github.com/eugene-augier/clean-code-javascript-fr
- ð©ðª German: https://github.com/marcbruederlin/clean-code-javascript
- ð®ð© Indonesian: https://github.com/andirkh/clean-code-javascript/
- ð®ð¹ Italian: https://github.com/frappacchio/clean-code-javascript/
- ð¯ðµ Japanese: https://github.com/mitsuruog/clean-code-javascript/
- ð°ð· Korean: https://github.com/qkraudghgh/clean-code-javascript-ko
- ðµð± Polish: https://github.com/greg-dev/clean-code-javascript-pl
- ð·ðº Russian:
- https://github.com/BoryaMogila/clean-code-javascript-ru/
- https://github.com/maksugr/clean-code-javascript
- ðªðž Spanish: https://github.com/tureey/clean-code-javascript
- ðºðŸ Spanish (Uruguay): https://github.com/andersontr15/clean-code-javascript-es
- ð·ðž Serbian: https://github.com/doskovicmilos/clean-code-javascript
- ð¹ð· Turkish: https://github.com/bsonmez/clean-code-javascript/tree/turkish-translation
- ðºðŠ Ukrainian: https://github.com/mindfr1k/clean-code-javascript-ua
- ð»ð³ Vietnamese: https://github.com/hienvd/clean-code-javascript/
- ð®ð· Persian: https://github.com/hamettio/clean-code-javascript