user3479586
user3479586

Reputation: 169

Should the Object class ever be referenced in Java?

I found this part of code:

Map<String, Object> myMap = ...

It seems like the above should replace Object with some abstract class or interface that provides more structure for the value in the map. Is there any good reason to directly reference the Object class?

Upvotes: 0

Views: 46

Answers (1)

Paul
Paul

Reputation: 20061

API calls/responses (consuming/producing JSON) will always have a String key but the value may be text, numeric, boolean, array, or an object.

In the specific case of my project we use Spring MVC (which uses Jackson under the hood). Our controllers always consume domain objects directly, e.g. an instance of the User class. Processing a Map with more than a couple of keys is a chore and prone to error.

We frequently return Map<String, Object> because responses almost always include metadata that is generated when the request is made. For example, a GET request made to myapp/api/users might return something like:

{
  count: 2,
  timestamp: '2020-11-06T17:24:12.123Z',
  users: [
    {id: 1, firstName: 'Alice', lastName: 'Ackbar'},
    {id: 2, firstName: 'Boba', lastName: 'Bling'}
  ]
}

While the users property contains serialized User entities the remaining fields exist solely for the response. There is no point to creating a UsersResponseEntity class.

Upvotes: 2

Related Questions