2

I have a Data Access Layer that uses a json API.

If the structure of the program looks like:

    Controller
        |
 Data Access Layer

Is it best to convert the response strings into objects in the Data Access Layer and return them as types to the Controller

OR

Should I be returning strings back to the Controller, when it makes requests, and deserializing the json string there?

I figured that if I ever need to attach a new API to the program then passing objects to the Data Access Layer will hide the fact I'm communicating via json. However, I also realise that having a method like, in the data access layer:

public Foo Get(Bar bar)

will have to serialize the object to json, make the request and then deserialize back to an object. This clearly breaks the single responsibility principle.

  • 1
    If having the DAL manage (de)serialization violates the single responsibility principle, how does have the controller handle it not violate the SRP? – JimmyJames May 17 '17 at 16:29
  • @JimmyJames That is a very good point. I definitely overlooked that but after reading Ewan's answer it makes perfect sense now. – Joe Dawtry May 17 '17 at 18:58
4

"Data Access Layer" is perhaps not the right term, But I think it IS the right place.

Say I have a repository class which is implemented with a database. It has a tonne of get, update, process etc methods on it which essentially store and retrieve data objects.

Now a highly paid consultant says we need to move everything into cloud based nano services with agile(tm).

So I get the interface for the repository and write a new implementation which calls an api, which runs the original repo and returns the result.

All fine and dandy, the interface is hiding the implementation from the consuming code.

The fact that each implementation is tightly coupled to either HttpClient, JsonSerialiser or MsSqlClient is less important.

Although its not impossible to consider an implementation where these things are wrapped in interfaces and injected. They already have an abstraction layer in the form of the repository.

The only odd thing is naming. I now have a repository I would probably have called a service if I had written it the other way around.

But this is probably a reason to stop calling things MyObjectService.

  • 1
    note: I just thought. If you actually wrote a json serialiser from scratch and put the code in the repo that would be wrong. I'm assuming you are using Json.net or some other library – Ewan May 17 '17 at 17:34
  • I am indeed using a library. Thanks for the great answer! – Joe Dawtry May 17 '17 at 18:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.