REST API Client – When to Use Abstract Classes vs Interfaces

abstract classcinterfacesprogramming practicesweb-api

I'm trying to write a REST API client for practice and I'm having trouble figuring out how lay out the project.

The approach I'm taking right now has Actions, DomainObjects, Requests, and a class that deals with authorization and headers and such (CoreClient) that exposes a generic DoPut<T>(string address,T item) and similar verbs.

Examples

Action: UpdateRecordCode (contains logic)

DomainObject: RecordCode (entity)

Request: UpdateRecordCodeRequest (entity, holds a record Id and a list of things to add to it)

Question 1:
How do I determine which classes should implement interfaces – and what interfaces I should have in the first place – and which should inherit?

My best guess so far is that Actions should inherit from an ActionBase because each Action is basically a kind of ActionBase. DomainObjects should probably implement something so that they're consistent, but I'm not sure what.

The trickiest part is Requests; ideally, I'd like other parts of the application to handle Requests generally, such that I could, in the UI, have a list of Requests a user might choose. I've tried this both ways, but keep going back to a concrete class as both feel weird. Interfaces, for example, end up with having to say something like IRequest<UpdateRecordCode<UpdateRecordCodeRequest>>, which seems silly.

Question 2: Am I just doing this wrong? I feel like everybody's written a dozen API clients – I've written a number with minimal planning – but I'm trying to do this "right" this time around and it's, well, hard.

I know there are many duplicates of the "Interface or abstract class?" question, but I think this is distinct from those as it's about how they work together rather than simply "X or Y?"

Best Answer

The over-engineering architects will disagree with me, but in a language such as C#, interfaces only exist to allow multiple inheritance, and they do that poorly, having no implementation. That is, if you can find some common implementation code, it is better to use a base class instead of an interface, except when you need some form of multiple inheritance. Since C# only allows multiple inheritance in the form of interfaces, you are stuck with an interface.

In the case of your specific example, you have not explained why the design warrants interfaces or classes. What you call a "request" seems to be a combination of of an action (verbs) and parameters (nouns). This can be expressed in many ways, but the most logical for me would be a composite object containing the action and parameters. The action does not have to be specified using a class or an interface.