【发布时间】:2016-12-15 00:15:39
【问题描述】:
我将发布我的代码:
/*
* Role will ALWAYS reserve the session key "role".
*/
package goserver
const (
ROLE_KEY string = "role"
)
type Role string
//if index is higher or equal than role, will pass
type RolesHierarchy []Role
func (r Role) String() string {
return string(r)
}
func NewRole(session ServerSession) Role {
return session.GetValue(ROLE_KEY).(Role)
}
func (this Role) IsRole(role Role, hierarchy RolesHierarchy) bool {
if role == this {
return true
}
if len(hierarchy) == 0 {
return false
}
var thisI int = 0
var roleI int = 0
//Duped roles in hierarchy are verified in verifyConfig during parse
for i, r := range hierarchy {
if this == r {
thisI = i
}
if role == r {
roleI = i
}
}
//TODO I can probably condense what follows into one if
if thisI == 0 && roleI == 0 {
return false
}
return thisI >= roleI
}
func (this *Role) AssumeRole(session ServerSession, role Role) {
session.SetValue(ROLE_KEY, role)
*this = role
}
需要注意的是,ServerSession也是一个接口,调用“ServerSessioner”对我来说感觉很奇怪。
我正在玩弄用 IsRole() 和 AssumeRole() 创建接口的想法,但是“Roler”似乎很不稳定。我突然意识到,除了标准的“er”后缀之外,我真的不知道或曾经遇到过接口的命名约定。我似乎确实记得 VS C++ 的约定是在所有内容前面加上一个“I”。这是“惯用语”吗?
有什么建议吗?
【问题讨论】:
-
我会称它为
RoleSupport,但接触English.SE 确实是一项有趣的尝试。请考虑不要使用this来命名方法接收者:这是不习惯的 Go 语言。 One example 讨论这些问题。 -
不是单个字母,而是有意义的缩写——单个字母可以用于短函数(包括你的)。 “任何其他语言”肯定是夸大其词。好吧,出于某种原因,这对我来说不是问题:不同的语言只是感觉不同。新手程序员确实努力成为一招一式的狗,试图将他们学到的技能带到他们面临的任何新语言中(我自己肯定去过那里),但理解语言背后的哲学并坚持下去总是更好。跨度>
-
至少这降低了下一个程序员处理你的代码的 WTF 因素。 ;-)
-
WTF 因素,“this”或“self”在我“知道”的至少六种语言中是“惯用的”
-
@Dale 它不在 Go 中,请参阅:In Go is naming the receiver variable 'self' misleading or good practise?
标签: go interface naming-conventions naming