Skip to content

Commit

Permalink
Make Context.NONE a Specialized Subclass (#24140)
Browse files Browse the repository at this point in the history
Make Context.NONE a Specialized Subclass
  • Loading branch information
alzimmermsft authored Sep 15, 2021
1 parent 7993d1d commit 0dde54a
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions sdk/core/azure-core/src/main/java/com/azure/core/util/Context.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.azure.core.annotation.Immutable;
import com.azure.core.util.logging.ClientLogger;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
Expand All @@ -21,14 +22,28 @@
*/
@Immutable
public class Context {
private final ClientLogger logger = new ClientLogger(Context.class);
private static final ClientLogger LOGGER = new ClientLogger(Context.class);

// All fields must be immutable.
//
/**
* Signifies that no data needs to be passed to the pipeline.
*/
public static final Context NONE = new Context(null, null, null);
public static final Context NONE = new Context(null, null, null) {
@Override
public Optional<Object> getData(Object key) {
if (key == null) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("key cannot be null"));
}

return Optional.empty();
}

@Override
public Map<Object, Object> getValues() {
return Collections.emptyMap();
}
};

private final Context parent;
private final Object key;
Expand Down Expand Up @@ -72,7 +87,7 @@ private Context(Context parent, Object key, Object value) {
*/
public Context addData(Object key, Object value) {
if (key == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("key cannot be null"));
throw LOGGER.logExceptionAsError(new IllegalArgumentException("key cannot be null"));
}
return new Context(this, key, value);
}
Expand Down Expand Up @@ -119,7 +134,7 @@ public static Context of(Map<Object, Object> keyValues) {
*/
public Optional<Object> getData(Object key) {
if (key == null) {
throw logger.logExceptionAsError(new IllegalArgumentException("key cannot be null"));
throw LOGGER.logExceptionAsError(new IllegalArgumentException("key cannot be null"));
}
for (Context c = this; c != null; c = c.parent) {
if (key.equals(c.key)) {
Expand Down

0 comments on commit 0dde54a

Please sign in to comment.