Glued acronyms and golang naming convention

ababo picture ababo · Oct 3, 2016 · Viewed 9.2k times · Source

Is there a way to make the constants below to be more readable without breaking golang naming convention?

const ( // stream types
    MPEGDASHStream  = iota
    HLSStream       = iota
    MPEGTSUDPStream = iota
    MPEGTSRTPStream = iota
)

Answer

icza picture icza · Oct 3, 2016

Go's naming convention prefers MixedCaps rather than underscores, so don't use them. Source: Effective Go: MixedCaps

Usually when you have constants for different values of an entity, a more easily readable way is to start constant names with the entity, which is then followed by the name of the concrete value. Great examples are the net/http package:

const (
    MethodGet  = "GET"
    MethodHead = "HEAD"
    MethodPost = "POST"
    // ...
)

const (
    StatusContinue           = 100 // RFC 7231, 6.2.1
    StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
    StatusProcessing         = 102 // RFC 2518, 10.1

    StatusOK                 = 200 // RFC 7231, 6.3.1
    StatusCreated            = 201 // RFC 7231, 6.3.2
    // ...
)

Also you don't need to repeat the expression with iota identifier. Spec: Constant declarations:

Within a parenthesized const declaration list the expression list may be omitted from any but the first declaration. Such an empty list is equivalent to the textual substitution of the first preceding non-empty expression list and its type if any. Omitting the list of expressions is therefore equivalent to repeating the previous list.

So in your case it could simply look like this, which is quite clear and readable:

// stream types
const (
    StreamMPEGDASH = iota
    StreamHLS
    StreamMPEGTSUDP
    StreamMPEGTSRTP
)

Also see Go Code Review Comments for more details. Acronyms can be found in the Initialisms section:

Words in names that are initialisms or acronyms (e.g. "URL" or "NATO") have a consistent case. For example, "URL" should appear as "URL" or "url" (as in "urlPony", or "URLPony"), never as "Url". Here's an example: ServeHTTP not ServeHttp.

This rule also applies to "ID" when it is short for "identifier," so write "appID" instead of "appId".