Skip to content

[Fork] - ๐Ÿšฟ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ๋ฅผ ์œ„ํ•œ ํด๋ฆฐ์ฝ”๋“œ - ํ•œ๊ธ€ ๋ฒˆ์—ญํŒ ๐Ÿ‡ฐ๐Ÿ‡ท

License

Notifications You must be signed in to change notification settings

DNDACADEMY/dnd-external-clean-code-typescript

ย 
ย 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

70 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

clean-code-typescript Tweet

๋ฒˆ์—ญ ์ž‘์—… ์ง„ํ–‰์ค‘์ž…๋‹ˆ๋‹ค.

ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ๋ฅผ ์œ„ํ•œ ํด๋ฆฐ์ฝ”๋“œ.
clean-code-javascript์—์„œ ์˜๊ฐ์„ ๋ฐ›์•˜์Šต๋‹ˆ๋‹ค.

๋ชฉ์ฐจ

  1. ์†Œ๊ฐœ(Introduction)
  2. ๋ณ€์ˆ˜(Variables)
  3. ํ•จ์ˆ˜(Functions)
  4. Objects and Data Structures
  5. Classes
  6. SOLID
  7. Testing
  8. Concurrency
  9. Error Handling
  10. ์„œ์‹(Formatting)
  11. ์ฃผ์„(Comments)
  12. ๋ฒˆ์—ญ(Translations)

์†Œ๊ฐœ(Introduction)

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

Robert C. Martin์˜ ์ฑ…์ธ ํด๋ฆฐ ์ฝ”๋“œ์— ์žˆ๋Š” ์†Œํ”„ํŠธ์›จ์–ด ๊ณตํ•™ ๋ฐฉ๋ฒ•๋ก ์„ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์— ์ ์šฉํ•œ ๊ธ€์ž…๋‹ˆ๋‹ค. ์ด ๊ธ€์€ ์Šคํƒ€์ผ ๊ฐ€์ด๋“œ๊ฐ€ ์•„๋‹™๋‹ˆ๋‹ค. ์ด ๊ธ€์€ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์—์„œ ์ฝ๊ธฐ ์‰ฝ๊ณ , ์žฌ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•˜๋ฉฐ, ๋ฆฌํŒฉํ† ๋ง ๊ฐ€๋Šฅํ•œ ์†Œํ”„ํŠธ์›จ์–ด๋ฅผ ์ž‘์„ฑํ•˜๊ธฐ ์œ„ํ•œ ๊ฐ€์ด๋“œ์ž…๋‹ˆ๋‹ค.

์—ฌ๊ธฐ ์žˆ๋Š” ๋ชจ๋“  ๊ทœ์น™์„ ์—„๊ฒฉํ•˜๊ฒŒ ๋”ฐ๋ฅผ ํ•„์š”๋Š” ์—†์œผ๋ฉฐ, ๋ณดํŽธ์ ์œผ๋กœ ํ†ต์šฉ๋˜๋Š” ๊ทœ์น™์€ ์•„๋‹™๋‹ˆ๋‹ค. ์ด ๊ธ€์€ ํ•˜๋‚˜์˜ ์ง€์นจ์ผ ๋ฟ์ด๋ฉฐ, ํด๋ฆฐ ์ฝ”๋“œ์˜ ์ €์ž๊ฐ€ ์ˆ˜๋…„๊ฐ„ ๊ฒฝํ—˜ํ•œ ๋‚ด์šฉ์„ ๋ฐ”ํƒ•์œผ๋กœ ์ •๋ฆฌํ•œ ๊ฒƒ์ž…๋‹ˆ๋‹ค.

