Discuss: Classes are well supported in D, with Design by Contracts. Shouldn't we take advantage of that?
H. S. Teoh
hsteoh at qfbox.info
Sat Sep 13 15:26:15 UTC 2025
On Sat, Sep 13, 2025 at 12:43:38AM +0000, Brother Bill via Digitalmars-d-learn wrote:
> I'm not clear about why 'class'es are on the 'avoid' list.
Whose avoid list?
I'd say that I usually don't use classes, not because I'm trying to
avoid them, but because I don't need to. Most of the time my programming
problem can be solved with by-value structs, DbI (design by
introspection), and pseudo-functional style range-based programming.
But that doesn't mean I don't use classes at all. If my programming
problem is best solved using classes, why not use them? They're in D
for a reason.
The thing about D is that it is multi-paradigm. This means that your
toolbox has more than just classes and DbC. You also have DbI,
templates, metaprogramming, compile-time introspection, functional-style
range-based programming, string mixins, low-level assembly, etc.. Each
of these tools have their areas of strength and areas of weakness; you
choose them based on the specific programming problem at hand, and
you're not obligated to use any one of them if you choose not to.
There's this joke that applying computer technology is finding the right
wrench to pound in the correct screw, which may be an apt description of
what one is forced to do in many single-paradigm languages where the
only tool you have is a wrench, and you have to use it whether or not
your programming problem is a bolt. But I like to think that in D, you
actually have a screwdriver that you can use when your problem is a
screw, and it also has a hammer when you need to pound in a nail. Use
the right tool for the right job.
> D has excellent support for Single inheritance, Interfaces, Design by
> Contract (DbC), GC, etc.
I don't use DbC often, but I do appreciate that D has it when I do use
it.
> I'm aware that there is a small run time cost for selecting the right
> virtual method.
Yes, but it also depends on whether this is on your program's hot path
or not. If not, uglifying your code for the sake of "performance" is
usually wasted effort. Your decision rather should be driven by which
construct better suits your programming problem, than blindly foregoing
virtual methods (or any other construct) because of "performance"
without even having profiled your program to learn its actual
bottlenecks. (Which are almost always not where you think they are. I
used to think I knew, until I started using real profilers and
discovering that I was wrong most of the time.)
> To reduce this cost, one must final-ize methods that don't need to be
> overridden.
Again, profile before making decisions like these.
> Using classes is a major reason that I chose D.
[...]
Great. Welcome to D!
T
--
BREAKFAST.COM halted...Cereal Port Not Responding. -- YHL
More information about the Digitalmars-d-learn
mailing list