Skip to content

EmbeddedEntityBinding exception handling and refactoring #1

@kerbymart

Description

@kerbymart
  • Renaming: The unclear variable names are renamed to increase code readability. For instance, the variable is gets renamed to objectInputStream.

  • Extract Function: These two serialization and deserialization operations, which are currently static methods could be made non-static.

  • Exception Handling: Instead of printing stack traces, we can throw a custom unchecked exception.

  • Using Optional: The serialize and deserialize methods return null when there's an exception which can lead to null pointer exceptions. Instead, we can return an Optional from these methods.

public class SerializationException extends RuntimeException {
    public SerializationException(String cause) {
        super(cause);
    }
}

//class remained the same
public class EmbeddedEntityBinding extends ComparableBinding implements Serializable {

    public static final EmbeddedEntityBinding BINDING = new EmbeddedEntityBinding();

    public Optional<byte[]> serialize(Object obj) {
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
            objectOutputStream.writeObject(obj);
            return Optional.of(byteArrayOutputStream.toByteArray());
        } catch (IOException e) {
            throw new SerializationException("Failed to serialize object");
        }
    }

    public <T> Optional<T> deserialize(byte[] data, Class<T> clazz) {
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            Object readObject = objectInputStream.readObject();
            return Optional.ofNullable(clazz.isInstance(readObject) ? clazz.cast(readObject) : null);
        } catch (IOException e) {
            throw new SerializationException("Failed to deserialize object");
        } catch (ClassNotFoundException e) {
            throw new SerializationException("Failed to find class during deserialization");
        }
    }

    @Override
    public Comparable readObject(@NotNull ByteArrayInputStream stream) {
        return Try.of(() -> {
            byte[] serialized = ByteStreams.toByteArray(stream);
            return deserialize(serialized, Comparable.class).orElseThrow();
        }).getOrNull();
    }
  
    @Override
    public void writeObject(@NotNull LightOutputStream output, @NotNull Comparable object) {
        byte[] serialized = serialize(object).orElseThrow();
        output.write(serialized);
    }
}

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions