commercetools / commercetools-sdk-java-v2

The e-commerce SDK from commercetools for Java.
https://commercetools.github.io/commercetools-sdk-java-v2/javadoc/index.html
Apache License 2.0
34 stars 15 forks source link

Marker interfaces for types that has custom field. #246

Closed ahmetoz closed 2 years ago

ahmetoz commented 2 years ago

Model types that has custom field (CustomFields, CustomFieldsDraft) does not have any interface that could mark it. For instance jvm-sdk has those marker interfaces.

Fields like custom has lots of common parts for all resource types so using them in generic utilities make sense, without an interface it's hard to keep type safety. I guess implementor could write a wrapper/decorator to do it but it's lot of boilerplate code as there are lots of models and extra object creation.

Also it might be good to know the typeId of the CustomFields based on the model Type, I guess jvm-sdk exposes those as constants.

ahmetoz commented 2 years ago

On the Custom field, type fields types defined with java.lang.Object, mostly those are without javadocs, so while writing builders for those it's hard to know what to pass, what to compare etc.. would not it better to use more strict types and javadocs for those ? I also think that library rely on the jackson so for json represantations maybe JsonNode could be used ?

jenschude commented 2 years ago

We may introduce a marker interface, also I'm unsure atm how to best introduce it.

The problem with the fields themselves is that Object is the least common denominator. The fields should be correctly deserialized regarding their type, but the SDK can't give more guidance. Here applies the same as with attribute values. In order to have type safe accessors you could create a CustomFieldAccessor as like as the AttributeAccessor

public static class CustomFieldAccessor {
    public static Long asLong(final FieldContainer container, final String field) {
        return (Long) container.values().get(field);
    }
}

final Long foo = category.getCustom()
        .getFields()
        .withFieldContainer(fieldContainer -> CustomFieldAccessor.asLong(fieldContainer, "foo"));

We may introduce one directly in the SDK too.

Please see also #233

jenschude commented 2 years ago

I added a CustomFieldAccessor with f720615 for the next release

jenschude commented 2 years ago

Released 8.0.0-beta.1 as a pre-release with the added CustomFieldAccessor

Akii commented 2 years ago

@ahmetoz if you want stronger types I am almost finished with type-safe custom fields: https://github.com/Akii/commercetools-sdk-java-v2-custom-types/pull/1

jenschude commented 2 years ago

Marker interfaces have been added with 8.0.1

Thanks for the report