์†Œํ”„ํŠธ์›จ์–ด ๊ณตํ•™ ๊ธฐ์ˆ ์˜ ์—ญ์‚ฌ๋Š” 50๋…„์ด ์กฐ๊ธˆ ๋„˜์—ˆ๊ณ , ๋ฐฐ์›Œ์•ผ ํ•  ๊ฒƒ์ด ์—ฌ์ „ํžˆ ๋งŽ์Šต๋‹ˆ๋‹ค. ์†Œํ”„ํŠธ์›จ์–ด ์„ค๊ณ„๊ฐ€ ๊ฑด์ถ• ์„ค๊ณ„๋งŒํผ ์˜ค๋ž˜๋˜์—ˆ์„ ๋•Œ๋Š” ์•„๋งˆ๋„ ์•„๋ž˜ ๊ทœ์น™๋“ค๋ณด๋‹ค ์—„๊ฒฉํ•œ ๊ทœ์น™์„ ๋”ฐ๋ผ์•ผ ํ•  ๊ฒƒ์ž…๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ์ง€๊ธˆ์€ ์ด ์ง€์นจ์„ ๋‹น์‹ ๊ณผ ๋‹น์‹  ํŒ€์ด ์ž‘์„ฑํ•˜๋Š” ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ ์ฝ”๋“œ์˜ ํ’ˆ์งˆ์„ ํ‰๊ฐ€ํ•˜๋Š” ๊ธฐ์ค€์œผ๋กœ ์‚ผ์œผ์„ธ์š”.

ํ•œ ๊ฐ€์ง€ ๋” ๋ง๋ถ™์ด์ž๋ฉด, ์ด ๊ทœ์น™๋“ค์„ ์•Œ๊ฒŒ ๋œ๋‹ค ํ•ด์„œ ๋‹น์žฅ ๋” ๋‚˜์€ ๊ฐœ๋ฐœ์ž๊ฐ€ ๋˜๋Š” ๊ฒƒ์€ ์•„๋‹ˆ๋ฉฐ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•  ๋•Œ ์‹ค์ˆ˜๋ฅผ ํ•˜์ง€ ์•Š๊ฒŒ ํ•ด์ฃผ๋Š” ๊ฒƒ์€ ์•„๋‹™๋‹ˆ๋‹ค. ํ›Œ๋ฅญํ•œ ๋„์ž๊ธฐ๋“ค์ด ์ฒ˜์Œ์—” ๋ง๋ž‘ํ•œ ์ ํ† ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜๋“ฏ์ด ๋ชจ๋“  ์ฝ”๋“œ๋ฅผ ์ฒ˜์Œ๋ถ€ํ„ฐ ์™„๋ฒฝํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ๋‹น์‹ ์€ ํŒ€์›๋“ค๊ณผ ๊ฐ™์ด ์ฝ”๋“œ๋ฅผ ๋ฆฌ๋ทฐํ•˜๋ฉฐ ์ ์  ์™„๋ฒฝํ•˜๊ฒŒ ๋งŒ๋“ค์–ด ๋‚˜๊ฐ€์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๋‹น์‹ ์ด ์ฒ˜์Œ ์ž‘์„ฑํ•œ ์ฝ”๋“œ๋ฅผ ๊ณ ์น  ๋•Œ ์ ˆ๋Œ€๋กœ ์ž์‹ ์„ ์งˆํƒ€ํ•˜์ง€ ๋งˆ์„ธ์š”. ๋Œ€์‹  ์ฝ”๋“œ๋ฅผ ๋ถ€์ˆ˜๊ณ  ๋” ๋‚˜์€ ์ฝ”๋“œ๋ฅผ ๋งŒ๋“œ์„ธ์š”!

โฌ† ์ƒ๋‹จ์œผ๋กœ

๋ณ€์ˆ˜(Variables)

์˜๋ฏธ์žˆ๋Š” ๋ณ€์ˆ˜ ์ด๋ฆ„์„ ์‚ฌ์šฉํ•˜์„ธ์š”

์ฝ๋Š” ์‚ฌ๋žŒ์œผ๋กœ ํ•˜์—ฌ๊ธˆ ๋ณ€์ˆ˜๋งˆ๋‹ค ์–ด๋–ค ์ ์ด ๋‹ค๋ฅธ์ง€ ์•Œ ์ˆ˜ ์žˆ๋„๋ก ์ด๋ฆ„์„ ๊ตฌ๋ณ„ํ•˜์„ธ์š”.

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์ด๋‚˜ ์กฐ๊ฑด๋ฌธ ๋Œ€์‹  ๊ธฐ๋ณธ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์„ธ์š”

๊ธฐ๋ณธ ๋งค๊ฐœ๋ณ€์ˆ˜๋Š” short circuiting๋ณด๋‹ค ๋ณดํ†ต ๋ช…๋ฃŒํ•ฉ๋‹ˆ๋‹ค.

