๋ฒ์ญ ์์ ์งํ์ค์ ๋๋ค.
ํ์
์คํฌ๋ฆฝํธ๋ฅผ ์ํ ํด๋ฆฐ์ฝ๋.
clean-code-javascript์์ ์๊ฐ์ ๋ฐ์์ต๋๋ค.
- ์๊ฐ
- ๋ณ์
- ํจ์
- ๊ฐ์ฒด์ ์๋ฃ๊ตฌ์กฐ
- ํด๋์ค
- SOLID
- ํ ์คํธ
- ๋์์ฑ
- ์๋ฌ ์ฒ๋ฆฌ
- ์์
- ์ฃผ์
- ๋ฒ์ญ
Robert C. Martin์ ์ฑ ์ธ ํด๋ฆฐ ์ฝ๋์ ์๋ ์ํํธ์จ์ด ๊ณตํ ๋ฐฉ๋ฒ๋ก ์ ํ์ ์คํฌ๋ฆฝํธ์ ์ ์ฉํ ๊ธ์ ๋๋ค. ์ด ๊ธ์ ์คํ์ผ ๊ฐ์ด๋๊ฐ ์๋๋๋ค. ์ด ๊ธ์ ํ์ ์คํฌ๋ฆฝํธ์์ ์ฝ๊ธฐ ์ฝ๊ณ , ์ฌ์ฌ์ฉ ๊ฐ๋ฅํ๋ฉฐ, ๋ฆฌํฉํ ๋ง ๊ฐ๋ฅํ ์ํํธ์จ์ด๋ฅผ ์์ฑํ๊ธฐ ์ํ ๊ฐ์ด๋์ ๋๋ค.
์ฌ๊ธฐ ์๋ ๋ชจ๋ ๊ท์น์ ์๊ฒฉํ๊ฒ ๋ฐ๋ฅผ ํ์๋ ์์ผ๋ฉฐ, ๋ณดํธ์ ์ผ๋ก ํต์ฉ๋๋ ๊ท์น์ ์๋๋๋ค. ์ด ๊ธ์ ํ๋์ ์ง์นจ์ผ ๋ฟ์ด๋ฉฐ, ํด๋ฆฐ ์ฝ๋์ ์ ์๊ฐ ์๋ ๊ฐ ๊ฒฝํํ ๋ด์ฉ์ ๋ฐํ์ผ๋ก ์ ๋ฆฌํ ๊ฒ์ ๋๋ค.
์ํํธ์จ์ด ๊ณตํ ๊ธฐ์ ์ ์ญ์ฌ๋ 50๋ ์ด ์กฐ๊ธ ๋์๊ณ , ๋ฐฐ์์ผ ํ ๊ฒ์ด ์ฌ์ ํ ๋ง์ต๋๋ค. ์ํํธ์จ์ด ์ค๊ณ๊ฐ ๊ฑด์ถ ์ค๊ณ๋งํผ ์ค๋๋์์ ๋๋ ์๋ง๋ ์๋ ๊ท์น๋ค๋ณด๋ค ์๊ฒฉํ ๊ท์น์ ๋ฐ๋ผ์ผ ํ ๊ฒ์ ๋๋ค. ํ์ง๋ง ์ง๊ธ์ ์ด ์ง์นจ์ ๋น์ ๊ณผ ๋น์ ํ์ด ์์ฑํ๋ ํ์ ์คํฌ๋ฆฝํธ ์ฝ๋์ ํ์ง์ ํ๊ฐํ๋ ๊ธฐ์ค์ผ๋ก ์ผ์ผ์ธ์.
ํ ๊ฐ์ง ๋ ๋ง๋ถ์ด์๋ฉด, ์ด ๊ท์น๋ค์ ์๊ฒ ๋๋ค ํด์ ๋น์ฅ ๋ ๋์ ๊ฐ๋ฐ์๊ฐ ๋๋ ๊ฒ์ ์๋๋ฉฐ ์ฝ๋๋ฅผ ์์ฑํ ๋ ์ค์๋ฅผ ํ์ง ์๊ฒ ํด์ฃผ๋ ๊ฒ์ ์๋๋๋ค. ํ๋ฅญํ ๋์๊ธฐ๋ค์ด ์ฒ์์ ๋ง๋ํ ์ ํ ๋ถํฐ ์์ํ๋ฏ์ด ๋ชจ๋ ์ฝ๋๋ฅผ ์ฒ์๋ถํฐ ์๋ฒฝํ ์ ์์ต๋๋ค. ํ์ง๋ง ๋น์ ์ ํ์๋ค๊ณผ ๊ฐ์ด ์ฝ๋๋ฅผ ๋ฆฌ๋ทฐํ๋ฉฐ ์ ์ ์๋ฒฝํ๊ฒ ๋ง๋ค์ด ๋๊ฐ์ผ ํฉ๋๋ค. ๋น์ ์ด ์ฒ์ ์์ฑํ ์ฝ๋๋ฅผ ๊ณ ์น ๋ ์ ๋๋ก ์์ ์ ์งํํ์ง ๋ง์ธ์. ๋์ ์ฝ๋๋ฅผ ๋ถ์๊ณ ๋ ๋์ ์ฝ๋๋ฅผ ๋ง๋์ธ์!
์ฝ๋ ์ฌ๋์ผ๋ก ํ์ฌ๊ธ ๋ณ์๋ง๋ค ์ด๋ค ์ ์ด ๋ค๋ฅธ์ง ์ ์ ์๋๋ก ์ด๋ฆ์ ๊ตฌ๋ณํ์ธ์.
Bad:
function between<T>(a1: T, a2: T, a3: T): boolean {
return a2 <= a1 && a1 <= a3;
}
Good:
function between<T>(value: T, left: T, right: T): boolean {
return left <= value && value <= right;
}
๋ฐ์ํ ์ ์๋ ์ด๋ฆ์ ๊ทธ ๋ณ์์ ๋ํด์ ๋ฐ๋ณด ๊ฐ์ด ์๋ฆฌ๋ด์ด ํ ๋ก ํ ์ ๋ฐ์ ์์ต๋๋ค.
Bad:
type DtaRcrd102 = {
genymdhms: Date;
modymdhms: Date;
pszqint: number;
}
Good:
type Customer = {
generationTimestamp: Date;
modificationTimestamp: Date;
recordId: number;
}
Bad:
function getUserInfo(): User;
function getUserDetails(): User;
function getUserData(): User;
Good:
function getUser(): User;
์ฝ๋๋ฅผ ์ธ ๋๋ณด๋ค ์ฝ์ ๋๊ฐ ๋ ๋ง๊ธฐ ๋๋ฌธ์ ์ฐ๋ฆฌ๊ฐ ์ฐ๋ ์ฝ๋๋ ์ฝ์ ์ ์๊ณ ๊ฒ์์ด ๊ฐ๋ฅํด์ผ ํฉ๋๋ค. ํ๋ก๊ทธ๋จ์ ์ดํดํ ๋ ์๋ฏธ์๋ ๋ณ์ ์ด๋ฆ์ ์ง์ง ์์ผ๋ฉด ์ฝ๋ ์ฌ๋์ผ๋ก ํ์ฌ๊ธ ์ด๋ ค์์ ์ค ์ ์์ต๋๋ค. ๊ฒ์ ๊ฐ๋ฅํ ์ด๋ฆ์ ์ง์ผ์ธ์. TSLint์ ๊ฐ์ ๋๊ตฌ๋ ์ด๋ฆ์ด ์๋ ์์๋ฅผ ์๋ณํ ์ ์๋๋ก ๋์์ค๋๋ค.
Bad:
// 86400000์ด ๋๋์ฒด ๋ญ์ง?
setTimeout(restart, 86400000);
Good:
// ๋๋ฌธ์๋ก ์ด๋ฃจ์ด์ง ์์๋ก ์ ์ธํ์ธ์.
const MILLISECONDS_IN_A_DAY = 24 * 60 * 60 * 1000;
setTimeout(restart, MILLISECONDS_IN_A_DAY);
Bad:
declare const users: Map<string, User>;
for (const keyValue of users) {
// users ๋งต์ ์ํ
}
Good:
declare const users: Map<string, User>;
for (const [id, user] of users) {
// users ๋งต์ ์ํ
}
๋ช
์์ ์ธ ๊ฒ์ด ์์์ ์ธ ๊ฒ๋ณด๋ค ์ข์ต๋๋ค.
๋ช
๋ฃํจ์ ์ต๊ณ ์
๋๋ค.
Bad:
const u = getUser();
const s = getSubscription();
const t = charge(u, s);
Good:
const user = getUser();
const subscription = getSubscription();
const transaction = charge(user, subscription);
ํด๋์ค/ํ์ /๊ฐ์ฒด์ ์ด๋ฆ์ ์๋ฏธ๊ฐ ๋ด๊ฒจ์๋ค๋ฉด, ๋ณ์ ์ด๋ฆ์์ ๋ฐ๋ณตํ์ง ๋ง์ธ์.
Bad:
type Car = {
carMake: string;
carModel: string;
carColor: string;
}
function print(car: Car): void {
console.log(`${car.carMake} ${car.carModel} (${car.carColor})`);
}
Good:
type Car = {
make: string;
model: string;
color: string;
}
function print(car: Car): void {
console.log(`${car.make} ${car.model} (${car.color})`);
}
๊ธฐ๋ณธ ๋งค๊ฐ๋ณ์๋ short circuiting๋ณด๋ค ๋ณดํต ๋ช ๋ฃํฉ๋๋ค.
Bad:
function loadPages(count?: number) {
const loadCount = count !== undefined ? count : 10;
// ...
}
Good:
function loadPages(count: number = 10) {
// ...
}
์๋ฅผ ๋ค์ด ๊ทธ๊ฒ๋ค์ ๊ฐ ์์ฒด๋ณด๋ค ๊ฐ์ด ๊ตฌ๋ณ๋์ด์ผ ํ ๋์ ๊ฐ์ด ์ฝ๋์ ์๋๋ฅผ ์๋ ค์ฃผ๋๋ฐ์ enum
์ ๋์์ ์ค ์ ์์ต๋๋ค.
Bad:
const GENRE = {
ROMANTIC: 'romantic',
DRAMA: 'drama',
COMEDY: 'comedy',
DOCUMENTARY: 'documentary',
}
projector.configureFilm(GENRE.COMEDY);
class Projector {
// Projector์ ์ ์ธ
configureFilm(genre) {
switch (genre) {
case GENRE.ROMANTIC:
// ์คํ๋์ด์ผ ํ๋ ๋ก์ง
}
}
}
Good:
enum GENRE {
ROMANTIC,
DRAMA,
COMEDY,
DOCUMENTARY,
}
projector.configureFilm(GENRE.COMEDY);
class Projector {
// Projector์ ์ ์ธ
configureFilm(genre) {
switch (genre) {
case GENRE.ROMANTIC:
// ์คํ๋์ด์ผ ํ๋ ๋ก์ง
}
}
}
ํจ์ ๋งค๊ฐ๋ณ์์ ๊ฐ์๋ฅผ ์ ํํ๋ ๊ฒ์ ํจ์๋ฅผ ํ ์คํธํ๊ธฐ ์ฝ๊ฒ ๋ง๋ค์ด์ฃผ๊ธฐ ๋๋ฌธ์ ๋๋ผ์ธ ์ ๋๋ก ์ค์ํฉ๋๋ค. ํจ์ ๋งค๊ฐ๋ณ์๊ฐ 3๊ฐ ์ด์์ธ ๊ฒฝ์ฐ, ๊ฐ๊ธฐ ๋ค๋ฅธ ์ธ์๋ก ์ฌ๋ฌ ๋ค๋ฅธ ์ผ์ด์ค๋ฅผ ํ ์คํธํด์ผ ํ๋ฏ๋ก ๊ฒฝ์ฐ์ ์๊ฐ ๋งค์ฐ ๋ง์์ง๋๋ค.
ํ ๊ฐ ํน์ ๋ ๊ฐ์ ๋งค๊ฐ๋ณ์๊ฐ ์ด์์ ์ธ ๊ฒฝ์ฐ๊ณ , ๊ฐ๋ฅํ๋ค๋ฉด ์ธ ๊ฐ๋ ํผํด์ผ ํฉ๋๋ค. ๊ทธ ์ด์์ ๊ฒฝ์ฐ์๋ ํฉ์ณ์ผ ํฉ๋๋ค. ๋ ๊ฐ ์ด์์ ๋งค๊ฐ๋ณ์๋ฅผ ๊ฐ์ง ๊ฒฝ์ฐ, ํจ์๊ฐ ๋ง์ ๊ฒ์ ํ ๊ฐ๋ฅ์ฑ์ด ๋์์ง๋๋ค. ๊ทธ๋ ์ง ์์ ๊ฒฝ์ฐ, ๋๋ถ๋ถ ์์ ๊ฐ์ฒด๋ ํ๋์ ๋งค๊ฐ๋ณ์๋ก ์ถฉ๋ถํ ๊ฒ์ ๋๋ค.
๋ง์ ๋งค๊ฐ๋ณ์๋ฅผ ์ฌ์ฉํด์ผ ํ๋ค๋ฉด ๊ฐ์ฒด ๋ฆฌํฐ๋ด์ ์ฌ์ฉํ๋ ๊ฒ์ ๊ณ ๋ คํด๋ณด์ธ์.
ํจ์๊ฐ ๊ธฐ๋ํ๋ ์์ฑ์ ๋ช ํํ๊ฒ ํ๊ธฐ ์ํด, ๊ตฌ์กฐ ๋ถํด ๊ตฌ๋ฌธ์ ์ฌ์ฉํ ์ ์์ต๋๋ค. ์ด ๊ตฌ๋ฌธ์ ๋ช ๊ฐ์ ์ฅ์ ์ ๊ฐ์ง๊ณ ์์ต๋๋ค:
-
์ด๋ค ์ฌ๋์ด ํจ์ ์๊ทธ๋์ณ(๋งค๊ฐ๋ณ์์ ํ์ , ๋ฐํ๊ฐ์ ํ์ ๋ฑ)๋ฅผ ๋ณผ ๋, ์ด๋ค ์์ฑ์ด ์ฌ์ฉ๋๋์ง ์ฆ์ ์ ์ ์์ต๋๋ค.
-
๋ช ๋ช ๋ ๋งค๊ฐ๋ณ์์ฒ๋ผ ๋ณด์ด๊ฒ ํ ๋ ์ฌ์ฉํ ์ ์์ต๋๋ค.
-
๋ํ ๊ตฌ์กฐ ๋ถํด๋ ํจ์๋ก ์ ๋ฌ๋ ๋งค๊ฐ๋ณ์ ๊ฐ์ฒด์ ํน์ ํ ์์ ๊ฐ์ ๋ณต์ ํ๋ฉฐ ์ด๊ฒ์ ์ฌ์ด๋ ์ดํํธ๋ฅผ ๋ฐฉ์งํ๋๋ฐ ๋์์ ์ค๋๋ค. ์ ์์ฌํญ: ๋งค๊ฐ๋ณ์ ๊ฐ์ฒด๋ก๋ถํฐ ๊ตฌ์กฐ ๋ถํด๋ ๊ฐ์ฒด์ ๋ฐฐ์ด์ ๋ณต์ ๋์ง ์์ต๋๋ค.
-
ํ์ ์คํฌ๋ฆฝํธ๋ ์ฌ์ฉํ์ง ์์ ์์ฑ์ ๋ํด์ ๊ฒฝ๊ณ ๋ฅผ ์ฃผ๋ฉฐ, ๊ตฌ์กฐ ๋ถํด๋ฅผ ์ฌ์ฉํ๋ฉด ๊ฒฝ๊ณ ๋ฅผ ๋ฐ์ง ์์ ์ ์์ต๋๋ค.
Bad:
function createMenu(title: string, body: string, buttonText: string, cancellable: boolean) {
// ...
}
createMenu('Foo', 'Bar', 'Baz', true);
Good:
function createMenu(options: { title: string, body: string, buttonText: string, cancellable: boolean }) {
// ...
}
createMenu({
title: 'Foo',
body: 'Bar',
buttonText: 'Baz',
cancellable: true
});
type aliases๋ฅผ ์ฌ์ฉํด์ ๊ฐ๋ ์ฑ์ ๋ ๋์ผ ์ ์์ต๋๋ค:
type MenuOptions = { title: string, body: string, buttonText: string, cancellable: boolean };
function createMenu(options: MenuOptions) {
// ...
}
createMenu({
title: 'Foo',
body: 'Bar',
buttonText: 'Baz',
cancellable: true
});
์ด๊ฒ์ ์ํํธ์จ์ด ๊ณตํ์์ ๋จ์ฐ์ฝ ์ค์ํ ๊ท์น์ ๋๋ค. ํจ์๊ฐ ํ๊ฐ์ง ์ด์์ ์ญํ ์ ์ํํ ๋ ์์ฑํ๊ณ ํ ์คํธํ๊ณ ์ถ๋ก ํ๊ธฐ ์ด๋ ค์์ง๋๋ค. ํจ์๋ฅผ ํ๋์ ํ๋์ผ๋ก ์ ์ํ ์ ์์ ๋, ์ฝ๊ฒ ๋ฆฌํฉํ ๋งํ ์ ์์ผ๋ฉฐ ์ฝ๋๋ฅผ ๋์ฑ ๋ช ๋ฃํ๊ฒ ์ฝ์ ์ ์์ต๋๋ค. ์ด ๊ฐ์ด๋์์ ์ด ๋ถ๋ถ๋ง ์๊ธฐ๊ฒ์ผ๋ก ๋ง๋ค์ด๋ ๋น์ ์ ๋ง์ ๊ฐ๋ฐ์๋ณด๋ค ์์ค ์ ์์ต๋๋ค.
Bad:
function emailClients(clients: Client[]) {
clients.forEach((client) => {
const clientRecord = database.lookup(client);
if (clientRecord.isActive()) {
email(client);
}
});
}
Good:
function emailClients(clients: Client[]) {
clients.filter(isActiveClient).forEach(email);
}
function isActiveClient(client: Client) {
const clientRecord = database.lookup(client);
return clientRecord.isActive();
}
Bad:
function addToDate(date: Date, month: number): Date {
// ...
}
const date = new Date();
// ๋ฌด์์ด ์ถ๊ฐ๋๋์ง ํจ์ ์ด๋ฆ๋ง์ผ๋ก ์ ์ถํ๊ธฐ ์ด๋ ต์ต๋๋ค
addToDate(date, 1);
Good:
function addMonthToDate(date: Date, month: number): Date {
// ...
}
const date = new Date();
addMonthToDate(date, 1);
ํจ์๊ฐ ํ๊ฐ์ง ์ด์์ ์ถ์ํํ๋ค๋ฉด ๊ทธ ํจ์๋ ๋๋ฌด ๋ง์ ์ผ์ ํ๊ฒ ๋ฉ๋๋ค. ์ฌ์ฌ์ฉ์ฑ๊ณผ ์ฌ์ด ํ ์คํธ๋ฅผ ์ํด์ ํจ์๋ฅผ ์ชผ๊ฐ์ธ์.
Bad:
function parseCode(code: string) {
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:
const REGEXES = [ /* ... */ ];
function parseCode(code: string) {
const tokens = tokenize(code);
const syntaxTree = parse(tokens);
syntaxTree.forEach((node) => {
// parse...
});
}
function tokenize(code: string): Token[] {
const statements = code.split(' ');
const tokens: Token[] = [];
REGEXES.forEach((regex) => {
statements.forEach((statement) => {
tokens.push( /* ... */ );
});
});
return tokens;
}
function parse(tokens: Token[]): SyntaxTree {
const syntaxTree: SyntaxTree[] = [];
tokens.forEach((token) => {
syntaxTree.push( /* ... */ );
});
return syntaxTree;
}
์ฝ๋๊ฐ ์ค๋ณต๋์ง ์๋๋ก ์ต์ ์ ๋คํ์ธ์. ์ค๋ณต๋ ์ฝ๋๋ ์ด๋ค ๋ก์ง์ ๋ณ๊ฒฝํ ๋ ํ ๊ณณ ์ด์์ ๋ณ๊ฒฝํด์ผ ํ๊ธฐ ๋๋ฌธ์ ์ข์ง ์์ต๋๋ค.
๋น์ ์ด ๋ ์คํ ๋์ ์ด์ํ๋ฉด์ ์ฌ๊ณ ๋ฅผ ์ถ์ ํ๋ค๊ณ ์์ํด๋ณด์ธ์: ๋ชจ๋ ํ ๋งํ , ์ํ, ๋ง๋, ์๋ ๋ฑ. ๊ด๋ฆฌํ๋ ๋ชฉ๋ก์ด ์ฌ๋ฌ๊ฐ์ผ ๋ ํ ๋งํ ๋ฅผ ๋ฃ์ ์๋ฆฌ๋ฅผ ์ ๊ณตํ ๋๋ง๋ค ๋ชจ๋ ๋ชฉ๋ก์ ์์ ํด์ผ ํฉ๋๋ค. ๊ด๋ฆฌํ๋ ๋ชฉ๋ก์ด ๋จ ํ๋์ผ ๋๋ ํ ๊ณณ๋ง ์์ ํ๋ฉด ๋ฉ๋๋ค!
๋น์ ์ ์ข ์ข ๋ ๊ฐ ์ด์์ ์ฌ์ํ ๋ค๋ฅธ ๊ฒ๋ค์ด ์๋ค๊ณ ๋ง์ ๊ฒ๋ค์ด ๊ณต์ ๋๋ ์ค๋ณต๋๋ ์ฝ๋๋ฅผ ์์ฑํฉ๋๋ค. ํ์ง๋ง ๊ทธ ๋ช๊ฐ์ง ๋ค๋ฅธ ๊ฒ์ผ๋ก ์ธํด ๊ฐ์ ์ญํ ์ ํ๋ ๋ ๊ฐ ์ด์์ ํจ์๋ฅผ ๋ง๋ค๊ฒ ๋ฉ๋๋ค. ์ค๋ณต๋ ์ฝ๋๋ฅผ ์ ๊ฑฐํ๋ ๊ฒ์ ์กฐ๊ธ์ฉ ๋ค๋ฅธ ์ญํ ์ ํ๋ ๊ฒ์ ๋ฌถ์์ผ๋ก์จ ํ๋์ ํจ์/๋ชจ๋/ํด๋์ค๋ก ์ฒ๋ฆฌํ๋ ์ถ์ํ๋ฅผ ๋ง๋๋ ๊ฒ์ ์๋ฏธํฉ๋๋ค.
์ถ์ํ๋ฅผ ์ฌ๋ฐ๋ฅด๊ฒ ํ๋ ๊ฒ์ ์ค์ํ๋ฉฐ, ์ด๊ฒ์ SOLID ์์น์ ๋ฐ๋ฅด๋ ์ด์ ์ด๊ธฐ๋ ํฉ๋๋ค. ์ฌ๋ฐ๋ฅด์ง ์์ ์ถ์ํ๋ ์ค๋ณต๋ ์ฝ๋๋ณด๋ค ๋์๋ฏ๋ก ์ฃผ์ํ์ธ์! ์ข์ ์ถ์ํ๋ฅผ ํ ์ ์๋ค๋ฉด ๊ทธ๋ ๊ฒ ํ๋ผ๋ ๋ง์ ๋๋ค! ๋ฐ๋ณตํ์ง ๋ง์ธ์. ๊ทธ๋ ์ง ์์ผ๋ฉด ํ๋๋ฅผ ๋ณ๊ฒฝํ ๋๋ง๋ค ์ฌ๋ฌ ๊ณณ์ ๋ณ๊ฒฝํ๊ฒ ๋ ๊ฒ์ ๋๋ค.
Bad:
function showDeveloperList(developers: Developer[]) {
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: Manager[]) {
managers.forEach((manager) => {
const expectedSalary = manager.calculateExpectedSalary();
const experience = manager.getExperience();
const portfolio = manager.getMBAProjects();
const data = {
expectedSalary,
experience,
portfolio
};
render(data);
});
}
Good:
class Developer {
// ...
getExtraDetails() {
return {
githubLink: this.githubLink,
}
}
}
class Manager {
// ...
getExtraDetails() {
return {
portfolio: this.portfolio,
}
}
}
function showEmployeeList(employee: Developer | Manager) {
employee.forEach((employee) => {
const expectedSalary = employee.calculateExpectedSalary();
const experience = employee.getExperience();
const extra = employee.getExtraDetails();
const data = {
expectedSalary,
experience,
extra,
};
render(data);
});
}
๋น์ ์ ์ค๋ณต๋ ์ฝ๋์ ๋ํด์ ๋นํ์ ์ผ๋ก ์๊ฐํด์ผ ํฉ๋๋ค. ๊ฐ๋์ ์ค๋ณต๋ ์ฝ๋์ ๋ถํ์ํ ์ถ์ํ๋ก ์ธํ ๋ณต์ก์ฑ ๊ฐ์ ๋ง๋ฐ๊ฟ์ด ์์ ์ ์์ต๋๋ค. ์๋ก ๋ค๋ฅธ ๋ ๊ฐ์ ๋ชจ๋์ ๊ตฌํ์ด ์ ์ฌํด๋ณด์ด์ง๋ง ์๋ก ๋ค๋ฅธ ๋๋ฉ์ธ์ ์กด์ฌํ๋ ๊ฒฝ์ฐ, ์ฝ๋ ์ค๋ณต์ ๊ณตํต๋ ์ฝ๋์์ ์ถ์ถํด์ ์ค๋ณต์ ์ค์ด๋ ๊ฒ๋ณด๋ค ๋์ ์ ํ์ผ ์ ์์ต๋๋ค. ์ด ๊ฒฝ์ฐ์ ์ถ์ถ๋ ๊ณตํต์ ์ฝ๋๋ ๋ ๋ชจ๋ ์ฌ์ด์์ ๊ฐ์ ์ ์ธ ์์กด์ฑ์ด ๋ํ๋๊ฒ ๋ฉ๋๋ค.
Bad:
type MenuConfig = { title?: string, body?: string, buttonText?: string, cancellable?: boolean };
function createMenu(config: MenuConfig) {
config.title = config.title || 'Foo';
config.body = config.body || 'Bar';
config.buttonText = config.buttonText || 'Baz';
config.cancellable = config.cancellable !== undefined ? config.cancellable : true;
// ...
}
createMenu({ body: 'Bar' });
Good:
type MenuConfig = { title?: string, body?: string, buttonText?: string, cancellable?: boolean };
function createMenu(config: MenuConfig) {
const menuConfig = Object.assign({
title: 'Foo',
body: 'Bar',
buttonText: 'Baz',
cancellable: true
}, config);
// ...
}
createMenu({ body: 'Bar' });
๋์์ผ๋ก, ๊ธฐ๋ณธ ๊ฐ์ ๊ตฌ์กฐ ๋ถํด๋ฅผ ์ฌ์ฉํด์ ํด๊ฒฐํ ์ ์์ต๋๋ค:
type MenuConfig = { title?: string, body?: string, buttonText?: string, cancellable?: boolean };
function createMenu({ title = 'Foo', body = 'Bar', buttonText = 'Baz', cancellable = true }: MenuConfig) {
// ...
}
createMenu({ body: 'Bar' });
์ฌ์ด๋ ์ดํํธ์ undefined
ํน์ null
๊ฐ์ ๋ช
์์ ์ผ๋ก ๋๊ธฐ๋ ์์์น๋ชปํ ํ๋์ ํผํ๊ธฐ ์ํด์ ํ์
์คํฌ๋ฆฝํธ ์ปดํ์ผ๋ฌ์๊ฒ ๊ทธ๊ฒ์ ํ๋ฝํ์ง์๋๋ก ์ค์ ํ ์ ์์ต๋๋ค. ํ์
์คํฌ๋ฆฝํธ์์ --strictNullChecks
์ต์
์ ํ์ธํ์ธ์.
ํ๋๊ทธ๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ ํด๋น ํจ์๊ฐ ํ ๊ฐ์ง ์ด์์ ์ผ์ ํ๋ค๋ ๊ฒ์ ๋ปํฉ๋๋ค. ํจ์๋ ํ ๊ฐ์ง์ ์ผ์ ํด์ผํฉ๋๋ค. boolean ๋ณ์๋ก ์ธํด ๋ค๋ฅธ ์ฝ๋๊ฐ ์คํ๋๋ค๋ฉด ๊ทธ ํจ์๋ฅผ ์ชผ๊ฐ๋๋ก ํ์ธ์.
Bad:
function createFile(name: string, temp: boolean) {
if (temp) {
fs.create(`./temp/${name}`);
} else {
fs.create(name);
}
}
Good:
function createTempFile(name: string) {
createFile(`./temp/${name}`);
}
function createFile(name: string) {
fs.create(name);
}
ํจ์๋ ๊ฐ์ ๊ฐ์ ธ์์ ๋ค๋ฅธ ๊ฐ์ ๋ฐํํ๋ ๊ฒ ์ด์ธ์ ๋ค๋ฅธ ๊ฒ์ ํ ๊ฒฝ์ฐ ์ฌ์ด๋ ์ดํํธ๋ฅผ ๋ฐ์์ํฌ ์ ์์ต๋๋ค. ์ฌ์ด๋ ์ดํํธ๋ ํ์ผ์ ์ด๋ค๊ฑฐ๋, ์ ์ญ ๋ณ์๋ฅผ ์กฐ์ํ๋ค๊ฑฐ๋, ๋ปํ์ง ์๊ฒ ๋ฏ์ ์ฌ๋์๊ฒ ๋น์ ์ ์ ์ฌ์ฐ์ ์ก๊ธํ ์ ์์ต๋๋ค.
๋น์ ์ ๊ฐ๋ ํ๋ก๊ทธ๋จ์์ ์ฌ์ด๋ ์ดํํธ๋ฅผ ๊ฐ์ง ํ์๊ฐ ์์ต๋๋ค. ์ด์ ์ ์ฌ๋ก์์์ ๊ฐ์ด ๋น์ ์ ํ์ผ์ ์จ์ผํ ๋๊ฐ ์์ต๋๋ค. ๋น์ ์ด ํ๊ณ ์ถ์ ๊ฒ์ ์ด๊ฒ์ ํ๋ ๊ณณ์ ์ค์ํํ๋ ๊ฒ์ ๋๋ค. ํน์ ํ์ผ์ ์ฐ๊ธฐ ์ํด ๋ช ๊ฐ์ ํจ์์ ํด๋์ค๋ฅผ ๋ง๋ค์ง ๋ง์ธ์. ๊ทธ๊ฒ์ ํํ๋ ์๋น์ค๋ฅผ ํ๋๋ง ๋ง๋์ธ์. ์ค์ง ํ๋์ ๋๋ค.
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.
let name = 'Robert C. Martin';
function toBase64() {
name = btoa(name);
}
toBase64();
// If we had another function that used this name, now it'd be a Base64 value
console.log(name); // expected to print 'Robert C. Martin' but instead 'Um9iZXJ0IEMuIE1hcnRpbg=='
Good:
const name = 'Robert C. Martin';
function toBase64(text: string): string {
return btoa(text);
}
const encodedName = toBase64(name);
console.log(name);
In JavaScript, primitives are passed by value and objects/arrays are passed by reference. In the case of objects and arrays, if your function makes a change in a shopping cart array, for example, by adding an item to purchase, then any other function that uses that cart
array will be affected by this addition. That may be great, however it can be bad too. Let's imagine a bad situation:
The user clicks the "Purchase", button which calls 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 "Add to Cart" button on an item they don't actually want before the network request begins? If that happens and the network request begins, then that purchase function will send the accidentally added item because it has a reference to a shopping cart array that the addItemToCart
function modified by adding an unwanted item.
A great solution would be for the addItemToCart
to always clone the cart
, edit it, and return the clone. This ensures that no other functions that are holding onto a reference of the shopping cart will be affected by any changes.
Two caveats to mention to this approach:
-
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! (see pure function)
-
Cloning big objects can be very expensive in terms of performance. Luckily, this isn't a big issue in practice because there are great libraries that allow this kind of programming approach to be fast and not as memory intensive as it would be for you to manually clone objects and arrays.
Bad:
function addItemToCart(cart: CartItem[], item: Item): void {
cart.push({ item, date: Date.now() });
};
Good:
function addItemToCart(cart: CartItem[], item: Item): CartItem[] {
return [...cart, { item, date: Date.now() }];
};
Polluting globals is a bad practice in JavaScript because you could clash with another library and the user of your API would be none-the-wiser until they get an exception in production. Let's think about an example: what if you wanted to extend JavaScript's native Array method to have 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 classes and simply extend the Array
global.
Bad:
declare global {
interface Array<T> {
diff(other: T[]): Array<T>;
}
}
if (!Array.prototype.diff) {
Array.prototype.diff = function <T>(other: T[]): T[] {
const hash = new Set(other);
return this.filter(elem => !hash.has(elem));
};
}
Good:
class MyArray<T> extends Array<T> {
diff(other: T[]): T[] {
const hash = new Set(other);
return this.filter(elem => !hash.has(elem));
};
}
๊ฐ๋ฅํ๋ค๋ฉด ์ด๋ฐ ๋ฐฉ์์ ํ๋ก๊ทธ๋๋ฐ์ ์งํฅํ์ธ์.
Bad:
const contributions = [
{
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 < contributions.length; i++) {
totalOutput += contributions[i].linesOfCode;
}
Good:
const contributions = [
{
name: 'Uncle Bobby',
linesOfCode: 500
}, {
name: 'Suzie Q',
linesOfCode: 1500
}, {
name: 'Jimmy Gosling',
linesOfCode: 150
}, {
name: 'Gracie Hopper',
linesOfCode: 1000
}
];
const totalOutput = contributions
.reduce((totalLines, output) => totalLines + output.linesOfCode, 0);
Bad:
if (subscription.isTrial || account.balance > 0) {
// ...
}
Good:
function canActivateService(subscription: Subscription, account: Account) {
return subscription.isTrial || account.balance > 0;
}
if (canActivateService(subscription, account)) {
// ...
}
Bad:
function isEmailNotUsed(email: string): boolean {
// ...
}
if (isEmailNotUsed(email)) {
// ...
}
Good:
function isEmailUsed(email): boolean {
// ...
}
if (!isEmailUsed(node)) {
// ...
}
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.
Bad:
class Airplane {
private type: string;
// ...
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();
default:
throw new Error('Unknown airplane type.');
}
}
private getMaxAltitude(): number {
// ...
}
}
Good:
abstract class Airplane {
protected getMaxAltitude(): number {
// shared logic with subclasses ...
}
// ...
}
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();
}
}
TypeScript is a strict syntactical superset of JavaScript and adds optional static type checking to the language. Always prefer to specify types of variables, parameters and return values to leverage the full power of TypeScript features. It makes refactoring more easier.
Bad:
function travelToTexas(vehicle: Bicycle | Car) {
if (vehicle instanceof Bicycle) {
vehicle.pedal(currentLocation, new Location('texas'));
} else if (vehicle instanceof Car) {
vehicle.drive(currentLocation, new Location('texas'));
}
}
Good:
type Vehicle = Bicycle | Car;
function travelToTexas(vehicle: Vehicle) {
vehicle.move(currentLocation, new Location('texas'));
}
Modern browsers do a lot of optimization under-the-hood at runtime. A lot of times, if you are optimizing then you are just wasting your time. There are 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.
for (let i = 0, len = list.length; i < len; i++) {
// ...
}
Good:
for (let i = 0; i < list.length; i++) {
// ...
}
Dead code is just as bad as duplicate code. There's no reason to keep it in your codebase. If it's not being called, get rid of it! It will still be safe in your version history if you still need it.
Bad:
function oldRequestModule(url: string) {
// ...
}
function requestModule(url: string) {
// ...
}
const req = requestModule;
inventoryTracker('apples', req, 'www.inventory-awesome.io');
Good:
function requestModule(url: string) {
// ...
}
const req = requestModule;
inventoryTracker('apples', req, 'www.inventory-awesome.io');
Use generators and iterables when working with collections of data used like a stream.
There are some good reasons:
- decouples the callee from the generator implementation in a sense that callee decides how many items to access
- lazy execution, items are streamed on demand
- built-in support for iterating items using the
for-of
syntax - iterables allow to implement optimized iterator patterns
Bad:
function fibonacci(n: number): number[] {
if (n === 1) return [0];
if (n === 2) return [0, 1];
const items: number[] = [0, 1];
while (items.length < n) {
items.push(items[items.length - 2] + items[items.length - 1]);
}
return items;
}
function print(n: number) {
fibonacci(n).forEach(fib => console.log(fib));
}
// Print first 10 Fibonacci numbers.
print(10);
Good:
// Generates an infinite stream of Fibonacci numbers.
// The generator doesn't keep the array of all numbers.
function* fibonacci(): IterableIterator<number> {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
function print(n: number) {
let i = 0;
for (const fib of fibonacci()) {
if (i++ === n) break;
console.log(fib);
}
}
// Print first 10 Fibonacci numbers.
print(10);
There are libraries that allow working with iterables in a similar way as with native arrays, by
chaining methods like map
, slice
, forEach
etc. See itiriri for
an example of advanced manipulation with iterables (or itiriri-async for manipulation of async iterables).
import itiriri from 'itiriri';
function* fibonacci(): IterableIterator<number> {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
itiriri(fibonacci())
.take(10)
.forEach(fib => console.log(fib));
TypeScript supports getter/setter syntax. Using getters and setters to access data from objects that encapsulate behavior could be better than simply looking for a property on an object. "Why?" you might ask. Well, here's a list of reasons:
- When you want to do more beyond getting an object property, you don't have to look up and change every accessor in your codebase.
- Makes adding validation simple when doing a
set
. - Encapsulates the internal representation.
- Easy to add logging and error handling when getting and setting.
- You can lazy load your object's properties, let's say getting it from a server.
Bad:
type BankAccount = {
balance: number;
// ...
}
const value = 100;
const account: BankAccount = {
balance: 0,
// ...
};
if (value < 0) {
throw new Error('Cannot set negative balance.');
}
account.balance = value;
Good:
class BankAccount {
private accountBalance: number = 0;
get balance(): number {
return this.accountBalance;
}
set balance(value: number) {
if (value < 0) {
throw new Error('Cannot set negative balance.');
}
this.accountBalance = value;
}
// ...
}
// Now `BankAccount` encapsulates the validation logic.
// If one day the specifications change, and we need extra validation rule,
// we would have to alter only the `setter` implementation,
// leaving all dependent code unchanged.
const account = new BankAccount();
account.balance = 100;
TypeScript supports public
(default), protected
and private
accessors on class members.
Bad:
class Circle {
radius: number;
constructor(radius: number) {
this.radius = radius;
}
perimeter() {
return 2 * Math.PI * this.radius;
}
surface() {
return Math.PI * this.radius * this.radius;
}
}
Good:
class Circle {
constructor(private readonly radius: number) {
}
perimeter() {
return 2 * Math.PI * this.radius;
}
surface() {
return Math.PI * this.radius * this.radius;
}
}
TypeScript's type system allows you to mark individual properties on an interface / class as readonly. This allows you to work in a functional way (unexpected mutation is bad).
For more advanced scenarios there is a built-in type Readonly
that takes a type T
and marks all of its properties as readonly using mapped types (see mapped types).
Bad:
interface Config {
host: string;
port: string;
db: string;
}
Good:
interface Config {
readonly host: string;
readonly port: string;
readonly db: string;
}
Case of Array, you can create a read-only array by using ReadonlyArray<T>
.
do not allow changes such as push()
and fill()
, but can use features such as concat()
and slice()
that do not change the value.
Bad:
const array: number[] = [ 1, 3, 5 ];
array = []; // error
array.push(100); // array will updated
Good:
const array: ReadonlyArray<number> = [ 1, 3, 5 ];
array = []; // error
array.push(100); // error
Declaring read-only arguments in TypeScript 3.4 is a bit easier.
function hoge(args: readonly string[]) {
args.push(1); // error
}
Prefer const assertions for literal values.
Bad:
const config = {
hello: 'world'
};
config.hello = 'world'; // value is changed
const array = [ 1, 3, 5 ];
array[0] = 10; // value is changed
// writable objects is returned
function readonlyData(value: number) {
return { value };
}
const result = readonlyData(100);
result.value = 200; // value is changed
Good:
// read-only object
const config = {
hello: 'world'
} as const;
config.hello = 'world'; // error
// read-only array
const array = [ 1, 3, 5 ] as const;
array[0] = 10; // error
// You can return read-only objects
function readonlyData(value: number) {
return { value } as const;
}
const result = readonlyData(100);
result.value = 200; // error
Use type when you might need a union or intersection. Use interface when you want extends
or implements
. There is no strict rule however, use the one that works for you.
For a more detailed explanation refer to this answer about the differences between type
and interface
in TypeScript.
Bad:
interface EmailConfig {
// ...
}
interface DbConfig {
// ...
}
interface Config {
// ...
}
//...
type Shape = {
// ...
}
Good:
type EmailConfig = {
// ...
}
type DbConfig = {
// ...
}
type Config = EmailConfig | DbConfig;
// ...
interface Shape {
// ...
}
class Circle implements Shape {
// ...
}
class Square implements Shape {
// ...
}
The class' size is measured by its responsibility. Following the Single Responsibility principle a class should be small.
Bad:
class Dashboard {
getLanguage(): string { /* ... */ }
setLanguage(language: string): void { /* ... */ }
showProgress(): void { /* ... */ }
hideProgress(): void { /* ... */ }
isDirty(): boolean { /* ... */ }
disable(): void { /* ... */ }
enable(): void { /* ... */ }
addSubscription(subscription: Subscription): void { /* ... */ }
removeSubscription(subscription: Subscription): void { /* ... */ }
addUser(user: User): void { /* ... */ }
removeUser(user: User): void { /* ... */ }
goToHomePage(): void { /* ... */ }
updateProfile(details: UserDetails): void { /* ... */ }
getVersion(): string { /* ... */ }
// ...
}
Good:
class Dashboard {
disable(): void { /* ... */ }
enable(): void { /* ... */ }
getVersion(): string { /* ... */ }
}
// split the responsibilities by moving the remaining methods to other classes
// ...
Cohesion defines the degree to which class members are related to each other. Ideally, all fields within a class should be used by each method. We then say that the class is maximally cohesive. In practice, this however is not always possible, nor even advisable. You should however prefer cohesion to be high.
Coupling refers to how related or dependent are two classes toward each other. Classes are said to be low coupled if changes in one of them doesn't affect the other one.
Good software design has high cohesion and low coupling.
Bad:
class UserManager {
// Bad: each private variable is used by one or another group of methods.
// It makes clear evidence that the class is holding more than a single responsibility.
// If I need only to create the service to get the transactions for a user,
// I'm still forced to pass and instance of `emailSender`.
constructor(
private readonly db: Database,
private readonly emailSender: EmailSender) {
}
async getUser(id: number): Promise<User> {
return await db.users.findOne({ id });
}
async getTransactions(userId: number): Promise<Transaction[]> {
return await db.transactions.find({ userId });
}
async sendGreeting(): Promise<void> {
await emailSender.send('Welcome!');
}
async sendNotification(text: string): Promise<void> {
await emailSender.send(text);
}
async sendNewsletter(): Promise<void> {
// ...
}
}
Good:
class UserService {
constructor(private readonly db: Database) {
}
async getUser(id: number): Promise<User> {
return await this.db.users.findOne({ id });
}
async getTransactions(userId: number): Promise<Transaction[]> {
return await this.db.transactions.find({ userId });
}
}
class UserNotifier {
constructor(private readonly emailSender: EmailSender) {
}
async sendGreeting(): Promise<void> {
await this.emailSender.send('Welcome!');
}
async sendNotification(text: string): Promise<void> {
await this.emailSender.send(text);
}
async sendNewsletter(): Promise<void> {
// ...
}
}
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.
You might be wondering then, "when should I use inheritance?" It depends on your problem at hand, but this is a decent list of when inheritance makes more sense than composition:
-
Your inheritance represents an "is-a" relationship and not a "has-a" relationship (Human->Animal vs. User->UserDetails).
-
You can reuse code from the base classes (Humans can move like all animals).
-
You want to make global changes to derived classes by changing a base class. (Change the caloric expenditure of all animals when they move).
Bad:
class Employee {
constructor(
private readonly name: string,
private readonly email: string) {
}
// ...
}
// Bad because Employees "have" tax data. EmployeeTaxData is not a type of Employee
class EmployeeTaxData extends Employee {
constructor(
name: string,
email: string,
private readonly ssn: string,
private readonly salary: number) {
super(name, email);
}
// ...
}
Good:
class Employee {
private taxData: EmployeeTaxData;
constructor(
private readonly name: string,
private readonly email: string) {
}
setTaxData(ssn: string, salary: number): Employee {
this.taxData = new EmployeeTaxData(ssn, salary);
return this;
}
// ...
}
class EmployeeTaxData {
constructor(
public readonly ssn: string,
public readonly salary: number) {
}
// ...
}
This pattern is very useful and commonly used in many libraries. It allows your code to be expressive, and less verbose. For that reason, use method chaining and take a look at how clean your code will be.
Bad:
class QueryBuilder {
private collection: string;
private pageNumber: number = 1;
private itemsPerPage: number = 100;
private orderByFields: string[] = [];
from(collection: string): void {
this.collection = collection;
}
page(number: number, itemsPerPage: number = 100): void {
this.pageNumber = number;
this.itemsPerPage = itemsPerPage;
}
orderBy(...fields: string[]): void {
this.orderByFields = fields;
}
build(): Query {
// ...
}
}
// ...
const queryBuilder = new QueryBuilder();
queryBuilder.from('users');
queryBuilder.page(1, 100);
queryBuilder.orderBy('firstName', 'lastName');
const query = queryBuilder.build();
Good:
class QueryBuilder {
private collection: string;
private pageNumber: number = 1;
private itemsPerPage: number = 100;
private orderByFields: string[] = [];
from(collection: string): this {
this.collection = collection;
return this;
}
page(number: number, itemsPerPage: number = 100): this {
this.pageNumber = number;
this.itemsPerPage = itemsPerPage;
return this;
}
orderBy(...fields: string[]): this {
this.orderByFields = fields;
return this;
}
build(): Query {
// ...
}
}
// ...
const query = new QueryBuilder()
.from('users')
.page(1, 100)
.orderBy('firstName', 'lastName')
.build();
As stated in Clean Code, "There should never be more than one reason for a class to change". It's tempting to jam-pack a class with a lot of functionality, like when you can only take one suitcase on your flight. The issue with this is that your class won't be conceptually cohesive and it will give it many reasons to change. Minimizing the amount of times you need to change a class is important. It's important because if too much functionality is in one class and you modify a piece of it, it can be difficult to understand how that will affect other dependent modules in your codebase.
Bad:
class UserSettings {
constructor(private readonly user: User) {
}
changeSettings(settings: UserSettings) {
if (this.verifyCredentials()) {
// ...
}
}
verifyCredentials() {
// ...
}
}
Good:
class UserAuth {
constructor(private readonly user: User) {
}
verifyCredentials() {
// ...
}
}
class UserSettings {
private readonly auth: UserAuth;
constructor(private readonly user: User) {
this.auth = new UserAuth(user);
}
changeSettings(settings: UserSettings) {
if (this.auth.verifyCredentials()) {
// ...
}
}
}
As stated by Bertrand Meyer, "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification." What does that mean though? This principle basically states that you should allow users to add new functionalities without changing existing code.
Bad:
class AjaxAdapter extends Adapter {
constructor() {
super();
}
// ...
}
class NodeAdapter extends Adapter {
constructor() {
super();
}
// ...
}
class HttpRequester {
constructor(private readonly adapter: Adapter) {
}
async fetch<T>(url: string): Promise<T> {
if (this.adapter instanceof AjaxAdapter) {
const response = await makeAjaxCall<T>(url);
// transform response and return
} else if (this.adapter instanceof NodeAdapter) {
const response = await makeHttpCall<T>(url);
// transform response and return
}
}
}
function makeAjaxCall<T>(url: string): Promise<T> {
// request and return promise
}
function makeHttpCall<T>(url: string): Promise<T> {
// request and return promise
}
Good:
abstract class Adapter {
abstract async request<T>(url: string): Promise<T>;
// code shared to subclasses ...
}
class AjaxAdapter extends Adapter {
constructor() {
super();
}
async request<T>(url: string): Promise<T>{
// request and return promise
}
// ...
}
class NodeAdapter extends Adapter {
constructor() {
super();
}
async request<T>(url: string): Promise<T>{
// request and return promise
}
// ...
}
class HttpRequester {
constructor(private readonly adapter: Adapter) {
}
async fetch<T>(url: string): Promise<T> {
const response = await this.adapter.request<T>(url);
// transform response and return
}
}
This is a scary term for a very simple concept. It's formally defined as "If S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.)." That's an even scarier definition.
The best explanation for this is if you have a parent class and a child class, then the parent class and child class can be used interchangeably without getting incorrect results. This might still be confusing, so let's take a look at the classic Square-Rectangle example. Mathematically, a square is a rectangle, but if you model it using the "is-a" relationship via inheritance, you quickly get into trouble.
Bad:
class Rectangle {
constructor(
protected width: number = 0,
protected height: number = 0) {
}
setColor(color: string): this {
// ...
}
render(area: number) {
// ...
}
setWidth(width: number): this {
this.width = width;
return this;
}
setHeight(height: number): this {
this.height = height;
return this;
}
getArea(): number {
return this.width * this.height;
}
}
class Square extends Rectangle {
setWidth(width: number): this {
this.width = width;
this.height = width;
return this;
}
setHeight(height: number): this {
this.width = height;
this.height = height;
return this;
}
}
function renderLargeRectangles(rectangles: Rectangle[]) {
rectangles.forEach((rectangle) => {
const area = rectangle
.setWidth(4)
.setHeight(5)
.getArea(); // BAD: Returns 25 for Square. Should be 20.
rectangle.render(area);
});
}
const rectangles = [new Rectangle(), new Rectangle(), new Square()];
renderLargeRectangles(rectangles);
Good:
abstract class Shape {
setColor(color: string): this {
// ...
}
render(area: number) {
// ...
}
abstract getArea(): number;
}
class Rectangle extends Shape {
constructor(
private readonly width = 0,
private readonly height = 0) {
super();
}
getArea(): number {
return this.width * this.height;
}
}
class Square extends Shape {
constructor(private readonly length: number) {
super();
}
getArea(): number {
return this.length * this.length;
}
}
function renderLargeShapes(shapes: Shape[]) {
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);
ISP states that "Clients should not be forced to depend upon interfaces that they do not use.". This principle is very much related to the Single Responsibility Principle. What it really means is that you should always design your abstractions in a way that the clients that are using the exposed methods do not get the whole pie instead. That also include imposing the clients with the burden of implementing methods that they donโt actually need.
Bad:
interface SmartPrinter {
print();
fax();
scan();
}
class AllInOnePrinter implements SmartPrinter {
print() {
// ...
}
fax() {
// ...
}
scan() {
// ...
}
}
class EconomicPrinter implements SmartPrinter {
print() {
// ...
}
fax() {
throw new Error('Fax not supported.');
}
scan() {
throw new Error('Scan not supported.');
}
}
Good:
interface Printer {
print();
}
interface Fax {
fax();
}
interface Scanner {
scan();
}
class AllInOnePrinter implements Printer, Fax, Scanner {
print() {
// ...
}
fax() {
// ...
}
scan() {
// ...
}
}
class EconomicPrinter implements Printer {
print() {
// ...
}
}
This principle states two essential things:
-
High-level modules should not depend on low-level modules. Both should depend on abstractions.
-
Abstractions should not depend upon details. Details should depend on abstractions.
This can be hard to understand at first, but if you've worked with Angular, you've seen an implementation of this principle in the form of Dependency Injection (DI). While they are not identical concepts, DIP keeps high-level modules from knowing the details of its low-level modules and setting them up. It can accomplish this through DI. A huge benefit of this is that it reduces the coupling between modules. Coupling is a very bad development pattern because it makes your code hard to refactor.
DIP is usually achieved by a using an inversion of control (IoC) container. An example of a powerful IoC container for TypeScript is InversifyJs
Bad:
import { readFile as readFileCb } from 'fs';
import { promisify } from 'util';
const readFile = promisify(readFileCb);
type ReportData = {
// ..
}
class XmlFormatter {
parse<T>(content: string): T {
// Converts an XML string to an object T
}
}
class ReportReader {
// BAD: We have created a dependency on a specific request implementation.
// We should just have ReportReader depend on a parse method: `parse`
private readonly formatter = new XmlFormatter();
async read(path: string): Promise<ReportData> {
const text = await readFile(path, 'UTF8');
return this.formatter.parse<ReportData>(text);
}
}
// ...
const reader = new ReportReader();
await report = await reader.read('report.xml');
Good:
import { readFile as readFileCb } from 'fs';
import { promisify } from 'util';
const readFile = promisify(readFileCb);
type ReportData = {
// ..
}
interface Formatter {
parse<T>(content: string): T;
}
class XmlFormatter implements Formatter {
parse<T>(content: string): T {
// Converts an XML string to an object T
}
}
class JsonFormatter implements Formatter {
parse<T>(content: string): T {
// Converts a JSON string to an object T
}
}
class ReportReader {
constructor(private readonly formatter: Formatter) {
}
async read(path: string): Promise<ReportData> {
const text = await readFile(path, 'UTF8');
return this.formatter.parse<ReportData>(text);
}
}
// ...
const reader = new ReportReader(new XmlFormatter());
await report = await reader.read('report.xml');
// or if we had to read a json report
const reader = new ReportReader(new JsonFormatter());
await report = await reader.read('report.json');
ํ ์คํธ๋ ๋ฐฐํฌ๋ณด๋ค ์ค์ํฉ๋๋ค. ํ ์คํธ๊ฐ ์๊ฑฐ๋ ๋ถ์กฑํ ๊ฒฝ์ฐ, ์ฝ๋๋ฅผ ๋ฐฐํฌํ ๋๋ง๋ค ๋น์ ์ ์ด๋ค ๊ฒ์ด ์๋ํ์ง ์์์ง ํ์คํ์ง ์์ ๊ฒ์ ๋๋ค. ์ ์ ํ ์์ ํ ์คํธ๋ฅผ ๊ตฌ์ฑํ๋ ๊ฒ์ ๋น์ ์ ํ์๊ฒ ๋ฌ๋ ค์์ง๋ง, (๋ชจ๋ ๋ฌธ์ฅ๊ณผ ๋ธ๋์น์์) 100%์ ์ปค๋ฒ๋ฆฌ์ง๋ฅผ ๊ฐ์ง๋ค๋ฉด ๋งค์ฐ ๋์ ์์ ๊ฐ๊ณผ ๋ง์์ ํํ๋ฅผ ์ป์ ๊ฒ์ ๋๋ค. ์ด๋ ํ๋ฅญํ ํ ์คํธ ํ๋ ์์ํฌ๋ฟ๋ง ์๋๋ผ, ์ข์ ์ปค๋ฒ๋ฆฌ์ง ๋๊ตฌ๋ฅผ ์ฌ์ฉํด์ผ ํ๋ค๋ ๊ฒ์ ์๋ฏธํฉ๋๋ค.
ํ ์คํธ๋ฅผ ์์ฑํ์ง ์์ ๋ณ๋ช ์ ์์ต๋๋ค. ํ์ ์คํฌ๋ฆฝํธ์ ํ์ ์ ์ง์ํ๋ ๋ง์ ์์ ์ข์ ์๋ฐ์คํฌ๋ฆฝํธ ํ ์คํธ ํ๋ ์์ํฌ๊ฐ ์์ผ๋ฏ๋ก ๋น์ ์ ํ์ด ์ ํธํ๋ ๊ฒ์ ์ฐพ์ ์ฌ์ฉํ์ธ์. ๋น์ ์ ํ์ ์ ํฉํ ํ ์คํธ ํ๋ ์์ํฌ๋ฅผ ์ฐพ์๋ค๋ฉด, ๋น์ ์ด ๋ง๋๋ ๋ชจ๋ ์๋ก์ด ๊ธฐ๋ฅ/๋ชจ๋์ ์ํ ํ ์คํธ๋ฅผ ํญ์ ์์ฑํ๋ ๊ฒ์ ๋ชฉํ๋ก ํ์ธ์. ํ ์คํธ ๊ธฐ๋ฐ ๊ฐ๋ฐ(TDD)์ด ๋น์ ์ด ์ ํธํ๋ ๋ฐฉ๋ฒ์ด๋ผ๋ฉด, ๋งค์ฐ ์ข์ต๋๋ค. ํ์ง๋ง ์ค์ํ ๊ฑด ์ด๋ค ๊ธฐ๋ฅ์ ๋ง๋ค๊ฑฐ๋ ๊ธฐ์กด์ ๊ฒ์ ๋ฆฌํฉํ ๋งํ๊ธฐ ์ ์ ๋ชฉํํ๋ ์ปค๋ฒ๋ฆฌ์ง๋ฅผ ๋ฌ์ฑํ๋ ๊ฒ์ ๋๋ค.
-
์คํจํ๋ ๋จ์ ํ ์คํธ๋ฅผ ์์ฑํ๊ธฐ ์ ์๋ ์ค์ ์ฝ๋๋ฅผ ์์ฑํ์ง ๋ง์ธ์.
-
์ปดํ์ผ์ ์คํจํ์ง ์์ผ๋ฉด์ ์คํ์ด ์คํจํ๋ ์ ๋๋ก๋ง ๋จ์ ํ ์คํธ๋ฅผ ์์ฑํ์ธ์.
-
์คํจํ๋ ๋จ์ ํ ์คํธ๋ฅผ ํต๊ณผํ ์ ๋๋ก๋ง ์ค์ ์ฝ๋๋ฅผ ์์ฑํ์ธ์.
๋ช ๋ฃํ ํ ์คํธ๋ ๋ค์ ๊ท์น์ ๋ฐ๋ผ์ผ ํฉ๋๋ค:
-
Fast ํ ์คํธ๋ ๋น๋ฒํ๊ฒ ์คํ๋๋ฏ๋ก ๋นจ๋ผ์ผ ํฉ๋๋ค.
-
Independent ํ ์คํธ๋ ์๋ก ์ข ์์ ์ด์ง ์์ต๋๋ค. ๋ ๋ฆฝ์ ์ผ๋ก ์คํํ๋ ์ง ์์ ์๊ด์์ด ๋ชจ๋ ์คํํ๋ ์ง ๋์ผํ ๊ฒฐ๊ณผ๊ฐ ๋์์ผ ํฉ๋๋ค.
-
Repeatable ํ ์คํธ๋ ์ด๋ค ํ๊ฒฝ์์๋ ๋ฐ๋ณต๋ ์ ์์ต๋๋ค. ํ ์คํธ๊ฐ ์คํจํ๋๋ฐ์ ๋ณ๋ช ์ด ์์ด์ผ ํฉ๋๋ค.
-
Self-Validating ํ ์คํธ๋ ํต๊ณผ ํน์ ์คํจ๋ก ๋ตํด์ผ ํฉ๋๋ค. ํ ์คํธ๊ฐ ํต๊ณผ๋์๋ค๋ฉด ๋ก๊ทธ ํ์ผ์ ๋ณด๋ฉฐ ๋น๊ตํ ํ์๋ ์์ต๋๋ค.
-
Timely ๋จ์ ํ ์คํธ๋ ์ค์ ์ฝ๋๋ฅผ ์์ฑํ๊ธฐ ์ ์ ์์ฑํด์ผ ํฉ๋๋ค. ์ค์ ์ฝ๋๋ฅผ ์์ฑํ ํ์ ํ ์คํธ๋ฅผ ์์ฑํ๋ค๋ฉด, ํ ์คํธ๋ฅผ ์์ฑํ๋ ๊ฒ์ด ๋๋ฌด ๊ณ ๋จํ๊ฒ ๋๊ปด์ง ๊ฒ์ ๋๋ค.
๋ํ, ํ ์คํธ๋ ๋จ์ผ ์ฑ ์ ์์น์ ๋ฐ๋ผ์ผ ํฉ๋๋ค. ๋จ์ ํ ์คํธ ํ๋๋น ํ๋์ assert ๊ตฌ๋ฌธ์ ์์ฑํ์ธ์.
Bad:
import { assert } from 'chai';
describe('AwesomeDate', () => {
it('handles date boundaries', () => {
let date: AwesomeDate;
date = new AwesomeDate('1/1/2015');
assert.equal('1/31/2015', date.addDays(30));
date = new AwesomeDate('2/1/2016');
assert.equal('2/29/2016', date.addDays(28));
date = new AwesomeDate('2/1/2015');
assert.equal('3/1/2015', date.addDays(28));
});
});
Good:
import { assert } from 'chai';
describe('AwesomeDate', () => {
it('handles 30-day months', () => {
const date = new AwesomeDate('1/1/2015');
assert.equal('1/31/2015', date.addDays(30));
});
it('handles leap year', () => {
const date = new AwesomeDate('2/1/2016');
assert.equal('2/29/2016', date.addDays(28));
});
it('handles non-leap year', () => {
const date = new AwesomeDate('2/1/2015');
assert.equal('3/1/2015', date.addDays(28));
});
});
ํ ์คํธ๊ฐ ์คํจํ ๋, ํ ์คํธ์ ์ด๋ฆ์ ์ด๋ค ๊ฒ์ด ์๋ชป๋์๋์ง ๋ณผ ์ ์๋ ์ฒซ ๋ฒ์งธ ํ์์ ๋๋ค.
Bad:
describe('Calendar', () => {
it('2/29/2020', () => {
// ...
});
it('throws', () => {
// ...
});
});
Good:
describe('Calendar', () => {
it('should handle leap year', () => {
// ...
});
it('should throw when format is invalid', () => {
// ...
});
});
์ฝ๋ฐฑ์ ๋ช
๋ฃํ์ง ์๊ณ , ์ง๋์น ์์ ์ค์ฒฉ๋ ์ฝ๋ฐฑ ์ง์ฅ์ ์ ๋ฐํ ์ ์์ต๋๋ค.
์ฝ๋ฐฑ ๋ฐฉ์์ ์ฌ์ฉํ๊ณ ์๋ ๊ธฐ์กด์ ํจ์๋ฅผ ํ๋ก๋ฏธ์ค๋ฅผ ๋ฐํํ๋ ํจ์๋ก ๋ณํ์์ผ์ฃผ๋ ์ ํธ๋ฆฌํฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๊ฐ ์์ต๋๋ค.
(Node.js๋ฅผ ์ฌ์ฉํ๋ค๋ฉด util.promisify
๋ฅผ ํ์ธํด์ฃผ์ธ์. ์ผ๋ฐ์ ์ธ ๋ชฉ์ ์ด๋ผ๋ฉด pify, es6-promisify๋ฅผ ํ์ธํด์ฃผ์ธ์.)
Bad:
import { get } from 'request';
import { writeFile } from 'fs';
function downloadPage(url: string, saveTo: string, callback: (error: Error, content?: string) => void) {
get(url, (error, response) => {
if (error) {
callback(error);
} else {
writeFile(saveTo, response.body, (error) => {
if (error) {
callback(error);
} else {
callback(null, response.body);
}
});
}
});
}
downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html', (error, content) => {
if (error) {
console.error(error);
} else {
console.log(content);
}
});
Good:
import { get } from 'request';
import { writeFile } from 'fs';
import { promisify } from 'util';
const write = promisify(writeFile);
function downloadPage(url: string, saveTo: string): Promise<string> {
return get(url)
.then(response => write(saveTo, response));
}
downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html')
.then(content => console.log(content))
.catch(error => console.error(error));
ํ๋ก๋ฏธ์ค๋ ์ฝ๋๋ฅผ ๋์ฑ ๊ฐ๊ฒฐํ๊ฒ ํด์ฃผ๋ ๋ช๋ช์ ํฌํผ ๋ฉ์๋๋ฅผ ์ง์ํฉ๋๋ค:
ํจํด | ์ค๋ช |
---|---|
Promise.resolve(value) |
ํด๊ฒฐ(resolve)๋ ํ๋ก๋ฏธ์ค๋ก ๊ฐ์ ๋ณํํจ. |
Promise.reject(error) |
๊ฑฐ๋ถ(reject)๋ ํ๋ก๋ฏธ์ค๋ก ์๋ฌ๋ฅผ ๋ณํํจ. |
Promise.all(promises) |
์ ๋ฌ๋ ๋ชจ๋ ํ๋ก๋ฏธ์ค๊ฐ ์ดํํ ๊ฐ์ ๋ฐฐ์ด์ ์ดํํ๋ ์ ํ๋ก๋ฏธ์ค ๊ฐ์ฒด๋ฅผ ๋ฐํํ๊ฑฐ๋ ๊ฑฐ๋ถ๋ ์ฒซ ๋ฒ์งธ ํ๋ก๋ฏธ์ค์ ์ด์ ๋ก ๊ฑฐ๋ถํจ. |
Promise.race(promises) |
์ ๋ฌ๋ ํ๋ก๋ฏธ์ค์ ๋ฐฐ์ด์์ ๊ฐ์ฅ ๋จผ์ ์๋ฃ๋ ๊ฒฐ๊ณผ/์๋ฌ๋ก ์ดํ/๊ฑฐ๋ถ๋ ์ ํ๋ก๋ฏธ์ค ๊ฐ์ฒด๋ฅผ ๋ฐํํจ. |
Promise.all
๋ ๋ณ๋ ฌ์ ์ผ๋ก ์์
์ ์ํํ ํ์๊ฐ ์์ ๋ ์ ์ฉํฉ๋๋ค. Promise.race
๋ ํ๋ก๋ฏธ์ค๋ฅผ ์ํ ํ์์์๊ณผ ๊ฐ์ ๊ฒ์ ๊ตฌํํ๋ ๊ฒ์ ์ฝ๊ฒ ํ ์ ์๋๋ก ๋์์ค๋๋ค.
With async
/await
syntax you can write code that is far cleaner and more understandable than chained promises. Within a function prefixed with async
keyword you have a way to tell the JavaScript runtime to pause the execution of code on the await
keyword (when used on a promise).
async
/await
๊ตฌ๋ฌธ์ ์ฌ์ฉํ๋ฉด ์ฐ๊ฒฐ๋ ํ๋ก๋ฏธ์ค ๊ตฌ๋ฌธ๋ณด๋ค ํจ์ฌ ๋ ๋ช
๋ฃํ๊ณ ์ดํดํ๊ธฐ ์ฌ์ด ์ฝ๋๋ฅผ ์์ฑํ ์ ์์ต๋๋ค. async
ํค์๋๊ฐ ์์ ๋ถ์ฌ์ง ํจ์๋ await
ํค์๋์์ ์ฝ๋์ ์คํ์ ๋ฉ์ถ๋ค๋ ๊ฒ์ ์๋ฐ์คํฌ๋ฆฝํธ ๋ฐํ์์๊ฒ ์๋ ค์ค๋๋ค.
Bad:
import { get } from 'request';
import { writeFile } from 'fs';
import { promisify } from 'util';
const write = util.promisify(writeFile);
function downloadPage(url: string, saveTo: string): Promise<string> {
return get(url).then(response => write(saveTo, response));
}
downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html')
.then(content => console.log(content))
.catch(error => console.error(error));
Good:
import { get } from 'request';
import { writeFile } from 'fs';
import { promisify } from 'util';
const write = promisify(writeFile);
async function downloadPage(url: string, saveTo: string): Promise<string> {
const response = await get(url);
await write(saveTo, response);
return response;
}
// somewhere in an async function
try {
const content = await downloadPage('https://en.wikipedia.org/wiki/Robert_Cecil_Martin', 'article.html');
console.log(content);
} catch (error) {
console.error(error);
}
์๋ฌ๋ฅผ ๋์ง๋ ๊ฒ์ ์ข์ ๊ฒ์ ๋๋ค! ์๋ฌ๋ฅผ ๋์ง๋ค๋ ๊ฒ์ ๋ฐํ์์ด ๋น์ ์ ํ๋ก๊ทธ๋จ์์ ๋ญ๊ฐ ์๋ชป๋์์ ๋ ์๋ณํ๊ณ ํ์ฌ ์คํ์์ ํจ์ ์คํ์ ๋ฉ์ถ๊ณ , (๋ ธ๋์์) ํ๋ก์ธ์ค๋ฅผ ์ข ๋ฃํ๋ฉฐ, ์คํ ํธ๋ ์ด์ค๋ฅผ ์ฝ์์ ๋ณด์ฌ์ค์ผ๋ก์จ ๋น์ ์๊ฒ ํด๋น ์๋ฌ๋ฅผ ์๋ ค์ฃผ๋ ๊ฒ์ ์๋ฏธํฉ๋๋ค.
ํ์
์คํฌ๋ฆฝํธ๋ฟ๋ง ์๋๋ผ ์๋ฐ์คํฌ๋ฆฝํธ๋ ์ด๋ค ๊ฐ์ฒด๋ ์ง ์๋ฌ๋ฅผ throw
ํ๋ ๊ฒ์ ํ์ฉํฉ๋๋ค. ๋ํ, ํ๋ก๋ฏธ์ค๋ ์ด๋ค ๊ฐ์ฒด๋ผ๋ ๊ฑฐ๋ถ๋ ์ ์์ต๋๋ค.
Error
ํ์
์๋ throw
๊ตฌ๋ฌธ์ ์ฌ์ฉํ๋ ๊ฒ์ด ๋ฐ๋์งํฉ๋๋ค. ๋น์ ์ ์๋ฌ๊ฐ ์์ ์ฝ๋์ catch
๊ตฌ๋ฌธ์์ ์กํ ์ ์๊ธฐ ๋๋ฌธ์
๋๋ค.
๋ฌธ์์ด ๋ฉ์์ง๊ฐ ์กํ๋ ๊ฒ์ ๋งค์ฐ ํผ๋์ค๋ฌ์ฐ๋ฉฐ ์ด๋ ๋๋ฒ๊น
์ ๋ ๊ณ ํต์ค๋ฝ๊ฒ ๋ง๋ญ๋๋ค.
์ด์ ๊ฐ์ ์ด์ ๋ก ๋น์ ์ Error
ํ์
์ผ๋ก ํ๋ก๋ฏธ์ค๋ฅผ ๊ฑฐ๋ถํด์ผํฉ๋๋ค.
Bad:
function calculateTotal(items: Item[]): number {
throw 'Not implemented.';
}
function get(): Promise<Item[]> {
return Promise.reject('Not implemented.');
}
Good:
function calculateTotal(items: Item[]): number {
throw new Error('Not implemented.');
}
function get(): Promise<Item[]> {
return Promise.reject(new Error('Not implemented.'));
}
// ๋๋ ์๋์ ๋์ผํฉ๋๋ค:
async function get(): Promise<Item[]> {
throw new Error('Not implemented.');
}
Error
ํ์
์ ์ฌ์ฉํ๋ ์ฅ์ ์ try/catch/finally
๊ตฌ๋ฌธ์ ์ํด ์ง์๋๊ณ ์์์ ์ผ๋ก ๋ชจ๋ ์๋ฌ๊ฐ ๋๋ฒ๊น
์ ๋งค์ฐ ๊ฐ๋ ฅํ stack
์์ฑ์ ๊ฐ์ง๊ณ ์๊ธฐ ๋๋ฌธ์
๋๋ค.
๋ ํ๋์ ๋์์ ์์ต๋๋ค. throw
๊ตฌ๋ฌธ์ ์ฌ์ฉํ์ง ์๋ ๋์ , ํญ์ ์ฌ์ฉ์ ์ ์ ๊ฐ์ฒด๋ฅผ ๋ฐํํ๋ ๊ฒ์
๋๋ค.
ํ์
์คํฌ๋ฆฝํธ๋ ์ด๊ฒ์ ํจ์ฌ ๋ ์ฝ๊ฒ ๋ง๋ญ๋๋ค.
์๋์ ์์ ๋ฅผ ํ์ธํ์ธ์:
type Result<R> = { isError: false, value: R };
type Failure<E> = { isError: true, error: E };
type Failable<R, E> = Result<R> | Failure<E>;
function calculateTotal(items: Item[]): Failable<number, 'empty'> {
if (items.length === 0) {
return { isError: true, error: 'empty' };
}
// ...
return { isError: false, value: 42 };
}
์ด ์์ด๋์ด์ ์์ธํ ์ค๋ช ์ ์๋ฌธ์ ์ฐธ๊ณ ํ์ธ์.
์กํ ์๋ฌ๋ฅผ ๋ฐ๋ผ๋ณด๋ ๊ฒ๋ง์ผ๋ก๋ ํด๋น ์๋ฌ๋ฅผ ๊ณ ์น๊ฑฐ๋ ๋์ํ ์ ์์ต๋๋ค. ์ฝ์์ ์๋ฌ๋ฅผ ๊ธฐ๋กํ๋ ๊ฒ(console.log
)์ ์ฝ์์ ์ถ๋ ฅ๋ ๋ง์ ๊ฒ๋ค ์ฌ์ด์์ ๋ฐ๊ฒฌ๋์ง ๋ชปํ ์ ์๊ธฐ ๋๋ฌธ์ ๊ทธ๋ค์ง ์ข์ ์ ํ์ ์๋๋๋ค. ๋น์ ์ด ์ด๋ค ์ฝ๋๋ฅผ try/catch
๋ก ๊ฐ์๋ค๋ฉด, ๊ทธ ์ฝ๋์์ ์๋ฌ๊ฐ ์ผ์ด๋ ์ ์์ผ๋ฉฐ, ์ฆ ์๋ฌ๊ฐ ๋ฐ์ํ์ ๋์ ๋ํ ๊ณํ์ด๋ ์ฅ์น๊ฐ ์์ด์ผ ํ๋ค๋ ๊ฒ์ ์๋ฏธํฉ๋๋ค.
Bad:
try {
functionThatMightThrow();
} catch (error) {
console.log(error);
}
// ์๋ ์์ ๋ ํจ์ฌ ๋์ฉ๋๋ค.
try {
functionThatMightThrow();
} catch (error) {
// ์๋ฌ๋ฅผ ๋ฌด์
}
Good:
import { logger } from './logging'
try {
functionThatMightThrow();
} catch (error) {
logger.log(error);
}
์์ ๊ฐ์ ์ด์ ๋ก try/catch
๋ก๋ถํฐ ์กํ ์๋ฌ๋ฅผ ๋ฌด์ํ๋ฉด ์๋ฉ๋๋ค.
Bad:
getUser()
.then((user: User) => {
return sendEmail(user.email, 'Welcome!');
})
.catch((error) => {
console.log(error);
});
Good:
import { logger } from './logging'
getUser()
.then((user: User) => {
return sendEmail(user.email, 'Welcome!');
})
.catch((error) => {
logger.log(error);
});
// ๋๋ async/await ๊ตฌ๋ฌธ์ ์ฌ์ฉํ ์ ์์ต๋๋ค:
try {
const user = await getUser();
await sendEmail(user.email, 'Welcome!');
} catch (error) {
logger.log(error);
}
์์์ ์ฃผ๊ด์ ์ ๋๋ค. ์ฌ๊ธฐ์ ์๋ ๋ง์ ๊ท์น๋ค๊ณผ ๊ฐ์ด ๋น์ ์ด ๋ฐ๋ฅด๊ธฐ ์ด๋ ค์ด ๊ท์น์ ์์ต๋๋ค. ์ค์ํ ์ ์ ์์์ ๋ํด์ ๋ ผ์ํ์ง ์๋ ๊ฒ์ ๋๋ค. ์์์ ์๋ํํ๊ธฐ ์ํ ๋๊ตฌ๋ค์ด ๋งค์ฐ ๋ง์ต๋๋ค. ๊ทธ ์ค ํ๋๋ฅผ ์ฌ์ฉํ์ธ์! ์์์ ๋ํด ๋ ผ์ํ๋ ๊ฒ์ ์์ง๋์ด์๊ฒ ์๊ฐ๊ณผ ๋ ๋ญ๋น์ผ ๋ฟ์ ๋๋ค. ๋ฐ๋ผ์ผํ๋ ์ผ๋ฐ์ ์ธ ๊ท์น์ ์ผ๊ด์ ์ธ ์์ ๊ท์น์ ์ง์ผ์ผํ๋ ๊ฒ์ ๋๋ค.
TSLint๋ผ๊ณ ๋ถ๋ฆฌ๋ ํ์ ์คํฌ๋ฆฝํธ๋ฅผ ์ํ ๊ฐ๋ ฅํ ๋๊ตฌ๊ฐ ์์ต๋๋ค. ์ด๊ฒ์ ์ฝ๋์ ๊ฐ๋ ์ฑ๊ณผ ์ ์ง๋ณด์์ฑ์ ๊ทน์ ์ผ๋ก ๊ฐ์ ์ํค๋๋ก ๋์์ฃผ๋ ์ ์ ๋ถ์ ๋๊ตฌ์ ๋๋ค. ํ๋ก์ ํธ์ ์ฐธ๊ณ ํ ์ ์๋ TSLint ์ค์ ์ ์ฌ์ฉํ ์ค๋น๊ฐ ๋์์ต๋๋ค:
-
TSLint Config Standard - ํ์ค ์คํ์ผ ๊ท์น
-
TSLint Config Airbnb - ์์ด๋น์๋น ์คํ์ผ ๊ฐ์ด๋
-
TSLint Clean Code - Clean Code: A Handbook of Agile Software Craftsmanship์ ์๊ฐ ๋ฐ์ TSLint ๊ท์น
-
TSLint react - React & JSX์ ๊ด๋ จ๋ lint ๊ท์น
-
TSLint + Prettier - Prettier ์ฝ๋ ํฌ๋งทํฐ๋ฅผ ์ํ lint ๊ท์น
-
ESLint rules for TSLint - ํ์ ์คํฌ๋ฆฝํธ๋ฅผ ์ํ ESLint ๊ท์น
-
Immutable - ํ์ ์คํฌ๋ฆฝํธ์์ ๋ณ๊ฒฝ์ ํ๋ฝํ์ง ์๋ ๊ท์น
๋ํ, ํ๋ฅญํ ์๋ฃ์ธ ํ์ ์คํฌ๋ฆฝํธ ์คํ์ผ ๊ฐ์ด๋์ ์ฝ๋ฉ ์ปจ๋ฒค์ ์ ์ฐธ๊ณ ํด์ฃผ์ธ์.
์ญ์์ฃผ: TSLint๋ deprecated๋์์ต๋๋ค. Roadmap: TSLint -> ESLint ์ด์๋ฅผ ํ์ธํด์ฃผ์ธ์.
๋์๋ฌธ์๋ฅผ ๊ตฌ๋ถํ์ฌ ์์ฑํ๋ ๊ฒ์ ๋น์ ์๊ฒ ๋ณ์, ํจ์ ๋ฑ์ ๋ํด์ ๋ง์ ๊ฒ์ ์๋ ค์ค๋๋ค. ์ด ๊ท์น์ ์ฃผ๊ด์ ์ด์ด์, ๋น์ ์ ํ์ด ์ํ๋ ๊ฒ์ ์ ํํด์ผ ํฉ๋๋ค. ์ค์ํ ์ ์ ์ด๋ค ๊ฑธ ์ ํํ์๋ ์ง ๊ฐ์ ์ผ๊ด์ ์ด์ด์ผ ํ๋ค๋ ๊ฒ์ ๋๋ค.
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() {}
type animal = { /* ... */ }
type Container = { /* ... */ }
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() {}
type Animal = { /* ... */ }
type Container = { /* ... */ }
ํด๋์ค, ์ธํฐํ์ด์ค, ํ์
๊ทธ๋ฆฌ๊ณ ๋ค์์คํ์ด์ค ์ด๋ฆ์๋ PascalCase
๋ฅผ ์ฌ์ฉํ์ธ์.
๋ณ์, ํจ์ ๊ทธ๋ฆฌ๊ณ ํด๋์ค ๋ฉค๋ฒ ์ด๋ฆ์๋ camelCase
๋ฅผ ์ฌ์ฉํ์ธ์.
ํจ์๊ฐ ๋ค๋ฅธ ํจ์๋ฅผ ํธ์ถํ ๋, ์ฝ๋์์ ์ด ํจ์๋ค์ ์์ง์ ์ผ๋ก ๊ฐ๊น๊ฒ ์ ์งํ๋๋ก ํ์ธ์. ์ด์์ ์ผ๋ก๋, ํธ์ถํ๋ ํจ์๋ฅผ ํธ์ถ์ ๋นํ๋ ํจ์ ๋ฐ๋ก ์์ ์์น์ํค๋๊ฒ ์ข์ต๋๋ค. ์ฐ๋ฆฌ๋ ์ ๋ฌธ์ฒ๋ผ ์ฝ๋๋ฅผ ์์์ ์๋๋ก ์ฝ๋ ๊ฒฝํฅ์ด ์๊ธฐ ๋๋ฌธ์, ์ฝ๋๋ฅผ ์์ฑํ ๋์๋ ์ด๋ฐ ๋ฐฉ์์ผ๋ก ์ฝ๋ ๊ฒ์ ๊ณ ๋ คํด์ผ ํฉ๋๋ค.
Bad:
class PerformanceReview {
constructor(private readonly employee: Employee) {
}
private lookupPeers() {
return db.lookup(this.employee.id, 'peers');
}
private lookupManager() {
return db.lookup(this.employee, 'manager');
}
private getPeerReviews() {
const peers = this.lookupPeers();
// ...
}
review() {
this.getPeerReviews();
this.getManagerReview();
this.getSelfReview();
// ...
}
private getManagerReview() {
const manager = this.lookupManager();
}
private getSelfReview() {
// ...
}
}
const review = new PerformanceReview(employee);
review.review();
Good:
class PerformanceReview {
constructor(private readonly employee: Employee) {
}
review() {
this.getPeerReviews();
this.getManagerReview();
this.getSelfReview();
// ...
}
private getPeerReviews() {
const peers = this.lookupPeers();
// ...
}
private lookupPeers() {
return db.lookup(this.employee.id, 'peers');
}
private getManagerReview() {
const manager = this.lookupManager();
}
private lookupManager() {
return db.lookup(this.employee, 'manager');
}
private getSelfReview() {
// ...
}
}
const review = new PerformanceReview(employee);
review.review();
import
๊ตฌ๋ฌธ์ ์ฝ๊ธฐ ์ฝ๊ณ ๋ช
๋ฃํ๊ฒ ํ๋ฉด ๋น์ ์ ํ์ฌ ์ฝ๋์ ์์กด์ฑ์ ๋น ๋ฅด๊ฒ ํ์ธํ ์ ์์ต๋๋ค. ๋ค์๊ณผ ๊ฐ์ import
๊ตฌ๋ฌธ ์ ๋ฆฌ๋ฅผ ์ํ ์ข์ ๋ฐฉ๋ฒ๋ค์ ์ ์ฉํด๋ณด์ธ์:
- import ๊ตฌ๋ฌธ์ ์ํ๋ฒณ ์์๋๋ก ๋ฐฐ์ดํ๊ณ ๊ทธ๋ฃนํํด์ผ ํฉ๋๋ค.
- ์ฌ์ฉํ์ง ์์ import ๊ตฌ๋ฌธ์ ์ ๊ฑฐ๋์ด์ผ ํฉ๋๋ค.
- ์ด๋ฆ์ด ์๋ import ๊ตฌ๋ฌธ์ ์ํ๋ฒณ ์์๋๋ก ๋ฐฐ์ดํด์ผ ํฉ๋๋ค. (์:
import {A, B, C} from 'foo';
) - import ํ๋ ์์ค์ฝ๋๋ ๊ทธ๋ฃน ๋ด์์ ์ํ๋ฒณ ์์๋๋ก ๋ฐฐ์ดํด์ผ ํฉ๋๋ค. (์:
import * as foo from 'a'; import * as bar from 'b';
) - import ๊ตฌ๋ฌธ์ ๊ทธ๋ฃน์ ๋น ์ค๋ก ๊ตฌ๋ถ๋์ด์ผ ํฉ๋๋ค.
- ๊ทธ๋ฃน์ ๋ค์ ์์๋ฅผ ์ค์ํด์ผ ํฉ๋๋ค:
- ํด๋ฆฌํ (์:
import 'reflect-metadata';
) - Node ๋ด์ฅ ๋ชจ๋ (์:
import fs from 'fs';
) - ์ธ๋ถ ๋ชจ๋ (์:
import { query } from 'itiriri';
) - ๋ด๋ถ ๋ชจ๋ (์:
import { UserService } from 'src/services/userService';
) - ์์ ๋๋ ํ ๋ฆฌ์์ ๋ถ๋ฌ์ค๋ ๋ชจ๋ (์:
import foo from '../foo'; import qux from '../../foo/qux';
) - ๋์ผํ ๊ณ์ธต์ ๋๋ ํ ๋ฆฌ์์ ๋ถ๋ฌ์ค๋ ๋ชจ๋ (์:
import bar from './bar'; import baz from './bar/baz';
)
- ํด๋ฆฌํ (์:
Bad:
import { TypeDefinition } from '../types/typeDefinition';
import { AttributeTypes } from '../model/attribute';
import { ApiCredentials, Adapters } from './common/api/authorization';
import fs from 'fs';
import { ConfigPlugin } from './plugins/config/configPlugin';
import { BindingScopeEnum, Container } from 'inversify';
import 'reflect-metadata';
Good:
import 'reflect-metadata';
import fs from 'fs';
import { BindingScopeEnum, Container } from 'inversify';
import { AttributeTypes } from '../model/attribute';
import { TypeDefinition } from '../types/typeDefinition';
import { ApiCredentials, Adapters } from './common/api/authorization';
import { ConfigPlugin } from './plugins/config/configPlugin';
tsconfig.json
์ compilerOptions
์น์
์์์ paths
์ baseUrl
์์ฑ์ ์ ์ํด ๋ ๋ณด๊ธฐ ์ข์ import ๊ตฌ๋ฌธ์ ์์ฑํด์ฃผ์ธ์.
์ด ๋ฐฉ๋ฒ์ import ๊ตฌ๋ฌธ์ ์ฌ์ฉํ ๋ ๊ธด ์๋๊ฒฝ๋ก๋ฅผ ์์ฑํ๋ ๊ฒ์ ํผํ๊ฒ ๋์์ค ๊ฒ์ ๋๋ค.
Bad:
import { UserService } from '../../../services/UserService';
Good:
import { UserService } from '@services/UserService';
// tsconfig.json
...
"compilerOptions": {
...
"baseUrl": "src",
"paths": {
"@services": ["services/*"]
}
...
}
...
์ฃผ์์ ์ฌ์ฉํ๋ ๊ฒ์ ์ฃผ์ ์์ด ์ฝ๋๋ฅผ ์์ฑํ๋ ๊ฒ์ด ์คํจํ๋ค๋ ํ์์ ๋๋ค. ์ฝ๋๋ ๋จ์ผ ์ง์ค ๊ณต๊ธ์(Single source of truth)์ด์ด์ผ ํฉ๋๋ค.
๋์ ์ฝ๋์ ์ฃผ์๋ค ๋ฌ์ง ๋ง๋ผ. ์๋ก ์ง๋ผ.
โ Brian W. Kernighan and P. J. Plaugher
์ฃผ์์ ์ฌ๊ณผ์ผ ๋ฟ, ํ์ํ ๊ฒ์ด ์๋๋๋ค. ์ข์ ์ฝ๋๋ ๋๋ถ๋ถ ๊ทธ ์กด์ฌ ์์ฒด๋ก ๋ฌธ์ํ๊ฐ ๋ฉ๋๋ค.
Bad:
// subscription์ด ํ์ฑํ ์ํ์ธ์ง ์ฒดํฌํฉ๋๋ค.
if (subscription.endDate > Date.now) { }
Good:
const isSubscriptionActive = subscription.endDate > Date.now;
if (isSubscriptionActive) { /* ... */ }
๋ฒ์ ๊ด๋ฆฌ ์์คํ ์ด ์กด์ฌํ๋ ์ด์ ์ ๋๋ค. ์ฌ์ฉํ์ง ์๋ ์ฝ๋๋ ๊ธฐ๋ก์ ๋จ๊ธฐ์ธ์.
Bad:
type User = {
name: string;
email: string;
// age: number;
// jobPosition: string;
}
Good:
type User = {
name: string;
email: string;
}
๋ฒ์ ๊ด๋ฆฌ ์์คํ
์ ์ฌ์ฉํ์ธ์! ์ฃฝ์ ์ฝ๋, ์ฃผ์ ์ฒ๋ฆฌ๋ ์ฝ๋, ํนํ ์ผ๊ธฐ ๊ฐ์ ์ฃผ์์ ํ์ ์์ต๋๋ค. ๋์ ์ ๊ธฐ๋ก์ ๋ณด๊ธฐ ์ํด git log
๋ช
๋ น์ด๋ฅผ ์ฌ์ฉํ์ธ์!
Bad:
/**
* 2016-12-20: Removed monads, didn't understand them (RM)
* 2016-10-01: Improved using special monads (JP)
* 2016-02-03: Added type-checking (LI)
* 2015-03-14: Implemented combine (JR)
*/
function combine(a: number, b: number): number {
return a + b;
}
Good:
function combine(a: number, b: number): number {
return a + b;
}
์ด๊ฑด ๋ณดํต ์ฝ๋๋ฅผ ์ด์ง๋ฝํ๊ธฐ๋ง ํฉ๋๋ค. ํจ์์ ๋ณ์ ์ด๋ฆ์ ์ ์ ํ ๋ค์ฌ์ฐ๊ธฐ์ ์์์ผ๋ก ๋น์ ์ ์ฝ๋์ ์๊ฐ์ ์ธ ๊ตฌ์กฐ๊ฐ ๋ณด์ด๋๋ก ํ์ธ์.
๋๋ถ๋ถ์ IDE(ํตํฉ ๊ฐ๋ฐ ํ๊ฒฝ)์์๋ ์ฝ๋ ๋ธ๋ก์ ์ ๊ธฐ/ํผ์น๊ธฐ
ํ ์ ์๋ ๊ธฐ๋ฅ์ ์ง์ํฉ๋๋ค. (Visual Studio Code์ folding regions๋ฅผ ํ์ธํด๋ณด์ธ์).
Bad:
////////////////////////////////////////////////////////////////////////////////
// Client class
////////////////////////////////////////////////////////////////////////////////
class Client {
id: number;
name: string;
address: Address;
contact: Contact;
////////////////////////////////////////////////////////////////////////////////
// public methods
////////////////////////////////////////////////////////////////////////////////
public describe(): string {
// ...
}
////////////////////////////////////////////////////////////////////////////////
// private methods
////////////////////////////////////////////////////////////////////////////////
private describeAddress(): string {
// ...
}
private describeContact(): string {
// ...
}
};
Good:
class Client {
id: number;
name: string;
address: Address;
contact: Contact;
public describe(): string {
// ...
}
private describeAddress(): string {
// ...
}
private describeContact(): string {
// ...
}
};
์ถํ์ ๊ฐ์ ์ ์ํด ์ฝ๋์ ๋ฉ๋ชจ๋ฅผ ๋จ๊ฒจ์ผํ ๋, // TODO
์ฃผ์์ ์ฌ์ฉํ์ธ์. ๋๋ถ๋ถ์ IDE๋ ์ด๋ฐ ์ข
๋ฅ์ ์ฃผ์์ ํน๋ณํ๊ฒ ์ง์ํ๊ธฐ ๋๋ฌธ์ ํด์ผํ ์ผ ๋ชฉ๋ก์ ๋น ๋ฅด๊ฒ ๊ฒํ ํ ์ ์์ต๋๋ค.
ํ์ง๋ง TODO ์ฃผ์์ด ๋์ ์ฝ๋์ ๋ํ ๋ณ๋ช ์ ์๋๋ผ๋ ๊ฒ์ ๋ช ์ฌํ์ธ์.
Bad:
function getActiveSubscriptions(): Promise<Subscription[]> {
// ensure `dueDate` is indexed.
return db.subscriptions.find({ dueDate: { $lte: new Date() } });
}
Good:
function getActiveSubscriptions(): Promise<Subscription[]> {
// TODO: ensure `dueDate` is indexed.
return db.subscriptions.find({ dueDate: { $lte: new Date() } });
}
์ด ๊ธ์ ๋ค๋ฅธ ์ธ์ด๋ก๋ ์ฝ์ ์ ์์ต๋๋ค:
- Brazilian Portuguese: vitorfreitas/clean-code-typescript
- Chinese:
- Japanese: MSakamaki/clean-code-typescript
- Russian: Real001/clean-code-typescript
- Turkish: ozanhonamlioglu/clean-code-typescript
- Korean: 738/clean-code-typescript
๋ฒ์ญ์ด ์๋ฃ๋๋ฉด ์ฐธ๊ณ ๋ฌธํ์ ์ถ๊ฐ๋ฉ๋๋ค. ์์ธํ ๋ด์ฉ๊ณผ ์งํ์ํฉ์ ๋ณด๊ณ ์ถ๋ค๋ฉด ์ด ๋ ผ์๋ฅผ ํ์ธํ์ธ์. ๋น์ ์ ๋น์ ์ ์ธ์ด์ ์ด ๊ธ์ ๋ฒ์ญํจ์ผ๋ก์จ ํด๋ฆฐ ์ฝ๋ ์ปค๋ฎค๋ํฐ์ ์ค์ํ ๊ธฐ์ฌ๋ฅผ ํ ์ ์์ต๋๋ค.