On Wed, Jun 17, 2020 at 11:50:27AM +0000, Per Nordlöw via Digitalmars-d-learn 
wrote:
> Should a range-compliant aggregate type realizing a parser be encoded
> as a struct or class?

Preferably a struct IMO, but see below.


> In dmd `Lexer` and `Parser` are both classes.

Probably for historical reasons.


> In general how should I reason about whether an aggregate type should
> be encoded as a struct or class?

1) Does it need runtime polymorphism? If it does, use a class. If not,
probably a struct.

2) Does it make more sense as a by-value type, or a by-reference type?
In several of my projects, for example, I've had aggregate types start
out as structs (because of (1)), but eventually rewritten as (final)
classes because I started finding myself using `ref` or `&` everywhere
to get by-reference semantics.

My rule-of-thumb is basically adopted from TDPL: a struct as a
"glorified int" with by-value semantics, a class is a more traditional
OO object. If my aggregate behaves like a glorified int, then a struct
is a good choice. If it behaves more like a traditional OO encapsulated
type, then a class is probably the right answer.


T

-- 
Many open minds should be closed for repairs. -- K5 user

Reply via email to