Bad:

function loadPages(count?: number) {
  const loadCount = count !== undefined ? count : 10;
  // ...
}

Good:

function loadPages(count: number = 10) {
  // ...
}

โฌ† ์ƒ๋‹จ์œผ๋กœ

์˜๋„๋ฅผ ์•Œ๋ ค์ฃผ๊ธฐ ์œ„ํ•ด enum์„ ์‚ฌ์šฉํ•˜์„ธ์š”

์˜ˆ๋ฅผ ๋“ค์–ด ๊ทธ๊ฒƒ๋“ค์˜ ๊ฐ’ ์ž์ฒด๋ณด๋‹ค ๊ฐ’์ด ๊ตฌ๋ณ„๋˜์–ด์•ผ ํ•  ๋•Œ์™€ ๊ฐ™์ด ์ฝ”๋“œ์˜ ์˜๋„๋ฅผ ์•Œ๋ ค์ฃผ๋Š”๋ฐ์— 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:
        // ์‹คํ–‰๋˜์–ด์•ผ ํ•˜๋Š” ๋กœ์ง
    }
  }
}

โฌ† ์ƒ๋‹จ์œผ๋กœ

ํ•จ์ˆ˜(Functions)

ํ•จ์ˆ˜์˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋Š” 2๊ฐœ ํ˜น์€ ๊ทธ ์ดํ•˜๊ฐ€ ์ด์ƒ์ ์ž…๋‹ˆ๋‹ค

ํ•จ์ˆ˜ ๋งค๊ฐœ๋ณ€์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ์ œํ•œํ•˜๋Š” ๊ฒƒ์€ ํ•จ์ˆ˜๋ฅผ ํ…Œ์ŠคํŠธํ•˜๊ธฐ ์‰ฝ๊ฒŒ ๋งŒ๋“ค์–ด์ฃผ๊ธฐ ๋•Œ๋ฌธ์— ๋†€๋ผ์šธ ์ •๋„๋กœ ์ค‘์š”ํ•ฉ๋‹ˆ๋‹ค. ํ•จ์ˆ˜ ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ 3๊ฐœ ์ด์ƒ์ธ ๊ฒฝ์šฐ, ๊ฐ๊ธฐ ๋‹ค๋ฅธ ์ธ์ˆ˜๋กœ ์—ฌ๋Ÿฌ ๋‹ค๋ฅธ ์ผ€์ด์Šค๋ฅผ ํ…Œ์ŠคํŠธํ•ด์•ผ ํ•˜๋ฏ€๋กœ ๊ฒฝ์šฐ์˜ ์ˆ˜๊ฐ€ ๋งค์šฐ ๋งŽ์•„์ง‘๋‹ˆ๋‹ค.

ํ•œ ๊ฐœ ํ˜น์€ ๋‘ ๊ฐœ์˜ ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ์ด์ƒ์ ์ธ ๊ฒฝ์šฐ๊ณ , ๊ฐ€๋Šฅํ•˜๋‹ค๋ฉด ์„ธ ๊ฐœ๋Š” ํ”ผํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๊ทธ ์ด์ƒ์˜ ๊ฒฝ์šฐ์—๋Š” ํ•ฉ์ณ์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๋‘ ๊ฐœ ์ด์ƒ์˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๊ฐ€์งˆ ๊ฒฝ์šฐ, ํ•จ์ˆ˜๊ฐ€ ๋งŽ์€ ๊ฒƒ์„ ํ•  ๊ฐ€๋Šฅ์„ฑ์ด ๋†’์•„์ง‘๋‹ˆ๋‹ค. ๊ทธ๋ ‡์ง€ ์•Š์€ ๊ฒฝ์šฐ, ๋Œ€๋ถ€๋ถ„ ์ƒ์œ„ ๊ฐ์ฒด๋Š” ํ•˜๋‚˜์˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ถฉ๋ถ„ํ•  ๊ฒƒ์ž…๋‹ˆ๋‹ค.

๋งŽ์€ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค๋ฉด ๊ฐ์ฒด ๋ฆฌํ„ฐ๋Ÿด์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•ด๋ณด์„ธ์š”.

