vendredi 23 juin 2023

Wrap a loosely typed interface and make it strongly typed

There is an external API that I have to use with the following signature:

class Item {
    String type;
    String name;
    ///...setters, getters
}

interface ItemFinder {
     List<Item> getItemsByType(String type);
}

In my application,

If I call getItemsByType("vegetables"), then I receive List(Item(type="vegetables", name="Lettuce"), Item(type="vegetables", name="Tomato"))

If I call getItemsByType("berries"), then I receive List(Item(type="berries", name="Strawberry"), Item(type="berries", name="Cranberry"))

If I call getItemsByType("shapes"), then I receive List(Item(type="shapes", name="Square"), Item(type="shapes", name="Triangle")) etc... and there are dozens of types like this.

I want to avoid common type errors, I.e. avoid assigning berries to vegetables.

What is the best way to wrap this loosely typed interface, to make it more strongly typed? I.e. what is the best way to implement something like the following:

class Vegetable /* maybe extends something ? */ {
    String name;
}
class Berry /* maybe extends something ? */ {
    String name;
}
class Shape /* maybe extends something ? */ {
    String name;
}
...
List<Berry> berries = getStronglyTyped(Berry.class); // maybe some factory here instead of a class ?

Aucun commentaire:

Enregistrer un commentaire