Skip to content

Commit 3abc25d

Browse files
arefbehboudischauder
authored andcommitted
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
1 parent cacb14c commit 3abc25d

9 files changed

+47
-57
lines changed

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

+26-26
Original file line numberDiff line numberDiff line change
@@ -81,32 +81,32 @@ <T> void executeDelete(AggregateChange<T> aggregateChange) {
8181
private void execute(DbAction<?> action, JdbcAggregateChangeExecutionContext executionContext) {
8282

8383
try {
84-
if (action instanceof DbAction.InsertRoot) {
85-
executionContext.executeInsertRoot((DbAction.InsertRoot<?>) action);
86-
} else if (action instanceof DbAction.BatchInsertRoot<?>) {
87-
executionContext.executeBatchInsertRoot((DbAction.BatchInsertRoot<?>) action);
88-
} else if (action instanceof DbAction.Insert) {
89-
executionContext.executeInsert((DbAction.Insert<?>) action);
90-
} else if (action instanceof DbAction.BatchInsert) {
91-
executionContext.executeBatchInsert((DbAction.BatchInsert<?>) action);
92-
} else if (action instanceof DbAction.UpdateRoot) {
93-
executionContext.executeUpdateRoot((DbAction.UpdateRoot<?>) action);
94-
} else if (action instanceof DbAction.Delete) {
95-
executionContext.executeDelete((DbAction.Delete<?>) action);
96-
} else if (action instanceof DbAction.BatchDelete<?>) {
97-
executionContext.executeBatchDelete((DbAction.BatchDelete<?>) action);
98-
} else if (action instanceof DbAction.DeleteAll) {
99-
executionContext.executeDeleteAll((DbAction.DeleteAll<?>) action);
100-
} else if (action instanceof DbAction.DeleteRoot) {
101-
executionContext.executeDeleteRoot((DbAction.DeleteRoot<?>) action);
102-
} else if (action instanceof DbAction.BatchDeleteRoot) {
103-
executionContext.executeBatchDeleteRoot((DbAction.BatchDeleteRoot<?>) action);
104-
} else if (action instanceof DbAction.DeleteAllRoot) {
105-
executionContext.executeDeleteAllRoot((DbAction.DeleteAllRoot<?>) action);
106-
} else if (action instanceof DbAction.AcquireLockRoot) {
107-
executionContext.executeAcquireLock((DbAction.AcquireLockRoot<?>) action);
108-
} else if (action instanceof DbAction.AcquireLockAllRoot) {
109-
executionContext.executeAcquireLockAllRoot((DbAction.AcquireLockAllRoot<?>) action);
84+
if (action instanceof DbAction.InsertRoot<?> insertRoot) {
85+
executionContext.executeInsertRoot(insertRoot);
86+
} else if (action instanceof DbAction.BatchInsertRoot<?> batchInsertRoot) {
87+
executionContext.executeBatchInsertRoot(batchInsertRoot);
88+
} else if (action instanceof DbAction.Insert<?> insert) {
89+
executionContext.executeInsert(insert);
90+
} else if (action instanceof DbAction.BatchInsert<?> batchInsert) {
91+
executionContext.executeBatchInsert(batchInsert);
92+
} else if (action instanceof DbAction.UpdateRoot<?> updateRoot) {
93+
executionContext.executeUpdateRoot(updateRoot);
94+
} else if (action instanceof DbAction.Delete<?> delete) {
95+
executionContext.executeDelete(delete);
96+
} else if (action instanceof DbAction.BatchDelete<?> batchDelete) {
97+
executionContext.executeBatchDelete(batchDelete);
98+
} else if (action instanceof DbAction.DeleteAll<?> deleteAll) {
99+
executionContext.executeDeleteAll(deleteAll);
100+
} else if (action instanceof DbAction.DeleteRoot<?> deleteRoot) {
101+
executionContext.executeDeleteRoot(deleteRoot);
102+
} else if (action instanceof DbAction.BatchDeleteRoot<?> batchDeleteRoot) {
103+
executionContext.executeBatchDeleteRoot(batchDeleteRoot);
104+
} else if (action instanceof DbAction.DeleteAllRoot<?> deleteAllRoot) {
105+
executionContext.executeDeleteAllRoot(deleteAllRoot);
106+
} else if (action instanceof DbAction.AcquireLockRoot<?> acquireLockRoot) {
107+
executionContext.executeAcquireLock(acquireLockRoot);
108+
} else if (action instanceof DbAction.AcquireLockAllRoot<?> acquireLockAllRoot) {
109+
executionContext.executeAcquireLockAllRoot(acquireLockAllRoot);
110110
} else {
111111
throw new RuntimeException("unexpected action");
112112
}

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

+2-2
Original file line numberDiff line numberDiff line change
@@ -312,8 +312,8 @@ private <S> Object setIdAndCascadingProperties(DbAction.WithEntity<S> action, @N
312312
@SuppressWarnings("unchecked")
313313
private PersistentPropertyPath<?> getRelativePath(DbAction<?> action, PersistentPropertyPath<?> pathToValue) {
314314

315-
if (action instanceof DbAction.Insert) {
316-
return pathToValue.getExtensionForBaseOf(((DbAction.Insert) action).getPropertyPath());
315+
if (action instanceof DbAction.Insert insert) {
316+
return pathToValue.getExtensionForBaseOf(insert.getPropertyPath());
317317
}
318318

319319
if (action instanceof DbAction.InsertRoot) {

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

+2-2
Original file line numberDiff line numberDiff line change
@@ -192,9 +192,9 @@ public Object readValue(@Nullable Object value, TypeInformation<?> type) {
192192
return value;
193193
}
194194

195-
if (value instanceof Array) {
195+
if (value instanceof Array array) {
196196
try {
197-
return super.readValue(((Array) value).getArray(), type);
197+
return super.readValue(array.getArray(), type);
198198
} catch (SQLException | ConverterNotFoundException e) {
199199
LOG.info("Failed to extract a value of type %s from an Array; Attempting to use standard conversions", e);
200200
}

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

+2-2
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ Expression getMappedObject(Expression expression, @Nullable RelationalPersistent
148148
Assert.state(table != null, String.format("The column %s must have a table set", column));
149149

150150
Column columnFromTable = table.column(field.getMappedColumnName());
151-
return column instanceof Aliased ? columnFromTable.as(((Aliased) column).getAlias()) : columnFromTable;
151+
return column instanceof Aliased aliased ? columnFromTable.as(aliased.getAlias()) : columnFromTable;
152152
}
153153

154154
if (expression instanceof SimpleFunction function) {
@@ -162,7 +162,7 @@ Expression getMappedObject(Expression expression, @Nullable RelationalPersistent
162162

163163
SimpleFunction mappedFunction = SimpleFunction.create(function.getFunctionName(), mappedArguments);
164164

165-
return function instanceof Aliased ? mappedFunction.as(((Aliased) function).getAlias()) : mappedFunction;
165+
return function instanceof Aliased aliased ? mappedFunction.as(aliased.getAlias()) : mappedFunction;
166166
}
167167

168168
throw new IllegalArgumentException(String.format("Cannot map %s", expression));

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

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public Class<?>[] getSpecificTargetClasses() {
3737

3838
@Override
3939
public boolean canRead(EvaluationContext context, @Nullable Object target, String name) {
40-
return target instanceof ResultSetAccessor && ((ResultSetAccessor) target).hasValue(name);
40+
return target instanceof ResultSetAccessor resultSetAccessor && resultSetAccessor.hasValue(name);
4141
}
4242

4343
@Override

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

+4-8
Original file line numberDiff line numberDiff line change
@@ -491,8 +491,7 @@ public ContentNoId getEmbedded() {
491491

492492
public boolean equals(final Object o) {
493493
if (o == this) return true;
494-
if (!(o instanceof DummyEntity)) return false;
495-
final DummyEntity other = (DummyEntity) o;
494+
if (!(o instanceof DummyEntity other)) return false;
496495
final Object this$rootId = this.getRootId();
497496
final Object other$rootId = other.getRootId();
498497
if (this$rootId == null ? other$rootId != null : !this$rootId.equals(other$rootId)) return false;
@@ -623,8 +622,7 @@ public Map<String, Tag> getTagMap() {
623622

624623
public boolean equals(final Object o) {
625624
if (o == this) return true;
626-
if (!(o instanceof Content)) return false;
627-
final Content other = (Content) o;
625+
if (!(o instanceof Content other)) return false;
628626
final Object this$id = this.getId();
629627
final Object other$id = other.getId();
630628
if (this$id == null ? other$id != null : !this$id.equals(other$id)) return false;
@@ -725,8 +723,7 @@ public Map<String, Tag> getTagMap() {
725723

726724
public boolean equals(final Object o) {
727725
if (o == this) return true;
728-
if (!(o instanceof ContentNoId)) return false;
729-
final ContentNoId other = (ContentNoId) o;
726+
if (!(o instanceof ContentNoId other)) return false;
730727
final Object this$single = this.getSingle();
731728
final Object other$single = other.getSingle();
732729
if (this$single == null ? other$single != null : !this$single.equals(other$single)) return false;
@@ -805,8 +802,7 @@ public String getName() {
805802

806803
public boolean equals(final Object o) {
807804
if (o == this) return true;
808-
if (!(o instanceof Tag)) return false;
809-
final Tag other = (Tag) o;
805+
if (!(o instanceof Tag other)) return false;
810806
final Object this$id = this.getId();
811807
final Object other$id = other.getId();
812808
if (this$id == null ? other$id != null : !this$id.equals(other$id)) return false;

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

+2-2
Original file line numberDiff line numberDiff line change
@@ -941,8 +941,8 @@ void mappingMapKeyToChildShouldNotResultInDuplicateColumn() {
941941
@Nullable
942942
private SqlIdentifier getAlias(Object maybeAliased) {
943943

944-
if (maybeAliased instanceof Aliased) {
945-
return ((Aliased) maybeAliased).getAlias();
944+
if (maybeAliased instanceof Aliased aliased) {
945+
return aliased.getAlias();
946946
}
947947
return null;
948948
}

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

+6-12
Original file line numberDiff line numberDiff line change
@@ -115,10 +115,8 @@ void fieldForFkShouldNotBeCreatedTwice() {
115115

116116
ChangeSet changeSet = writer.createChangeSet(ChangeSetMetadata.create(), new DatabaseChangeLog());
117117

118-
Optional<Change> tableWithFk = changeSet.getChanges().stream().filter(change -> {
119-
return change instanceof CreateTableChange
120-
&& ((CreateTableChange) change).getTableName().equals("table_with_fk_field");
121-
}).findFirst();
118+
Optional<Change> tableWithFk = changeSet.getChanges().stream().filter(change -> change instanceof CreateTableChange createTableChange
119+
&& createTableChange.getTableName().equals("table_with_fk_field")).findFirst();
122120
assertThat(tableWithFk.isPresent()).isEqualTo(true);
123121

124122
List<ColumnConfig> columns = ((CreateTableChange) tableWithFk.get()).getColumns();
@@ -181,9 +179,7 @@ void createForeignKeyForOneToOneWithMultipleChildren() {
181179

182180

183181
void assertCreateTable(ChangeSet changeSet, String tableName, Tuple... columnTuples) {
184-
Optional<Change> createTableOptional = changeSet.getChanges().stream().filter(change -> {
185-
return change instanceof CreateTableChange && ((CreateTableChange) change).getTableName().equals(tableName);
186-
}).findFirst();
182+
Optional<Change> createTableOptional = changeSet.getChanges().stream().filter(change -> change instanceof CreateTableChange createTableChange && createTableChange.getTableName().equals(tableName)).findFirst();
187183
assertThat(createTableOptional.isPresent()).isTrue();
188184
CreateTableChange createTable = (CreateTableChange) createTableOptional.get();
189185
assertThat(createTable.getColumns())
@@ -193,11 +189,9 @@ void assertCreateTable(ChangeSet changeSet, String tableName, Tuple... columnTup
193189

194190
void assertAddForeignKey(ChangeSet changeSet, String baseTableName, String baseColumnNames,
195191
String referencedTableName, String referencedColumnNames) {
196-
Optional<Change> addFkOptional = changeSet.getChanges().stream().filter(change -> {
197-
return change instanceof AddForeignKeyConstraintChange
198-
&& ((AddForeignKeyConstraintChange) change).getBaseTableName().equals(baseTableName)
199-
&& ((AddForeignKeyConstraintChange) change).getBaseColumnNames().equals(baseColumnNames);
200-
}).findFirst();
192+
Optional<Change> addFkOptional = changeSet.getChanges().stream().filter(change -> change instanceof AddForeignKeyConstraintChange addForeignKeyConstraintChange
193+
&& addForeignKeyConstraintChange.getBaseTableName().equals(baseTableName)
194+
&& addForeignKeyConstraintChange.getBaseColumnNames().equals(baseColumnNames)).findFirst();
201195
assertThat(addFkOptional.isPresent()).isTrue();
202196
AddForeignKeyConstraintChange addFk = (AddForeignKeyConstraintChange) addFkOptional.get();
203197
assertThat(addFk.getBaseTableName()).isEqualTo(baseTableName);

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

+2-2
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,8 @@ public ApplicationListener<?> idSetting() {
6666

6767
return (ApplicationListener<BeforeConvertEvent>) event -> {
6868

69-
if (event.getEntity() instanceof DummyEntity) {
70-
setIds((DummyEntity) event.getEntity());
69+
if (event.getEntity() instanceof DummyEntity dummyEntity) {
70+
setIds(dummyEntity);
7171
}
7272
};
7373
}

0 commit comments

Comments
 (0)