Use UFCS for reducing dependencies

Paul Backus snarwin at gmail.com
Sun Jul 17 16:15:07 UTC 2022


On Sunday, 17 July 2022 at 12:08:38 UTC, Bastiaan Veelo wrote:
> 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);
>     }
> }
> ```

Another possibility:

```d
struct PNG
{
     static PNG load(Source)(Source source)
         if (isInputRange!Source && is(ElementType!Source == 
ubyte))
     {
         // etc.
     }
}
```

This way, the PNG module itself is completely agnostic about what 
data source it loads from, and has no explicit dependencies 
(except on `std.range`, I guess).


More information about the Digitalmars-d mailing list