In Go is naming the receiver variable 'self' misleading or good practice?

前端 未结 6 1453
青春惊慌失措
青春惊慌失措 2020-12-01 02:42

I have seen a fair amount of blogs & videos on Go and as far as I recall, none of the authors use \'self\' or \'this\' for the receiver variable when writing methods. H

6条回答
  •  生来不讨喜
    2020-12-01 03:17

    I can see no particularly compelling reason to avoid the this / self convention. Other posts here merely cite community norms or describe aspects of method dispatch which have no bearing on naming conventions.

    These code review guidelines reject this or self without giving any reason at all, unless you can read something into the implied claim that go places less emphasis on methods than other languages.

    One advantage of committing to a this or self convention is that it helps to highlight violations of the Law of Demeter. Code such as this:

    func (w *ChunkWriter) Write(recId uint32, msg []byte) (recs uint64, err error) {
        recs = w.chunk.Records
        err = w.handle.Write(recId, msg)
        if err == nil {
            recs++
            w.chunk.Records = recs
        }
        return
    }
    

    appears on the face of it to be reaching into w's members inappropriately. In fact it is accessing members of its receiver, which is perfectly proper.

提交回复
热议问题