eclipse-vertx / vert.x

Vert.x is a tool-kit for building reactive applications on the JVM
http://vertx.io
Other
14.25k stars 2.06k forks source link

JsonObject: add methods for type checking #1711

Open DieterDePaepe opened 7 years ago

DieterDePaepe commented 7 years ago

Currently, JsonObject has multiple getXXX methods for the basic data types (Integer, Long, String...).

public Integer getInteger(String key)
// Default returned when no value present for key
public Integer getInteger(String key, Integer def)

There currently isn't a method to check whether a value holds the expected data type. It can be done by using above methods and catching the ClassCastException, but it seems better to provide methods like:

// Unchanged
public Integer getInteger(String key)

public boolean isInteger(String key)
// Default returned when no value present for key OR value is of different type
public Integer getInteger(String key, Integer def)
codingchili commented 7 years ago

How about returning an Optional<> for get methods instead of throwing/catching exceptions or returning defaults? This way JsonObjects does not have to return null, we get type checking, avoid exception handling and does not have to add new methods for each object type.

vietj commented 7 years ago

@codingchili Optional definitely breaks compatiblity

vietj commented 7 years ago

@DieterDePaepe perhaps hasInteger(String key) ?

vietj commented 7 years ago

@codingchili that being said Optional is nice

DieterDePaepe commented 7 years ago

Optional would be the best solution, I would consider it when upgrading the major version.

Keeping the restriction in mind, one workaround would be getOptInteger().

Alternatively, the hasInteger() suggestion is also fine by me, though I prefer an approach using Optional.