Skip to content

Commit e69902c

Browse files
refactor: change event deserialization return type to optional
1 parent 50e44f2 commit e69902c

File tree

3 files changed

+10
-8
lines changed

3 files changed

+10
-8
lines changed

src/env/application/presenter/event/serialization/EventDeserializer.java

+4-2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010

1111
import application.presenter.event.model.Event;
1212

13+
import java.util.Optional;
14+
1315
/**
1416
* Interface that models an event deserializer.
1517
*/
@@ -18,7 +20,7 @@ public interface EventDeserializer {
1820
* Deserialize an event from string.
1921
* @param eventKey the key of the event.
2022
* @param event the event in string format.
21-
* @return the deserialized event.
23+
* @return the deserialized event as an optional.
2224
*/
23-
Event<?> fromString(String eventKey, String event);
25+
Optional<Event<?>> fromString(String eventKey, String event);
2426
}

src/env/application/presenter/event/serialization/EventDeserializerImpl.java

+5-5
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import java.lang.reflect.Type;
2323
import java.util.HashMap;
2424
import java.util.Map;
25+
import java.util.Optional;
2526

2627
/**
2728
* Implementation of the {@link EventDeserializer} interface that allows an event to be
@@ -45,10 +46,9 @@ public EventDeserializerImpl() {
4546
}
4647

4748
@Override
48-
public final Event<?> fromString(final String eventKey, final String event) {
49-
if (!this.typeMap.containsKey(eventKey)) {
50-
throw new IllegalArgumentException("Event not supported");
51-
}
52-
return new Gson().fromJson(event, this.typeMap.get(eventKey));
49+
public final Optional<Event<?>> fromString(final String eventKey, final String event) {
50+
return Optional.of(eventKey)
51+
.filter(this.typeMap::containsKey)
52+
.map(key -> new Gson().fromJson(event, this.typeMap.get(key)));
5353
}
5454
}

src/env/infrastructure/events/KafkaClient.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ public void poll(final Consumer<Event<?>> eventConsumer) {
7272
this.kafkaConsumer.poll(Duration.ofMillis(POLLING_TIME)).forEach(event -> {
7373
// log the event
7474
Logger.getLogger(KafkaClient.class.getName()).fine(event.toString());
75-
eventConsumer.accept(this.eventDeserializer.fromString(event.key(), event.value()));
75+
this.eventDeserializer.fromString(event.key(), event.value()).ifPresent(eventConsumer);
7676
});
7777
}
7878
}

0 commit comments

Comments
 (0)