Is using generics like this a type of code smell? [closed]

Posted on

Problem

Lets say I have the following interfaces

interface IRealm
{
    Tile GetTile(int x, int y);
    bool SetTile(int x, int y, Tile tile);
}

interface IRealmSize
{
    int TilesWide { get; }
    int TilesHigh { get; }
}

The intefaces are separate as I have both infinite realms with no size and bounded realms with a fixed size.
One class uses these realms, but requires that the realm has a fixed size.

class RealmRenderer<T> where T : IRealm, IRealmSize
{
    public RealmRenderer(T realm) { ... }
}

Is there any drawbacks to doing it like this?

I could see an alternative like the following

interface IBoundedRealm : IRealm, IRealmSize { /* intentionally empty */ }

class RealmRenderer
{
    public RealmRenderer(IBoundedRealm realm) { ... }
}

But this creates a stricter requirement for the various realm types to implement this specific interface just to satisfy the renderer, where using generics leaves this specific requirement out of the realm implementation.

Solution

Having multiple interface constraints on a single generic parameter isn’t a code smell; it can make sense in a number of cases.

However, for the two interfaces you mention, does it make sense to have an IRealmSize that isn’t part of an IRealm? It may make be more appropriate to use:

interface IBoundedRealm : IRealm
{
    int TilesWide { get; }
    int TilesHigh { get; }
}

Leave a Reply

Your email address will not be published. Required fields are marked *