Post

Naming convention

구글의 스타일 가이드 모음https://github.com/google/styleguide

http://docs.navercorp.com/coding-convention/

Helper class / Utility class

helper class는 특정 클래스의 작업을 도와주는 유틸리티 클래스라고 생각하면 된다. 어떤 기능을 제공하기는 하는데, 그 자체로 그 어플리케이션의 핵심 로직은 아닌 클래스를 의미한다. 예를 들면 DB를 다룬다거나, 안드로이드에서 CustomTabs를 띄워주는 기능을 한다거나. utility class와 하는 일은 비슷하지만, utility class는 모든 메서드가 static이라는 차이점이 있다. 즉, helper class가 더 큰 개념이라고 보면 된다.

클래스 네이밍 suffix는 디자인 패턴 참조해서 역할에 맞게

[코딩 노트] 大 : Design Pattern, 디자인 패턴

파일 이름은 클래스 이름과 동일하게

대문자로 시작하도록 한다. utils, main 이런건 예외. 패키지 이름은 그냥 붙여서 다 소문자로. apigateway

Parameter vs Argument

Parameter 는 함수를 선언할 때의변수의 이름

Argument 는 함수를 호출하면서전달하는/받는 값

  • Parameter 는 ‘파라미터’ 또는 ‘매개변수’, ‘인수’로,
  • Argument 는 ‘아규먼트’, ‘인자’, 또는 ‘전달인자’로

DATE FORMAT 상수 네이밍? 애초에 DATE FORMAT 상수가 필요할까?

https://stackoverflow.com/questions/52818450/java-constant-names-conventions-for-date-formats

DateTimeFormatter 클래스에서도 제공하고 있는건 ISO\_DATE\_TIME 같은 의미론적 상수이지, YYYY\_MM\_DD 같은 value를 그대로 옮긴 이름이 아니다.

Naming convention

Suffixes are sometimes useful:
  • max - to mean the maximum value something can have.
  • foo\_cnt - 어떤 항목 foo의 개수를 의미하는 변수. len(foo)
  • num_of_xxx 보다는 xxxCount 같은걸 사용한다.
  • key - key value.
  • idx - 요것도 자주 씀.
  • For example: retry_max to mean the maximum number of retries, retry_cnt to mean the current retry count.
file : path, dir, name
1
2
3
4
5
/home/user/foo.var
   ------------------ path
   ----------         dir
   ------- name

boolean variables에도 ` is` prefix 붙여야 하나?
  • 파라미터에는 is 붙이는게 좋아보인다. 이건 아무렇게나 해도 상관 없음
  • getter는 is 붙인다는게 argue가 없다.
  • field에 붙여야 하느냐 말아야 하느냐는 좀 불명확하다. 컨벤션에 해당 내용이 없는 경우도 많고, 있다 해도 의견이 분분…
  • 코틀린에서는 필드명 자체를 isMobile로 네이밍 하는 것이 좋아보인다.
    • (Kotlin In Action 예제코드)
  • 자바에서는 필드명을 그냥 mobile로 쓰는게 좋아보인다.
    • lombok이 getter setter 만들어주는 규약이 코틀린 getter setter 만들어주는 규약과 동일해서 그냥 mobile로 써도 상관없다.
    • 코틀린 -> 자바 필드를 참조할 때는 isMobile, setMobile 있으면 isMobile로 참조하게 되므로 mobile이든 isMobile이든 상관없다.
    • 자바 -> 코틀린 프로퍼티를 호출할 일이 있을 때도 getter, setter 통해 참조하므로 어느쪽이든 상관없다.
    • 다만!! JSP에서 참조할 때 코틀린 처럼 자동으로 getter를 불러주는데… 이 때 변수명이 mobile이면 obj.mobile -> obj.isMobile() 이렇게 연결된다. 근데 변수명이 isMobile이면 obj.isMobile -> obj.getIsMobile 로 연결된다 ㅡㅡ… 그래서 그냥 mobile이 나은 듯.
  • Jackson 사용 할 때에도 차이점이 있다.( 자바 필드는 mobile로 네이밍 추천 )
    • 필드명이 isMobile이든, mobile이든 serialization 하면 json에서는 mobile이 된다.
    • json serialization 결과를 isMobile 로 만들고 싶은 경우, @JsonProperty("isMobile") 할텐데,
      • 이 때 필드명이 isMobile이라면 json에 {isMobile, mobile} 둘 다 포함된다.
      • 필드명이 mobile이라면 json에 {isMobile} 만 포함된다.
    • 참고 ) 또한, 매핑하려는 응답이 isAgree 인 경우, getter/setter는 isIsAgree()/setIsAgree() 이어야 isAgree 응답-필드를 매핑할 수 있다. ( 이 경우 @JsonProperty로 해결 )
결론
  • param에는 is 붙인다
  • getter에도 is 붙인다
  • java field에는 is 붙이지 않는다
  • kotlin field에는 is 붙인다
lombok과 kotlin의 boolean 타입 getter setter 생성 규칙
1
2
3
4
5
6
7
8
9
10
11
12
#### lombok
// boolean 타입 변수명이 mobile이면, 롬복은 isMobile()와 setMobile() 를 만들어준다
boolean mobile; -> isMobile(), setMobile()
// (예외) if (이름이 is로 시작하고 곧바로 title-case letter가 오면서 && 타입이 boolean 필드)
boolean isMobile; -> isMobile(), setMobile()
// wrapper type Boolean은 boolean이 아니다.
Boolean isMobile; -> getIsMobile(), setIsMobile()


#### kt
var isMobile: Boolean -> isMobile(), setMobile()

Kotlin ( Java )

https://kotlinlang.org/docs/reference/coding-conventions.html

https://developer.android.com/kotlin/style-guide

1
2
3
4
5
6
7
8
9
10
11
12
13
class DeclarationProcessor { val x: Int }        // :는 변수 이름에 붙인다.
object EmptyDeclarationProcessor : DeclarationProcessor() { ... }


fun processDeclarations() { ... }    // except : factory function
var declarationCount = ...           // local이든 property든. except : reference to singleton
private val \_backingProperty = "a"


const val MAX\_COUNT = 8
val USER\_NAME\_FIELD = "UserName"
enum class Color { RED, GREEN }     // 아무거나 써도 되긴 한다만 보통 UPPERCASE

  • 상수는 UPPERCASE\_WITH\_UNDERSCORE
    • 이 때 상수란 const가 아니어도 쓰임이 상수이면 상수로 간주한다.
    • 즉 top-level 프로퍼티이거나,
    • custom get()을 정의하지 않는 object class의 val 프로퍼티이면서 불변 데이터를 가지고 있는 경우
    • This includes immutable types and immutable collections of immutable types as well as scalars and string if marked as const.

Java

구글 스타일 이 좋긴 한데, 너무 복잡하고 양이 많아서 짧은 시간에 협업할 때는 부적절한 듯. 그래서 자주 쓰는건,

네이밍 규칙은 http://www.oracle.com/technetwork/java/codeconventions-135099.html
파일 이름은 클래스 명과 동일하게 한다.
각각의 자바 소스 파일은 하나의 public (class | interface)를 포함.
private (class | interface)가 public 클래스와 연결되어 있을 경우는 하나의 소스파일에 둘 수 있음.
이 경우 public (class | interfcae)는 파일 내에서 첫 번째 클래스 또는 인터페이스여야 함.
indent는 스페이스바 4개
중괄호는 K&R style
static은 상수인 경우 (Immutable class 포함) UPPERCASE_WITH_UNDERSCORE
static 변수인 경우 (mutable) camelCase

https://source.android.com/setup/code-style#follow-field-naming-conventions

android 개발 시 따라야 하는 컨벤션은 아니고, android open source project에 참여 시 따라야 하는 컨벤션.

python

https://www.python.org/dev/peps/pep-0008/#naming-conventions

함수, 메소드, 변수에 lowercase\_with\_underscore

non-public methods and instance variables 에는 \_single\_leading\_underscore를 사용한다. 근데 이거 빼고는 다 함수는 lowerCamelCase라… 함수같은 경우 개인적으로 짤 때는 PEP8을 따르지 않는 것이 좋겠다.

https://github.com/google/styleguide/blob/gh-pages/pyguide.md

C++ ( C )

리눅스 커널과 파이썬 같은 경우 \_를 쓰도록 되어 있는데, 요즘 나오는 언어들은 대체로 camelCase를 쓰는 것 같다. 리눅스 커널이나 파이썬은 레거시 코드와 통일성을 유지하기 위해 그대로 언더바로 가는게 아닐까 싶기도 하다. https://google.github.io/styleguide/cppguide.html file name은 ClassName.cpp 로.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#define FLAG       // Google이 C++이면 꼭 필요한거 아님 절대 macro쓰지 말란다.
namespace lowercasenounderscore {          // namespace 안쪽 indent 하지 않는다!
class UrlTable { ...
typedef struct  { } UrlTableProperties;

void trackingOrderProcess()     // 함수는 camelCase
int num\_dns\_connections;        // 변수는 lowercase\_with\_underscore
TrackingOrder \*foo;             // 포인터는 중간만 아니면 어디다 붙이든 상관없음.



const int kDaysInAWeek = 7;
const int DAYS\_IN\_A\_WEEK = 7;    // 나는 UPPER\_CASE로 함.
// enum도 const와 똑같이 UPPER\_CASE.
\_refrobnicate\_data\_tables(), \_destroy\_cache()
// Functions that are there, but shouldn't be called directly, or have obscure uses, or whatever: one or more underscores at the beginning

C#

https://msdn.microsoft.com/en-us/library/ms229002(v=vs.110).aspx

if와 중괄호 Style

if()는 꼭 공백을 두고, 중괄호 없는 if는 한 줄로 작성하며 웬만하면 중괄호를 쓴다. {는 개행하지 말고 선행 문장과 같은 라인에 둔다. ( K&R style ) 함수형 프로그래밍에서 객체를 리턴할 경우( return { ... ) 개행한 다음 {를 쓰면 문법에러가 발생하기 때문에 일관성이 없어진다.

1
2
3
4
if (a) {
b( );
}

HTML naming convention - id, class

https://google.github.io/styleguide/htmlcssguide.html#ID_and_Class_Name_Delimiters

단어 abbr convention

authentication -> authn authorization -> authz authority -> auth state -> state status -> stat

changeSupport.firePropertyChange() - “통지”의 의미로.

This post is licensed under CC BY 4.0 by the author.