Use UFCS for reducing dependencies

Bastiaan Veelo Bastiaan at Veelo.net
Sun Jul 17 12:08:38 UTC 2022


On Saturday, 16 July 2022 at 22:10:13 UTC, Hipreme wrote:
> Old habits die hard.

[...]

> After some refactoring in my project, trying to reduce 
> dependencies, I came to a solution that we should not create 
> dependencies like that.

Instead of using versions and sub-modules, using templates and 
conditional compilation is probably easier:

```d
struct PNG
{
     this(T)(T source)
     {
         static if (is(T == string))
         {
             pragma(msg, "conditional dependency on stdio");
             import std.stdio;

             // Load from file
         }
         else static if (is(T == ubyte[]))
         {
             // Decode from memory
         }
         else
             static assert(false, "Unsupported source type " ~ 
T.stringof);
     }
}

void main()
{
     // auto png = PNG("somewhere.png");
     auto png = PNG(new ubyte[10]);
}
```

Only the code that corresponds to the type that the constructor 
is called with gets compiled in, including any imports that are 
there. So the import of `std.stdio` only happens if a PNG is read 
from file.

Another tip: unless you need polymorphism or reference behaviour 
for your type, a `struct` is often preferred over a `class`. Old 
habits die hard :-)

-- Bastiaan.


More information about the Digitalmars-d mailing list