4

Say i have a Rest API that has a POST and GET method.

If i want to overwrite a resource in the API i can call the GET method to get the original item and then call the POST method to replace that resource after i am done modifying it.

Should i add the update functionality to the client class like in the first approach or should i make a new class and add the update functionality there and call the client class externally like in the second approach

First approach

class BookApiClient{

 Client restClient = ClientBuilder.newClient();

 public Book getBook(String id){

 // code to get book using rest client
 }

 public void postBook(){

 //code to post a book

 }


 public void updateBookTitle(String id, String newTitle){

  Book book = getBook(id);

  book.setTitle(newTitle);

  postBook(book);

 }

}

Second approach

class BookUpdater{

 BookApiClient bookService;

 public BookUpdater(BookApiClient bookService){

   this.bookService = bookService;

 }

  public void updateBookTitle(String id, String newTitle){

  Book book = bookService.getBook(id);

  book.setTitle(newTitle);

  bookService.postBook(book);

 }

}

Would it be a violation of single responsibility principle to add the updateBookTitle method to the client class or have that as a different like in the second approach

Claudiga
  • 149

2 Answers2

6

The first approach seems fine and consistent. It doesn't contradict SRP: The single responsibility principle is not about what the class does but about its reasons to change, as explained by Uncle Bob (the "inventor" of SRP) in this excellent article.

Furthermore, your REST API could offer a proper PUT instead of POST for a full replace (and PATCH for a partial update). Using the first approach would therefore have the advantage of hiding the details of the API, and offer a simpler interface for handling books.

The BookAPIClient would then act as a remote facade. The single reason to change it would be the evolution of the book API.

Christophe
  • 81,699
-1

Yes.

The client should only be concerned with communication with the server. It should only have methods which the server offers. It's only, 'reason to change' if you will, should be that the server has changed.

UpdateTitle adds extra business logic which should be in a different layer of your application.

What if, for example, when updating a title you also want to write an audit log to your auditClient? do you now inject audit client into BookClient just in case that one method is called? Where would the madness end?

Furthermore your GET book request should use a POST incase the id string exceeds the max URL length!!!

Ewan
  • 83,178