Skip to content

Commit d5b4817

Browse files
authored
Convert if-else chains to switch expressions (#17874) (#18965)
Signed-off-by: BeomSeogKim <[email protected]>
1 parent bd914cb commit d5b4817

File tree

12 files changed

+228
-264
lines changed

12 files changed

+228
-264
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
2121
- Add `epoch_micros` date format ([#14669](https://github.com/opensearch-project/OpenSearch/issues/14669))
2222

2323
### Changed
24+
- Refactor `if-else` chains to use `Java 17 pattern matching switch expressions`(([#18965](https://github.com/opensearch-project/OpenSearch/pull/18965))
2425
- Add CompletionStage variants to methods in the Client Interface and default to ActionListener impl ([#18998](https://github.com/opensearch-project/OpenSearch/pull/18998))
2526
- IllegalArgumentException when scroll ID references a node not found in Cluster ([#19031](https://github.com/opensearch-project/OpenSearch/pull/19031))
2627
- Adding ScriptedAvg class to painless spi to allowlist usage from plugins ([#19006](https://github.com/opensearch-project/OpenSearch/pull/19006))

libs/common/src/main/java/org/opensearch/common/Numbers.java

Lines changed: 44 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -83,44 +83,60 @@ public static boolean isValidDouble(double value) {
8383
* stored value cannot be converted to a long that stores the exact same
8484
* value. */
8585
public static long toLongExact(Number n) {
86-
if (n instanceof Byte || n instanceof Short || n instanceof Integer || n instanceof Long) {
87-
return n.longValue();
88-
} else if (n instanceof Float || n instanceof Double) {
89-
double d = n.doubleValue();
90-
if (d != Math.round(d)) {
91-
throw new IllegalArgumentException(n + " is not an integer value");
86+
return switch (n) {
87+
case Byte b -> b.longValue();
88+
case Short s -> s.longValue();
89+
case Integer i -> i.longValue();
90+
case Long l -> l;
91+
case Float f -> {
92+
double d = f.doubleValue();
93+
if (d != Math.round(d)) {
94+
throw new IllegalArgumentException(f + " is not an integer value");
95+
}
96+
yield f.longValue();
9297
}
93-
return n.longValue();
94-
} else if (n instanceof BigDecimal) {
95-
return ((BigDecimal) n).toBigIntegerExact().longValueExact();
96-
} else if (n instanceof BigInteger) {
97-
return ((BigInteger) n).longValueExact();
98-
} else {
99-
throw new IllegalArgumentException(
98+
case Double d -> {
99+
if (d != Math.round(d)) {
100+
throw new IllegalArgumentException(d + " is not an integer value");
101+
}
102+
yield d.longValue();
103+
}
104+
case BigDecimal bd -> bd.toBigIntegerExact().longValueExact();
105+
case BigInteger bi -> bi.longValueExact();
106+
default -> throw new IllegalArgumentException(
100107
"Cannot check whether [" + n + "] of class [" + n.getClass().getName() + "] is actually a long"
101108
);
102-
}
109+
};
103110
}
104111

105112
/** Return the {@link BigInteger} that {@code n} stores, or throws an exception if the
106113
* stored value cannot be converted to a {@link BigInteger} that stores the exact same
107114
* value. */
108115
public static BigInteger toBigIntegerExact(Number n) {
109-
if (n instanceof Byte || n instanceof Short || n instanceof Integer || n instanceof Long) {
110-
return BigInteger.valueOf(n.longValue());
111-
} else if (n instanceof Float || n instanceof Double) {
112-
double d = n.doubleValue();
113-
if (d != Math.round(d)) {
114-
throw new IllegalArgumentException(n + " is not an integer value");
116+
return switch (n) {
117+
case Byte b -> BigInteger.valueOf(b.longValue());
118+
case Short s -> BigInteger.valueOf(s.longValue());
119+
case Integer i -> BigInteger.valueOf(i.longValue());
120+
case Long l -> BigInteger.valueOf(l.longValue());
121+
case Float f -> {
122+
double d = f.doubleValue();
123+
if (d != Math.round(d)) {
124+
throw new IllegalArgumentException(f + " is not an integer value");
125+
}
126+
yield BigInteger.valueOf(f.longValue());
115127
}
116-
return BigInteger.valueOf(n.longValue());
117-
} else if (n instanceof BigDecimal) {
118-
return ((BigDecimal) n).toBigIntegerExact();
119-
} else if (n instanceof BigInteger) {
120-
return ((BigInteger) n);
121-
} else {
122-
throw new IllegalArgumentException("Cannot convert [" + n + "] of class [" + n.getClass().getName() + "] to a BigInteger");
123-
}
128+
case Double d -> {
129+
if (d != Math.round(d)) {
130+
throw new IllegalArgumentException(d + " is not an integer value");
131+
}
132+
yield BigInteger.valueOf(d.longValue());
133+
}
134+
case BigDecimal bd -> bd.toBigIntegerExact();
135+
case BigInteger bi -> bi;
136+
default -> throw new IllegalArgumentException(
137+
"Cannot convert [" + n + "] of class [" + n.getClass().getName() + "] to a BigInteger"
138+
);
139+
};
124140
}
125141

126142
/** Return the unsigned long (as {@link BigInteger}) that {@code n} stores, or throws an exception if the

libs/core/src/main/java/org/opensearch/ExceptionsHelper.java

Lines changed: 25 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -112,53 +112,40 @@ private ErrorMessages() {
112112
private ExceptionsHelper() {}
113113

114114
public static RuntimeException convertToRuntime(Exception e) {
115-
if (e instanceof RuntimeException) {
116-
return (RuntimeException) e;
117-
}
118-
return new OpenSearchException(e);
115+
return switch (e) {
116+
case RuntimeException re -> re;
117+
default -> new OpenSearchException(e);
118+
};
119119
}
120120

121121
public static OpenSearchException convertToOpenSearchException(Exception e) {
122-
if (e instanceof OpenSearchException) {
123-
return (OpenSearchException) e;
124-
}
125-
return new OpenSearchException(e);
122+
return switch (e) {
123+
case OpenSearchException oe -> oe;
124+
default -> new OpenSearchException(e);
125+
};
126126
}
127127

128128
public static RestStatus status(Throwable t) {
129-
if (t != null) {
130-
if (t instanceof OpenSearchException) {
131-
return ((OpenSearchException) t).status();
132-
} else if (t instanceof IllegalArgumentException) {
133-
return RestStatus.BAD_REQUEST;
134-
} else if (t instanceof InputCoercionException) {
135-
return RestStatus.BAD_REQUEST;
136-
} else if (t instanceof JsonParseException) {
137-
return RestStatus.BAD_REQUEST;
138-
} else if (t instanceof OpenSearchRejectedExecutionException) {
139-
return RestStatus.TOO_MANY_REQUESTS;
140-
} else if (t instanceof NotXContentException) {
141-
return RestStatus.BAD_REQUEST;
142-
}
143-
}
144-
return RestStatus.INTERNAL_SERVER_ERROR;
129+
return switch (t) {
130+
case OpenSearchException ose -> ose.status();
131+
case IllegalArgumentException ignored -> RestStatus.BAD_REQUEST;
132+
case InputCoercionException ignored -> RestStatus.BAD_REQUEST;
133+
case JsonParseException ignored -> RestStatus.BAD_REQUEST;
134+
case NotXContentException ignored -> RestStatus.BAD_REQUEST;
135+
case OpenSearchRejectedExecutionException ignored -> RestStatus.TOO_MANY_REQUESTS;
136+
case null, default -> RestStatus.INTERNAL_SERVER_ERROR;
137+
};
145138
}
146139

147140
public static String summaryMessage(Throwable t) {
148-
if (t != null) {
149-
if (t instanceof OpenSearchException) {
150-
return getExceptionSimpleClassName(t) + "[" + t.getMessage() + "]";
151-
} else if (t instanceof IllegalArgumentException) {
152-
return ErrorMessages.INVALID_ARGUMENT;
153-
} else if (t instanceof InputCoercionException) {
154-
return ErrorMessages.JSON_COERCION_FAILED;
155-
} else if (t instanceof JsonParseException) {
156-
return ErrorMessages.JSON_PARSE_FAILED;
157-
} else if (t instanceof OpenSearchRejectedExecutionException) {
158-
return ErrorMessages.TOO_MANY_REQUESTS;
159-
}
160-
}
161-
return ErrorMessages.INTERNAL_FAILURE;
141+
return switch (t) {
142+
case OpenSearchException ose -> getExceptionSimpleClassName(t) + "[" + ose.getMessage() + "]";
143+
case IllegalArgumentException ignored -> ErrorMessages.INVALID_ARGUMENT;
144+
case InputCoercionException ignored -> ErrorMessages.JSON_COERCION_FAILED;
145+
case JsonParseException ignored -> ErrorMessages.JSON_PARSE_FAILED;
146+
case OpenSearchRejectedExecutionException ignored -> ErrorMessages.TOO_MANY_REQUESTS;
147+
case null, default -> "Internal failure";
148+
};
162149
}
163150

164151
public static Throwable unwrapCause(Throwable t) {

libs/core/src/main/java/org/opensearch/core/common/bytes/BytesReference.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,10 @@ public interface BytesReference extends Comparable<BytesReference>, ToXContentFr
6363
static BytesReference bytes(XContentBuilder xContentBuilder) {
6464
xContentBuilder.close();
6565
OutputStream stream = xContentBuilder.getOutputStream();
66-
if (stream instanceof ByteArrayOutputStream) {
67-
return new BytesArray(((ByteArrayOutputStream) stream).toByteArray());
68-
} else {
69-
return ((BytesStream) stream).bytes();
70-
}
66+
return switch (stream) {
67+
case ByteArrayOutputStream baos -> new BytesArray(baos.toByteArray());
68+
default -> ((BytesStream) stream).bytes();
69+
};
7170
}
7271

7372
/**

libs/core/src/main/java/org/opensearch/core/common/logging/LoggerMessageFormat.java

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -169,24 +169,16 @@ private static void deeplyAppendParameter(StringBuilder sbuf, Object o, Set<Obje
169169
} else {
170170
// check for primitive array types because they
171171
// unfortunately cannot be cast to Object[]
172-
if (o instanceof boolean[]) {
173-
booleanArrayAppend(sbuf, (boolean[]) o);
174-
} else if (o instanceof byte[]) {
175-
byteArrayAppend(sbuf, (byte[]) o);
176-
} else if (o instanceof char[]) {
177-
charArrayAppend(sbuf, (char[]) o);
178-
} else if (o instanceof short[]) {
179-
shortArrayAppend(sbuf, (short[]) o);
180-
} else if (o instanceof int[]) {
181-
intArrayAppend(sbuf, (int[]) o);
182-
} else if (o instanceof long[]) {
183-
longArrayAppend(sbuf, (long[]) o);
184-
} else if (o instanceof float[]) {
185-
floatArrayAppend(sbuf, (float[]) o);
186-
} else if (o instanceof double[]) {
187-
doubleArrayAppend(sbuf, (double[]) o);
188-
} else {
189-
objectArrayAppend(sbuf, (Object[]) o, seen);
172+
switch (o) {
173+
case boolean[] boolArr -> booleanArrayAppend(sbuf, boolArr);
174+
case byte[] byteArr -> byteArrayAppend(sbuf, byteArr);
175+
case char[] charArr -> charArrayAppend(sbuf, charArr);
176+
case short[] shortArr -> shortArrayAppend(sbuf, shortArr);
177+
case int[] intArr -> intArrayAppend(sbuf, intArr);
178+
case long[] longArr -> longArrayAppend(sbuf, longArr);
179+
case float[] floatArr -> floatArrayAppend(sbuf, floatArr);
180+
case double[] doubleArr -> doubleArrayAppend(sbuf, doubleArr);
181+
default -> objectArrayAppend(sbuf, (Object[]) o, seen);
190182
}
191183
}
192184
}

libs/nio/src/main/java/org/opensearch/nio/NioSelectorGroup.java

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -183,10 +183,9 @@ private static void startSelectors(Iterable<NioSelector> selectors, ThreadFactor
183183
Thread.currentThread().interrupt();
184184
throw new IllegalStateException("Interrupted while waiting for selector to start.", e);
185185
} catch (ExecutionException e) {
186-
if (e.getCause() instanceof RuntimeException) {
187-
throw (RuntimeException) e.getCause();
188-
} else {
189-
throw new RuntimeException("Exception during selector start.", e);
186+
switch (e.getCause()) {
187+
case RuntimeException re -> throw re;
188+
default -> throw new RuntimeException("Exception during selector start.", e);
190189
}
191190
}
192191
}

libs/nio/src/main/java/org/opensearch/nio/SocketChannelContext.java

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -142,12 +142,10 @@ public boolean connect() throws IOException {
142142
return true;
143143
} else if (connectContext.isCompletedExceptionally()) {
144144
Exception exception = connectException;
145-
if (exception == null) {
146-
throw new AssertionError("Should have received connection exception");
147-
} else if (exception instanceof IOException) {
148-
throw (IOException) exception;
149-
} else {
150-
throw (RuntimeException) exception;
145+
switch (exception) {
146+
case null -> throw new AssertionError("Should have received connection exception");
147+
case IOException ioException -> throw ioException;
148+
default -> throw (RuntimeException) exception;
151149
}
152150
}
153151

server/src/main/java/org/opensearch/action/DocWriteRequest.java

Lines changed: 28 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -263,33 +263,39 @@ static ActionRequestValidationException validateDocIdLength(String id, ActionReq
263263

264264
/** write a document write (index/delete/update) request*/
265265
static void writeDocumentRequest(StreamOutput out, DocWriteRequest<?> request) throws IOException {
266-
if (request instanceof IndexRequest) {
267-
out.writeByte((byte) 0);
268-
((IndexRequest) request).writeTo(out);
269-
} else if (request instanceof DeleteRequest) {
270-
out.writeByte((byte) 1);
271-
((DeleteRequest) request).writeTo(out);
272-
} else if (request instanceof UpdateRequest) {
273-
out.writeByte((byte) 2);
274-
((UpdateRequest) request).writeTo(out);
275-
} else {
276-
throw new IllegalStateException("invalid request [" + request.getClass().getSimpleName() + " ]");
266+
switch (request) {
267+
case IndexRequest indexRequest -> {
268+
out.writeByte((byte) 0);
269+
indexRequest.writeTo(out);
270+
}
271+
case DeleteRequest deleteRequest -> {
272+
out.writeByte((byte) 1);
273+
deleteRequest.writeTo(out);
274+
}
275+
case UpdateRequest updateRequest -> {
276+
out.writeByte((byte) 2);
277+
updateRequest.writeTo(out);
278+
}
279+
default -> throw new IllegalStateException("invalid request [" + request.getClass().getSimpleName() + " ]");
277280
}
278281
}
279282

280283
/** write a document write (index/delete/update) request without shard id*/
281284
static void writeDocumentRequestThin(StreamOutput out, DocWriteRequest<?> request) throws IOException {
282-
if (request instanceof IndexRequest) {
283-
out.writeByte((byte) 0);
284-
((IndexRequest) request).writeThin(out);
285-
} else if (request instanceof DeleteRequest) {
286-
out.writeByte((byte) 1);
287-
((DeleteRequest) request).writeThin(out);
288-
} else if (request instanceof UpdateRequest) {
289-
out.writeByte((byte) 2);
290-
((UpdateRequest) request).writeThin(out);
291-
} else {
292-
throw new IllegalStateException("invalid request [" + request.getClass().getSimpleName() + " ]");
285+
switch (request) {
286+
case IndexRequest indexRequest -> {
287+
out.writeByte((byte) 0);
288+
indexRequest.writeThin(out);
289+
}
290+
case DeleteRequest deleteRequest -> {
291+
out.writeByte((byte) 1);
292+
deleteRequest.writeThin(out);
293+
}
294+
case UpdateRequest updateRequest -> {
295+
out.writeByte((byte) 2);
296+
updateRequest.writeThin(out);
297+
}
298+
default -> throw new IllegalStateException("invalid request [" + request.getClass().getSimpleName() + " ]");
293299
}
294300
}
295301

server/src/main/java/org/opensearch/action/bulk/BulkItemResponse.java

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -630,14 +630,11 @@ public void writeThin(StreamOutput out) throws IOException {
630630
}
631631

632632
private void writeResponseType(StreamOutput out) throws IOException {
633-
if (response instanceof IndexResponse) {
634-
out.writeByte((byte) 0);
635-
} else if (response instanceof DeleteResponse) {
636-
out.writeByte((byte) 1);
637-
} else if (response instanceof UpdateResponse) {
638-
out.writeByte((byte) 3); // make 3 instead of 2, because 2 is already in use for 'no responses'
639-
} else {
640-
throw new IllegalStateException("Unexpected response type found [" + response.getClass() + "]");
633+
switch (response) {
634+
case IndexResponse ignored -> out.writeByte((byte) 0);
635+
case DeleteResponse ignored -> out.writeByte((byte) 1);
636+
case UpdateResponse ignored -> out.writeByte((byte) 3); // make 3 instead of 2, because 2 is already in use for 'no responses'
637+
default -> throw new IllegalStateException("Unexpected response type found [" + response.getClass() + "]");
641638
}
642639
}
643640
}

0 commit comments

Comments
 (0)