Alternatives to OOP in D
H. S. Teoh
hsteoh at qfbox.info
Mon Sep 1 22:13:12 UTC 2025
On Mon, Sep 01, 2025 at 09:28:29PM +0000, Andy Valencia via Digitalmars-d-learn wrote:
> On Monday, 1 September 2025 at 16:26:15 UTC, H. S. Teoh wrote:
>
> > OOP is useful for certain classes (ha) of problems, but not all, as
> > the OOP proponents would like you to believe. Some classes of
> > problems are better solved with other means.
>
> Do note that I had to bite the bullet and write an OO File class, just
> so I could write emulated (but compilation/type compatible) subclasses
> of File. String- and ubyte[]-based reader/writer instances,
> specifically. Think Python's StringIO.
Yeah, OO is useful for that.
OTOH I've also tended to use the following pattern for testing functions
that do I/O:
auto processFile(File = std.stdio.File)(File input) {
...
foreach (line; input.byLine) { ... }
...
}
unittest {
struct MockFile {
auto byLine() {
return ... /* mock implementation of .byLine here */
}
}
auto output = processFile(MockFile());
assert(output == expectedOutput);
}
So normally, `File` will bind to std.stdio.File, but the unittest can
override this to be a mock file type where I can use simple code to
inject input strings to test the implementation of processFile. The nice
thing about this is that MockFile doesn't have to implement most of
std.stdio.File's API; only those actually used by processFile().
Whereas if you used a subclass you may have to write more code just to
do lip service to the base class API so that it will compile, even if
some of this code may actually never get used.
Also, since this is a template, when not compiling with -unittest the
MockFile instantiation of processFile never happens, so the release
build binary does not contain unittest template bloat, and processFile
binds directly to std.stdio.File without any intermediate indirections.
> It sure made a number of things easy once I could use polymorphism wrt
> File. I'm very glad that D has classic OO semantics available.
[...]
As I said, OO has its place, and should be used when it's appropriate.
Just don't shoehorn every programming problem and its neighbour's
NP-complete dog into an OO paradigm when it doesn't even fit OO's
domain.
T
--
All men are mortal. Socrates is mortal. Therefore all men are Socrates.
More information about the Digitalmars-d-learn
mailing list