Skip to content

Commit

Permalink
Remove comparison to true for booleans (#51723)
Browse files Browse the repository at this point in the history
While we use `== false` as a more visible form of boolean negation
(instead of `!`), the true case is implied and the true value does not
need to explicitly checked. This commit converts cases that have slipped
into the code checking for `== true`.
  • Loading branch information
rjernst committed Feb 1, 2020
1 parent 61622c4 commit 21224ca
Show file tree
Hide file tree
Showing 54 changed files with 88 additions and 91 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ import org.elasticsearch.gradle.LoggedExec
import org.gradle.api.GradleException
import org.gradle.api.Task
import org.gradle.api.tasks.Exec
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Internal

/**
* A fixture for integration tests which runs in a separate process launched by Ant.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ public void apply(Project project) {

TaskProvider<Task> destructiveDistroTest = project.getTasks().register("destructiveDistroTest");
for (ElasticsearchDistribution distribution : distributions) {
if (distribution.getType() != Type.DOCKER || runDockerTests == true) {
if (distribution.getType() != Type.DOCKER || runDockerTests) {
TaskProvider<?> destructiveTask = configureDistroTest(project, distribution);
destructiveDistroTest.configure(t -> t.dependsOn(destructiveTask));
}
Expand Down Expand Up @@ -152,7 +152,7 @@ public void apply(Project project) {
//
// The shouldTestDocker property could be null, hence we use Boolean.TRUE.equals()
boolean shouldExecute = distribution.getType() != Type.DOCKER
|| Boolean.TRUE.equals(vmProject.findProperty("shouldTestDocker")) == true;
|| Boolean.TRUE.equals(vmProject.findProperty("shouldTestDocker"));

if (shouldExecute) {
t.dependsOn(vmTask);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,19 +53,19 @@ private static DockerAvailability getDockerAvailability(Project project) {
// Since we use a multi-stage Docker build, check the Docker version since 17.05
lastResult = runCommand(project, dockerPath, "version", "--format", "{{.Server.Version}}");

if (lastResult.isSuccess() == true) {
if (lastResult.isSuccess()) {
version = Version.fromString(lastResult.stdout.trim(), Version.Mode.RELAXED);

isVersionHighEnough = version.onOrAfter("17.05.0");

if (isVersionHighEnough == true) {
if (isVersionHighEnough) {
// Check that we can execute a privileged command
lastResult = runCommand(project, dockerPath, "images");
}
}
}

boolean isAvailable = isVersionHighEnough && lastResult.isSuccess() == true;
boolean isAvailable = isVersionHighEnough && lastResult.isSuccess();

return new DockerAvailability(isAvailable, isVersionHighEnough, dockerPath, version, lastResult);
}
Expand Down Expand Up @@ -125,7 +125,7 @@ private static class DockerAvailability {
public static void assertDockerIsAvailable(Project project, List<String> tasks) {
DockerAvailability availability = getDockerAvailability(project);

if (availability.isAvailable == true) {
if (availability.isAvailable) {
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public static Version fromString(final String s, final Mode mode) {
Objects.requireNonNull(s);
Matcher matcher = mode == Mode.STRICT ? pattern.matcher(s) : relaxedPattern.matcher(s);
if (matcher.matches() == false) {
String expected = mode == Mode.STRICT == true
String expected = mode == Mode.STRICT
? "major.minor.revision[-(alpha|beta|rc)Number][-SNAPSHOT]"
: "major.minor.revision[-extra]";
throw new IllegalArgumentException("Invalid version format: '" + s + "'. Should be " + expected);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ static TermVectorsResponse createTestInstance() {
long tookInMillis = randomNonNegativeLong();
boolean found = randomBoolean();
List<TermVectorsResponse.TermVector> tvList = null;
if (found == true){
if (found){
boolean hasFieldStatistics = randomBoolean();
boolean hasTermStatistics = randomBoolean();
boolean hasScores = randomBoolean();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@ private Circle parseCircle(StreamTokenizer stream) throws IOException, ParseExce
double lat = nextNumber(stream);
double radius = nextNumber(stream);
double alt = Double.NaN;
if (isNumberNext(stream) == true) {
if (isNumberNext(stream)) {
alt = nextNumber(stream);
}
Circle circle = new Circle(lon, lat, alt, radius);
Expand Down Expand Up @@ -560,7 +560,7 @@ private String nextCloser(StreamTokenizer stream) throws IOException, ParseExcep
}

private String nextComma(StreamTokenizer stream) throws IOException, ParseException {
if (nextWord(stream).equals(COMMA) == true) {
if (nextWord(stream).equals(COMMA)) {
return COMMA;
}
throw new ParseException("expected " + COMMA + " but found: " + tokenString(stream), stream.lineno());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ private Default(long interval,
public void register(Matcher matcher) {
registered.getAndIncrement();
Long previousValue = registry.put(matcher, relativeTimeSupplier.getAsLong());
if (running.compareAndSet(false, true) == true) {
if (running.compareAndSet(false, true)) {
scheduler.accept(interval, this::interruptLongRunningExecutions);
}
assert previousValue == null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public LeafBucketCollector getLeafCollector(LeafReaderContext ctx,
@Override
public void collect(int doc, long bucket) throws IOException {
// get fields
if (includeDocument(doc) == true) {
if (includeDocument(doc)) {
stats = bigArrays.grow(stats, bucket + 1);
RunningStats stat = stats.get(bucket);
// add document fields to correlation stats
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ public void add(final String[] fieldNames, final double[] fieldVals) {
deltas.put(fieldName, fieldValue * docCount - fieldSum.get(fieldName));

// update running mean, variance, skewness, kurtosis
if (means.containsKey(fieldName) == true) {
if (means.containsKey(fieldName)) {
// update running means
m1 = means.get(fieldName);
d = fieldValue - m1;
Expand Down Expand Up @@ -194,7 +194,7 @@ private void updateCovariance(final String[] fieldNames, final Map<String, Doubl
dR = deltas.get(fieldName);
HashMap<String, Double> cFieldVals = (covariances.get(fieldName) != null) ? covariances.get(fieldName) : new HashMap<>();
for (String cFieldName : cFieldNames) {
if (cFieldVals.containsKey(cFieldName) == true) {
if (cFieldVals.containsKey(cFieldName)) {
newVal = cFieldVals.get(cFieldName) + 1.0 / (docCount * (docCount - 1.0)) * dR * deltas.get(cFieldName);
cFieldVals.put(cFieldName, newVal);
} else {
Expand Down Expand Up @@ -224,7 +224,7 @@ public void merge(final RunningStats other) {
this.variances.put(fieldName, other.variances.get(fieldName).doubleValue());
this.skewness.put(fieldName , other.skewness.get(fieldName).doubleValue());
this.kurtosis.put(fieldName, other.kurtosis.get(fieldName).doubleValue());
if (other.covariances.containsKey(fieldName) == true) {
if (other.covariances.containsKey(fieldName)) {
this.covariances.put(fieldName, other.covariances.get(fieldName));
}
this.docCount = other.docCount;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ public void addPainlessClass(Class<?> clazz, boolean importClassName) {
String importedCanonicalClassName = javaClassName.substring(javaClassName.lastIndexOf('.') + 1).replace('$', '.');

if (canonicalClassName.equals(importedCanonicalClassName)) {
if (importClassName == true) {
if (importClassName) {
throw new IllegalArgumentException("must use no_import parameter on class [" + canonicalClassName + "] with no package");
}
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public RatedSearchHit(SearchHit searchHit, OptionalInt rating) {
}

RatedSearchHit(StreamInput in) throws IOException {
this(new SearchHit(in), in.readBoolean() == true ? OptionalInt.of(in.readVInt()) : OptionalInt.empty());
this(new SearchHit(in), in.readBoolean() ? OptionalInt.of(in.readVInt()) : OptionalInt.empty());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ public void assertElasticsearchFailure(Shell.Result result, String expectedMessa
Shell.Result error = journaldWrapper.getLogs();
assertThat(error.stdout, containsString(expectedMessage));

} else if (Platforms.WINDOWS == true) {
} else if (Platforms.WINDOWS) {

// In Windows, we have written our stdout and stderr to files in order to run
// in the background
Expand Down
4 changes: 2 additions & 2 deletions server/src/main/java/org/elasticsearch/common/Rounding.java
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ static class TimeUnitRounding extends Rounding {
this.unit = unit;
this.timeZone = timeZone;
this.unitRoundsToMidnight = this.unit.field.getBaseUnit().getDuration().toMillis() > 3600000L;
this.fixedOffsetMillis = timeZone.getRules().isFixedOffset() == true ?
this.fixedOffsetMillis = timeZone.getRules().isFixedOffset() ?
timeZone.getRules().getOffset(Instant.EPOCH).getTotalSeconds() * 1000 : TZ_OFFSET_NON_FIXED;
}

Expand Down Expand Up @@ -486,7 +486,7 @@ static class TimeIntervalRounding extends Rounding {
throw new IllegalArgumentException("Zero or negative time interval not supported");
this.interval = interval;
this.timeZone = timeZone;
this.fixedOffsetMillis = timeZone.getRules().isFixedOffset() == true ?
this.fixedOffsetMillis = timeZone.getRules().isFixedOffset() ?
timeZone.getRules().getOffset(Instant.EPOCH).getTotalSeconds() * 1000 : TZ_OFFSET_NON_FIXED;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ void validateLinearRing(CoordinateNode coordinates, boolean coerce) {
// close linear ring iff coerce is set and ring is open, otherwise throw parse exception
if (!coordinates.children.get(0).coordinate.equals(
coordinates.children.get(coordinates.children.size() - 1).coordinate)) {
if (coerce == true) {
if (coerce) {
coordinates.children.add(coordinates.children.get(0));
} else {
throw new ElasticsearchParseException("invalid LinearRing found (coordinates are not closed)");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ private static PointBuilder parsePoint(StreamTokenizer stream, final boolean ign
return null;
}
PointBuilder pt = new PointBuilder(nextNumber(stream), nextNumber(stream));
if (isNumberNext(stream) == true) {
if (isNumberNext(stream)) {
GeoPoint.assertZValue(ignoreZValue, nextNumber(stream));
}
nextCloser(stream);
Expand Down Expand Up @@ -224,7 +224,7 @@ private static LineStringBuilder parseLinearRing(StreamTokenizer stream, final b
int coordinatesNeeded = coerce ? 3 : 4;
if (coordinates.size() >= coordinatesNeeded) {
if (!coordinates.get(0).equals(coordinates.get(coordinates.size() - 1))) {
if (coerce == true) {
if (coerce) {
coordinates.add(coordinates.get(0));
} else {
throw new ElasticsearchParseException("invalid LinearRing found (coordinates are not closed)");
Expand Down Expand Up @@ -352,7 +352,7 @@ private static String nextCloser(StreamTokenizer stream) throws IOException, Ela
}

private static String nextComma(StreamTokenizer stream) throws IOException, ElasticsearchParseException {
if (nextWord(stream).equals(COMMA) == true) {
if (nextWord(stream).equals(COMMA)) {
return COMMA;
}
throw new ElasticsearchParseException("expected " + COMMA + " but found: " + tokenString(stream), stream.lineno());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ private TemporalAccessor doParse(String input) {
for (DateTimeFormatter formatter : parsers) {
ParsePosition pos = new ParsePosition(0);
Object object = formatter.toFormat().parseObject(input, pos);
if (parsingSucceeded(object, input, pos) == true) {
if (parsingSucceeded(object, input, pos)) {
return (TemporalAccessor) object;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public Class<Shape> processedClass() {

@Override
public List<IndexableField> indexShape(ParseContext context, Shape shape) {
if (fieldType.pointsOnly() == true) {
if (fieldType.pointsOnly()) {
// index configured for pointsOnly
if (shape instanceof XShapeCollection && XShapeCollection.class.cast(shape).pointsOnly()) {
// MULTIPOINT data: index each point separately
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public RangeFieldType fieldType() {

@Override
public Builder docValues(boolean docValues) {
if (docValues == true) {
if (docValues) {
throw new IllegalArgumentException("field [" + name + "] does not currently support " + TypeParsers.DOC_VALUES);
}
return super.docValues(docValues);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,7 @@ public InnerHitBuilder setDocValueFields(List<FieldAndFormat> docValueFields) {
* Adds a field to load from the docvalue and return.
*/
public InnerHitBuilder addDocValueField(String field, String format) {
if (docValueFields == null || docValueFields.isEmpty() == true) {
if (docValueFields == null || docValueFields.isEmpty()) {
docValueFields = new ArrayList<>();
}
docValueFields.add(new FieldAndFormat(field, format));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ void writeChunk(FileChunk newChunk) throws IOException {
assert lastPosition == chunk.position : "last_position " + lastPosition + " != chunk_position " + chunk.position;
lastPosition += chunk.content.length();
if (chunk.lastChunk) {
assert pendingChunks.isEmpty() == true : "still have pending chunks [" + pendingChunks + "]";
assert pendingChunks.isEmpty() : "still have pending chunks [" + pendingChunks + "]";
fileChunkWriters.remove(chunk.md.name());
assert fileChunkWriters.containsValue(this) == false : "chunk writer [" + newChunk.md + "] was not removed";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ protected String getTypeFromElement(Aggregator element) {

// Anonymous classes (such as NonCollectingAggregator in TermsAgg) won't have a name,
// we need to get the super class
if (element.getClass().getSimpleName().isEmpty() == true) {
if (element.getClass().getSimpleName().isEmpty()) {
return element.getClass().getSuperclass().getSimpleName();
}
if (element instanceof MultiBucketAggregatorWrapper) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ protected QueryProfileBreakdown createProfileBreakdown() {
protected String getTypeFromElement(Query query) {
// Anonymous classes won't have a name,
// we need to get the super class
if (query.getClass().getSimpleName().isEmpty() == true) {
if (query.getClass().getSimpleName().isEmpty()) {
return query.getClass().getSuperclass().getSimpleName();
}
return query.getClass().getSimpleName();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ public static String format(String fmt, Map<String, Object> values) {
final Matcher matcher = PARAM_REGEX.matcher(fmt);

boolean result = matcher.find();

if (result) {
final StringBuffer sb = new StringBuffer();
do {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -700,7 +700,7 @@ private synchronized NodeAndClient buildNode(int nodeId, Settings settings,
onTransportServiceStarted.run(); // reusing an existing node implies its transport service already started
return nodeAndClient;
}
assert reuseExisting == true || nodeAndClient == null : "node name [" + name + "] already exists but not allowed to use it";
assert reuseExisting || nodeAndClient == null : "node name [" + name + "] already exists but not allowed to use it";

SecureSettings secureSettings = Settings.builder().put(settings).getSecureSettings();
if (secureSettings instanceof MockSecureSettings) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,15 +237,15 @@ public XContentBuilder doXContentBody(XContentBuilder builder, Params params) th
builder.field(Fields.MAX_LENGTH.getPreferredName(), maxLength);
builder.field(Fields.AVG_LENGTH.getPreferredName(), getAvgLength());
builder.field(Fields.ENTROPY.getPreferredName(), getEntropy());
if (showDistribution == true) {
if (showDistribution) {
builder.field(Fields.DISTRIBUTION.getPreferredName(), getDistribution());
}
if (format != DocValueFormat.RAW) {
builder.field(Fields.MIN_LENGTH_AS_STRING.getPreferredName(), format.format(getMinLength()));
builder.field(Fields.MAX_LENGTH_AS_STRING.getPreferredName(), format.format(getMaxLength()));
builder.field(Fields.AVG_LENGTH_AS_STRING.getPreferredName(), format.format(getAvgLength()));
builder.field(Fields.ENTROPY_AS_STRING.getPreferredName(), format.format(getEntropy()));
if (showDistribution == true) {
if (showDistribution) {
builder.startObject(Fields.DISTRIBUTION_AS_STRING.getPreferredName());
for (Map.Entry<String, Double> e: getDistribution().entrySet()) {
builder.field(e.getKey(), format.format(e.getValue()).toString());
Expand All @@ -259,7 +259,7 @@ public XContentBuilder doXContentBody(XContentBuilder builder, Params params) th
builder.nullField(Fields.AVG_LENGTH.getPreferredName());
builder.field(Fields.ENTROPY.getPreferredName(), 0.0);

if (showDistribution == true) {
if (showDistribution) {
builder.nullField(Fields.DISTRIBUTION.getPreferredName());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws
builder.startObject();
builder.field(ID.getPreferredName(), id);
builder.field(Job.ID.getPreferredName(), jobId);
if (params.paramAsBoolean(ToXContentParams.FOR_INTERNAL_STORAGE, false) == true) {
if (params.paramAsBoolean(ToXContentParams.FOR_INTERNAL_STORAGE, false)) {
builder.field(CONFIG_TYPE.getPreferredName(), TYPE);
}
builder.field(QUERY_DELAY.getPreferredName(), queryDelay.getStringRep());
Expand All @@ -485,7 +485,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws
if (chunkingConfig != null) {
builder.field(CHUNKING_CONFIG.getPreferredName(), chunkingConfig);
}
if (headers.isEmpty() == false && params.paramAsBoolean(ToXContentParams.FOR_INTERNAL_STORAGE, false) == true) {
if (headers.isEmpty() == false && params.paramAsBoolean(ToXContentParams.FOR_INTERNAL_STORAGE, false)) {
builder.field(HEADERS.getPreferredName(), headers);
}
if (delayedDataCheckConfig != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,7 @@ private void validateServerConfiguration(String prefix) {
assert prefix.endsWith(".ssl");
SSLConfiguration configuration = getSSLConfiguration(prefix);
final String enabledSetting = prefix + ".enabled";
if (settings.getAsBoolean(enabledSetting, false) == true) {
if (settings.getAsBoolean(enabledSetting, false)) {
// Client Authentication _should_ be required, but if someone turns it off, then this check is no longer relevant
final SSLConfigurationSettings configurationSettings = SSLConfigurationSettings.withPrefix(prefix + ".");
if (isConfigurationValidForServerUsage(configuration) == false) {
Expand Down
Loading

0 comments on commit 21224ca

Please sign in to comment.