Skip to content

Commit

Permalink
Remove duplicate code in ConstantPool class
Browse files Browse the repository at this point in the history
Motivation:

Currently, valueOf() and newInstance() use almost same code to create new constant.
For maintainability, it's better to share duplicate code among them.

Motification:

Added new private functions.
- checkNotNullAndNotEmpty() is for checking whether the name of a constant is null and empty.
- newConstant0() is for creating a new constant.

Result:

- Compact source code
- Improvement of maintainability
  • Loading branch information
JongYoon Lim authored and normanmaurer committed Apr 29, 2015
1 parent 31a6ab9 commit c4d69e9
Showing 1 changed file with 29 additions and 28 deletions.
57 changes: 29 additions & 28 deletions common/src/main/java/io/netty/util/ConstantPool.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,31 +55,24 @@ public T valueOf(Class<?> firstNameComponent, String secondNameComponent) {
* @param name the name of the {@link Constant}
*/
public T valueOf(String name) {
if (name == null) {
throw new NullPointerException("name");
}

if (name.isEmpty()) {
throw new IllegalArgumentException("empty name");
}
T c;

synchronized (constants) {
T c = constants.get(name);
if (c == null) {
c = newConstant(nextId, name);
constants.put(name, c);
nextId ++;
if (exists(name)) {
c = constants.get(name);
} else {
c = newInstance0(name);
}

return c;
}

return c;
}

/**
* Returns {@code true} if a {@link AttributeKey} exists for the given {@code name}.
*/
public boolean exists(String name) {
ObjectUtil.checkNotNull(name, "name");
checkNotNullAndNotEmpty(name);
synchronized (constants) {
return constants.containsKey(name);
}
Expand All @@ -91,27 +84,35 @@ public boolean exists(String name) {
*/
@SuppressWarnings("unchecked")
public T newInstance(String name) {
if (name == null) {
throw new NullPointerException("name");
if (exists(name)) {
throw new IllegalArgumentException(String.format("'%s' is already in use", name));
}

if (name.isEmpty()) {
throw new IllegalArgumentException("empty name");
}
T c = newInstance0(name);

return c;
}

// Be careful that this dose not check whether the argument is null or empty.
private T newInstance0(String name) {
synchronized (constants) {
T c = constants.get(name);
if (c == null) {
c = newConstant(nextId, name);
constants.put(name, c);
nextId ++;
} else {
throw new IllegalArgumentException(String.format("'%s' is already in use", name));
}
T c = newConstant(nextId, name);
constants.put(name, c);
nextId++;
return c;
}
}

private String checkNotNullAndNotEmpty(String name) {
ObjectUtil.checkNotNull(name, "name");

if (name.isEmpty()) {
throw new IllegalArgumentException("empty name");
}

return name;
}

protected abstract T newConstant(int id, String name);

@Deprecated
Expand Down

0 comments on commit c4d69e9

Please sign in to comment.