IT TIP

Go, CamelCase 또는 Semi-CamelCase에서 함수 이름을 지정하는 방법은 무엇입니까?

itqueen 2021. 1. 10. 19:43
반응형

Go, CamelCase 또는 Semi-CamelCase에서 함수 이름을 지정하는 방법은 무엇입니까?


Go에서 MongoDB 데이터베이스의 컬렉션에 문서를 삽입하는 함수를 작성하고 싶습니다. 함수 이름을 지정하는 것이 더 낫습니다.

  • writeToMongoDB 또는
  • WriteToMongoD?

두 번째는 CamelCase인데 첫 번째 스타일을 사용하는 사람을 보았 기 때문에 어떤 것이 더 적합한 지 잘 모르겠습니다. 감사.


통사론

Go에서 이것은 스타일의 문제가 아니라 구문의 문제입니다.

내 보낸 이름 (즉, 정의 된 패키지 이외의 패키지에서 사용할 수있는 식별자)은 대문자로 시작합니다. 따라서 메서드가 공용 API의 일부인 경우 다음과 같이 작성해야합니다.

WriteToDB

그러나 내부 도우미 메서드 인 경우 다음과 같이 작성해야합니다.

writeToDB

이러한 방식으로 키워드를 사용하여 내보내기 ( extern, public등) 를 정의하는 것보다 이점은 식별자를 이름의 일부로 만들면 식별자가 사용되는 위치를 찾을 필요없이 내보낼 지 여부를 알 수 있다는 것입니다. 정의되었습니다 (정의에 키워드가 포함되어 있는지 확인하기 위해).

참조 : 사양에서 내 보낸 식별자 .

i18n

Go는 UTF-8로 인코딩되고 식별자 이름에 문자 또는 숫자 속성이있는 모든 유니 코드 문자를 지원하기 때문에 대소 문자 개념이없는 로캘의 일부 사용자는 내 보낸 메서드를 만드는 데 문제가있을 수 있습니다 (기본값은 내보내기되지 않음). 이 경우 (말장난 의도) X수출을 표시 하기 위해 식별자에 접두사를 붙이는 것이 일반적 입니다. 예를 들면 :X日本語

참조 : 유니 코드 식별자에 무슨 일이 있습니까? FAQ에서.

스타일

일반적인 스타일에 관한 한, 항상 camel-case를 사용하는 것입니다 (앞에서 언급 한 첫 글자는 제외). 여기에는 상수, 함수 및 기타 식별자가 포함됩니다. 예를 들어 (내 보낸) 상수 목록은 다음과 같습니다.

const (
    StateConnected = iota
    StateError
    StateDone

    internalStateMask = 0x2 
)

또한 약어는 항상 동일한 대소 문자로 작성되므로 다음 중 하나를 작성합니다.

dbWrite
writeDB

writeDb또는 대신 DbWrite.


Go에서는 혼합 캡을 사용하는 것이 관례입니다. 문서에서 : https://golang.org/doc/effective_go.html#mixed-caps

마지막으로 Go의 관례는 여러 단어로 된 이름을 쓰는 데 밑줄 대신 MixedCaps 또는 mixedCaps를 사용하는 것입니다.

대문자로 시작하는 파일 수준 이름은 패키지 수준에서 내보내집니다. https://golang.org/doc/effective_go.html#Getters

또한 모두 대문자로 두문자어를 쓰는 것이 관례입니다. 그래서 아래는 괜찮습니다.

writeToMongoDB // unexported, only visible within the package

또는

WriteToMongoDB // exported

그리고 아닙니다 :

writeToMongoDb

이름

Go에서 이름은 다른 언어만큼이나 중요합니다. 의미 론적 효과도 있습니다 . 패키지 외부의 이름의 가시성은 첫 번째 문자가 대문자인지 여부에 따라 결정됩니다 . 따라서 Go 프로그램의 명명 규칙에 대해 이야기하는 데 시간을 할애 할 가치가 있습니다.

패키지 이름

패키지를 가져 오면 패키지 이름이 콘텐츠에 대한 접근자가됩니다.

import "bytes" the importing package can talk about bytes.Buffer. It's helpful if everyone using the package can use the same name to refer to its contents, which implies that the package name should be good: short, concise, evocative. By convention, packages are given lower case, single-word names; there should be no need for underscores or mixedCaps. Err on the side of brevity, since everyone using your package will be typing that name. And don't worry about collisions a priori. The package name is only the default name for imports; it need not be unique across all source code, and in the rare case of a collision the importing package can choose a different name to use locally. In any case, confusion is rare because the file name in the import determines just which package is being used.

Another convention is that the package name is the base name of its source directory; the package in src/encoding/base64 is imported as "encoding/base64" but has name base64, not encoding_base64 and not encodingBase64.

The importer of a package will use the name to refer to its contents, so exported names in the package can use that fact to avoid stutter. (Don't use the import . notation, which can simplify tests that must run outside the package they are testing, but should otherwise be avoided.) For instance, the buffered reader type in the bufio package is called Reader, not BufReader, because users see it as bufio.Reader, which is a clear, concise name. Moreover, because imported entities are always addressed with their package name, bufio.Reader does not conflict with io.Reader. Similarly, the function to make new instances of ring.Ring—which is the definition of a constructor in Go—would normally be called NewRing, but since Ring is the only type exported by the package, and since the package is called ring, it's called just New, which clients of the package see as ring.New. Use the package structure to help you choose good names.

Another short example is once.Do; once.Do(setup) reads well and would not be improved by writing once.DoOrWaitUntilDone(setup). Long names don't automatically make things more readable. A helpful doc comment can often be more valuable than an extra long name.

Getters

Go doesn't provide automatic support for getters and setters. There's nothing wrong with providing getters and setters yourself, and it's often appropriate to do so, but it's neither idiomatic nor necessary to put Get into the getter's name. If you have a field called owner (lower case, unexported), the getter method should be called Owner (upper case, exported), not GetOwner. The use of upper-case names for export provides the hook to discriminate the field from the method. A setter function, if needed, will likely be called SetOwner. Both names read well in practice:

owner := obj.Owner()
if owner != user {
    obj.SetOwner(user)
}

Interface names

By convention, one-method interfaces are named by the method name plus an -er suffix or similar modification to construct an agent noun: Reader, Writer, Formatter, CloseNotifier etc.

There are a number of such names and it's productive to honor them and the function names they capture. Read, Write, Close, Flush, String and so on have canonical signatures and meanings. To avoid confusion, don't give your method one of those names unless it has the same signature and meaning. Conversely, if your type implements a method with the same meaning as a method on a well-known type, give it the same name and signature; call your string-converter method String not ToString.

MixedCaps

Finally, the convention in Go is to use MixedCaps or mixedCaps rather than underscores to write multiword names.

ref: Effective Go


In Golang, any variable (or a function) with an identifier starting with an upper-case letter (example, CamelCase) is made public (accessible) to all other packages in your program, whereas those starting with a lower-case letter (example, camelCase) is not accessible to any package except the one it is being declared in.

You should use CamelCase in case you intend to use the variable (or function) in another package, or you can safely stick with camelCase.

ReferenceURL : https://stackoverflow.com/questions/38616687/which-way-to-name-a-function-in-go-camelcase-or-semi-camelcase

반응형