Skip to content

Misuse of Java generics in RedisTemplate related API [DATAREDIS-857] #1431

Open
@spring-projects-issues

Description

@spring-projects-issues

Martin Benda opened DATAREDIS-857 and commented

The design of spring-data-redis API is severely flawed in its (mis)use of generics. The API is type-unsafe and cannot be used without unchecked generic type casts.

Example of type-unsafety:

StringRedisTemplate template = ...;
...
// this compiles fine, no warning, however...
RedisMap<String, Long> map = new DefaultRedisMap<>(template.boundHashOps("key"));
map.put("a", 1L); // throws ClassCastException

Another example of nonsensical use of generic can be found in RedisScript factory methods:

// why this method returns *raw* type RediscScript? it should return RedisScript<T>
static <T> RedisScript of(String script, Class<T> resultType);

// on the other-hand, this method should not be type-parameterized at all, it should return RedisScript<?> or maybe RedisScript<Void>
static <T> RedisScript<T> of(String script);

Another example if generics misuse is the SessionCallback interface. There is no way to implement this interface without @SuppressWarnings("unchecked"). Type-parameterization of the execute method just makes no sense:

...
@Override
public <K, V> String execute(RedisOperations<K, V> operations) {
    // cannot use operations without unchecked type-casts
    @SuppressWarnings("unchecked")
    RedisOperations<String, String> ops = (RedisOperations<String, String>) operations;
    ...
}

One of the causes of these problems is that there is no compile-time linkage between RedisOperations and RedisSerializer type parameters. This leads to "fake" type-safety when clients of the API can use type parameters that are incompatible with actual runtime types without warning. Compare this to lettuce.io — the key/value type parameters of StatefulRedisConnection are derived from the codec instance passed to the various connect methods — this is correct use of generics that ensures type-safety.

Spring-data-redis still provides a convenient way of accessing Redis in a spring-based applications (for example the data repository support is useful), however the quality of the RedisTemplate API is lower than one would expect from an official spring library. Using lettuce directly is less error-prone and offers better programming experience


Affects: 2.0.9 (Kay SR9)

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions