John Donvan
John Donvan

Reputation: 566

Should I have different APIs methods for different concrete classes?

I am writing an APIs for greeting cards.

A card contains just List of lines and Card ID. The card has method called Greeting.

A line is just set of characters.

I have an interface Card and several concrete classes that implements this interface, i. e, ChristmasCard, EasterCard... etc.

I am writing an API method that returns the card by ID.

From design perspective, is it better to write single API method that returns any type of card based on the ID, or, its better to write an API for every card type ?

Upvotes: 0

Views: 51

Answers (1)

Alexis Pavlidis
Alexis Pavlidis

Reputation: 1080

These kinds of questions have always the same answer which is: It depends, all the design patterns have trade offs and that's software engineering.

In general though my approach would be something like the following.
So having the Card being the abstraction and containing the id you should probably define the findById returning any type (meaning it will return the abstraction type, Card) because this operation is only using the id field which is agnostic to the derivatives of the Card class. In that way your API code is decoupled from the specific implementations of the Card interface. You can go a little more further by using generics if you want your code to be reused to other Entities who share the same logic.

If you write an API for every card type as you proposed then your API is coupled to the implementation so every new derivative added would affect your API as well (as you should probably add the new added type to your API).

In general you want to depend on abstractions and not on implementation details

Upvotes: 2

Related Questions