ํ•จ์ˆ˜๊ฐ€ ๊ธฐ๋Œ€ํ•˜๋Š” ์†์„ฑ์„ ๋ช…ํ™•ํ•˜๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•ด, ๊ตฌ์กฐ ๋ถ„ํ•ด ๊ตฌ๋ฌธ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ๊ตฌ๋ฌธ์€ ๋ช‡ ๊ฐœ์˜ ์žฅ์ ์„ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค:

  1. ์–ด๋–ค ์‚ฌ๋žŒ์ด ํ•จ์ˆ˜ ์‹œ๊ทธ๋‹ˆ์ณ(๋งค๊ฐœ๋ณ€์ˆ˜์˜ ํƒ€์ž…, ๋ฐ˜ํ™˜๊ฐ’์˜ ํƒ€์ž… ๋“ฑ)๋ฅผ ๋ณผ ๋•Œ, ์–ด๋–ค ์†์„ฑ์ด ์‚ฌ์šฉ๋˜๋Š”์ง€ ์ฆ‰์‹œ ์•Œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

  2. ๋ช…๋ช…๋œ ๋งค๊ฐœ๋ณ€์ˆ˜์ฒ˜๋Ÿผ ๋ณด์ด๊ฒŒ ํ•  ๋•Œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

  3. ๋˜ํ•œ ๊ตฌ์กฐ ๋ถ„ํ•ด๋Š” ํ•จ์ˆ˜๋กœ ์ „๋‹ฌ๋œ ๋งค๊ฐœ๋ณ€์ˆ˜ ๊ฐ์ฒด์˜ ํŠน์ •ํ•œ ์›์‹œ ๊ฐ’์„ ๋ณต์ œํ•˜๋ฉฐ ์ด๊ฒƒ์€ ์‚ฌ์ด๋“œ ์ดํŽ™ํŠธ๋ฅผ ๋ฐฉ์ง€ํ•˜๋Š”๋ฐ ๋„์›€์„ ์ค๋‹ˆ๋‹ค. ์œ ์˜์‚ฌํ•ญ: ๋งค๊ฐœ๋ณ€์ˆ˜ ๊ฐ์ฒด๋กœ๋ถ€ํ„ฐ ๊ตฌ์กฐ ๋ถ„ํ•ด๋œ ๊ฐ์ฒด์™€ ๋ฐฐ์—ด์€ ๋ณต์ œ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

  4. ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ๋Š” ์‚ฌ์šฉํ•˜์ง€ ์•Š์€ ์†์„ฑ์— ๋Œ€ํ•ด์„œ ๊ฒฝ๊ณ ๋ฅผ ์ฃผ๋ฉฐ, ๊ตฌ์กฐ ๋ถ„ํ•ด๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๊ฒฝ๊ณ ๋ฅผ ๋ฐ›์ง€ ์•Š์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

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

๋‹น์‹ ์€ ์ค‘๋ณต๋œ ์ฝ”๋“œ์— ๋Œ€ํ•ด์„œ ๋น„ํŒ์ ์œผ๋กœ ์ƒ๊ฐํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๊ฐ€๋”์€ ์ค‘๋ณต๋œ ์ฝ”๋“œ์™€ ๋ถˆํ•„์š”ํ•œ ์ถ”์ƒํ™”๋กœ ์ธํ•œ ๋ณต์žก์„ฑ ๊ฐ„์˜ ๋งž๋ฐ”๊ฟˆ์ด ์žˆ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์„œ๋กœ ๋‹ค๋ฅธ ๋‘ ๊ฐœ์˜ ๋ชจ๋“ˆ์˜ ๊ตฌํ˜„์ด ์œ ์‚ฌํ•ด๋ณด์ด์ง€๋งŒ ์„œ๋กœ ๋‹ค๋ฅธ ๋„๋ฉ”์ธ์— ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ, ์ฝ”๋“œ ์ค‘๋ณต์€ ๊ณตํ†ต๋œ ์ฝ”๋“œ์—์„œ ์ถ”์ถœํ•ด์„œ ์ค‘๋ณต์„ ์ค„์ด๋Š” ๊ฒƒ๋ณด๋‹ค ๋‚˜์€ ์„ ํƒ์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ๊ฒฝ์šฐ์— ์ถ”์ถœ๋œ ๊ณตํ†ต์˜ ์ฝ”๋“œ๋Š” ๋‘ ๋ชจ๋“ˆ ์‚ฌ์ด์—์„œ ๊ฐ„์ ‘์ ์ธ ์˜์กด์„ฑ์ด ๋‚˜ํƒ€๋‚˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

