auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static boolean isFieldObjectType(String fieldName){ if(fieldName == null){ return false; } return OBJECTTYPE_FIELD.equalsIgnoreCase(fieldName); }

Target:
No need for null check
Source:
public static String createArrayFieldNameFromCountField(String countField){ if(countField == null){ return null; } if(!doesFieldNameMatchArrayCountPattern(countField)){ return countField; } return countField.substring(0, countField.length() - 1); }

Target:
Just a single line is enough: if(doesFieldName...) then return countField.substring(...) else countField
Source:
public void explain(OperationContext ctx, CRUDFindRequest req) { initialize(ctx,req); ExecutionContext executionContext = new ExecutionContext(ctx,null); JsonDoc doc=new JsonDoc(executionPlan.explain(executionContext)); ArrayList<DocCtx> l=new ArrayList<>(1); l.add(new DocCtx(doc)); ctx.setDocumentStream(new ListDocumentStream<DocCtx>(l)); }

Target:
Why not Arrays.asList(doc)?
Source:
protected EntityMetadata retrieveMetadata(Path injectionPath, String entityName, String entityVersion) { EntityMetadata emd = metadataMap.get(entityName); if (emd != null) { String defaultVersion = emd.getEntityInfo().getDefaultVersion(); if (!isValidReference(entityVersion, requestVersion, defaultVersion)) { throw Error.get(CrudConstants.ERR_METADATA_APPEARS_TWICE, entityName + ":" + entityVersion + " and " + requestVersion); } } return metadataMap.get(entityName); }

Target:
return emd;
Source:
private static Set<String> asSet(String... x) { HashSet<String> set=new HashSet<>(); for(String a:x) set.add(a); return set; }

Target:
My personal preference is to use brackets even for one line loops and condition. Not a blocker to merging.
Source:
public Integer getTo() { if (to == null) { return null; } else return this.to; }

Target:
return to; is enough.
Source:
public static void assertNoErrors(Response response) throws MultipleFailureException{ List<Throwable> errors = new ArrayList<Throwable>(); for(Error error : response.getErrors()){ Exception e = new Exception(error.getMessage(), error); e.printStackTrace(); errors.add(e); } if(!errors.isEmpty()){ throw new MultipleFailureException(errors); } }

Target:
Error extends RuntimeException, this is unnecessary overhead.
Source:
public static int getBrightness( Color color ) { if ( color == null ) { return BRIGHTNESS_THRESHOLD + 1; } final int r = color.getRed(); final int g = color.getGreen(); final int b = color.getBlue(); int brightness = ( r > g ) ? r : g; if ( b > brightness ) { brightness = b; } return brightness; }

Target:
Did you write this from scratch?
Source:
public final LogicalPageKey getLogicalPage( final int page ) { if ( isPaginationFinished() == false ) { throw new IllegalStateException(); } try { return logicalPages.get( page ); } catch ( IndexOutOfBoundsException e ) { throw e; } }

Target:
As there's no extra handling when an IndexOutOfBoundsException is caught, both old and new code behaves the same way: any exception thrown by `logicalPages.get( page )` will always be thrown back! As so, the try-catch is dispensable and it's best to leave the code as it was.
Source:
protected RenderNode getDeepestLastChild( RenderBox lineBox ) { if ( lineBox.getLastChild() != null && lineBox.getLastChild() instanceof RenderBox ) { return getDeepestLastChild( lineBox ); } return lineBox.getLastChild(); }

Target:
Infinite loop? You probably wanted to pass a cast version of lineBox.getlastChild instead.
Source:
protected Boolean getAutoCorrectFontMetrics() { return false; }

Target:
unless you want to allow <null> values, use the primitive boolean instead of the java.lang.Boolean object.
Source:
public void setBaudRate(int b) { baudRate = b; }

Target:
I don't see any references to this setter, can you restore this class? This class is meant to be constructed with the appropriate values on creation. Maybe a properties file could support different serial settings, such as used in: /romraider/src/main/java/com/romraider/logger/external/apsx/plugin/ApsxDataSource.java
Source:
public int hashCode() { return Objects.hash(value); }

Target:
👍 really minor, probably it can just return `value` to avoid integer boxing with `Objects.hash` or use `Integer#hashCode`.
Source:
public T valueForInsert(Object value) { return implicitCast(value); }

