lundi 6 janvier 2020

Generics or Inheritance for API request object

I know this might be an opinion-based question, but, I'd rather to ask as there might be some design principle for this.

I'm having a .net C# web API application to expose few APIs to retrieve some data from a database. I'm also using mediateR on this project. The APIs, they all get one request object but all of them have exact same properties. Imagine, we have a BaseProduct class from which ProductA, ProductB, and ProductChave been inherited in the domain project. Now, I need to expose APIs to return these three objects to the users. Here's an example of two of the request objects.

With Inheritance:

public abstract class BaseGetProductRequest { // the props here }
public class GetProductARequest : BaseGetProductRequest, IRequest<GetProductAResponse> { }
public class GetProductBRequest : BaseGetProductRequest, IRequest<GetProductBResponse> { }

Each of the above requests also has its own request handler class.

With using generics: (BaseProduct is a domain object class from which different product types are inherited)

public class GetProductRequest<TProductType> where TProductType : BaseProduct, IRequest<ProductType[]> { }

So, the question is: Which one the following would be a better approach to take from a design point of view?

  1. To take the Inheritance approach as above
  2. Or to implement the requests and request handlers using generics so we'll end up with less files

Personally, I would prefer the first approach as I want to literally have separate request objects for each API, this way it looks cleaner to me besides that would be consistent with the rest of the code as well (as not all the request objects can be implemented generically). Besides, if by any chance in the future there is a need to add a type-specific property for a request object, then, our code will be more flexible with that change.

Is there like any specific design guidelines which recommends for example taking one over another? Thanks for your opinions in advance.

Aucun commentaire:

Enregistrer un commentaire