โฌ† ์ƒ๋‹จ์œผ๋กœ

Object.assign ํ˜น์€ ๊ตฌ์กฐ ๋ถ„ํ•ด๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๊ธฐ๋ณธ ๊ฐ์ฒด๋ฅผ ๋งŒ๋“œ์„ธ์š”

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

โฌ† ์ƒ๋‹จ์œผ๋กœ

์‚ฌ์ด๋“œ ์ดํŽ™ํŠธ๋ฅผ ํ”ผํ•˜์„ธ์š” (ํŒŒํŠธ 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.
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);

โฌ† ์ƒ๋‹จ์œผ๋กœ

์‚ฌ์ด๋“œ ์ดํŽ™ํŠธ๋ฅผ ํ”ผํ•˜์„ธ์š” (ํŒŒํŠธ 2)

In JavaScript, primitives are passed by value and objects/arrays are passed by reference. In the case of objects and arrays, if your function makes a change in a shopping cart array, for example, by adding an item to purchase, then any other function that uses 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:

  1. There might be cases where you actually want to modify the input object, but when you adopt this programming practice you will find that those cases are pretty rare. Most things can be refactored to have no side effects! (see pure function)

  2. Cloning big objects can be very expensive in terms of performance. Luckily, this isn't a big issue in practice because there are great libraries that allow this kind of programming approach to be fast and not as memory intensive as it would be for you to manually clone objects and arrays.

Bad:

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

โฌ† ์ƒ๋‹จ์œผ๋กœ

Objects and Data Structures

Use getters and setters

TypeScript supports getter/setter syntax. Using getters and setters to access data from objects that encapsulate behavior could be better than simply looking for a property on an object. "Why?" you might ask. Well, here's a list of reasons:

  • When you want to do more beyond getting an object property, you don't have to look up and change every accessor in your codebase.
  • Makes adding validation simple when doing 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;

โฌ† ์ƒ๋‹จ์œผ๋กœ

Make objects have private/protected members

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

โฌ† ์ƒ๋‹จ์œผ๋กœ

Prefer immutability

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

โฌ† ์ƒ๋‹จ์œผ๋กœ

type vs. interface

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

โฌ† ์ƒ๋‹จ์œผ๋กœ

Classes

Classes should be small

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

โฌ† ์ƒ๋‹จ์œผ๋กœ

High cohesion and low coupling

Cohesion defines the degree to which class members are related to each other. Ideally, all fields within a class should be used by each method. We then say that the class 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> {
    // ...
  }
}

โฌ† ์ƒ๋‹จ์œผ๋กœ

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.

You might be wondering then, "when should I use inheritance?" It depends on your problem at hand, but this is a decent list of when inheritance makes more sense than composition:

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

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

  3. You want to make global changes to derived classes by changing a base class. (Change the caloric expenditure of all animals when they move).

Bad:

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

  // ...
}

โฌ† ์ƒ๋‹จ์œผ๋กœ

Use method chaining

This pattern is very useful and commonly used in many libraries. It allows your code to be expressive, and less verbose. For that reason, use method chaining and take a look at how clean your code will be.

Bad:

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

โฌ† ์ƒ๋‹จ์œผ๋กœ

SOLID

Single Responsibility Principle (SRP)

As stated in Clean Code, "There should never be more than one reason for a class to change". It's tempting to jam-pack a class with a lot of functionality, like when you can only take one suitcase on your flight. The issue with this is that your class won't be conceptually cohesive and it will give it many reasons to change. Minimizing the amount of times you need to change a class is important. It's important because if too much functionality is in one class and you modify a piece of it, it can be difficult to understand how that will affect other dependent modules in your codebase.

Bad:

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

โฌ† ์ƒ๋‹จ์œผ๋กœ

Open/Closed Principle (OCP)