Target:
I think the default implementation should return the value as-is unchanged. Has a lower overhead and is closer to the prior behavior before the introduction of the method. Will also be easier to reason about what is happening.
Source:
public StringType(StreamInput in) throws IOException { if (in.getVersion().onOrAfter(Version.V_4_2_0)) { if (in.readBoolean()) { // see writeTo lengthLimit = Integer.MAX_VALUE; } else { lengthLimit = in.readInt(); } } else { lengthLimit = Integer.MAX_VALUE; } }

Target:
Given that we already use `readInt` /`writeInt` instead of the `vInt` variants, couldn't we just write the `MAX_VALUE` directly and avoid the boolean?
Source:
public static <I, O> LazyMapList<I, O> of(List<I> list, Function<? super I, ? extends O> mapper) { if (!(list instanceof RandomAccess)) { throw new IllegalArgumentException( "The argument of the List type must support " + "fast (generally constant time) random access."); } return new LazyMapList<>(list, mapper); }

Target:
Btw I'm not sure if this restriction is necessary. E.g. if you look at the implementation of `get` of `LinkedList` there is no "extra" slow-down caused by using `LazyMapList`
Source:
protected void doMerge(Mapper mergeWith, boolean updateAllTypes) { super.doMerge(mergeWith, updateAllTypes); var mw = ((KeywordFieldMapper) mergeWith); this.ignoreAbove = ((KeywordFieldMapper) mergeWith).ignoreAbove; if (!Objects.equals(this.lengthLimit, mw.lengthLimit)) { throw new IllegalArgumentException( "mapper [" + name() + "] has different length_limit settings, current [" + this.fieldType().lengthLimit + "], merged [" + mw.fieldType().lengthLimit + "]"); } }

Target:
```suggestion this.ignoreAbove = mw.ignoreAbove; ```
Source:
public void setNextDocId(int docId) throws IOException { this.docId = docId; }

Target:
Looks like we could remove the exception annotation from the parent class?
Source:
public static DataType<?> ofNameOrNull(String typeName) { return TYPES_BY_NAME_OR_ALIAS.getOrDefault(typeName, null); }

Target:
Could use `.get` instead of `.getOrDefault`
Source:
public static Map<String, Object> toMap(BytesReference bytes, XContentType xContentType) { try { final InputStream inputStream = getUncompressedInputStream(bytes); XContentParser parser = xContentType.xContent().createParser( NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, inputStream ); return parser.map(); } catch (IOException e) { throw new UncheckedIOException(e); } }

Target:
shall we maybe utilize autoclosable on input stream? ``` try (InputStream inputStream = getUncompressedInputStream(bytes)) { .. ```
Source:
private static void checkLengthIs2(int actualLength) { assert actualLength == 2 : "The value of a GeoPoint must be a double array with 2 items, not " + actualLength; }

Target:
Isn't this a runtime check method which should validate also without assertions enabled?
Source:
public static DataType<?> getCommonType(DataType<?> firstType, DataType<?> secondType) { TypeCompatibility compatibility = compatibility(firstType, secondType); if (!compatibility.isCompatible()) { return null; } return compatibility.getCommonType(); }

Target:
Not sure if it's worth changing, but I think for common cases the TypeCompatibility creation could be avoided (if types match, undefined case, maybe even the "by precedence" case)
Source:
public List<Symbol> outputs() { return List.copyOf(outputs); }

Target:
Why is this required? Or why not at `AnalyzedView`?
Source:
private boolean isPrimaryKey(RelationInfo relationInfo) { return relationInfo != null && (relationInfo.primaryKey().size() > 1 || (relationInfo.primaryKey().size() == 1 && !relationInfo.primaryKey().get(0).name().equals("_id"))); }

Target:
```suggestion return relationInfo.primaryKey().size() > 1 || (relationInfo.primaryKey().size() == 1 && !relationInfo.primaryKey().get(0).name().equals("_id")); ``` I think we don't have `null` `RelationInfo` entries.
Source:
public void test_create_table_with_check_fail_on_update() { execute("create table t (id integer primary key, qty integer constraint check_1 check (qty > 0))"); execute("insert into t(id, qty) values(0, 1)"); refresh(); execute("select id, qty from t order by id"); assertEquals(1, response.rowCount()); assertEquals(printedTable(response.rows()), "0| 1\n"); execute("update t set qty = 1 where id = 0 returning id, qty"); assertEquals(1, response.rowCount()); assertEquals(printedTable(response.rows()), "0| 1\n"); expectedException.expectMessage(containsString("Failed CONSTRAINT check_1 CHECK (\"qty\" > 0) and values")); execute("update t set qty = -1 where id = 0"); }

Target:
```suggestion ```
Source:
public <U> ColumnConstraint<U> map(Function<? super T, ? extends U> mapper) { return new CheckColumnConstraint(name, columnName, expression, expressionStr); }

Target:
```suggestion return new CheckColumnConstraint<>(name, columnName, mapper.apply(expression), expressionStr); ``` Please take care of generic warnings. Don't ignore them
Source:
public void test_update_by_id_with_subquery_returning_id() throws Exception { execute("create table test (id int primary key, message string) clustered into 2 shards"); execute("insert into test values(1, 'msg');"); assertEquals(1, response.rowCount()); refresh(); execute("update test set message='updated' where id = (select 1) returning id"); assertThat(printedTable(response.rows()), is("1\n" )); refresh(); }

Target:
```suggestion ```
Source:
public void test_update_by_id_where_no_row_is_matching() throws Exception { execute("create table test (id int primary key, message string) clustered into 2 shards"); execute("insert into test values(1, 'msg');"); assertEquals(1, response.rowCount()); refresh(); execute("update test set message='updated' where id = 99 returning id"); assertThat(response.cols()[0], is("id")); assertThat(response.rowCount(), is(0L)); refresh(); }

Target:
```suggestion ```
Source:
public long averageSizePerRowInBytes() { if (numDocs == -1) { return numDocs; } return sizeInBytes / numDocs; }

Target:
Maybe return `-1` directly. Had a "wait what?" moment here because looking at `return numDocs` isolated I didn't get why it's okay to return that as `averageSizePerRowInBytes` value.
Source:
public ByteBuf allocate(int capacity) { accountBytes.accept(capacity); // TODO: should we hold onto the buffers and release them as well? // contract would require it, but there is no resource behind it that must be released return Unpooled.wrappedBuffer(new byte[capacity]); }

Target:
any reasons not to use platform aware `return Unpooled.buffer(capacity)` ?
Source:
public Double visitLiteral(Literal literal, Stats stats) { Object value = literal.value(); if (value instanceof Boolean) { Boolean val = (Boolean) literal.value(); return (val == null || !val) ? 0.0 : 1.0; } return super.visitLiteral(literal, stats); }

Target:
minor: could use `(Boolean) value` instead to avoid one call.
Source:
public CompletableFuture<Integer> killAll() { for (KillAllListener killAllListener : killAllListeners) { try { killAllListener.killAllJobs(); } catch (Throwable t) { LOGGER.error("Failed to call killAllJobs on listener={} error={}", t, killAllListener); } } Collection<UUID> toKill = ImmutableList.copyOf(activeTasks.keySet()); if (toKill.isEmpty()) { return CompletableFuture.completedFuture(0); } return killTasks(toKill, null); }

Target:
arguments in wrong order?
Source:
public CompletableFuture<Integer> killJobs(Collection<UUID> toKill, @Nullable String reason) { for (KillAllListener killAllListener : killAllListeners) { for (UUID job : toKill) { try { killAllListener.killJob(job); } catch (Throwable t) { LOGGER.error("Failed to call killJob on listener={}, err={}", t, killAllListener); } } } return killTasks(toKill, reason); }

Target:
also here, wrong arguments order
Source:
public AnalyzedKill analyze(KillStatement<Expression> killStatement, Function<ParameterExpression, Symbol> convertParamFunction, CoordinatorTxnCtx txnCtx) { var exprAnalyzerWithoutFields = new ExpressionAnalyzer( functions, txnCtx, convertParamFunction, FieldProvider.UNSUPPORTED, null); Symbol jobId; if (killStatement.jobId() != null) { jobId = exprAnalyzerWithoutFields.convert( killStatement.jobId(), new ExpressionAnalysisContext()); } else { jobId = null; } return new AnalyzedKill(jobId); }

Target:
Could move this also into the `if` brach below, so that it is not created for `KILL ALL`
Source:
AnalyzedStatement analyzeShowTransaction(Analysis analysis) { AnalyzedStatement analyzedStatement = analyzer.unboundAnalyze(rewriteShowTransaction(), analysis.sessionContext(), ParamTypeHints.EMPTY); analysis.rootRelation((AnalyzedRelation) analyzedStatement); return analyzedStatement; }

Target:
could we use the `unboundAnalyze()` helper method here as well?
Source:
AnalyzedStatement analyzeShowTransaction(Analysis analysis) { return unboundAnalyze(rewriteShowTransaction(), analysis, ParamTypeHints.EMPTY); }

Target:
why not use `unboundAnalyze(query, analysis)` and thus use `analysis.paramTypeHints()` here as well?
Source:
public void testSubSelectWhere() throws Exception { setup.setUpCharacters(); execute("select id, name " + "from (select * from characters where female = true) as ch " + "where name like 'Arthur'"); assertThat(printedTable(response.rows()), is("4| Arthur\n")); assertThat(printedTable(response.rows()), is("4| Arthur\n")); }

Target:
This is redundant?
Source:
public ColumnContext next() { if (!hasNext()) { throw new NoSuchElementException("Columns iterator exhausted"); } Reference ref = columns.next(); if (ref.column().isTopLevel() == false) { return new ColumnContext(tableInfo, ref, null); } // Tables created with CrateDB < 4.0 don't have any positional information stored inside the meta data so // we must fallback to old behaviour which uses a simple increased iterating based var. Integer position = ref.position(); if (position == null) { position = ordinal.intValue(); } ordinal++; return new ColumnContext(tableInfo, ref, position); }

Target:
Maybe make `ordinal` a primitive int directly? `++` would cause boxing (although low values are cached, so it's a non issue). The memory footprint should also not increase, due to memory alignment I think a short takes up the same space as an int anyway.
Source:
public boolean matchesSafely(Engine.Searcher searcher) { try { this.count = (int) searcher.searcher().count(query); return count == totalHits; } catch (IOException e) { return false; } }

Target:
Redundant cast to int
Source:
public static Matcher<Engine.Searcher> engineSearcherTotalHits(Query query, int totalHits) { return new EngineSearcherTotalHitsMatcher(query, totalHits); }

Target:
could be package private
Source:
public static Matcher<Engine.Searcher> engineSearcherTotalHits(int totalHits) { return new EngineSearcherTotalHitsMatcher(Queries.newMatchAllQuery(), totalHits); }

Target:
could be package private
Source:
public void test_psql_format_from_string() { Period period = PGIntervalParser.apply("@ 1 year 1 mon 1 day 1 hour 1 minute 1 secs"); Assert.assertEquals(period, new Period().withYears(1).withMonths(1).withDays(1).withHours(1).withMinutes(1).withSeconds(1)); }

Target:
We generally prefer `assertThat(..., is(..))` for better error messages.
Source:
public IntervalLiteral(String value, Sign sign, IntervalField startField, @Nullable IntervalField endField) { checkNotNull(value, "value is null"); checkNotNull(sign, "sign is null"); checkNotNull(startField, "startField is null"); this.value = value; this.sign = sign; this.startField = startField; this.endField = endField; }

Target:
aren't these validations already handled by the parser?
Source:
public LongObjectHashMap<Long> measureGroupingOnLongArray() { LongObjectHashMap<Long> sumByKey = new LongObjectHashMap<>(); for (long number : numbers) { sumByKey.compute(number, (key, oldValue) -> { if (oldValue == null) { return 0L; } else { return oldValue + number; } }); } return sumByKey; }

Target:
should this be `number`? (adding the first value for a key right? )
Source:
private void processGeneratedExpressionColumn(Reference reference, Input<?> expressionInput) { toInject.put(reference, expressionInput); final ColumnIdent ident = reference.column(); if (!ident.isTopLevel()) { List<Reference> references = nestedReferenceByTopLevelColumnName.getOrDefault( ident.name(), new ArrayList<>()); references.add(reference); nestedReferenceByTopLevelColumnName.put(ident.name(), references); } }

Target:
I think a manual `.get()` followed by an `if (.. null)` would be more efficient as right now the `new ArrayList<>()` is always evaluated, not just when there is no element found.
Source:
public void testExecuteSingleUploadBlobSizeTooLarge() throws IOException { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(containsString("can't be larger than 5gb")); final long blobSize = ByteSizeUnit.GB.toBytes(randomIntBetween(6, 10)); final S3BlobStore blobStore = mock(S3BlobStore.class); final S3BlobContainer blobContainer = new S3BlobContainer(mock(BlobPath.class), blobStore); blobContainer.executeSingleUpload(blobStore, randomAlphaOfLengthBetween(1, 10), null, blobSize); }

Target:
this should be placed right before the expected exception ocurs so it won't catch any unexpected exceptions.
Source:
public Map<Object, Object> value(Object value) { Map<Object, Object> map = (Map<Object, Object>) value; if (map == null) { return map; } return new HashMap<>(map); }

Target:
Why is the copy here necessary?
Source:
public void testCreateColumnWithDefaultExpression() throws Exception { execute("create table test (col1 text default 'foo')"); ensureYellow(); String expectedMapping = "{\"default\":{" + "\"dynamic\":\"strict\",\"_meta\":{}," + "\"dynamic_templates\":[{\"strings\":{\"match_mapping_type\":\"string\",\"mapping\":{\"doc_values\":true,\"store\":false,\"type\":\"keyword\"}}}]," + "\"properties\":{\"col1\":{\"type\":\"keyword\",\"position\":1,\"default_expr\":\"'foo'\"}}}}"; assertEquals(expectedMapping, getIndexMapping("test")); }

Target:
```suggestion ensureYellow(); ``` Shouldn't be needed to retrieve the index mapping. The `create table` only returns when the cluster state has been updated (shard initialization is async, but that's not required here)
Source:
public <T> int getStart(int pStart, int pEnd, int currentRowIdx, @Nullable Comparator<T> cmp, List<T> rows) { if (pStart == currentRowIdx) { return pStart; } else { if (cmp != null) { return findFirstPreviousPeer(rows, currentRowIdx, cmp); } else { return currentRowIdx; } } }

Target:
Could this potentially go past the partition boundary?
Source:
public void testQuerySysJobsLogReturnsLogEntriesRelevantToUser() { executeAsSuperuser("select 2"); executeAsSuperuser("select 3"); execute("select 1", null, testUserSession()); String stmt = "select username, stmt " + "from sys.jobs_log " + "where stmt in ('select 1', 'select 2', 'select 3') " + "order by stmt"; executeAsSuperuser(stmt); assertThat(printedTable(response.rows()), is("privileges_test_user| select 1\n" + "crate| select 2\n" + "crate| select 3\n")); executeAsSuperuser("grant dql on table sys.jobs_log to " + TEST_USERNAME); execute(stmt, null, testUserSession()); assertThat(printedTable(response.rows()), is("privileges_test_user| select 1\n")); }

Target:
I'm wondering if instead it would make sense to have a unit test for the concrete `StaticTableDefinition` ? Would be cheaper to execute and probably also more deterministic We've full integration tests already to make sure that the filtering works when everything is integrated.
Source:
public Operation build() { return new Operation(method, summary, notes, responseModel, uniqueId, position, tags, produces, consumes, protocol, securityReferences, parameters, responseMessages, deprecated, isHidden, nickname); }

Target:
@adrianbk I dont think we need to introduce an operation id generator concept. Thats what the plugin model is for, there is an operation builder plugin to enrich the operation model already. So l think the direction @who has taken would be the best approach. Just so we dont over engineer it, its probably fine to generate a operation id regardless. The extensibility mechanism allows folks to override the name if they wish.
Source:
public Jackson2Annotator(GenerationConfig generationConfig) { super(generationConfig); this.generationConfig = generationConfig; }

Target:
This can be removed.
Source:
private static String addFullDetailsParam(ParamsMap params, String urlParams) { if (params != null && params.size() > 0 && params.get(FULL_DETAILS_QUERY_PARAM) != null) { return urlParams + FULL_DETAILS_QUERY_PARAM + "="+ params.get(FULL_DETAILS_QUERY_PARAM); } return urlParams; }

Target:
It looks like the second check (_params.size() > 0_) can be removed. If the params is not null, params.get() will not fail. After that, we have two cases. If params contain "fullDetails", we will have only two checks instead of three (params.size() is removed). If params does not contain "fullDetails", we will have also only two checks (as in the current implementation, with .size() in place), only that we replaced .size() with .get().
Source:
public <R> R getOwnedEntities(MambuEntityType parentEntity, String parentId, MambuEntityType ownedEntity, String relatedEntityId, ParamsMap params, boolean requiresFullDetails) throws MambuApiException { if (parentEntity == null || ownedEntity == null) { throw new IllegalArgumentException("Parent Entity and Owned Entity cannot be null"); } Class<?> parentClass = parentEntity.getEntityClass(); Class<?> ownedClass = ownedEntity.getEntityClass(); ApiDefinition apiDefinition ; apiDefinition = createApiDefinitionForGetOwnedEntities(requiresFullDetails, parentClass, ownedClass); return execute(apiDefinition, parentId, relatedEntityId, params); }

Target:
just curious, why this approach and not on a single line of code?
Source:
private ApiDefinition getApiDefinitionForPaginatedList(boolean requiresFullDetails, Class<?> clazz) { ApiDefinition apiDefinition; if (requiresFullDetails == true) { apiDefinition = new ApiDefinition(ApiType.GET_LIST_WITH_DETAILS, clazz); } else { apiDefinition = new ApiDefinition(ApiType.GET_LIST, clazz); } return apiDefinition; }

Target:
can use without "== true"
Source:
private static void createAndAddDocumentIdsForClient(ClientExpanded clientExpanded) throws MambuApiException { // check if other document IDs are allowed boolean areOtherDocIdsAllowed = getOtherDocumentTemplateIdsEnabeled(); if (areOtherDocIdsAllowed) { // create and add doc IDs List<IdentificationDocument> idDocs = new ArrayList<IdentificationDocument>(); IdentificationDocument doc = new IdentificationDocument(); doc.setDocumentId("DFG1234"); doc.setDocumentType("Passport"); doc.setIssuingAuthority("Vancouver"); idDocs.add(doc); clientExpanded.setIdDocuments(idDocs); } }

Target:
We can use the diamond operator here.
Source:
public Boolean deleteLoanRepayment(String accountId, String repaymentId) throws MambuApiException { // Example: GET endpoint "/api/loans/{LOAN_ID}/repayments/{REPAYMENT_ID} // Available since Mambu 4.3 if (accountId == null && repaymentId == null) { throw new IllegalArgumentException("Account ID and Repayment ID must not be null!"); } return serviceExecutor.deleteOwnedEntity(MambuEntityType.LOAN_ACCOUNT, accountId, MambuEntityType.REPAYMENTS, repaymentId); }

Target:
Shouldn't we use the OR operator instead of AND?
Source:
private static void testDownloadLatestDbBackup() throws MambuApiException, IOException { methodName = new Object() {}.getClass().getEnclosingMethod().getName(); System.out.println(methodName = "\nIn " + methodName); DatabaseService databaseService = MambuAPIFactory.getDatabaseService(); DatabaseBackup response = databaseService.downloadLatestDbBackup(); System.out.println("Backup was successfuly downloaded = " + (response.getContent().toByteArray() != null)); }

Target:
Nice! You can optionally try/catch (and log) any IO exceptions in this method
Source:
public MambuAPIModule(Protocol protocol, String domain, String username, String password) { this.domain = Preconditions.checkNotNull(domain, "domain cannot be null"); this.username = Preconditions.checkNotNull(username, "username cannot be null"); this.password = Preconditions.checkNotNull(password, "password cannot be null"); this.protocol = Preconditions.checkNotNull(protocol, "protocol cannot be null").name(); }

Target:
may want to consider making the "protocol" to be the first line to match params order
Source:
public boolean updateClientCustomField(String clientId, String customFieldId, String fieldValue) throws MambuApiException { // Execute request for PATCH API to update custom field value for a client. See MBU-6661 // e.g. PATCH "{ "value": "10" }" /host/api/clients/clientId/custominformation/customFieldId // Make ParamsMap with JSON request for Update API ParamsMap params = ServiceHelper.makeParamsForUpdateCustomField(clientId, customFieldId, fieldValue); return serviceExecutor.execute(updateClientCustomField, clientId, customFieldId, params); }

Target:
Maybe on the next refactoring you can use inheritance or the composition pattern to extract these updateCustomField and deleteCustomField methods to e.g. an abstract class so that they don't have to be implemented in almost every service.
Source:
public static TransactionChannel getDemoTransactionChannel() throws MambuApiException { OrganizationService organizationService = MambuAPIFactory.getOrganizationService(); List<TransactionChannel> transactionChannels = organizationService.getTransactionChannels(); if (transactionChannels == null) { return null; } int randomIndex = (int) Math.round(Math.random() * (transactionChannels.size() - 1)); randomIndex = 1; return transactionChannels.get(randomIndex); }

Target:
Not it's not random anymore ;)
Source:
public boolean deleteTasks(String taskId) throws MambuApiException { // create the api call String urlString = new String(mambuAPIService.createUrl(TASKS + "/" + taskId)); String jsonResponse = mambuAPIService.executeRequest(urlString, Method.DELETE); // On success the response is: returnCode: 0
returnStatus: SUCCESS // An exception can be thrown: E.g, ({"returnCode":980,"returnStatus":"INVALID_TASK_ID"}) // Parse the response. (Though, as no exception was thrown here, must be a "SUCCESS" response) boolean deletionStatus = false; MambuApiResponseMessage response = new MambuApiResponseMessage(jsonResponse); if (response.getReturnCode() == 0) deletionStatus = true; return deletionStatus; }

Target:
Please add {..}.
Source:
private EVCacheClient selectClient(List<EVCacheClient> clients) { if (clients == null) { if (log.isDebugEnabled()) log.debug("clients is null returning null!!!"); return null; } if (clients.size() == 1) { return clients.get(0); // Frequently used scenario } // Get absolute value of current val to ensure correctness even at 9 quintillion+ requests final long currentVal = Math.abs(numberOfModOps.incrementAndGet()); // make sure to truncate after the mod. This allows up to 2^31 clients. final int index = (int) (currentVal % clients.size()); return clients.get(index); }

Target:
can you move the Math.abs to the next line for index.
Source:
void setApp(@NonNull AppWithState app) { impl.app = app; }

Target:
Is there reason behind how you access this wrt to property or accessor function? Perhaps we should change all these uses to getters/setters?
Source:
public static Map<String, Object> getMetadata() { return new HashMap<>(getClient().getMetadataState().getMetadata().toMap()); }

Target:
Can this call `Client.getMetadata` rather than require a separate method to retrieve `MetadataState`?
Source:
public static List<Breadcrumb> getBreadcrumbs() { Queue<Breadcrumb> store = getClient().getBreadcrumbState().getStore(); return new ArrayList<>(store); }

Target:
Can this call `Client.getBreadcrumbs` rather than require a separate method to retrieve `BreadcrumbState`?
Source:
public static Client init(@NonNull Context androidContext) { synchronized (lock) { if (client == null) { client = new Client(androidContext); NativeInterface.configureClientObservers(client); } else { logClientInitWarning(); } } return client; }

Target:
why did you choose to make a `synchronized (lock) {}` block rather than label the entire static method `public static synchronized Client init()`?
Source:
public static Map<String,Object> getAppData() { HashMap<String,Object> data = new HashMap<>(); AppData source = getClient().getAppData(); data.putAll(source.getAppData()); data.putAll(source.getAppDataMetaData()); data.putAll(source.getAppDataSummary()); return data; }

Target:
`getAppDataSummary` can be removed here as its contents are included in `getAppData` (same for device metadata)
Source:
void sendNativeSetupNotification() { setChanged(); super.notifyObservers(new Message(NativeInterface.MessageType.INSTALL, config)); final Client client = this; try { Async.run(new Runnable() { @Override public void run() { enqueuePendingNativeReports(); } }); } catch (RejectedExecutionException ex) { Logger.warn("Failed to enqueue native reports, will retry next launch: ", ex); } }

Target:
this variable is unused
Source:
void enqueuePendingNativeReports() { setChanged(); notifyObservers(new Message( NativeInterface.MessageType.DELIVER_PENDING, null)); }

Target:
The visibility of this method can be private
Source:
public void value(@NonNull File file) throws IOException { super.flush(); beforeValue(false); // add comma if in array // Copy the file contents onto the stream Reader input = null; try { FileInputStream fis = new FileInputStream(file); input = new BufferedReader(new InputStreamReader(fis, "UTF-8")); IOUtils.copy(input, out); } finally { IOUtils.closeQuietly(input); } out.flush(); }

Target:
do any of these objects also need closing?
Source:
private void trackSessionIfNeeded(boolean autoCaptured, Session session) { String releaseStage = getReleaseStage(); boolean notifyForRelease = client != null && configuration.shouldNotifyForReleaseStage(releaseStage); if ((configuration.shouldAutoCaptureSessions() || !autoCaptured) && notifyForRelease) { sessionQueue.add(session); sessionStore.write(session); // store session for sending trackedFirstSession = true; } }

Target:
why does this check if the client is not null here? shouldn't you always put a session in the queue/store even if the client is not initialized yet?
Source:
private static String getCpuAbi() { String cpuAbi = Build.CPU_ABI; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cpuAbi = SupportedAbiWrapper.getSupportedAbis(); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { cpuAbi = Abi2Wrapper.getAbi1andAbi2(); } return cpuAbi; }

Target:
This method can be simplified to ``` java if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return SupportedAbiWrapper.getSupportedAbis(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { return Abi2Wrapper.getAbi1andAbi2(); } return Build.CPU_ABI; ``` Also is it worth wrapping `Build.CPU_ABI` in an array so that the output format is always consistent regardless of API level?
Source:
protected String streamableToString(JsonStream.Streamable streamable) { StringWriter writer = new StringWriter(); JsonStream jsonStream = new JsonStream(writer); try { streamable.toStream(jsonStream); } catch(java.io.IOException e) return writer.toString(); }

Target:
nit: import?
Source:
public static int getTransactionIsolation(final String transactionIsolationName) { if (transactionIsolationName != null) { try { // use the english locale to avoid the infamous turkish locale bug final String upperCaseIsolationLevelName = Optional.of(transactionIsolationName.toUpperCase(Locale.ENGLISH)) .orElseThrow(IllegalArgumentException::new); return IsolationLevel.valueOf(upperCaseIsolationLevelName).getLevelId(); } catch (Exception e) { throw new IllegalArgumentException("Invalid transaction isolation value: " + transactionIsolationName); } } return -1; }

Target:
Why `Optional` is used here? It's absolutely redundant
Source:
public HikariCPCollector add(String name, PoolStats poolStats) { poolStatsMap.put(name, poolStats); return this; }

Target:
I am not a Prometheus user, but I want to understand why this is ``public``. It appears to only be used by ``/PrometheusMetricsTracker`` in the same package.
Source:
public void setAutoCommit(boolean autoCommit) throws SQLException { delegate.setAutoCommit(autoCommit); isAutoCommit = autoCommit; isCommitStateDirty = false; dirtyBits |= DIRTY_BIT_AUTOCOMMIT; }

Target:
This is not a valid change. The JavaDoc says: > If this method is called during a transaction and the auto-commit mode is changed, the transaction is committed > If setAutoCommit is called and the auto-commit mode is not changed, the call is a no-op. If auto-commit started as `false` and the user performed some SQL, then `isCommitStateDirty` is `true`. If the user calls `setAutoCommit(false)` during the transaction, it is a no-op (auto-commit is still _false_). Which means that `isCommitStateDirty` should _still_ be `true` also. This change would set it to `false` unconditionally.
Source:
final void markCommitStateDirty() { if (isAutoCommit || isReadOnly) { lastAccess = clockSource.currentTime(); } else { isCommitStateDirty = true; } }

Target:
This is more expensive. `markCommitStateDirty()` may be called dozens or hundreds of times in a single connection use, so `isReadOnly` is evaluated many times. However, `close()` is only called once per connection use, and therefore checking the `isReadOnly` flag there (where it is currently), is more efficient.
Source:
public Boolean call() throws Exception { long sleepBackoff = 200L; do { final PoolEntry poolEntry = createPoolEntry(); if (poolEntry == PoolEntry.MAXED_POOL_MARKER) { return Boolean.FALSE; } else if (poolEntry != null) { connectionBag.add(poolEntry); return Boolean.TRUE; } // addConnection() failed, so we sleep and retry quietlySleep(sleepBackoff); sleepBackoff = Math.min(connectionTimeout / 2, (long) (sleepBackoff * 1.3)); } while (true); }

Target:
I prefer to keep the static import.
Source:
private void setLoginTimeout(final DataSource dataSource, final long connectionTimeout) { if (connectionTimeout != Integer.MAX_VALUE) { try { dataSource.setLoginTimeout((int) TimeUnit.MILLISECONDS.toSeconds(Math.max(1000L, connectionTimeout))); } catch (SQLException e) { LOGGER.warn("{} - Unable to set DataSource login timeout", poolName, e); } catch (UnsupportedOperationException e) { LOGGER.warn("{} - Unable to set DataSource login timeout", poolName, e); } } }

Target:
As this is a pull request against _dev_, and _dev_ is Java 7/8 only, please combine this catch with the above using a multi-catch statement.
Source:
public CohortDefinition getPersonWithAttribute() { PersonAttributeCohortDefinition cd = new PersonAttributeCohortDefinition(); cd.addParameter(new Parameter("attributeType", "reporting.parameter.attributeType", PersonAttributeType.class)); cd.addParameter(new Parameter("values", "reporting.parameter.values", String.class, List.class, null)); return new MappedParametersCohortDefinition(cd, "attributeType", "attributeType", "values", "values"); }

Target:
I don't think this line is adding any value. Can't you just return "cd" if you aren't changing the names or mappings of any of the parameters?
Source:
public Map<String, Mapped<PatientDataDefinition>> getContainedDataDefinitions() { return containedDataDefinitions; }

Target:
Per above, can you change this to "if (containedDataDefinitions == null) { containedDataDefinitions = new HashMap... }; return containedDataDefinitions;
Source:
public Settings getState() { System.out.println(pathToProjectContainer); return this; }

Target:
You can probably remove this
Source:
public Stream(byte[] key) { this.key = key; checkLength(key, NaCl.Sodium.AES_128_CTR_KEYBYTES); }

Target:
Make use of import static, please. Into this way we just leave the constant into the code.
Source:
public Collection<GrantedAuthority> getAuthorities() { List<GrantedAuthority> roles = new ArrayList<>(1); roles.add(new SimpleGrantedAuthority(getUser().getRole().getShortName())); return roles; }

Target:
return List.of(new SimpleGrantedAuthority(getUser().getRole().getShortName()))
Source:
public AgentInfo approve(Long id, boolean approve) { Optional<AgentInfo> found = agentManagerRepository.findOne(idEqual(id)); AgentInfo agentInfo = null; if (found.isPresent()) { agentInfo = found.get(); agentInfo.setApproved(approve); agentManagerRepository.save(agentInfo); expireLocalCache(); } return agentInfo; }

Target:
check if explicit ```save``` is necessary .
Source:
public ConsoleProperties createConsoleProperties(PerfTest perfTest) { ConsoleProperties consoleProperties = ConsolePropertiesFactory.createEmptyConsoleProperties(); try { removePerftestResultDistributedFolderIfExist(perfTest); consoleProperties.setAndSaveDistributionDirectory(new Directory(getDistributionPath(perfTest))); consoleProperties.setConsoleHost(config.getCurrentIP()); consoleProperties.setIgnoreSampleCount(getSafe(perfTest.getIgnoreSampleCount())); consoleProperties.setSampleInterval(1000 * getSafe(perfTest.getSamplingInterval())); } catch (Exception e) { throw processException("Error while setting console properties", e); } return consoleProperties; }

Target:
I think this should not be called here.. it has the different behavior from createConsoleProperties()
Source:
public void addFileToPackage(TarArchiveOutputStream tarArchiveOutputStream, File file, String path) throws IOException { CompressionUtils.addFileToTar(tarArchiveOutputStream, file, getLibPath() + path); }

Target:
Please use static import for CompressionUtils. likewise addFolderToTar above.
Source:
void init() { ngrinderContext = System.getProperty("ngrinder.context", "agent"); workDirectory = System.getProperty("ngrinder.base.path", System.getProperty("user.dir")); if (isControllerContext()) { controllerHomeDir = resolveControllerHomeDir(); controllerHomeTmpDir = (controllerHomeDir + File.separator + NGRINDER_CONTROLLER_TEMP_FOLDER); } this.initAccessOfDirectories(); this.initAccessOfHosts(); }

Target:
Isn't it better to use ngrinder.user.dir ?
Source:
public <M> List<M> getEnabledModulesByClass(Class<M> moduleClass, M defaultPlugin) { ArrayList<M> pluginClasses = new ArrayList<M>(); if (defaultPlugin != null) { pluginClasses.add(defaultPlugin); } if (manager.getExtensions(moduleClass).size() > 0) { pluginClasses.addAll(manager.getExtensions(moduleClass)); } return pluginClasses; }

Target:
size 체크 없이 바로 `.addAll`해도 문제 없을 것 같아요.
Source:
public Map<String, Set<String>> readClasspathStorages() { Map<String, Set<String>> result = new LinkedHashMap<String, Set<String>>(); return result; }

Target:
따로 result 변수없이 바로 `return new LinkedHashMap<...>();`가 좋을 것 같습니다.
Source:
protected PluginClasspath createPluginClasspath() { if (RuntimeMode.DEVELOPMENT.equals(getRuntimeMode())) { return new DevelopmentPluginClasspath(); } return new NGrinderPluginClasspath(); }

Target:
Development Runtime 모드를 판별하는 기준이 뭐죠? Config에는 isDevMode 라는 메소드가 있는데, 이걸로 판별하는 편이 나을 듯.
Source:
static public Set<String> parseProtocolRequestHeader(String value) { if (StringUtils.isEmpty(value)) { return null; } Set<String> subprotocols = new LinkedHashSet<>(); if (!StringUtils.isEmpty(value)) { String[] values = value.split(","); for (String v : values) { subprotocols.add(v.trim()); } } return subprotocols; }

Target:
Just an observation... might it be more cool to return Collections.emptySet()?... if we have the option to reduce null usage we should do so... imho helps in the long run... but - I may be wrong...
Source:
public String getRequestUri() { return wrapped.getRequestPath(); }

Target:
please leave it that way - it's intentionally referencing the deprecated version.
Source:
public TemplateEngineFreemarkerAuthenticityTokenDirective(Context context) { this.authenticityToken = context.getSession().getAuthenticityToken(); }

Target:
please do this in the execute method. Otherwise you are always adding the __AT to the session - even if it is not needed...
Source:
public void clearLevel(String loggerName) { java.util.logging.Logger logger = loggers.get(loggerName); if (logger == null) { logger = java.util.logging.Logger.getLogger(loggerName); } logger.setLevel(null); }

Target:
is `loggerName` `@Nullable`?
Source:
static Binder proxy(Binder binder) { return (Binder) Proxy.newProxyInstance( ForbidInstallBinder.class.getClassLoader(), new Class[] {Binder.class}, new ForbidInstallBinder(binder)); }

Target:
This needs `Class<?>`
Source:
public void testCreateAnnouncementLocation() { URI baseURI = URI.create("http://example.com:8080"); URI baseWithSlash = URI.create("http://example.com:8080/"); String nodeId = "ffff"; URI expected = URI.create("http://example.com:8080/v1/announcement/" + nodeId); assertEquals(expected, HttpDiscoveryAnnouncementClient.createAnnouncementLocation(baseURI, nodeId)); assertEquals(expected, HttpDiscoveryAnnouncementClient.createAnnouncementLocation(baseWithSlash, nodeId)); }

Target:
Static import `createAnnouncementLocation`
Source:
public void testCreateAnnouncementLocation() { String nodeId = "ffff"; URI expected = URI.create("http://example.com:8080/v1/announcement/" + nodeId); assertEquals(expected, createAnnouncementLocation(URI.create("http://example.com:8080"), nodeId)); assertEquals(expected, createAnnouncementLocation(URI.create("http://example.com:8080/"), nodeId)); }

Target:
The actual/equals are flipped
Source:
private static boolean isPreserveAuthorization(Request request) { return request.getAttributes().get(PRESERVE_AUTHORIZATION_KEY) == TRUE; }

Target:
I'd use `equals` to make it clear we don't care about identity semantics (readers won't have to verify the value that is being set), but it's fine either way ```java TRUE.equals(request.getAttributes().get(PRESERVE_AUTHORIZATION_KEY));
Source:
DecayTDigest(TDigest digest, double alpha, Ticker ticker) { this(digest, alpha, ticker, TimeUnit.NANOSECONDS.toSeconds(ticker.read())); }

Target:
`private`? `@VisibleForTesting`?
Source:
public void testEmpty() { List<Object> response = client.execute( prepareGet().setUri(uriFor("/v1/person")).build(), createJsonResponseHandler(listCodec)); assertEquals(response, Collections.emptyList()); }

Target:
`ImmutableList.of()`
Source:
public DecayTDigest(double compression, double alpha, Ticker ticker) { digest = new TDigest(compression); this.alpha = alpha; this.ticker = ticker; landmarkInSeconds = TimeUnit.NANOSECONDS.toSeconds(ticker.read()); }

Target:
should this be package protected?
Source:
public void testDoesNotAllowCircularDependencies() throws Exception { Bootstrap bootstrap = new Bootstrap((Module) binder -> { binder.bind(InstanceA.class); binder.bind(InstanceB.class); }); try { bootstrap.initialize().getInstance(InstanceA.class); fail("should not allow circular dependencies"); } catch (ProvisionException e) { assertContains(e.getErrorMessages().iterator().next().getMessage(), "circular dependencies are disabled"); } }

Target:
Is the `(Module)` needed?
Source:
public Request(URI uri, String method, ListMultimap<String, String> headers, BodyGenerator bodyGenerator) { this(uri, method, headers, bodyGenerator, true); }

Target:
Add message telling people to use the builder.
Source:
public static boolean isPem(String data) { if (CERT_PATTERN.matcher(data).find()) { return true; } if (PUBLIC_KEY_PATTERN.matcher(data).find()) { return true; } if (PRIVATE_KEY_PATTERN.matcher(data).find()) { return true; } return false; }

Target:
Why not ```java return CERT_PATTERN.matcher(data).find() || PUBLIC_KEY_PATTERN.matcher(data).find() || PRIVATE_KEY_PATTERN.matcher(data).find();
Source:
TestJettyHttpsClientPem() { super("localhost", getResource("server.keystore").toString()); }

Target:
Make public since it will be constructed by TestNG (which probably bypasses security just fine but seems bad to rely on that)
Source:
private static HttpServer createServer(NodeInfo nodeInfo, HttpServerInfo httpServerInfo, HttpServerConfig config) { return createServer(new DummyServlet(Optional.empty()), nodeInfo, httpServerInfo, config); }

Target:
This is what the default constructor already does.
Source:
private void createAndStartServer() throws Exception { createAndStartServer(new DummyServlet(Optional.empty())); }

Target:
Use the default constructor for all of these
Source:
public void tearDown() throws IOException { if (!file.delete()) { throw new IOException("Error deleting " + file.getAbsolutePath()); } }

Target:
Do you want to check `exists`?
Source:
private static void closeQuietly(LifeCycle service) { try { if (service != null) { service.stop(); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } catch (Exception ignored) { } }

Target:
We can name this `e`, as we do elsewhere. I thought it needed to be `ignored` to prevent a warning, but apparently that's only a problem if the catch block is empty.
Source:
public void flush() { BufferedReader in = new BufferedReader(new StringReader(getBuffer().toString())); while (true) { try { String line = in.readLine(); if (line == null) { break; } if (logger.isInfoEnabled()) { logger.info(line); } } catch (IOException e) { throw new Error(e); // should never get here } } getBuffer().setLength(0); }

Target:
I don't think we need the "if" check. Just always log at info. The logger is going to check enabled anyway.... the "is enabled" is only useful when the log line does work
Source:
private static byte[] base64Decode(String base64) { return Base64.getMimeDecoder().decode(base64.getBytes(US_ASCII)); }

Target:
You could static import `getMimeDecoder` to match the other file
Source:
public String toString() { return MoreObjects.toStringHelper(this) .add("configurationBinding", configurationBinding) .toString(); }

Target:
Static import
Source:
public synchronized void onComplete(Result result) { Throwable throwable = result.getFailure(); if (throwable != null) { future.failed(throwable); } else { currentBuffer = null; currentBufferPosition = 0; future.completed(result.getResponse(), new GatheringByteArrayInputStream(buffers, size)); } }

Target:
Set `currentBuffer` to `new byte[0]` so `currentBuffer` is never null. This is a common trick to consolidate all checks to size checks (without nulls), but you have to be careful to not add the zero byte array to your outputs :)
Source:
protected void setup(Binder binder) { T configuration = buildConfigObject(config); if (predicate.test(configuration)) { if (module instanceof ConfigurationAwareModule) { install((ConfigurationAwareModule) module); } else { binder.install(module); } } }

Target:
Can you add a version in the parent that takes a normal Module? The current way of only taking ConditionalModule is confusing and leads to mistakes.
Source:
public List<Long> getQuantiles(List<Double> quantiles) { List<Long> accumulator = new ArrayList<Long>(quantiles.size()); for (Double q : quantiles) { accumulator.add(getQuantile(q)); } return accumulator; }

Target:
this can be `double q`
Source:
public static ThreadPoolExecutor newBoundedThreadPool(int maxThreads, ThreadFactory threadFactory) { BlockingQueue<Runnable> queue = new RefusingQueue<>(); return new ThreadPoolExecutor( 0, maxThreads, 60, TimeUnit.SECONDS, queue, threadFactory, (runnable, executor) -> queue.add(runnable)); }

Target:
Can you add: ``` java newBoundedThreadPool(int minThreads, int maxThreads, ThreadFactory threadFactory) newBoundedThreadPool(int minThreads, int maxThreads, ThreadFactory threadFactory, Duration keepAlive) ```
Source:
public RequestStats() { allResponse = new CounterStat(); informationalResponse = new CounterStat(); successfulResponse = new CounterStat(); redirectionResponse = new CounterStat(); clientErrorResponse = new CounterStat(); serverErrorResponse = new CounterStat(); requestFailed = new CounterStat(); requestCanceled = new CounterStat(); requestTime = new TimeStat(); responseTime = new TimeStat(); readBytes = new DistributionStat(); writtenBytes = new DistributionStat(); }

Target:
These can be in the field declaration.
Source:
private void setDelta(int bucket, int value) { int slot = bucketToSlot(bucket); // clear the old value byte clearMask = (byte) (BUCKET_MASK << shiftForBucket(bucket)); deltas[slot] &= (byte) ~clearMask; // set the new value byte setMask = (byte) (value << shiftForBucket(bucket)); deltas[slot] |= setMask; }

Target:
This cast is unnecessary. `deltas` is a byte array, so it's irrelevant that the negated mask is promoted to an int. I think this is just a case of an overly aggressive inspection.