Function attribute best practices

Ali Çehreli acehreli at yahoo.com
Tue Sep 13 21:18:04 UTC 2022


On 9/13/22 10:08, Paul Backus wrote:

 > Here's my attempt, covering all the attributes found under
 > [`MemberFunctionAttribute`][1] in the language spec:
 >
 > |Attribute|Affects |Inferred?|
 > |---------|--------|---------|
 > |nothrow  |Function|Yes      |
 > |pure     |Function|Yes      |
 > |@nogc    |Function|Yes      |
 > |@safe    |Function|Yes      |
 > |@system  |Function|Yes      |
 > |@trusted |Function|No       |
 > |@property|Function|No       |
 > |@disable |Function|No       |
 > |const    |this    |No       |
 > |immutable|this    |No       |
 > |inout    |this    |No       |
 > |shared   |this    |No       |
 > |return   |this    |Yes      |
 > |scope    |this    |Yes      |
 >
 > In general, attributes with a 'Yes' in the 'Inferred?' column should not
 > be applied explicitly to functions that are subject to [attribute
 > inference][2]. This includes functions defined inside templates, as well
 > as nested functions and functions with an inferred return type (i.e.,
 > `auto` functions).
 >
 > [1]: https://dlang.org/spec/function.html#MemberFunctionAttributes
 > [2]: https://dlang.org/spec/function.html#function-attribute-inference

That is great! I think we can improve it with guidelines for when to 
write an attribute or not.

For example, carried over from C++, I have this guideline: "put const to 
as many member function as you can." That guideline makes the function 
more useful because I can call it on mutable, const, and immutable 
objects. Great... Programmers can understand that.

Now let's compare it to what the const attribute on a member function 
says (I did not find it in the spec; so making it up): "Makes the 'this' 
reference const." Although correct, it does not help the programmer.

Or... What does pure mean? Does it tell the outside world that the 
function is pure or does it require to be called from pure code? I put 
that here because e.g. 'immutable' on a member function kind of does 
that: It requires to be called on an immutable object. Ok, not a fair 
comparison because there is no "pure object" but still, these are 
thoughts that I think programmers have in mind. (I do. :) )

Ali



More information about the Digitalmars-d-learn mailing list