As stated by Bertrand Meyer, "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification." What does that mean though? This principle basically states that you should allow users to add new functionalities without changing existing code.

Bad:

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

โฌ† ์ƒ๋‹จ์œผ๋กœ

Liskov Substitution Principle (LSP)

This is a scary term for a very simple concept. It's formally defined as "If S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may substitute objects of type T) without altering any of the desirable properties of that program (correctness, task performed, etc.)." That's an even scarier definition.

The best explanation for this is if you have a parent class and a child class, then the parent class and child class can be used interchangeably without getting incorrect results. This might still be confusing, so let's take a look at the classic Square-Rectangle example. Mathematically, a square is a rectangle, but if you model it using the "is-a" relationship via inheritance, you quickly get into trouble.

Bad:

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

โฌ† ์ƒ๋‹จ์œผ๋กœ

Interface Segregation Principle (ISP)

ISP states that "Clients should not be forced to depend upon interfaces that they do not use.". This principle is very much related to the Single Responsibility Principle. What it really means is that you should always design your abstractions in a way that the clients that are using the exposed methods do not get the whole pie instead. That also include imposing the clients with the burden of implementing methods that they donโ€™t actually need.

Bad:

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

โฌ† ์ƒ๋‹จ์œผ๋กœ

Dependency Inversion Principle (DIP)

This principle states two essential things:

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

  2. Abstractions should not depend upon details. Details should depend on abstractions.

This can be hard to understand at first, but if you've worked with Angular, you've seen an implementation of this principle in the form of Dependency Injection (DI). While they are not identical concepts, DIP keeps high-level modules from knowing the details of its low-level modules and setting them up. It can accomplish this through DI. A huge benefit of this is that it reduces the coupling between modules. Coupling is a very bad development pattern because it makes your code hard to refactor.

DIP is usually achieved by a using an inversion of control (IoC) container. An example of a powerful IoC container for TypeScript 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');

โฌ† ์ƒ๋‹จ์œผ๋กœ

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.

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

The three laws of TDD

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

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

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

โฌ† ์ƒ๋‹จ์œผ๋กœ

F.I.R.S.T. rules

Clean tests should follow the rules:

  • Fast tests should be fast because we want to run them frequently.

  • Independent tests should not depend on each other. They should provide same output whether run independently or all together in any order.

  • Repeatable tests should be repeatable in any environment and there should be no excuse for why they fail.

  • Self-Validating a test should answer with either Passed or Failed. You don't need to compare log files to answer if a test passed.

  • Timely unit tests should be written before the production code. If you write tests after the production code, you might find writing tests too hard.

โฌ† ์ƒ๋‹จ์œผ๋กœ

Single concept per test

Tests should also follow the Single Responsibility Principle. Make only one assert per unit test.

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

โฌ† ์ƒ๋‹จ์œผ๋กœ

The name of the test should reveal its intention

When a test fail, its name is the first indication of what may have gone wrong.

Bad:

describe('Calendar', () => {
  it('2/29/2020', () => {
    // ...
  });

  it('throws', () => {
    // ...
  });
});

Good:

describe('Calendar', () => {
  it('should handle leap year', () => {
    // ...
  });

  it('should throw when format is invalid', () => {
    // ...
  });
});

โฌ† ์ƒ๋‹จ์œผ๋กœ

Concurrency

Prefer promises vs callbacks

Callbacks aren't clean, and they cause excessive amounts of nesting (the callback hell).
There are utilities that transform existing functions using the callback style to a version that returns promises (for Node.js see util.promisify, for general purpose see 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));  

Promises supports a few helper methods that help make code more conscise:

Pattern Description
Promise.resolve(value) Convert a value into a resolved promise.
Promise.reject(error) Convert an error into a rejected promise.
Promise.all(promises) Returns a new promise which is fulfilled with an array of fulfillment values for the passed promises or rejects with the reason of the first promise that rejects.
Promise.race(promises) Returns a new promise which is fulfilled/rejected with the result/error of the first settled promise from the array of passed promises.

Promise.all is especially useful when there is a need to run tasks in parallel. Promise.race makes it easier to implement things like timeouts for promises.

โฌ† ์ƒ๋‹จ์œผ๋กœ

Async/Await are even cleaner than Promises

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

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

