From c8b9697c516eb735d740a685032b5ebbeaedfd9a Mon Sep 17 00:00:00 2001 From: arefbehboudi Date: Thu, 29 Aug 2024 18:26:23 +0330 Subject: [PATCH] Refactor code with instanceof pattern variable. In some cases, we currently use the traditional `instanceof` checks followed by explicit type casting. With the introduction of pattern matching in recent Java versions, we can refactor these checks to make the code more concise and readable. Original pull request #1868 --- .../jdbc/core/AggregateChangeExecutor.java | 52 +++++++++---------- .../JdbcAggregateChangeExecutionContext.java | 4 +- .../core/convert/MappingJdbcConverter.java | 4 +- .../data/jdbc/core/convert/QueryMapper.java | 4 +- .../ResultSetAccessorPropertyAccessor.java | 2 +- ...eChangeIdGenerationImmutableUnitTests.java | 12 ++--- .../core/convert/SqlGeneratorUnitTests.java | 4 +- .../LiquibaseChangeSetWriterUnitTests.java | 18 +++---- ...anuallyAssignedIdHsqlIntegrationTests.java | 4 +- 9 files changed, 47 insertions(+), 57 deletions(-) diff --git a/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/AggregateChangeExecutor.java b/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/AggregateChangeExecutor.java index 81138cd53c6..d3d81a4864e 100644 --- a/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/AggregateChangeExecutor.java +++ b/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/AggregateChangeExecutor.java @@ -81,32 +81,32 @@ void executeDelete(AggregateChange aggregateChange) { private void execute(DbAction action, JdbcAggregateChangeExecutionContext executionContext) { try { - if (action instanceof DbAction.InsertRoot) { - executionContext.executeInsertRoot((DbAction.InsertRoot) action); - } else if (action instanceof DbAction.BatchInsertRoot) { - executionContext.executeBatchInsertRoot((DbAction.BatchInsertRoot) action); - } else if (action instanceof DbAction.Insert) { - executionContext.executeInsert((DbAction.Insert) action); - } else if (action instanceof DbAction.BatchInsert) { - executionContext.executeBatchInsert((DbAction.BatchInsert) action); - } else if (action instanceof DbAction.UpdateRoot) { - executionContext.executeUpdateRoot((DbAction.UpdateRoot) action); - } else if (action instanceof DbAction.Delete) { - executionContext.executeDelete((DbAction.Delete) action); - } else if (action instanceof DbAction.BatchDelete) { - executionContext.executeBatchDelete((DbAction.BatchDelete) action); - } else if (action instanceof DbAction.DeleteAll) { - executionContext.executeDeleteAll((DbAction.DeleteAll) action); - } else if (action instanceof DbAction.DeleteRoot) { - executionContext.executeDeleteRoot((DbAction.DeleteRoot) action); - } else if (action instanceof DbAction.BatchDeleteRoot) { - executionContext.executeBatchDeleteRoot((DbAction.BatchDeleteRoot) action); - } else if (action instanceof DbAction.DeleteAllRoot) { - executionContext.executeDeleteAllRoot((DbAction.DeleteAllRoot) action); - } else if (action instanceof DbAction.AcquireLockRoot) { - executionContext.executeAcquireLock((DbAction.AcquireLockRoot) action); - } else if (action instanceof DbAction.AcquireLockAllRoot) { - executionContext.executeAcquireLockAllRoot((DbAction.AcquireLockAllRoot) action); + if (action instanceof DbAction.InsertRoot insertRoot) { + executionContext.executeInsertRoot(insertRoot); + } else if (action instanceof DbAction.BatchInsertRoot batchInsertRoot) { + executionContext.executeBatchInsertRoot(batchInsertRoot); + } else if (action instanceof DbAction.Insert insert) { + executionContext.executeInsert(insert); + } else if (action instanceof DbAction.BatchInsert batchInsert) { + executionContext.executeBatchInsert(batchInsert); + } else if (action instanceof DbAction.UpdateRoot updateRoot) { + executionContext.executeUpdateRoot(updateRoot); + } else if (action instanceof DbAction.Delete delete) { + executionContext.executeDelete(delete); + } else if (action instanceof DbAction.BatchDelete batchDelete) { + executionContext.executeBatchDelete(batchDelete); + } else if (action instanceof DbAction.DeleteAll deleteAll) { + executionContext.executeDeleteAll(deleteAll); + } else if (action instanceof DbAction.DeleteRoot deleteRoot) { + executionContext.executeDeleteRoot(deleteRoot); + } else if (action instanceof DbAction.BatchDeleteRoot batchDeleteRoot) { + executionContext.executeBatchDeleteRoot(batchDeleteRoot); + } else if (action instanceof DbAction.DeleteAllRoot deleteAllRoot) { + executionContext.executeDeleteAllRoot(deleteAllRoot); + } else if (action instanceof DbAction.AcquireLockRoot acquireLockRoot) { + executionContext.executeAcquireLock(acquireLockRoot); + } else if (action instanceof DbAction.AcquireLockAllRoot acquireLockAllRoot) { + executionContext.executeAcquireLockAllRoot(acquireLockAllRoot); } else { throw new RuntimeException("unexpected action"); } diff --git a/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/JdbcAggregateChangeExecutionContext.java b/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/JdbcAggregateChangeExecutionContext.java index 3c2dea5ddae..23647874f9b 100644 --- a/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/JdbcAggregateChangeExecutionContext.java +++ b/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/JdbcAggregateChangeExecutionContext.java @@ -312,8 +312,8 @@ private Object setIdAndCascadingProperties(DbAction.WithEntity action, @N @SuppressWarnings("unchecked") private PersistentPropertyPath getRelativePath(DbAction action, PersistentPropertyPath pathToValue) { - if (action instanceof DbAction.Insert) { - return pathToValue.getExtensionForBaseOf(((DbAction.Insert) action).getPropertyPath()); + if (action instanceof DbAction.Insert insert) { + return pathToValue.getExtensionForBaseOf(insert.getPropertyPath()); } if (action instanceof DbAction.InsertRoot) { diff --git a/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/MappingJdbcConverter.java b/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/MappingJdbcConverter.java index 258c1aefc4a..2b3ad379456 100644 --- a/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/MappingJdbcConverter.java +++ b/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/MappingJdbcConverter.java @@ -192,9 +192,9 @@ public Object readValue(@Nullable Object value, TypeInformation type) { return value; } - if (value instanceof Array) { + if (value instanceof Array array) { try { - return super.readValue(((Array) value).getArray(), type); + return super.readValue(array.getArray(), type); } catch (SQLException | ConverterNotFoundException e) { LOG.info("Failed to extract a value of type %s from an Array; Attempting to use standard conversions", e); } diff --git a/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/QueryMapper.java b/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/QueryMapper.java index b79d6b1db0d..9e04b7cc20f 100644 --- a/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/QueryMapper.java +++ b/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/QueryMapper.java @@ -148,7 +148,7 @@ Expression getMappedObject(Expression expression, @Nullable RelationalPersistent Assert.state(table != null, String.format("The column %s must have a table set", column)); Column columnFromTable = table.column(field.getMappedColumnName()); - return column instanceof Aliased ? columnFromTable.as(((Aliased) column).getAlias()) : columnFromTable; + return column instanceof Aliased aliased ? columnFromTable.as(aliased.getAlias()) : columnFromTable; } if (expression instanceof SimpleFunction function) { @@ -162,7 +162,7 @@ Expression getMappedObject(Expression expression, @Nullable RelationalPersistent SimpleFunction mappedFunction = SimpleFunction.create(function.getFunctionName(), mappedArguments); - return function instanceof Aliased ? mappedFunction.as(((Aliased) function).getAlias()) : mappedFunction; + return function instanceof Aliased aliased ? mappedFunction.as(aliased.getAlias()) : mappedFunction; } throw new IllegalArgumentException(String.format("Cannot map %s", expression)); diff --git a/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/ResultSetAccessorPropertyAccessor.java b/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/ResultSetAccessorPropertyAccessor.java index fd0b6b10090..f7b1199c0f0 100644 --- a/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/ResultSetAccessorPropertyAccessor.java +++ b/spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/ResultSetAccessorPropertyAccessor.java @@ -37,7 +37,7 @@ public Class[] getSpecificTargetClasses() { @Override public boolean canRead(EvaluationContext context, @Nullable Object target, String name) { - return target instanceof ResultSetAccessor && ((ResultSetAccessor) target).hasValue(name); + return target instanceof ResultSetAccessor resultSetAccessor && resultSetAccessor.hasValue(name); } @Override diff --git a/spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/AggregateChangeIdGenerationImmutableUnitTests.java b/spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/AggregateChangeIdGenerationImmutableUnitTests.java index 9336d4ef0c4..6e66e8e5a8b 100644 --- a/spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/AggregateChangeIdGenerationImmutableUnitTests.java +++ b/spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/AggregateChangeIdGenerationImmutableUnitTests.java @@ -491,8 +491,7 @@ public ContentNoId getEmbedded() { public boolean equals(final Object o) { if (o == this) return true; - if (!(o instanceof DummyEntity)) return false; - final DummyEntity other = (DummyEntity) o; + if (!(o instanceof DummyEntity other)) return false; final Object this$rootId = this.getRootId(); final Object other$rootId = other.getRootId(); if (this$rootId == null ? other$rootId != null : !this$rootId.equals(other$rootId)) return false; @@ -623,8 +622,7 @@ public Map getTagMap() { public boolean equals(final Object o) { if (o == this) return true; - if (!(o instanceof Content)) return false; - final Content other = (Content) o; + if (!(o instanceof Content other)) return false; final Object this$id = this.getId(); final Object other$id = other.getId(); if (this$id == null ? other$id != null : !this$id.equals(other$id)) return false; @@ -725,8 +723,7 @@ public Map getTagMap() { public boolean equals(final Object o) { if (o == this) return true; - if (!(o instanceof ContentNoId)) return false; - final ContentNoId other = (ContentNoId) o; + if (!(o instanceof ContentNoId other)) return false; final Object this$single = this.getSingle(); final Object other$single = other.getSingle(); if (this$single == null ? other$single != null : !this$single.equals(other$single)) return false; @@ -805,8 +802,7 @@ public String getName() { public boolean equals(final Object o) { if (o == this) return true; - if (!(o instanceof Tag)) return false; - final Tag other = (Tag) o; + if (!(o instanceof Tag other)) return false; final Object this$id = this.getId(); final Object other$id = other.getId(); if (this$id == null ? other$id != null : !this$id.equals(other$id)) return false; diff --git a/spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/convert/SqlGeneratorUnitTests.java b/spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/convert/SqlGeneratorUnitTests.java index 110c6fe615d..89d9a6756a1 100644 --- a/spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/convert/SqlGeneratorUnitTests.java +++ b/spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/convert/SqlGeneratorUnitTests.java @@ -941,8 +941,8 @@ void mappingMapKeyToChildShouldNotResultInDuplicateColumn() { @Nullable private SqlIdentifier getAlias(Object maybeAliased) { - if (maybeAliased instanceof Aliased) { - return ((Aliased) maybeAliased).getAlias(); + if (maybeAliased instanceof Aliased aliased) { + return aliased.getAlias(); } return null; } diff --git a/spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/mapping/schema/LiquibaseChangeSetWriterUnitTests.java b/spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/mapping/schema/LiquibaseChangeSetWriterUnitTests.java index 348d1b7bcf4..cc2746a99c6 100644 --- a/spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/mapping/schema/LiquibaseChangeSetWriterUnitTests.java +++ b/spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/mapping/schema/LiquibaseChangeSetWriterUnitTests.java @@ -115,10 +115,8 @@ void fieldForFkShouldNotBeCreatedTwice() { ChangeSet changeSet = writer.createChangeSet(ChangeSetMetadata.create(), new DatabaseChangeLog()); - Optional tableWithFk = changeSet.getChanges().stream().filter(change -> { - return change instanceof CreateTableChange - && ((CreateTableChange) change).getTableName().equals("table_with_fk_field"); - }).findFirst(); + Optional tableWithFk = changeSet.getChanges().stream().filter(change -> change instanceof CreateTableChange createTableChange + && createTableChange.getTableName().equals("table_with_fk_field")).findFirst(); assertThat(tableWithFk.isPresent()).isEqualTo(true); List columns = ((CreateTableChange) tableWithFk.get()).getColumns(); @@ -181,9 +179,7 @@ void createForeignKeyForOneToOneWithMultipleChildren() { void assertCreateTable(ChangeSet changeSet, String tableName, Tuple... columnTuples) { - Optional createTableOptional = changeSet.getChanges().stream().filter(change -> { - return change instanceof CreateTableChange && ((CreateTableChange) change).getTableName().equals(tableName); - }).findFirst(); + Optional createTableOptional = changeSet.getChanges().stream().filter(change -> change instanceof CreateTableChange createTableChange && createTableChange.getTableName().equals(tableName)).findFirst(); assertThat(createTableOptional.isPresent()).isTrue(); CreateTableChange createTable = (CreateTableChange) createTableOptional.get(); assertThat(createTable.getColumns()) @@ -193,11 +189,9 @@ void assertCreateTable(ChangeSet changeSet, String tableName, Tuple... columnTup void assertAddForeignKey(ChangeSet changeSet, String baseTableName, String baseColumnNames, String referencedTableName, String referencedColumnNames) { - Optional addFkOptional = changeSet.getChanges().stream().filter(change -> { - return change instanceof AddForeignKeyConstraintChange - && ((AddForeignKeyConstraintChange) change).getBaseTableName().equals(baseTableName) - && ((AddForeignKeyConstraintChange) change).getBaseColumnNames().equals(baseColumnNames); - }).findFirst(); + Optional addFkOptional = changeSet.getChanges().stream().filter(change -> change instanceof AddForeignKeyConstraintChange addForeignKeyConstraintChange + && addForeignKeyConstraintChange.getBaseTableName().equals(baseTableName) + && addForeignKeyConstraintChange.getBaseColumnNames().equals(baseColumnNames)).findFirst(); assertThat(addFkOptional.isPresent()).isTrue(); AddForeignKeyConstraintChange addFk = (AddForeignKeyConstraintChange) addFkOptional.get(); assertThat(addFk.getBaseTableName()).isEqualTo(baseTableName); diff --git a/spring-data-jdbc/src/test/java/org/springframework/data/jdbc/repository/JdbcRepositoryWithCollectionsAndManuallyAssignedIdHsqlIntegrationTests.java b/spring-data-jdbc/src/test/java/org/springframework/data/jdbc/repository/JdbcRepositoryWithCollectionsAndManuallyAssignedIdHsqlIntegrationTests.java index df2e8329e82..0f58e3b042d 100644 --- a/spring-data-jdbc/src/test/java/org/springframework/data/jdbc/repository/JdbcRepositoryWithCollectionsAndManuallyAssignedIdHsqlIntegrationTests.java +++ b/spring-data-jdbc/src/test/java/org/springframework/data/jdbc/repository/JdbcRepositoryWithCollectionsAndManuallyAssignedIdHsqlIntegrationTests.java @@ -66,8 +66,8 @@ public ApplicationListener idSetting() { return (ApplicationListener) event -> { - if (event.getEntity() instanceof DummyEntity) { - setIds((DummyEntity) event.getEntity()); + if (event.getEntity() instanceof DummyEntity dummyEntity) { + setIds(dummyEntity); } }; }