Should a parser type be a struct or class?

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Jun 17 14:04:18 UTC 2020


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


More information about the Digitalmars-d-learn mailing list