Tuesday, September 20, 2011

More Cowbell

I've been playing with Scala a bit since my last post, I actually took a little hiatus from Sedition to avoid burnout...

Scala is a very sexy language, it's very hard not to crack a sheepish grin when reading about it's features.

for instance:

class Foo[T <: { def bar(): Int }]
{
}


defines a generic class with the constraint that whatever class is used to specialize "T" must declare a function, 'bar' that returns an integer. "Big deal", you say, "use an interface" in in Java/C#. The above approach is cleaner you are using the minimal constraints to specify your requirements. (Note that I'm intentionally not using Scala vernacular for these paradigm/architecture terms, because I'd probably get it wrong).

in C# you could write something like:

interface IBar
{
   public int bar();
}

class Foo<T> where T : IBar
{
}


Not only is that more verbose than the Scala, it's more complicated that it needs to be. In my experience what tends to happen in code like that is that IBar starts getting all sort of things added to it. Then you find someone implementing 'stub' functions in some class solely to implement the interface, and solely to use as the type argument. (The open/closed principal can greatly mitigate this, you should strive for it in your code, but the entropy pressure is there nonetheless).

In C++, you can get an implicit type constraints just by using a function:

template<class T> class Foo
{
    void someFn(T& ob)
    {
         int val = ob.bar();
    }

};

this also creates a requirement that type T implement bar.... ...but it is implicit, and  not discoverable if Foo is of any appreciable size or is derived from later on.


--P


No comments:

Post a Comment

I welcome you're thoughts. Keep it classy, think of the children.