โฌ† ์ƒ๋‹จ์œผ๋กœ

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.

Always use Error for throwing or rejecting

JavaScript as well as TypeScript allow you to throw any object. A Promise can also be rejected with any reason object.
It is advisable to use the throw syntax with an Error type. This is because your error might be caught in higher level code with a catch syntax. It would be very confusing to catch a string message there and would make debugging more painful.
For the same reason you should reject promises with Error types.

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

// or equivalent to:

async function get(): Promise<Item[]> {
  throw new Error('Not implemented.');
}

The benefit of using Error types is that it is supported by the syntax try/catch/finally and implicitly all errors have the stack property which is very powerful for debugging.
There are also another alternatives, not to use the throw syntax and instead always return custom error objects. TypeScript makes this even easier. Consider following example:

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

For the detailed explanation of this idea refer to the original post.

โฌ† ์ƒ๋‹จ์œผ๋กœ

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.

Bad:

try {
  functionThatMightThrow();
} catch (error) {
  console.log(error);
}

// or even worse

try {
  functionThatMightThrow();
} catch (error) {
  // ignore error
}

Good:

import { logger } from './logging'

try {
  functionThatMightThrow();
} catch (error) {
  logger.log(error);
}

โฌ† ์ƒ๋‹จ์œผ๋กœ

Don't ignore rejected promises

For the same reason you shouldn't ignore caught errors from 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);
  });

// or using the async/await syntax:

try {
  const user = await getUser();
  await sendEmail(user.email, 'Welcome!');
} catch (error) {
  logger.log(error);
}

โฌ† ์ƒ๋‹จ์œผ๋กœ

์„œ์‹(Formatting)

์„œ์‹์€ ์ฃผ๊ด€์ ์ž…๋‹ˆ๋‹ค. ์—ฌ๊ธฐ์— ์žˆ๋Š” ๋งŽ์€ ๊ทœ์น™๋“ค๊ณผ ๊ฐ™์ด ๋‹น์‹ ์ด ๋”ฐ๋ฅด๊ธฐ ์–ด๋ ค์šด ๊ทœ์น™์€ ์—†์Šต๋‹ˆ๋‹ค. ์ค‘์š”ํ•œ ์ ์€ ์„œ์‹์— ๋Œ€ํ•ด์„œ ๋…ผ์Ÿํ•˜์ง€ ์•Š๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค. ์„œ์‹์„ ์ž๋™ํ™”ํ•˜๊ธฐ ์œ„ํ•œ ๋„๊ตฌ๋“ค์ด ๋งค์šฐ ๋งŽ์Šต๋‹ˆ๋‹ค. ๊ทธ ์ค‘ ํ•˜๋‚˜๋ฅผ ์‚ฌ์šฉํ•˜์„ธ์š”! ์„œ์‹์— ๋Œ€ํ•ด ๋…ผ์Ÿํ•˜๋Š” ๊ฒƒ์€ ์—”์ง€๋‹ˆ์–ด์—๊ฒŒ ์‹œ๊ฐ„๊ณผ ๋ˆ ๋‚ญ๋น„์ผ ๋ฟ์ž…๋‹ˆ๋‹ค. ๋”ฐ๋ผ์•ผํ•˜๋Š” ์ผ๋ฐ˜์ ์ธ ๊ทœ์น™์€ ์ผ๊ด€์ ์ธ ์„œ์‹ ๊ทœ์น™์„ ์ง€์ผœ์•ผํ•˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

TSLint๋ผ๊ณ  ๋ถˆ๋ฆฌ๋Š” ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ๋ฅผ ์œ„ํ•œ ๊ฐ•๋ ฅํ•œ ๋„๊ตฌ๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๊ฒƒ์€ ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ๊ณผ ์œ ์ง€๋ณด์ˆ˜์„ฑ์„ ๊ทน์ ์œผ๋กœ ๊ฐœ์„ ์‹œํ‚ค๋„๋ก ๋„์™€์ฃผ๋Š” ์ •์  ๋ถ„์„ ๋„๊ตฌ์ž…๋‹ˆ๋‹ค. ํ”„๋กœ์ ํŠธ์— ์ฐธ๊ณ ํ•  ์ˆ˜ ์žˆ๋Š” TSLint ์„ค์ •์„ ์‚ฌ์šฉํ•  ์ค€๋น„๊ฐ€ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค:

