我喜欢这样一个事实,即使用%
后缀命名类的约定,因为它有助于区分实例与高阶类。
(define ingredient%
(class object%
(init-field name taste price color)
(super-new)))
(define (total-price ingredients)
(for/sum (ingredient ingredients)
;; here "ingredient" stands for the instance, not the class ingredient%
(get-field price ingredient)))
另一方面,当我需要一个结构时,我正在努力为不与结构名称冲突的实例找到名称。
(struct ingredient (name taste price color))
(define (total-price ingredients)
(for/sum (igrdt ingredients)
;; igrdt is definitely a bad name
(ingredient-price igrdt)))
;; it looks even worse in arguments
(define (taste igrdt)
(match (ingredient-taste igrdt)
(('good) "It's good!")
(('bad) "Yuk...")
(else "It's something.")))
所以我也开始使用结构的后缀:§
。这个符号很容易在我的键盘上访问,唉可能不是标准的QWERTY符号,所以我想我稍后会把它改成$
。
(struct ingredient§ (name taste price color))
(define ingredient (ingredient§ "Carrot" 'good 1.0 'orange))
(displayln (format "I'm making a ~a cake." (ingredient§-name ingredient)))
无论符号是什么,我发现使用结构的后缀可以让您自由选择清晰的实例名称,而不必从变量中删除随机元音。
另一个选择是使用%
作为结构的前缀和类的后缀,以便结构访问器保持可读性:(%ingredient-name ingredient)
。
从快速的GitHub研究来看:https://github.com/search?p=1&q=struct-out+language%3Aracket&type=Code
看起来每个人都是按原样使用结构(除了少数使用CamelCase的学生,因为他们已经习惯了)。
那么我该怎么做才能将实例与结构类型区分开来呢?它甚至相关吗?我想远吗?我应该在软件工程上问这个吗?
命名惯例是struct
s没有特殊符号。这可能是因为struct
比类,单位,签名,组件等更像“计划”,但我可能是错的。
为struct
发明类似于类,单位等的东西没有任何问题。但它会随意而且是个人的,因此它应该被记录下来。
自从我开始使用Typed Racket以来,我一直在给结构首写字母,我对此非常满意。 Typed Racket中的大多数类型名称以大写字母开头,而struct是类型名称,因此初始大写的约定使结构名称看起来与其他类型一致。
即使在非类型化的Racket中,我也一直遵循这个惯例,它使代码清晰可读,并且当我将它移动到Typed Racket时没有问题。