Honey-Programming

[TIL-010] 20.07.31 본문

코드스테이츠/Today I Learned

[TIL-010] 20.07.31

Latte_is_horse 2020. 7. 31. 18:24

1. Summary(3 Line)

프리코스 5일차(3줄 요약)

- 코플릿을 하루 종일 페어와 풀이...

- 가독성 좋은 코드를 작성하는 방법을 찾아보자

- 드디어 한 주가 끝났다. 잘하고 있는걸까...


2. Today's Todo

  • 알고리즘 : 문제는 어떻게 풀까?

  • 알아보기 쉬운 코드 작성법

 

#1 알고리즘 : 문제는 어떻게 풀까?

Ex) 'foo'라는 단어를 찾아 전부 다른 단어로 바꿔주는 코드 작성

1) 텍스트를 입력으로 받는다.

   - 'foo'라는 단어를 찾는다.

   - 그 단어를 지운다.

   - 그 자리에 새로운 단어를 넣는다.

2) 바뀐 내용을 리턴한다.

 

 

위의 의사코드를 좀더 구체화 해보자.

 

1) 텍스트를 입력으로 받는다.

    1. 'foo'라는 단어를 찾는다.
       - 끝까지 일치하는지 확인해 본 후,

       - 'foo'라는 글자의 index가 -1이 아니면 단어가 있는 것이다.

    2. while index를 발견하면,
       - index를 이용해 'foo' 바로 앞까지의 텍스트를 얻어내고,
       - 'foo' 대신 새로운 단어를 넣는다.

       - 'foo' 이후의 텍스트를 넣는다.

    3. endwhile

 

2) 바뀐 내용을 리턴한다.

 

function replaceFoo(text) {
  
  while( text.indexOf('foo') !== -1 ) { // foo라는 글자의 index가 -1이 아니면 해당 단어를 찾은 것
    let index = text.indexOf('foo');
    let beforeText = text.slice(0, index);// index를 이용해 foo 바로 앞까지의 텍스트를 얻어내고
    let replaceText = 'BAR'; // foo 대신 새로운 단어를 넣는다
    
    let afterText = text.slice(index + 3); // foo 이후의 텍스트를 넣음. 'foo'는 세 글자 3 더함
    text = beforeText + replaceText + afterText;
  }

  return text; // 바뀐 내용을 리턴한다
}

 

foo를 찾는 부분과, 텍스트('foo')를 바꾸는 기능을 분리 해보자.

findFoo(text);
replaceFoo(text);

function findFoo(text) {
  return text.indexOf('foo'); // foo의 인덱스를 찾는다.
}

function replaceFoo(text) {
  while(findFoo(text) !== -1 ) {
    let index = findFoo(text); // index를 이용해 foo 바로 앞까지의 텍스트를 얻어내고
    let beforeText = text.slice(0, index);
    let replaceText = 'BAR'; // foo 대신 새로운 단어를 넣는다
    let afterText = text.slice(index + 3); // foo 이후의 텍스트를 넣음.'foo'는 세 글자 3 더함
    
    text = beforeText + replaceText + afterText;
  }

  return text; // 바뀐 내용을 리턴한다
}

 

 

'foo' 단어만 아닌 다른 단어들도 보편적으로 사용할 수 있게 함수를 보편화 시켜보자

find(text, searchString);
replace(text, searchString, replaceString);

function find(text, searchString){
  return text.indexOf(searchString); //searchString의 인덱스를 찾는다.
}

function replaceFoo(text, searchString, replaceString)) {
  while( find(text, searchString) !== -1 ) { 
    let index = find(text, searchString); // index를 이용해 searchString 바로 앞까지의 텍스트를 얻어내고
    let beforeText = text.slice(0, index); // searchString 대신 새로운 단어를 넣는다
    let replaceText = replaceString; // searchString 이후의 텍스트를 넣는다
    let afterText = text.slice(index + searchString.length); // 'searchString'의 길이만큼 더함
    
    text = beforeText + replaceText + afterText;
  }
  return text; // 바뀐 내용을 리턴한다
}

 

 

#2 알아보기 쉬운 코드 작성법

1) 코드 가독성

   - 코드의 목적이 뚜렷하고 자명해야 한다.

   - 구조가 일관되고, 예측 가능해야 한다.

 

 

2) 들여쓰기(Indentation)

   - 들여쓰기를 할 때는 Tab(탭)이 아닌 Space(스페이스)를 사용한다.

// Good
if (condition) {
  action();
}

// Bad
if (condition) {
action();
}

// Bad
if (condition) {
action();
  }

 

 

3) 이름 짓기(Naming)

   - 변수 이름 : 한 단어로 표현하는 것이 좋다. 핵심을 잘 묘사해주는 단어를 선택해야 한다.

// Good
let animals = ['cat', 'dog', 'fish'];

// Bad
let targetInputs = ['cat', 'dog', 'fish'];

// Bad
let array = ['cat', 'dog', 'fish'];

// array와 같은 Collections을 값으로 갖는 변수의 이름은 복수 명사가 좋습니다.

// Bad
let animalList = ['cat', 'dog', 'fish'];

// Bad
let animal = ['cat', 'dog', 'fish'];

 

 

4) Boolean 이름

   - 변수 이름 앞에 is 또는 are 붙인다.

// Good
let areEqual = true;

// Bad
let pass = true;

 

 