๋˜ํ•œ, ํ›Œ๋ฅญํ•œ ์ž๋ฃŒ์ธ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ ์Šคํƒ€์ผ ๊ฐ€์ด๋“œ์™€ ์ฝ”๋”ฉ ์ปจ๋ฒค์…˜์„ ์ฐธ๊ณ ํ•ด์ฃผ์„ธ์š”.

์—ญ์ž์ฃผ: 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 = { /* ... */ }

Prefer using PascalCase for class, interface, type and namespace names.
Prefer using camelCase for variables, functions and class members.

โฌ† ์ƒ๋‹จ์œผ๋กœ

Function callers and callees should be close

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

Bad:

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

โฌ† ์ƒ๋‹จ์œผ๋กœ

Organize imports

With clean and easy to read import statements you can quickly see the dependencies of current code. Make sure you apply following good practices for import statements:

  • Import statements should be alphabetized and grouped.
  • Unused imports should be removed.
  • Named imports must be alphabetized (i.e. import {A, B, C} from 'foo';)
  • Import sources must be alphabetized within groups, i.e.: import * as foo from 'a'; import * as bar from 'b';
  • Groups of imports are delineated by blank lines.
  • Groups must respect following order:
    • Polyfills (i.e. import 'reflect-metadata';)
    • Node builtin modules (i.e. import fs from 'fs';)
    • external modules (i.e. import { query } from 'itiriri';)
    • internal modules (i.e import { UserService } from 'src/services/userService';)
    • modules from a parent directory (i.e. import foo from '../foo'; import qux from '../../foo/qux';)
    • modules from the same or a sibling's directory (i.e. import bar from './bar'; import baz from './bar/baz';)

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

โฌ† ์ƒ๋‹จ์œผ๋กœ

์ฃผ์„(Comments)

์ฃผ์„์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์€ ์ฃผ์„ ์—†์ด ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋Š” ๊ฒƒ์ด ์‹คํŒจํ–ˆ๋‹ค๋Š” ํ‘œ์‹œ์ž…๋‹ˆ๋‹ค. ์ฝ”๋“œ๋Š” ๋‹จ์ผ ์ง„์‹ค ๊ณต๊ธ‰์›(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 ์ฃผ์„

์ถ”ํ›„์— ๊ฐœ์„ ์„ ์œ„ํ•ด ์ฝ”๋“œ์— ๋ฉ”๋ชจ๋ฅผ ๋‚จ๊ฒจ์•ผํ•  ๋•Œ, // 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() } });
}

โฌ† ์ƒ๋‹จ์œผ๋กœ

๋ฒˆ์—ญ(Translations)

์ด ๊ธ€์„ ๋‹ค๋ฅธ ์–ธ์–ด๋กœ๋„ ์ฝ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค:

๋ฒˆ์—ญ์ด ์™„๋ฃŒ๋˜๋ฉด ์ฐธ๊ณ ๋ฌธํ—Œ์— ์ถ”๊ฐ€๋ฉ๋‹ˆ๋‹ค. ์ž์„ธํ•œ ๋‚ด์šฉ๊ณผ ์ง„ํ–‰์ƒํ™ฉ์„ ๋ณด๊ณ ์‹ถ๋‹ค๋ฉด ์ด ๋…ผ์˜๋ฅผ ํ™•์ธํ•˜์„ธ์š”. ๋‹น์‹ ์€ ๋‹น์‹ ์˜ ์–ธ์–ด์— ์ด ๊ธ€์„ ๋ฒˆ์—ญํ•จ์œผ๋กœ์จ ํด๋ฆฐ ์ฝ”๋“œ ์ปค๋ฎค๋‹ˆํ‹ฐ์— ์ค‘์š”ํ•œ ๊ธฐ์—ฌ๋ฅผ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

About

[Fork] - ๐Ÿšฟ ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ๋ฅผ ์œ„ํ•œ ํด๋ฆฐ์ฝ”๋“œ - ํ•œ๊ธ€ ๋ฒˆ์—ญํŒ ๐Ÿ‡ฐ๐Ÿ‡ท

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 100.0%