Browse Source

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
pull/1869/head
arefbehboudi 1 year ago committed by Jens Schauder
parent
commit
c8b9697c51
No known key found for this signature in database
GPG Key ID: 74F6C554AE971567
  1. 52
      spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/AggregateChangeExecutor.java
  2. 4
      spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/JdbcAggregateChangeExecutionContext.java
  3. 4
      spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/MappingJdbcConverter.java
  4. 4
      spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/QueryMapper.java
  5. 2
      spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/ResultSetAccessorPropertyAccessor.java
  6. 12
      spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/AggregateChangeIdGenerationImmutableUnitTests.java
  7. 4
      spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/convert/SqlGeneratorUnitTests.java
  8. 18
      spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/mapping/schema/LiquibaseChangeSetWriterUnitTests.java
  9. 4
      spring-data-jdbc/src/test/java/org/springframework/data/jdbc/repository/JdbcRepositoryWithCollectionsAndManuallyAssignedIdHsqlIntegrationTests.java

52
spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/AggregateChangeExecutor.java

@ -81,32 +81,32 @@ class AggregateChangeExecutor {
private void execute(DbAction<?> action, JdbcAggregateChangeExecutionContext executionContext) { private void execute(DbAction<?> action, JdbcAggregateChangeExecutionContext executionContext) {
try { try {
if (action instanceof DbAction.InsertRoot) { if (action instanceof DbAction.InsertRoot<?> insertRoot) {
executionContext.executeInsertRoot((DbAction.InsertRoot<?>) action); executionContext.executeInsertRoot(insertRoot);
} else if (action instanceof DbAction.BatchInsertRoot<?>) { } else if (action instanceof DbAction.BatchInsertRoot<?> batchInsertRoot) {
executionContext.executeBatchInsertRoot((DbAction.BatchInsertRoot<?>) action); executionContext.executeBatchInsertRoot(batchInsertRoot);
} else if (action instanceof DbAction.Insert) { } else if (action instanceof DbAction.Insert<?> insert) {
executionContext.executeInsert((DbAction.Insert<?>) action); executionContext.executeInsert(insert);
} else if (action instanceof DbAction.BatchInsert) { } else if (action instanceof DbAction.BatchInsert<?> batchInsert) {
executionContext.executeBatchInsert((DbAction.BatchInsert<?>) action); executionContext.executeBatchInsert(batchInsert);
} else if (action instanceof DbAction.UpdateRoot) { } else if (action instanceof DbAction.UpdateRoot<?> updateRoot) {
executionContext.executeUpdateRoot((DbAction.UpdateRoot<?>) action); executionContext.executeUpdateRoot(updateRoot);
} else if (action instanceof DbAction.Delete) { } else if (action instanceof DbAction.Delete<?> delete) {
executionContext.executeDelete((DbAction.Delete<?>) action); executionContext.executeDelete(delete);
} else if (action instanceof DbAction.BatchDelete<?>) { } else if (action instanceof DbAction.BatchDelete<?> batchDelete) {
executionContext.executeBatchDelete((DbAction.BatchDelete<?>) action); executionContext.executeBatchDelete(batchDelete);
} else if (action instanceof DbAction.DeleteAll) { } else if (action instanceof DbAction.DeleteAll<?> deleteAll) {
executionContext.executeDeleteAll((DbAction.DeleteAll<?>) action); executionContext.executeDeleteAll(deleteAll);
} else if (action instanceof DbAction.DeleteRoot) { } else if (action instanceof DbAction.DeleteRoot<?> deleteRoot) {
executionContext.executeDeleteRoot((DbAction.DeleteRoot<?>) action); executionContext.executeDeleteRoot(deleteRoot);
} else if (action instanceof DbAction.BatchDeleteRoot) { } else if (action instanceof DbAction.BatchDeleteRoot<?> batchDeleteRoot) {
executionContext.executeBatchDeleteRoot((DbAction.BatchDeleteRoot<?>) action); executionContext.executeBatchDeleteRoot(batchDeleteRoot);
} else if (action instanceof DbAction.DeleteAllRoot) { } else if (action instanceof DbAction.DeleteAllRoot<?> deleteAllRoot) {
executionContext.executeDeleteAllRoot((DbAction.DeleteAllRoot<?>) action); executionContext.executeDeleteAllRoot(deleteAllRoot);
} else if (action instanceof DbAction.AcquireLockRoot) { } else if (action instanceof DbAction.AcquireLockRoot<?> acquireLockRoot) {
executionContext.executeAcquireLock((DbAction.AcquireLockRoot<?>) action); executionContext.executeAcquireLock(acquireLockRoot);
} else if (action instanceof DbAction.AcquireLockAllRoot) { } else if (action instanceof DbAction.AcquireLockAllRoot<?> acquireLockAllRoot) {
executionContext.executeAcquireLockAllRoot((DbAction.AcquireLockAllRoot<?>) action); executionContext.executeAcquireLockAllRoot(acquireLockAllRoot);
} else { } else {
throw new RuntimeException("unexpected action"); throw new RuntimeException("unexpected action");
} }

4
spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/JdbcAggregateChangeExecutionContext.java

@ -312,8 +312,8 @@ class JdbcAggregateChangeExecutionContext {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private PersistentPropertyPath<?> getRelativePath(DbAction<?> action, PersistentPropertyPath<?> pathToValue) { private PersistentPropertyPath<?> getRelativePath(DbAction<?> action, PersistentPropertyPath<?> pathToValue) {
if (action instanceof DbAction.Insert) { if (action instanceof DbAction.Insert insert) {
return pathToValue.getExtensionForBaseOf(((DbAction.Insert) action).getPropertyPath()); return pathToValue.getExtensionForBaseOf(insert.getPropertyPath());
} }
if (action instanceof DbAction.InsertRoot) { if (action instanceof DbAction.InsertRoot) {

4
spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/MappingJdbcConverter.java

@ -192,9 +192,9 @@ public class MappingJdbcConverter extends MappingRelationalConverter implements
return value; return value;
} }
if (value instanceof Array) { if (value instanceof Array array) {
try { try {
return super.readValue(((Array) value).getArray(), type); return super.readValue(array.getArray(), type);
} catch (SQLException | ConverterNotFoundException e) { } catch (SQLException | ConverterNotFoundException e) {
LOG.info("Failed to extract a value of type %s from an Array; Attempting to use standard conversions", e); LOG.info("Failed to extract a value of type %s from an Array; Attempting to use standard conversions", e);
} }

4
spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/QueryMapper.java

@ -148,7 +148,7 @@ public class QueryMapper {
Assert.state(table != null, String.format("The column %s must have a table set", column)); Assert.state(table != null, String.format("The column %s must have a table set", column));
Column columnFromTable = table.column(field.getMappedColumnName()); 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) { if (expression instanceof SimpleFunction function) {
@ -162,7 +162,7 @@ public class QueryMapper {
SimpleFunction mappedFunction = SimpleFunction.create(function.getFunctionName(), mappedArguments); 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)); throw new IllegalArgumentException(String.format("Cannot map %s", expression));

2
spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/convert/ResultSetAccessorPropertyAccessor.java

@ -37,7 +37,7 @@ class ResultSetAccessorPropertyAccessor implements PropertyAccessor {
@Override @Override
public boolean canRead(EvaluationContext context, @Nullable Object target, String name) { 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 @Override

12
spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/AggregateChangeIdGenerationImmutableUnitTests.java

@ -491,8 +491,7 @@ public class AggregateChangeIdGenerationImmutableUnitTests {
public boolean equals(final Object o) { public boolean equals(final Object o) {
if (o == this) return true; if (o == this) return true;
if (!(o instanceof DummyEntity)) return false; if (!(o instanceof DummyEntity other)) return false;
final DummyEntity other = (DummyEntity) o;
final Object this$rootId = this.getRootId(); final Object this$rootId = this.getRootId();
final Object other$rootId = other.getRootId(); final Object other$rootId = other.getRootId();
if (this$rootId == null ? other$rootId != null : !this$rootId.equals(other$rootId)) return false; if (this$rootId == null ? other$rootId != null : !this$rootId.equals(other$rootId)) return false;
@ -623,8 +622,7 @@ public class AggregateChangeIdGenerationImmutableUnitTests {
public boolean equals(final Object o) { public boolean equals(final Object o) {
if (o == this) return true; if (o == this) return true;
if (!(o instanceof Content)) return false; if (!(o instanceof Content other)) return false;
final Content other = (Content) o;
final Object this$id = this.getId(); final Object this$id = this.getId();
final Object other$id = other.getId(); final Object other$id = other.getId();
if (this$id == null ? other$id != null : !this$id.equals(other$id)) return false; if (this$id == null ? other$id != null : !this$id.equals(other$id)) return false;
@ -725,8 +723,7 @@ public class AggregateChangeIdGenerationImmutableUnitTests {
public boolean equals(final Object o) { public boolean equals(final Object o) {
if (o == this) return true; if (o == this) return true;
if (!(o instanceof ContentNoId)) return false; if (!(o instanceof ContentNoId other)) return false;
final ContentNoId other = (ContentNoId) o;
final Object this$single = this.getSingle(); final Object this$single = this.getSingle();
final Object other$single = other.getSingle(); final Object other$single = other.getSingle();
if (this$single == null ? other$single != null : !this$single.equals(other$single)) return false; if (this$single == null ? other$single != null : !this$single.equals(other$single)) return false;
@ -805,8 +802,7 @@ public class AggregateChangeIdGenerationImmutableUnitTests {
public boolean equals(final Object o) { public boolean equals(final Object o) {
if (o == this) return true; if (o == this) return true;
if (!(o instanceof Tag)) return false; if (!(o instanceof Tag other)) return false;
final Tag other = (Tag) o;
final Object this$id = this.getId(); final Object this$id = this.getId();
final Object other$id = other.getId(); final Object other$id = other.getId();
if (this$id == null ? other$id != null : !this$id.equals(other$id)) return false; if (this$id == null ? other$id != null : !this$id.equals(other$id)) return false;

4
spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/convert/SqlGeneratorUnitTests.java

@ -941,8 +941,8 @@ class SqlGeneratorUnitTests {
@Nullable @Nullable
private SqlIdentifier getAlias(Object maybeAliased) { private SqlIdentifier getAlias(Object maybeAliased) {
if (maybeAliased instanceof Aliased) { if (maybeAliased instanceof Aliased aliased) {
return ((Aliased) maybeAliased).getAlias(); return aliased.getAlias();
} }
return null; return null;
} }

18
spring-data-jdbc/src/test/java/org/springframework/data/jdbc/core/mapping/schema/LiquibaseChangeSetWriterUnitTests.java

@ -115,10 +115,8 @@ class LiquibaseChangeSetWriterUnitTests {
ChangeSet changeSet = writer.createChangeSet(ChangeSetMetadata.create(), new DatabaseChangeLog()); ChangeSet changeSet = writer.createChangeSet(ChangeSetMetadata.create(), new DatabaseChangeLog());
Optional<Change> tableWithFk = changeSet.getChanges().stream().filter(change -> { Optional<Change> tableWithFk = changeSet.getChanges().stream().filter(change -> change instanceof CreateTableChange createTableChange
return change instanceof CreateTableChange && createTableChange.getTableName().equals("table_with_fk_field")).findFirst();
&& ((CreateTableChange) change).getTableName().equals("table_with_fk_field");
}).findFirst();
assertThat(tableWithFk.isPresent()).isEqualTo(true); assertThat(tableWithFk.isPresent()).isEqualTo(true);
List<ColumnConfig> columns = ((CreateTableChange) tableWithFk.get()).getColumns(); List<ColumnConfig> columns = ((CreateTableChange) tableWithFk.get()).getColumns();
@ -181,9 +179,7 @@ class LiquibaseChangeSetWriterUnitTests {
void assertCreateTable(ChangeSet changeSet, String tableName, Tuple... columnTuples) { void assertCreateTable(ChangeSet changeSet, String tableName, Tuple... columnTuples) {
Optional<Change> createTableOptional = changeSet.getChanges().stream().filter(change -> { Optional<Change> createTableOptional = changeSet.getChanges().stream().filter(change -> change instanceof CreateTableChange createTableChange && createTableChange.getTableName().equals(tableName)).findFirst();
return change instanceof CreateTableChange && ((CreateTableChange) change).getTableName().equals(tableName);
}).findFirst();
assertThat(createTableOptional.isPresent()).isTrue(); assertThat(createTableOptional.isPresent()).isTrue();
CreateTableChange createTable = (CreateTableChange) createTableOptional.get(); CreateTableChange createTable = (CreateTableChange) createTableOptional.get();
assertThat(createTable.getColumns()) assertThat(createTable.getColumns())
@ -193,11 +189,9 @@ class LiquibaseChangeSetWriterUnitTests {
void assertAddForeignKey(ChangeSet changeSet, String baseTableName, String baseColumnNames, void assertAddForeignKey(ChangeSet changeSet, String baseTableName, String baseColumnNames,
String referencedTableName, String referencedColumnNames) { String referencedTableName, String referencedColumnNames) {
Optional<Change> addFkOptional = changeSet.getChanges().stream().filter(change -> { Optional<Change> addFkOptional = changeSet.getChanges().stream().filter(change -> change instanceof AddForeignKeyConstraintChange addForeignKeyConstraintChange
return change instanceof AddForeignKeyConstraintChange && addForeignKeyConstraintChange.getBaseTableName().equals(baseTableName)
&& ((AddForeignKeyConstraintChange) change).getBaseTableName().equals(baseTableName) && addForeignKeyConstraintChange.getBaseColumnNames().equals(baseColumnNames)).findFirst();
&& ((AddForeignKeyConstraintChange) change).getBaseColumnNames().equals(baseColumnNames);
}).findFirst();
assertThat(addFkOptional.isPresent()).isTrue(); assertThat(addFkOptional.isPresent()).isTrue();
AddForeignKeyConstraintChange addFk = (AddForeignKeyConstraintChange) addFkOptional.get(); AddForeignKeyConstraintChange addFk = (AddForeignKeyConstraintChange) addFkOptional.get();
assertThat(addFk.getBaseTableName()).isEqualTo(baseTableName); assertThat(addFk.getBaseTableName()).isEqualTo(baseTableName);

4
spring-data-jdbc/src/test/java/org/springframework/data/jdbc/repository/JdbcRepositoryWithCollectionsAndManuallyAssignedIdHsqlIntegrationTests.java

@ -66,8 +66,8 @@ public class JdbcRepositoryWithCollectionsAndManuallyAssignedIdHsqlIntegrationTe
return (ApplicationListener<BeforeConvertEvent>) event -> { return (ApplicationListener<BeforeConvertEvent>) event -> {
if (event.getEntity() instanceof DummyEntity) { if (event.getEntity() instanceof DummyEntity dummyEntity) {
setIds((DummyEntity) event.getEntity()); setIds(dummyEntity);
} }
}; };
} }

Loading…
Cancel
Save