5) 함수 이름(Function)

   - 함수 이름은 동사로 시작해야 한다.

Ex) calculateTotal 혹은 listInventory 등 같은 형식을 사용하면, 변수 이름의 의미가 자명해짐

// Good
let countWaterBlocks = function() {
  // do stuff
}

// Good
let counterWaterBlocksBetweenTowers = function() {
  // do stuff
}

// Bad
let waterBlocks = function() {
  // count how many blocks of water are collected between each tower
}

 

 

6) 변수 이름에서의 대문자

   - 변수 이름의 첫 글자를 대문자로 쓴다.

   - new 키워드를 사용한 함수에 한해서 대문자를 쓴다.

   - 상수(constant), 변수의 이름은 전체를 대문자로 쓴다.

// Example of a capitalized class constructor function name.
function Animal() {
}
// Example of an all-caps constant variable name.
const MAX_ITEMS_IN_QUEUE = 100;

 

 

7) 기호 / 구두점 찍기(Symbols / punctuation)

   - 중괄호를 생략하지 마라(문법적으로 생략이 가능하더라도)

// Good
for (key in object) {
  alert(key);
}

// Bad
for (key in object)
  alert(key);

 

인용(Quoting) 

   - 문자열을 쓸 때, 처음과 끝에 큰 따옴표("") 대신에 작은 따옴표('')를 써라.

// Good
let dog = 'dog';
let cat = 'cat';

// Acceptable(허용은 가능한)
let dog = "dog";
let cat = "cat";

// Bad (섞어 쓰지말것)
let dog = 'dog';
let cat = "cat";

// 줄 바꿈이 필요한 문자열을 정의할 때는 ` (backquote)를 사용하는 것도 한 방법
let multilineText = `this is line one
this is line two
this is line three`;

 

세미콜론(Semicolons)

   - 코드 문장 끝에는 항상 ; 세미콜론을 써라

// Good
alert('hi');

// Bad
alert('hi')
if, for, while 구문의 끝에는 세미콜론을 사용하지 않아야 합니다.

// Good
if (condition) {
  response();
}

// Bad
if (condition) {
  response();
};

함수 표현식, 즉 함수가 일반적인 구문의 끝에 쓰여진 경우, 
마치 if, for, while 구문의 끝처럼 보일지라도 코드 끝에 세미콜론 사용

// Good
let greet = function () {
  alert('hi');
};

// Bad
let greet = function () {
  alert('hi');
}

 

 

8) 연산자와 키워드(Operators and keywords)

   - 엄격한 비교 연산자를 사용해라. 반드시 === 와 !== 를 사용해라

// Good
// this comparison evaluates to false, because the number zero is not the same as the empty string.
if (0 === '') {
  alert('looks like they\'re equal');
}

// Bad
// This comparison evaluates to true, because after type coercion, zero and the empty string are equal.
if (0 == '') {
  alert('looks like they\'re equal');
}

 

 

9) 3항 연산자 (x ? y : z)

   - x가 참이면 y를 , 거짓이면 z를 실행한다.

x ? y : z;

   - 짧고 명확한 코드를 쓸 때만 3항 연산자를 사용해라. 남용하지는 말 것

return (actual === expected) ? 'passed' : 'FAILED ['+ testName + '] Expected "'+expected+'",but got '+'"'+actual+'"';

   - 이 경우에는 3항 연산자 보다는 if else문이 더 가독성이 좋다.

if (actual !== expected) {
  console.log('FAILED ' + testName + ': Expected ' + expected + ', but got ' + actual);
} else {
  console.log('passed');
}

 

 

10) 부정 연산자( not : ! )

   - 일반적으로 not 연산자(!)는 부정하는 대상 코드의 바로 앞에 붙여 사용

// Bad
if (! isEqual) {

// Good
if (!isEqual) {

 

 

11) 짧게 쓰기

// Not as good
function square(n) {
  let squaredN = n * n;
  return squaredN;
}

// Good
function square(n) {
  return n * n;
}

 

 

12) 되도록 부정을 사용하지 말기

   - 많은 부정을 사용하면, 코드의 명확성이 떨어짐

// Not as good
function square(n) {
  let squaredN = n * n;
  return squaredN;
}

// Good
function square(n) {
  return n * n;
}

 

 

13) Boolean 결과값은 바로 return 하세요

// Verbose
if(charSet.size < text.length) {
  return false;
}
return true;

// Concise
return charSet.size > text.length;

 

 

14) 주석

   - 주석은 코드를 쓴 이유 즉, 코드의 목적을 설명

 

 

15) 뱀 모양 vs 낙타 모양(Snake vs Camel Casing)

   - 변수의 이름을 지정할 때 'Camel Casing'으로 지정

// Good
let camelCased = 'Used in javascript';

// Bad
let snake_cased = 'Used in other languages';

JavaScript에서 '뱀 모양'을 사용하는 경우는, 상수 이름을 지을 때
const MAX_ITEMS_IN_QUEUE = 100;

'코드스테이츠 > Today I Learned' 카테고리의 다른 글

[TIL-012] 20.08.04  (0) 2020.08.04
[TIL-011] 20.08.03  (0) 2020.08.04
[TIL-009] 20.07.30  (0) 2020.07.30
[TIL-008] 20.07.29  (0) 2020.07.29
[TIL-007] 20.07.28  (0) 2020.07.28
Comments