Use switch expressions in yang-data-util 26/112126/2
authorRobert Varga <robert.varga@pantheon.tech>
Thu, 13 Jun 2024 11:45:31 +0000 (13:45 +0200)
committerRobert Varga <robert.varga@pantheon.tech>
Thu, 13 Jun 2024 12:16:35 +0000 (14:16 +0200)
We have a number of type-based dispatches using if/else/instanceof.
Convert these to switch statements/expressions with patterns for better
expressiveness.

Change-Id: I81c1c080483d693a6c3be37490a23c9d858c0d5f
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
data/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractNodeDataWithSchema.java
data/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractStringInstanceIdentifierCodec.java
data/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/CompositeNodeDataWithSchema.java
data/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/NormalizedNodeStreamWriterStack.java
data/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/codec/AbstractCodecFactory.java
data/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/codec/AbstractInputStreamNormalizer.java
data/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/impl/context/AbstractContext.java

index 7d1b176d52b696f2e2eb643e578513c7269826a7..9f322f8224bd8af44b0902c620c949718372e4ea 100644 (file)
@@ -43,21 +43,15 @@ public abstract sealed class AbstractNodeDataWithSchema<T extends DataSchemaNode
     }
 
     public static @NonNull AbstractNodeDataWithSchema<?> of(final DataSchemaNode schema) {
-        if (schema instanceof ContainerLike containerLike) {
-            return new ContainerNodeDataWithSchema(containerLike);
-        } else if (schema instanceof ListSchemaNode list) {
-            return new ListNodeDataWithSchema(list);
-        } else if (schema instanceof AnyxmlSchemaNode anyxml) {
-            return new AnyXmlNodeDataWithSchema(anyxml);
-        } else if (schema instanceof LeafSchemaNode leaf) {
-            return new LeafNodeDataWithSchema(leaf);
-        } else if (schema instanceof LeafListSchemaNode leafList) {
-            return new LeafListNodeDataWithSchema(leafList);
-        } else if (schema instanceof AnydataSchemaNode anydata) {
-            return new AnydataNodeDataWithSchema(anydata);
-        } else {
-            throw new IllegalStateException("Unsupported schema " + schema);
-        }
+        return switch (schema) {
+            case AnyxmlSchemaNode anyxml -> new AnyXmlNodeDataWithSchema(anyxml);
+            case ContainerLike containerLike -> new ContainerNodeDataWithSchema(containerLike);
+            case LeafSchemaNode leaf -> new LeafNodeDataWithSchema(leaf);
+            case ListSchemaNode list -> new ListNodeDataWithSchema(list);
+            case LeafListSchemaNode leafList -> new LeafListNodeDataWithSchema(leafList);
+            case AnydataSchemaNode anydata -> new AnydataNodeDataWithSchema(anydata);
+            default -> throw new IllegalStateException("Unsupported schema " + schema);
+        };
     }
 
     /**
@@ -131,7 +125,7 @@ public abstract sealed class AbstractNodeDataWithSchema<T extends DataSchemaNode
         if (getClass() != obj.getClass()) {
             return false;
         }
-        final AbstractNodeDataWithSchema<?> other = (AbstractNodeDataWithSchema<?>) obj;
+        final var other = (AbstractNodeDataWithSchema<?>) obj;
         return schema.equals(other.schema);
     }
 
index a449d54a415527c10a1efbe6c31ce50a85450d70..01dc6e7f74f5af40e0389877aeaa3abf1590b427 100644 (file)
@@ -18,6 +18,7 @@ import org.eclipse.jdt.annotation.Nullable;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.QNameModule;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
 import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
@@ -66,14 +67,18 @@ public abstract class AbstractStringInstanceIdentifierCodec extends AbstractName
             appendQName(sb, qname, lastModule);
             lastModule = qname.getModule();
 
-            if (arg instanceof NodeIdentifierWithPredicates nip) {
-                for (var entry : nip.entrySet()) {
-                    final var keyName = entry.getKey();
-                    appendQName(sb.append('['), keyName, lastModule).append('=');
-                    appendValue(sb, keyName.getModule(), entry.getValue()).append(']');
+            switch (arg) {
+                case NodeIdentifier nid -> {
+                    // no-op
                 }
-            } else if (arg instanceof NodeWithValue<?> val) {
-                appendValue(sb.append("[.="), lastModule, val.getValue()).append(']');
+                case NodeIdentifierWithPredicates nip -> {
+                    for (var entry : nip.entrySet()) {
+                        final var keyName = entry.getKey();
+                        appendQName(sb.append('['), keyName, lastModule).append('=');
+                        appendValue(sb, keyName.getModule(), entry.getValue()).append(']');
+                    }
+                }
+                case NodeWithValue<?> val -> appendValue(sb.append("[.="), lastModule, val.getValue()).append(']');
             }
         }
         return sb.toString();
index b79b299a2823be1455d2ed26529a30286ebe8182..f869509385cba9ffe9a444b13eb5f037adcfbdb8 100644 (file)
@@ -110,15 +110,12 @@ public sealed class CompositeNodeDataWithSchema<T extends DataSchemaNode> extend
     }
 
     public static @NonNull CompositeNodeDataWithSchema<?> of(final DataSchemaNode schema) {
-        if (schema instanceof ListSchemaNode list) {
-            return new ListNodeDataWithSchema(list);
-        } else if (schema instanceof LeafListSchemaNode leafList) {
-            return new LeafListNodeDataWithSchema(leafList);
-        } else if (schema instanceof ContainerLike containerLike) {
-            return new ContainerNodeDataWithSchema(containerLike);
-        } else {
-            return new CompositeNodeDataWithSchema<>(schema);
-        }
+        return switch (schema) {
+            case ContainerLike containerLike -> new ContainerNodeDataWithSchema(containerLike);
+            case LeafListSchemaNode leafList -> new LeafListNodeDataWithSchema(leafList);
+            case ListSchemaNode list -> new ListNodeDataWithSchema(list);
+            default -> new CompositeNodeDataWithSchema<>(schema);
+        };
     }
 
     void addChild(final AbstractNodeDataWithSchema<?> newChild) {
@@ -182,7 +179,7 @@ public sealed class CompositeNodeDataWithSchema<T extends DataSchemaNode> extend
     private static CaseNodeDataWithSchema findChoice(final Collection<AbstractNodeDataWithSchema<?>> childNodes,
             final DataSchemaNode choiceCandidate, final DataSchemaNode caseCandidate) {
         if (childNodes != null) {
-            for (AbstractNodeDataWithSchema<?> nodeDataWithSchema : childNodes) {
+            for (var nodeDataWithSchema : childNodes) {
                 if (nodeDataWithSchema instanceof ChoiceNodeDataWithSchema childChoice
                         && nodeDataWithSchema.getSchema().getQName().equals(choiceCandidate.getQName())) {
                     CaseNodeDataWithSchema casePrevious = childChoice.getCase();
index 4cc02c76963593750aec4c57e185183ae33d24f6..9710365afb9854d2af33f039001dd2eaf0fe7e0e 100644 (file)
@@ -267,16 +267,15 @@ public final class NormalizedNodeStreamWriterStack implements LeafrefResolver {
             ret = notification;
         } else {
             final var child = enterDataTree(name);
-            if (child instanceof ContainerEffectiveStatement container) {
-                ret = container;
-            } else if (child instanceof InputEffectiveStatement input) {
-                ret = input;
-            } else if (child instanceof OutputEffectiveStatement output) {
-                ret = output;
-            } else {
-                dataTree.exitToDataTree();
-                throw new IllegalArgumentException("Node " + child + " is not a container");
-            }
+            ret = switch (child) {
+                case ContainerEffectiveStatement container -> container;
+                case InputEffectiveStatement input -> input;
+                case OutputEffectiveStatement output -> output;
+                default -> {
+                    dataTree.exitToDataTree();
+                    throw new IllegalArgumentException("Node " + child + " is not a container");
+                }
+            };
         }
 
         schemaStack.push(ret);
index 134f49d0d293e43e011e0f82a5200381e17191ae..99f7cfae2430f638ac61e6c4d25bd4c552284361 100644 (file)
@@ -162,48 +162,26 @@ public abstract class AbstractCodecFactory<T extends TypeAwareCodec<?, ?, ?>> {
         }
 
         // Now deal with simple types. Note we consider union composed of purely simple types a simple type itself.
-        // The checks here are optimized for common types.
-        final T ret;
-        if (type instanceof StringTypeDefinition stringType) {
-            ret = stringCodec(stringType);
-        } else if (type instanceof Int8TypeDefinition int8type) {
-            ret = int8Codec(int8type);
-        } else if (type instanceof Int16TypeDefinition int16type) {
-            ret = int16Codec(int16type);
-        } else if (type instanceof Int32TypeDefinition int32type) {
-            ret = int32Codec(int32type);
-        } else if (type instanceof Int64TypeDefinition int64type) {
-            ret = int64Codec(int64type);
-        } else if (type instanceof Uint8TypeDefinition uint8type) {
-            ret = uint8Codec(uint8type);
-        } else if (type instanceof Uint16TypeDefinition uint16type) {
-            ret = uint16Codec(uint16type);
-        } else if (type instanceof Uint32TypeDefinition uint32type) {
-            ret = uint32Codec(uint32type);
-        } else if (type instanceof Uint64TypeDefinition uint64type) {
-            ret = uint64Codec(uint64type);
-        } else if (type instanceof BooleanTypeDefinition booleanType) {
-            ret = booleanCodec(booleanType);
-        } else if (type instanceof DecimalTypeDefinition decimalType) {
-            ret = decimalCodec(decimalType);
-        } else if (type instanceof EnumTypeDefinition enumType) {
-            ret = enumCodec(enumType);
-        } else if (type instanceof BitsTypeDefinition bitsType) {
-            ret = bitsCodec(bitsType);
-        } else if (type instanceof UnionTypeDefinition unionType) {
-            if (!isSimpleUnion(unionType)) {
-                return null;
-            }
-            ret = createSimpleUnion(unionType);
-        } else if (type instanceof BinaryTypeDefinition binaryType) {
-            ret = binaryCodec(binaryType);
-        } else if (type instanceof InstanceIdentifierTypeDefinition iidType) {
-            return instanceIdentifierCodec(iidType);
-        } else {
-            return null;
-        }
-
-        return cache.getSimple(type, verifyNotNull(ret));
+        final var ret = switch (type) {
+            case BinaryTypeDefinition binaryType -> binaryCodec(binaryType);
+            case BitsTypeDefinition bitsType -> bitsCodec(bitsType);
+            case BooleanTypeDefinition booleanType -> booleanCodec(booleanType);
+            case DecimalTypeDefinition decimalType -> decimalCodec(decimalType);
+            case EnumTypeDefinition enumType -> enumCodec(enumType);
+            case InstanceIdentifierTypeDefinition iidType -> instanceIdentifierCodec(iidType);
+            case Int8TypeDefinition int8type -> int8Codec(int8type);
+            case Int16TypeDefinition int16type -> int16Codec(int16type);
+            case Int32TypeDefinition int32type -> int32Codec(int32type);
+            case Int64TypeDefinition int64type -> int64Codec(int64type);
+            case StringTypeDefinition stringType -> stringCodec(stringType);
+            case Uint8TypeDefinition uint8type -> uint8Codec(uint8type);
+            case Uint16TypeDefinition uint16type -> uint16Codec(uint16type);
+            case Uint32TypeDefinition uint32type -> uint32Codec(uint32type);
+            case Uint64TypeDefinition uint64type -> uint64Codec(uint64type);
+            case UnionTypeDefinition unionType when isSimpleUnion(unionType) -> createSimpleUnion(unionType);
+            default -> null;
+        };
+        return ret == null ? null : cache.getSimple(type, ret);
     }
 
     private static boolean isSimpleUnion(final UnionTypeDefinition union) {
@@ -221,17 +199,16 @@ public abstract class AbstractCodecFactory<T extends TypeAwareCodec<?, ?, ?>> {
 
     private T createComplexCodecFor(final SchemaNode schema, final TypeDefinition<?> type,
             final LeafrefResolver resolver) {
-        if (type instanceof UnionTypeDefinition union) {
-            return createComplexUnion(schema, union, resolver);
-        } else if (type instanceof LeafrefTypeDefinition leafref) {
-            final var target = resolver.resolveLeafref(leafref);
-            final T ret = getSimpleCodecFor(target);
-            return ret != null ? ret : createComplexCodecFor(schema, target, resolver);
-        } else if (type instanceof IdentityrefTypeDefinition identityref) {
-            return identityRefCodec(identityref, schema.getQName().getModule());
-        } else {
-            throw new IllegalArgumentException("Unsupported type " + type);
-        }
+        return switch (type) {
+            case IdentityrefTypeDefinition identityref -> identityRefCodec(identityref, schema.getQName().getModule());
+            case LeafrefTypeDefinition leafref -> {
+                final var target = resolver.resolveLeafref(leafref);
+                final var ret = getSimpleCodecFor(target);
+                yield ret != null ? ret : createComplexCodecFor(schema, target, resolver);
+            }
+            case UnionTypeDefinition union -> createComplexUnion(schema, union, resolver);
+            default -> throw new IllegalArgumentException("Unsupported type " + type);
+        };
     }
 
     private T createSimpleUnion(final UnionTypeDefinition union) {
@@ -239,7 +216,7 @@ public abstract class AbstractCodecFactory<T extends TypeAwareCodec<?, ?, ?>> {
         final var codecs = new ArrayList<T>(types.size());
 
         for (var type : types) {
-            T codec = cache.lookupSimple(type);
+            var codec = cache.lookupSimple(type);
             if (codec == null) {
                 codec = verifyNotNull(getSimpleCodecFor(type), "Type %s did not resolve to a simple codec", type);
             }
@@ -256,7 +233,7 @@ public abstract class AbstractCodecFactory<T extends TypeAwareCodec<?, ?, ?>> {
         final var codecs = new ArrayList<T>(types.size());
 
         for (var type : types) {
-            T codec = cache.lookupSimple(type);
+            var codec = cache.lookupSimple(type);
             if (codec == null) {
                 codec = getSimpleCodecFor(type);
                 if (codec == null) {
index 2711d4f22b338a1c7d7968e356ae44fe10fdf011..7c642e71c8bf86ddb5b529831c3f42063579dd53 100644 (file)
@@ -156,15 +156,12 @@ public abstract class AbstractInputStreamNormalizer<T extends TypeAwareCodec<?,
             final InputStream stream) throws NormalizationException {
         final var stack = checkInferenceNotEmpty(inference);
         final var stmt = stack.currentStatement();
-        final QName expected;
-        if (stmt instanceof RpcEffectiveStatement rpc) {
-            expected = rpc.input().argument();
-        } else if (stmt instanceof ActionEffectiveStatement action) {
-            expected = action.input().argument();
-        } else {
-            throw invalidStatement(stmt);
-        }
-        return parseInputOutput(stream, stack, expected);
+        final var input = switch (stmt) {
+            case RpcEffectiveStatement rpc -> rpc.input();
+            case ActionEffectiveStatement action -> action.input();
+            default -> throw invalidStatement(stmt);
+        };
+        return parseInputOutput(stream, stack, input.argument());
     }
 
     @Override
@@ -172,15 +169,12 @@ public abstract class AbstractInputStreamNormalizer<T extends TypeAwareCodec<?,
             final InputStream stream) throws NormalizationException {
         final var stack = checkInferenceNotEmpty(inference);
         final var stmt = stack.currentStatement();
-        final QName expected;
-        if (stmt instanceof RpcEffectiveStatement rpc) {
-            expected = rpc.output().argument();
-        } else if (stmt instanceof ActionEffectiveStatement action) {
-            expected = action.output().argument();
-        } else {
-            throw invalidStatement(stmt);
-        }
-        return parseInputOutput(stream, stack, expected);
+        final var output = switch (stmt) {
+            case RpcEffectiveStatement rpc -> rpc.output();
+            case ActionEffectiveStatement action -> action.output();
+            default -> throw invalidStatement(stmt);
+        };
+        return parseInputOutput(stream, stack, output.argument());
     }
 
     private @NonNull NormalizationResult<ContainerNode> parseInputOutput(final @NonNull InputStream stream,
index f5f0418e8d3a7c807d26ee7d04815128130454a3..20e7ae7207815cca1b5860723631021b9ca0660d 100644 (file)
@@ -91,52 +91,34 @@ public abstract sealed class AbstractContext implements DataSchemaContext
     }
 
     public static @NonNull AbstractContext of(final @NonNull DataSchemaNode schema) {
-        if (schema instanceof ContainerLike containerLike) {
-            return new ContainerContext(containerLike);
-        } else if (schema instanceof ListSchemaNode list) {
-            return fromListSchemaNode(list);
-        } else if (schema instanceof LeafSchemaNode leaf) {
-            return new LeafContext(leaf);
-        } else if (schema instanceof ChoiceSchemaNode choice) {
-            return new ChoiceContext(choice);
-        } else if (schema instanceof LeafListSchemaNode leafList) {
-            return new LeafListContext(leafList);
-        } else if (schema instanceof AnydataSchemaNode anydata) {
-            return new OpaqueContext(anydata);
-        } else if (schema instanceof AnyxmlSchemaNode anyxml) {
-            return new OpaqueContext(anyxml);
-        } else {
-            throw new IllegalStateException("Unhandled schema " + schema);
-        }
+        return switch (schema) {
+            case AnydataSchemaNode anydata -> new OpaqueContext(anydata);
+            case AnyxmlSchemaNode anyxml -> new OpaqueContext(anyxml);
+            case ChoiceSchemaNode choice -> new ChoiceContext(choice);
+            case ContainerLike containerLike -> new ContainerContext(containerLike);
+            case LeafSchemaNode leaf -> new LeafContext(leaf);
+            case LeafListSchemaNode leafList -> new LeafListContext(leafList);
+            case ListSchemaNode list -> fromListSchemaNode(list);
+            default -> throw new IllegalStateException("Unhandled schema " + schema);
+        };
     }
 
     // FIXME: do we tolerate null argument? do we tolerate unknown subclasses?
     private static @Nullable AbstractContext lenientOf(final @Nullable DataSchemaNode schema) {
-        if (schema instanceof ContainerLike containerLike) {
-            return new ContainerContext(containerLike);
-        } else if (schema instanceof ListSchemaNode list) {
-            return fromListSchemaNode(list);
-        } else if (schema instanceof LeafSchemaNode leaf) {
-            return new LeafContext(leaf);
-        } else if (schema instanceof ChoiceSchemaNode choice) {
-            return new ChoiceContext(choice);
-        } else if (schema instanceof LeafListSchemaNode leafList) {
-            return new LeafListContext(leafList);
-        } else if (schema instanceof AnydataSchemaNode anydata) {
-            return new OpaqueContext(anydata);
-        } else if (schema instanceof AnyxmlSchemaNode anyxml) {
-            return new OpaqueContext(anyxml);
-        } else {
-            return null;
-        }
+        return switch (schema) {
+            case AnydataSchemaNode anydata -> new OpaqueContext(anydata);
+            case AnyxmlSchemaNode anyxml -> new OpaqueContext(anyxml);
+            case ChoiceSchemaNode choice -> new ChoiceContext(choice);
+            case ContainerLike containerLike -> new ContainerContext(containerLike);
+            case LeafSchemaNode leaf -> new LeafContext(leaf);
+            case LeafListSchemaNode leafList -> new LeafListContext(leafList);
+            case ListSchemaNode list -> fromListSchemaNode(list);
+            case null, default -> null;
+        };
     }
 
     private static @NonNull AbstractContext fromListSchemaNode(final ListSchemaNode potential) {
-        var keyDefinition = potential.getKeyDefinition();
-        if (keyDefinition.isEmpty()) {
-            return new ListContext(potential);
-        } else {
-            return new MapContext(potential);
-        }
+        final var keyDefinition = potential.getKeyDefinition();
+        return keyDefinition.isEmpty() ? new ListContext(potential) : new MapContext(potential);
     }
 }