Templates for DRY code

Ali Çehreli acehreli at yahoo.com
Sat Jan 6 01:33:11 UTC 2018


Nothing new here... I'm just reminded of how templates can help with DRY 
(don't repeat yourself) code.

Here is a piece of code that uses an alias to be flexible on the element 
type:

import std.conv;

alias MyType = double;    // <-- Nice, MyType is used twice below

void main() {
     MyType[] a;

     // ...

     string s = "1.2";
     a ~= s.to!MyType;     // <-- This usage is troubling
}

Although to!MyType looks like a good idea there, the two usages of 
MyType must be kept in sync manually. Why should we repeat MyType when 
it's already known to be ElementType!(typeof(a)) anyway. (Unfortunately, 
that syntax is not very clear in code.)

One solution is to wrap ~= in a function template. Now the conversion is 
automatically made to the element type of the array:

import std.conv;

void append(T, S)(ref T[] arr, S s) {
     arr ~= s.to!T;
}

void main() {
     double[] a;    // <-- Removed MyType alias as well

     // ...

     string s = "1.2";
     a.append(s);
}

In simple cases like this, one may not even need the alias. 'double' 
appears in just one place there.

I think append() could be a part of std.array but I can't find anything 
like that in Phobos.

Ali


More information about the Digitalmars-d-learn mailing list