简体   繁体   中英

Best way to update an object with another object of the same type in java in rest

I've came up with this question while designing a REST API.

To update a resource the client must submit the entire resource with updated fields. The thing is that not all fields are editable. What if the client sends a resource with updated fields that he was not supposed to update? Should I throw some kind of exception or just ignore them and update all editable fields? I came up with the following solution

class User {

    private String firstName; //non-editable
    private String lastName; //non-editable
    private String occupation; //editable
    private String address; //editable

    //getters and setters

}

public void updateUser(User original, User update) {
    original.setAddress(update.getAddress());
    original.setOccupation(update.getOccupation());
}

The issue I see here is that the updateUser method is tightly coupled with the User class. If I add or remove editable/non-editable fields I will always have to change the method. Is there some kind of best practices or patterns that address this kind of problem.

A static method on User would encapsulate this functionality correctly. That way you can keep all your user-specific code together.

    class User {

      private String firstName; //non-editable
      private String lastName; //non-editable
      private String occupation; //editable
      private String address; //editable

      static public void updateUser(User original, User update) {
        original.setAddress(update.getAddress());
        original.setOccupation(update.getOccupation());
      }
    }

Also, if you care so much about firstName/lastName not being changed after creation, I'd make sure to not include setters for them at all.

As a user of the API I would want to know when I'm editing values that aren't editable, because that probably means that I either have a bug in my code or that I misunderstood the functionality of the API. In either case I'd like to find that out as early in the process as possible, so I'd prefer to see an exception via an error code in the response, rather than what appears to be a success to me but doesn't actually do what I thought it did.

That said, it depends on the specific use-case. It's hard to say without more details on how the API is being used. It may make more sense to only update the editable fields and just make that really clear in the API documentation.

As coderkevin has already called out, using a static method on the User class would be an appropriate place to put the code that actually does the updates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM