Custom attributes (again)

Kapps opantm2+spam at gmail.com
Fri Apr 6 00:17:34 PDT 2012


On Friday, 6 April 2012 at 06:47:56 UTC, Walter Bright wrote:
> On 4/5/2012 5:00 AM, Manu wrote:
> > C# and Java both have attributes, following these established
> design patterns, I
> > don't think there should be any mystery over how they should
> be implemented.
>
> I was thinking of something along the lines of what has been 
> proposed here earlier:
>
>   @attr(identifier = expression)
>
> as a storage class, like:
>
>   @attr(foo = bar + 1) int x;
>
> and then:
>
>   __traits(hasAttribute, x, foo)
>
> would return true, and:
>
>   __traits(getAttribute, x, foo)
>
> would return the expression (bar+1). The expression would be 
> compile-time only, evaluated at the point of declaration.
>
> The implementation is simple enough, just attach to each symbol 
> an array of (identifier,expression) pairs.
>
> You could also omit the expression, and just have:
>
>   @attr(bar) int y;

I like it for the most part. One thing I'd like to see is placing 
multiple attributes both by using multiple @attr()'s, and by 
using comma separated identifier/expression pairs inside a single 
@attr. In other words, the following two declarations would be 
identical.

@attr(Description = "Blah", ReadOnly)
int ID;

@attr(Description = "Blah")
@attr(ReadOnly)
int ID;

My only concerns:

First, @attr() is a little verbose / not exactly pretty. This 
isn't really a big issue, since attributes aren't exactly piled 
on and it makes it easy to tell what's going on. It is a little 
uglier than in other languages however.

Secondly, from what I can tell it's an arbitrary key value combo. 
What would happen if you're working on a larger project and two 
unrelated libraries try to use the same attribute name to mean 
different things? With the module system this issue doesn't exist 
since you have to import it and can selectively/privately do so, 
but from what I understand the method you're proposing doesn't 
declare the attribute itself at all. Am I just misunderstanding 
this part?


More information about the Digitalmars-d mailing list