Skip to content

Latest commit

 

History

History
208 lines (140 loc) · 5.84 KB

의미있는 이름.md

File metadata and controls

208 lines (140 loc) · 5.84 KB

의도를 분명히 밝혀라, 그릇된 정보를 피해라

→ 따로 주석이 필요하다면 의도를 분명히 드러내지 못했다는 말이다.

→Info, Data 는 a, an, the 와 마찬가지로 의미가 불분명한 불 용어.

→의미가 분명히 다르면 사용해도 됨.

읽는 사람이 차이를 알도록 이름을 지어라

발음하기 쉬운 이름을 사용하라

검색하기 쉬운 이름을 사용하라

WORK_DAYS_PER_WEEK 와 같이 상수를 사용하지 않는다면

5가 들어가는 이름을 모두 찾은 다음, 의미를 분석해 원하는 상수를 가려내야 한다.

const int WORK_DAYS_PER_WEEK = 5;
//do somethings using WORK_DAYS_PER_WEEK

멤버 변수 접두어

붙이지 마 그냥 (ex : m_description)

이전과 다르게 객체는 강한 타입이며, IDE는 코드를 컴파일 하지 않고도 타입 오류를 감지할 정도로 발전함.

기억력 자랑 ㄴㄴ

완전히 간단한 루프를 제외한 다른 곳에서 문자 하나만 사용 하지마라.

일반적으로 반복 횟수를 세는 변수는 가능

  • i, j, k는 👌
  • l은 ❎ →죠낸 헷갈림

클래스 이름

클래스 이름과 객체 이름은 명사나 명사구가 적합

Manager, Processor, Data, Info 등과 같은 단어는 피하고, 동사는 사용하지 않는다.

The cat sat on the chair. Please hand in your assignments by the end of the week. Cleanliness is next to godliness. Plato was an influential philosopher in ancient Greece.

메서드 이름

메서드 이름은 동사나 동사구가 적합하다.

I washed the car yesterday. The dog ate my homework. John studies English and French. Lucy enjoys listening to music.

javabean 표준

  • 접근자(Accessor) : get
  • 변경자(Mutator) : set
  • 조건자(Predicate) : is

생성자를 중복 정의(overload) 할때는 정적 팩토리 메서드를 사용한다.

//Good! :)
Complex fulcrumPoint = Complex.FromRealNumber(23.0);

//Bad! :(
Complex fulcrumPoint = new Complex(23.0);
Integer answer = Integer.valueOf(1);

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
  • 정적 팩토리 메서드 장/단점
    • 장점
      1. 이름이 있으므로 생성자에 비해 가독성이 좋다.
      2. 호출할 때마다 새로운 객체를 생성할 필요가 없다.
      3. 하위 자료형 객체를 반환할 수 있다.
      4. 형인자 자료형(parameterized type) 객체를 만들 때 편하다.
    • 단점
      1. 정적 팩토리 메서드만 있는 클래스라면, 생성자가 없으므로 하위 클래스를 못 만든다.
      2. 정적 팩토리 메서드는 다른 정적 메서드와 잘 구분되지 않는다. (문서만으로 확인하기 어려울 수 있음)

코드에 농담 ㄴㄴ

→ 실무가 장난이냐!!

한 개념에 한 단어를 사용하라

DeviceManager

ProtocolController

  • 구분이 되는가?

    //매니져와 컨트롤러에서 어떤 이름이 들어가도 어색하지 않지 않은가?
    class DeviceMananger{
    	fun getDeviceInformation()
    }
    
    class ProtocolController{
    	fun getProtocolInformation()
    }

해법(문제) 영역에서 가져온 이름을 사용하라

//코드를 읽을 사람도 프로그래머, 우리가 배운 기술적 전문 용어를 사용해도 괜찮다.
fun ObserveInstruction()

//적절한 '프로그래머 용어'가 없다면, 문제 영역에서 발생한 이름을 가져온다.
fun checkKasperBlock()

의미 있는 맥락을 추가하라

변수에 의미있는 맥락을 추가해라? → 뭔 개소린가..?

→아하! '맥락'이라는 말은 그 변수가 어디 '소속'인지를 더 구체적으로 특정 하라는 말이구나!

//어떤 상태??
object Up
object Down

fun checkButtonState(val state :Any){

	when(state){
		is Up->{ }
		is Down->{ }
	}

}
sealed class Button{
	object Up : Button()
	object Down : Button()
}

fun checkButtonState(val state :Button){

	when(state){
		Button.Up->{ }
		Button.Down->{ }
	}

}

불필요한 맥락을 없애라.

만약 KakaoI 관련된 패키지라 한다 해서 모든 클래스 앞에 K를 붙이지 말자..

그러면 Shift + Command + F 를 누르면 굉장하게 멋진 광경을 볼 수 있을것..

실제 사용 예시

  1. 의미있는 이름 getKasperCommand() → selectKasperCommandByUserInput()
  2. 읽는 사람이 차이를 알도록 if(isExistSpan == null) → if(!isExistSpan)
private fun findKasper() {
        val curText = text.toString()

        val isExistSpan = text?.getSpans(0, 0, KasperSpan::class.java)?.firstOrNull()
        val kasperCommand = getKasperCommand()

        if (kasperCommand != null && isExistSpan == null) {
            val span = KasperSpan(context, kasperCommand)

            val ssb = SpannableStringBuilder()
                .append("$kasperCommand")
                .append(curText.subSequence(kasperCommand.length, curText.length))

            ssb.setSpan(
                span,
                0,
                kasperCommand.length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )

            setTextWithSelection(ssb, ssb.length)

        }
    }
  • 으디한번 Zero는 어떻게 했는지 볼까?

    private fun findKasper() {
            val curText = text ?: return
    
            val isExistSpan = isExistKasperSpan()
            val kasperCommand = selectKasperCommandByUserInput()
    
            if (isExistSpan) {// [/캐스퍼] 블록이 지워질 때
                checkKasperBlock(curText)
            }
    
            if (kasperCommand != null && !isExistSpan) {// [/캐스퍼] 가 입력되었을 때, 스팬을 입힘
                spanKasper(kasperCommand, curText)
            }
        }