참고 자료English languageNaming conventionS-I-DAvoid contractionsAvoid context duplicationReflect the expected resultNaming functionsA/HC/LC PatternActionsgetsetresetfetchremovedeletecomposehandleContextPrefixesishasshouldwillcanmin/maxprev/nextSingular and Plurals (단수, 복수 표시)
참고 자료
English language
변수와 함수 명명 시 영어로 써라
/* Bad - 스페인어 예시 */ const primerNombre = 'Gustavo' const amigos = ['Kate', 'John'] /* Good */ const firstName = 'Gustavo' const friends = ['Kate', 'John']
Naming convention
네이밍 컨벤션의 경우 다음과 같은 경우들이 있다.
camelCase
PascalCase
snake_case
- etc.
무엇을 쓰던 상관없지만, 한번 정하면 일관성 있게 쭉 사용하는 것이 좋다.
/* Bad - 네이밍 컨벤션 혼합 예시 */ const page_count = 5 const shouldUpdate = true /* Good - camelCase로 쭉 사용하는 경우 */ const pageCount = 5 const shouldUpdate = true /* Good as well - snake_case로 쭉사용하는 경우 */ const page_count = 5 const should_update = true
S-I-D
이름은 반드시 짧고(Short), 직관적이고(Intuitive), 서술적(Descriptive이여야 한다.
- Short : 가능한 짧게 명명
- Intuitive : 자연스럽게 읽혀야 함
- Descriptive : 이름에서 무엇을 하는지, 무엇을 위한 것인지가 분명하게 들어나야 한다.
/* Bad */ const a = 5 // "a" could mean anything const isPaginatable = a > 10 // "Paginatable" sounds extremely unnatural const shouldPaginatize = a > 10 // Made up verbs are so much fun! /* Good */ const postCount = 5 const hasPagination = postCount > 10 const shouldPaginate = postCount > 10 // alternatively
Avoid contractions
축약형, 줄임말을 쓰지 마라
축약형을 쓰는 것은 아무런 이점이 없을 뿐아니라 코드 가독성을 낮추기만 하므로 사용하지 말자.
짧게 명명하는 것이 좋긴 하지만 축약형을 쓰라는 의미는 아니다.
/* Bad */ // Item -> Itm 으로 축약 예시 // Click -> Clk 으로 축약 예시 const onItmClk = () => {} /* Good - 축약하지 않고 온전하게 사용 */ const onItemClick = () => {}
Avoid context duplication
가독성에 영향을 주지 않는 이상 문맥을 중복해서 적지 마라.
클래스명이 MenuItem이라서 handleClick만 적어도 메뉴를 클릭하는 것을 알 수 있으므로, handleMenuItemClick 이런 식으로 문맥을 중복해서 적지 않도록 하자.
class MenuItem { /* Method name duplicates the context (which is "MenuItem") */ handleMenuItemClick = (event) => { ... } /* Reads nicely as `MenuItem.handleClick()` */ handleClick = (event) => { ... } }
Reflect the expected result
이름에서 결과를 예측할 수 있어야 한다.
is@@@
의 경우 이름에서 True/False 느낌이 나므로 값은 항상boolean
타입이어야 한다.
- 넘기는 프롭 값이 disabled 라면 변수도 isDisabled 이렇게 통일시켜서 전달하는 것이 가독성에 더 좋다.
/* Bad */ // boolean처럼 이름을 지어놓고, const isEnabled = itemCount > 3 return <Button disabled={!isEnabled} /> /* Good */ const isDisabled = itemCount <= 3 return <Button disabled={isDisabled} />
Naming functions
A/HC/LC Pattern
prefix?
+action (
A
)+ high context (
HC
) + low context? (LC
)
잘 바뀌지 않는 것 → 자주 바뀌는 것 순으로 명명 순서가 지켜져야 한다.
예를 들면 아래와 같다.

Note: The order of context affects the meaning of a variable. For example,shouldUpdateComponent
means you are about to update a component, whileshouldComponentUpdate
tells you that component will update on itself, and you are but controlling when it should be updated. In other words, high context emphasizes the meaning of a variable.
Actions
함수 이름의 동사 파트다. 함수가 무엇을 하는지를 서술하는 가장 중요한 부분이다.
get
데이터에 접근할 때 ( getter 함수의 줄임말 )
function getFruitCount() { return this.fruits.length }
set
변수의 값을 설정하는 함수일 때 ( setter 함수의 줄임말 )
let fruits = 0 function setFruits(nextFruits) { fruits = nextFruits } setFruits(5) console.log(fruits) // 5
reset
변수 값을 초기값이나 초기상태로 되돌리는 경우
const initialFruits = 5 let fruits = initialFruits setFruits(10) console.log(fruits) // 10 function resetFruits() { fruits = initialFruits } resetFruits() console.log(fruits) // 5
fetch
데이터를 요청해서 받아와야 하는 경우 ( 약간의 시간을 소요하는 경우 ) - 예를 들어 async 요청
- 로컬DB로부터 데이터를 가져올 때
- 서버로부터 데이터를 가져올 때
function fetchPosts(postCount) { return fetch('https://api.dev/posts', {...}) }
remove
일부 데이터를 제거하는 경우
예를 들어 검색 페이지에서 여러개의 필터가 걸려있고, 그 중에서 하나의 필터를 제거하는 경우에는 delete가 아니라 remove를 사용해야 한다.
function removeFilter(filterName, filters) { return filters.filter((name) => name !== filterName) } const selectedFilters = ['price', 'availability', 'size'] removeFilter('price', selectedFilters)
delete
완전히 제거하는 경우
블로그 포스트 하나를 제거하는 경우를 생각해 보면, 일부를 제거하거나 수정하는 것이 아니라 글 하나를 통째로 제거하는 경우이므로 remove가 아닌 delete를 쓰는 것이 좋다.
function deletePost(id) { return database.find({ id }).delete() }
compose
기존에 존재하는 것들을 결합해서 새로운 것을 만드는 경우
function composePageUrl(pageName, pageId) { return (pageName.toLowerCase() + '-' + pageId) }
handle
특정 action을 핸들링하는 경우. 주로
callback
함수명에 많이 사용된다.function handleLinkClick() { console.log('Clicked a link!') } link.addEventListener('click', handleLinkClick)
Context
함수가 어디서 동작하는 지에 대한 도메인을 나타낸다.
함수는 거의 어떤 것에 대한 액션을 수행한다. 여기서 “어떤 것”에 해당하는 것이 도메인이다.
이를 함수명에 표기함으로써 어떤 도메인에 대한 행위인지를 알 수 있다.
/* A pure function operating with primitives */ function filter(list, predicate) { return list.filter(predicate) } /* Function operating exactly on posts */ function getRecentPosts(posts) { return filter(posts, (post) => post.date === Date.now()) }
Some language-specific assumptions may allow omitting the context. For example, in JavaScript, it's common thatfilter
operates on Array. Adding explicitfilterArray
would be unnecessary.
Prefixes
변수의 의미를 더욱 예측 가능하도록 만들어준다. 함수에서는 잘 쓰이지 않는다.
is
특정 값이나 상태가 맞는지 여부를 나타낼 때 ( 주로 boolean 타입 )
const color = 'blue' const isBlue = color === 'blue' // characteristic const isPresent = true // state if (isBlue && isPresent) { console.log('Blue is present!') }
has
특정 값을 가지고 있는지 여부를 나타낼 때 ( 마찬가지로 주로 boolean 타입 )
/* Bad */ const isProductsExist = productsCount > 0 const areProductsPresent = productsCount > 0 /* Good */ const hasProducts = productsCount > 0
should
~ 해야한다 로 강제성이 있는 경우에 사용 (will를 써도 무방)
특정 action을 수행 해야하는 상태인지 아닌지를 나타내는 경우로, boolean 변수명에 활용
function shouldUpdateUrl(url, expectedUrl) { return url !== expectedUrl }
will
~ 할 거다로 flag 성으로 나타내는 경우에 사용 (should를 써도 무방)
should와 유사하게, will or not 으로 boolean을 나타내는 변수명에 활용
willSkip: boolean
can
can or not으로 boolean을 나타내는 변수명에 활용
canGoback: boolean
min/max
최소값/최대값을 담는 변수일 경우
주로 바운더리나 limit을 표현할 때 많이 사용된다.
/** * Renders a random amount of posts within * the given min/max boundaries. */ function renderPosts(posts, minPosts, maxPosts) { return posts.slice(0, randomBetween(minPosts, maxPosts)) }
prev/next
현재 context를 기준으로 prev 상태와 next 상태를 표현할 때 유용하다.
주로 상태 변화를 나타낼 때 좋다.
의문 : 현재 값인데 왜 prev 라고 쓸까?
- 새롭게 바뀌는 next 값이 생기면서 과거의 데이터가 되므로 prev 라고 표현한다고 생각하면 편함
- prev 대신 current를 써도 무방할듯
function fetchPosts() { const prevPosts = this.state.posts const fetchedPosts = fetch('...') const nextPosts = concat(prevPosts, fetchedPosts) this.setState({ posts: nextPosts }) }
Singular and Plurals (단수, 복수 표시)
prefix와 마찬가지로 변수에 단수형인지 복수형인지를 표시함으로써 배열인지 아닌지를 나타낼 수 있다.
/* Bad */ const friends = 'Bob' // s로 복수형으로 지어놓고 단수형인 경우 const friend = ['Bob', 'Tony', 'Tanya'] // 단수형으로 지어놓고 배열을 담는 경우 /* Good */ const friend = 'Bob' const friends = ['Bob', 'Tony', 'Tanya']