auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public CompositeTriJoiner(List<SingleTriJoiner<A, B, C>> joinerList) { this.joinerList = joinerList; if (joinerList.isEmpty()) { throw new IllegalArgumentException("The joinerList (" + joinerList + ") must not be empty."); } }

Target:
Possibly throw before assigning.
Source:
protected UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination(long unimprovedTimeMillisSpentLimit, Score unimprovedScoreDifferenceThreshold, Clock clock) { this.unimprovedTimeMillisSpentLimit = unimprovedTimeMillisSpentLimit; this.unimprovedScoreDifferenceThreshold = unimprovedScoreDifferenceThreshold; if (unimprovedTimeMillisSpentLimit <= 0L) { throw new IllegalArgumentException("The unimprovedTimeMillisSpentLimit (" + unimprovedTimeMillisSpentLimit + ") cannot be negative."); } this.clock = clock; }

Target:
Suggestion: if you want to avoid the "align method parameters/call arguments when multiline or not" dilemma, format it like this: ```java protected UnimprovedTimeMillisSpentScoreDifferenceThresholdTermination( long unimprovedTimeMillisSpentLimit, Score unimprovedScoreDifferenceThreshold, Clock clock ) { // body } ``` This is compatible with both "align ... when multiline" that's part of KIE Java Conventions and Geoffrey's IDE settings that keep ignoring KIE Java Conventions in this regard :wink:. I don't like the aligning either. I chose to follow KIE conventions so I have that rule checked but I always format like this which keeps the rule from applying.
Source:
public void stepEnded(LocalSearchStepScope stepScope) { super.stepEnded(stepScope); if (waterLevelIncrementScore != null) { currentWaterLevel = currentWaterLevel.subtract(waterLevelIncrementScore); } else { Score increment = currentWaterLevel.multiply(waterLevelIncrementRatio); currentWaterLevel = currentWaterLevel.subtract(increment); } logger.debug(currentWaterLevel.toShortString()); }

Target:
@BorisKocian I think that this debug line needs to go away.
Source:
public void setWaterLevelIncrementScore(Score waterLevelIncrementScore) { this.waterLevelIncrementScore = waterLevelIncrementScore; this.waterLevelIncrementRatio = null; }

Target:
Use a simple setter (notice that the setWaterLevelIncrementRatio doesn't have this side effect) and have either the AcceptorConfig set the default value, similar to how it sets 400 for Late Acceptance.
Source:
public void phaseEnded(LocalSearchPhaseScope phaseScope) { super.phaseEnded(phaseScope); initialWaterLevel = null; waterLevelIncrementRatio = DEFAULT_WATER_LEVEL_INCREMENT_RATIO; waterLevelIncrementScore = null; }

Target:
Bug: running the phase twice (not really reproducible right now) will make it forget it's settings. remove these 2 lines.
Source:
public void fireSolvingStarted(DefaultSolverScope<Solution_> solverScope) { // Listeners can only be removed/added from the solver thread: no ConcurrentModificationException if (eventListenerSet.isEmpty()) { return; } final SolvingStartedEvent<Solution_> event = new SolvingStartedEvent<>(solver); for (SolverListener<Solution_> listener : eventListenerSet) { listener.solvingStarted(event); } }

Target:
Unused parameter - maybe consistent but confusing.
Source:
private void writeTimeGrainHoursHeaders() { for (TimeGrain timeGrain : solution.getTimeGrainList()) { LocalTime startTime = LocalTime.ofSecondOfDay(timeGrain.getStartingMinuteOfDay() * 60); LocalTime endTime = LocalTime.ofSecondOfDay( (timeGrain.getStartingMinuteOfDay() + timeGrain.GRAIN_LENGTH_IN_MINUTES) * 60); nextHeaderCell(TIME_FORMATTER.format(startTime)); } }

Target:
This variable is unused. It maybe a bug or useless code.
Source:
public boolean isGenerateDroolsTestOnError() { return generateDroolsTestOnError != null && generateDroolsTestOnError.booleanValue(); }

Target:
The getter should return null if it's null. For all Config classes, it's important to distinguish between null (= not filled in) and the default value (the value it gets when it's null). This for example impacts the programmatic API after reading a solver config XML file. Also note that solver config files are sometimes written to XML (see benchmark report).
Source:
public String toString() { return singleBenchmarkResult.toString() + "_" + problemStatisticType.toString(); }

Target:
when concatening strings with +, it's not needed to do .toString(). This gives the same result: ``` return singleBenchmarkResult + "_" + problemStatisticType; ``` Furthermore, it even avoids a nullpointerexception if for example problemStatisticType is null (which it never is in this particular case)
Source:
public void testKJarNotAvailable() { boolean caughtException = false; ScoreKJarReleaseIdConfig config = new ScoreKJarReleaseIdConfig(); config.setGroupId(groupId); config.setArtifactId(artifactId); //Use a non-existing version. config.setVersion("1.0.1"); DroolsScoreDirectorFactory scoreDirectorFactory = config.build(); }

Target:
Yes - the variable declared on line 80 is not used anywhere in the method.
Source:
protected int calculateActualMaximumSize(LocalSearchSolverPhaseScope scope) { return this.calculateFadingTabuSize(scope) + this.calculateRegularTabuSize(scope); }

Target:
Mind removing the "this." so it matches the rest of the planner code style?
Source:
public void setup() throws Exception{ this.metadataStore = new HazelcastMetadataStore(map); metadataStore.afterPropertiesSet(); }

Target:
`this.` must be used for properties access. The Checkstyle concern.
Source:
private void verifyMembershipEvent(final Message<?> msg, final int membershipEvent) { assertNotNull(msg); assertNotNull(msg.getPayload()); assertTrue(msg.getPayload() instanceof MembershipEvent); assertEquals(((MembershipEvent) msg.getPayload()).getEventType(), membershipEvent); assertNotNull(((MembershipEvent) msg.getPayload()).getMember()); }

Target:
must be flipped. I mean you should exchange `expected` and `actual`. See `assertEquals` source code :smile:
Source:
private void verifyDistributedObjectEvent(final Message<?> msg, final DistributedObjectEvent.EventType eventType, final String distributedObjectName) { assertNotNull(msg); assertNotNull(msg.getPayload()); assertTrue(msg.getPayload() instanceof DistributedObjectEvent); assertEquals(((DistributedObjectEvent) msg.getPayload()).getEventType(), eventType); assertNotNull( (((DistributedObjectEvent) msg.getPayload()).getDistributedObject()) .getName(), distributedObjectName); }

Target:
DITO
Source:
private void verifyLifecycleEvent(final Message<?> msg, final LifecycleState lifecycleState) { assertNotNull(msg); assertNotNull(msg.getPayload()); assertTrue(msg.getPayload() instanceof LifecycleEvent); assertEquals(((LifecycleEvent) msg.getPayload()).getState(), lifecycleState); }

Target:
OK. Revise, please, the whole project for this vulnerability.
Source:
private void verifyDistributedQueue() { Assert.assertEquals(true, distributedQueue.size() == DATA_COUNT); Iterator<?> it = distributedQueue.iterator(); int index = 0; while (it.hasNext()) { Assert.assertEquals(index, it.next()); index++; } }

Target:
Can be simplified: ``` int index = 0; for (Object o : distributedQueue) { Assert.assertEquals(index++, o); } ```
Source:
private List<String> splitToLength(String text, int subStringSize) { List<String> substrings = new ArrayList<String>(text.length() + subStringSize -1 / subStringSize); for (int idx = 0; idx < text.length(); idx += subStringSize) { String substring = text.substring(idx, Math.min(text.length(), idx + subStringSize)); substrings.add(substring); } return substrings; }

Target:
The mistake is here. `Div` operator has precedence over `minus`
Source:
protected Object handleRequestMessage(Message<?> requestMessage) { if (!this.initialized.getAndSet(true)) { initialize(); } return exchanger.exchange(requestMessage); }

Target:
An `AtomicBoolean` won't work here - you can get an NPE on the next statement. You need a synchronized block with a double null check.
Source:
public ImapMailInboundChannelAdapterSpec() { this.receiver = new ImapMailReceiver(); }

Target:
`Spec`s can't have `public` ctors: only access from factory methods.
Source:
public void handleMessage(Message<?> message) throws MessagingException { try { // todo support a gateway and have that gateway also handle message delivery receipt notifications // that will correlate this smsMessageId with the ID that comes back asynchronously from the SMSC indicating that // the message has been delivered. // this could require that we keep a correlation map since its possible upstream SMSC // unused return value -- see gateway SmesMessageSpecification specification = applyDefaultsIfNecessary( SmesMessageSpecification.fromMessage(this.smppSession, message) .setTimeFormatter(this.timeFormatter)); String[] smsMessageId = specification.send(); logger.debug( "sent message : "+message.getPayload()); logger.debug("message ID(s) for the sent message: " + Arrays.toString(smsMessageId)); } catch (Exception e) { throw new RuntimeException("Exception in trying to process the inbound SMPP message", e); } }

Target:
Having the `List<String> smsMessageId` it will be redundant to wrap array to String
Source:
private char[] fileToCharArray(File file) throws IOException { FileInputStream is = new FileInputStream(file); try { return streamToCharArray(is); } finally { is.close(); } }

Target:
Good catch!
Source:
public void write(AsyncHttpRequest request, DataSink sink, CompletedCallback completed) { Util.pump(stream, sink, completed); }

Target:
There's a variant of Util.pump that takes a length argument: ``` java public static void pump(final InputStream is, final int max, final DataSink ds, final CompletedCallback callback) ``` See: max. Specify that, and it won't read more than that many bytes from the stream.
Source:
private DefaultHttpClient getHttpClient(MetricServiceAppConfiguration passedConfig) { PoolingClientConnectionManager cm = new PoolingClientConnectionManager(); int maxTotalPoolConnections = passedConfig.getMetricServiceConfig().getMaxTotalPoolConnections(); int maxPoolConnectionsPerRoute = passedConfig.getMetricServiceConfig().getMaxPoolConnectionsPerRoute(); log.info("Setting up pool with total connections and max connections per route.", maxTotalPoolConnections, maxPoolConnectionsPerRoute); cm.setMaxTotal(maxTotalPoolConnections); cm.setDefaultMaxPerRoute(maxPoolConnectionsPerRoute); return new DefaultHttpClient(cm); }

Target:
maybe debug?
Source:
public void saveFormData(FormData formData) throws FormDataSaveException { try { formData.setSaveTime(new Date()); formService.saveFormData(formData); System.out.println(formData.getJsonPayload()); } catch (IOException e) { throw new FormDataSaveException(e); } }

Target:
I think this log is no longer in use.
Source:
boolean uploadFormDataToServer(List<FormData> allFormData, boolean result) throws IOException { for (FormData formData : allFormData) { String rawPayload = formData.getJsonPayload(); System.out.println(rawPayload); // inject consultation.sourceUuid formData = injectUuidToPayload(formData); // replace media paths with base64 string formData = replaceMediaPathWithBase64String(formData); if (formService.syncFormData(formData)) { formData.setStatus(STATUS_UPLOADED); //DO NOT save base64 string in DB formData.setJsonPayload(rawPayload); formService.saveFormData(formData); } else { result = false; } } return result; }

Target:
This is also no longer needed.
Source:
public void saveOrUpdateCohorts(List<Cohort> cohorts) throws CohortSaveException { try { for(Cohort cohort: cohorts){ if(cohortService.getCohortByUuid(cohort.getUuid()) == null){ cohortService.saveCohort(cohort); } else { cohortService.updateCohort(cohort); } } cohortService.saveCohorts(cohorts); } catch (IOException e) { throw new CohortSaveException(e); } }

Target:
Is this call supposed to be made after going through the loop?
Source:
public Boolean isSHREnabled(){ boolean enableSHR = true; try { MuzimaSetting muzimaSHRStatus = getSettingByProperty(SHR_STATUS_SETTING); enableSHR = muzimaSHRStatus.getValueBoolean(); } catch (MuzimaSettingFetchException e){ Log.e(getClass().getSimpleName(), "Could not fetch requireMedicalRecordNumber setting. ", e); } return enableSHR; }

Target:
Make enableSHR default value to false
Source:
protected void onPostExecute(Encounters encountersWithObservations) { if (encountersWithObservations == null) { Toast.makeText(observationsByEncounterAdapter.getContext(),"This patient does not have any SHR data.", Toast.LENGTH_SHORT).show(); return; } if (observationsByEncounterAdapter.getBackgroundListQueryTaskListener() != null) { observationsByEncounterAdapter.getBackgroundListQueryTaskListener().onQueryTaskFinish(); } }

Target:
Shouldn't we have two Toast messages, one when using SHR and another when not using SHR using if condition as ones in doInBackground
Source:
public void setCardDetail(CardDetails cardDetail) { CardDetail = cardDetail; }

Target:
Shouln't this be this.variable name. This is a Potential Null pointer Exception.
Source:
protected void onPreExecute() { System.out.println("onPreExecute"); Toast.makeText(EncryptedSharedHealthRecordSyncTask.context, "Uploading SHR Data", Toast.LENGTH_SHORT).show(); }

Target:
Logging using standard output
Source:
protected void onPostExecute(Integer[] result){ System.out.println("onPostExecute"); if(result[0] == SUCCESS) { Toast.makeText(EncryptedSharedHealthRecordSyncTask.context, "Uploaded " + result[1] +" SHR Data items", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(EncryptedSharedHealthRecordSyncTask.context, "Error Uploading SHR Data. Uploaded " + result[1] + ", Failed " + result[2], Toast.LENGTH_SHORT).show(); } syncInProgress = false; }

Target:
Logging using standard output
Source:
public void onBackPressed(){ patientAdapter.cancelBackgroundTask(); listView.clearFocus(); super.onBackPressed(); if(getCurrentFocus() != null) { System.out.println("Current focusssssssss: " + getCurrentFocus().toString()); } else { System.out.println("Current focusssssssss: null"); } }

Target:
Do we need to remove this?
Source:
public void onKeyboardClosed() { fabSearchButton.setVisibility(View.VISIBLE); // fabSearchButton.setFocusable(true); // boolean f=fabSearchButton.requestFocus(); listView.clearChoices(); if(getCurrentFocus() != null) { System.out.println("Current focus: " + getCurrentFocus().toString()); } else { System.out.println("Current focus: null"); } }

Target:
Do we need to remove this?
Source:
public TermsOfUse getTermsOfUse() { return termsOfUse; }

Target:
Can't this just be a string, rather than an object?
Source:
public SegmentRef toRef() { return new SegmentRef(checkNotNull(this.getId().toString(), "Can't create reference for segment without ID")); }

Target:
this is a bit weird, is calling the toString method actually the right thing to do?
Source:
public static void copyTo(Localized from, Localized to) { to.locale = from.locale; }

Target:
Should this be `protected` since if someone were to use this method on a sub-class, it wouldn't do the right thing.
Source:
public boolean equals(Object obj) { if (obj instanceof ApplicationCredentials) { ApplicationCredentials other = (ApplicationCredentials) obj; return Objects.equal(this.getApiKey(), other.getApiKey()); } return false; }

Target:
And again with an instance equality. Does it make sense to have credentials without an API key?
Source:
public void sendLastNEndpointsChangeEvent( Collection<String> forwardedEndpoints, Collection<String> endpointsEnteringLastN, Collection<String> conferenceEndpoints) { // We want endpointsEnteringLastN to always to reported. Consequently, // we will pretend that all lastNEndpoints are entering if no explicit // endpointsEnteringLastN is specified. // XXX do we really want that? if (endpointsEnteringLastN == null) { endpointsEnteringLastN = forwardedEndpoints; } String msg = createLastNEndpointsChangeEvent( forwardedEndpoints, endpointsEnteringLastN, conferenceEndpoints); sendMessage(msg); notifyForwardedEndpointsChanged(forwardedEndpoints, endpointsEnteringLastN, conferenceEndpoints); }

Target:
Hm, wondering if this feels a bit weird since this call already came from _outside_ the endpoint. If anything, it seems like we shouldn't forward this here and instead have BitrateController be the source of truth (like in your other PR)
Source:
public int resetAt(int seq) { int delta = Vp8Utils.getExtendedPictureIdDelta(seq, highestSeqNumReceived); if (delta < 0) { roc++; highestSeqNumReceived = seq; } return getIndex(seq, true); }

Target:
Should this also happen when `delta >= 0`?
Source:
public synchronized FrameInsertionResult insertPacket(@NotNull Vp8Packet packet) { int pictureId = packet.getPictureId(); VP8Frame frame = frameHistory.get(pictureId); if (frame != null) { return doFrameInsert(frame, packet); } frame = new VP8Frame(packet); if (!frameHistory.insert(pictureId, frame)) return null; return new FrameInsertionResult(frame, true); }

Target:
braces please
Source:
public Integer getInteger(String key, int defaultValue) { return parseValueOrDefault(key, Integer::parseInt, defaultValue); }

Target:
а возвращать Integer зачем? int же
Source:
public Response toResponseInternal(Response.StatusType status, LoggingLevel loggingLevel, T exception) { logException(exception, loggingLevel); return serializeException(status, exception); }

Target:
может тогда `protected`, раз он такой internal?
Source:
private static boolean isMasterDataSource() { String dataSourceName = DataSourceContextUnsafe.getDataSourceType(); return dataSourceName == null || MASTER.equals(dataSourceName); }

Target:
быть может это более уместно в самом getDataSourceType ? чтоб он не возвращал никогда нуллов
Source:
public String[] getPackagesToScan() { return packagesToScan.toArray(new String[packagesToScan.size()]); }

Target:
лучше new String[0], по перформансу лучше будет. Как-то кто-то (Коля кажется) скидывал статью про это. Суть - new String[packagesToScan.size()] - создат и проинитит массив с дефолтными значениями, потом toArray поверх запишет новых значений. а new String[0] выполнится в момент, с минимумом инициализации, а toArray умеет создавать массив сразу с нужными значениями
Source:
public static Date parseDate(String date, String format) { return parseDate(date, new SimpleDateFormat(format, Locale.getDefault())); }

Target:
Is a null check for the passed in "date" required here for safety?
Source:
public static KFunction<?> findKotlinFunction(Method method) { KFunction<?> kotlinFunction = ReflectJvmMapping.getKotlinFunction(method); if (kotlinFunction == null) { // Fallback to own lookup because there's no public Kotlin API for that kind of lookup until // https://youtrack.jetbrains.com/issue/KT-20768 gets resolved. return findKFunction(method).orElse(null); } return kotlinFunction; }

Target:
Ternary if?
Source:
public T getNullable() { T value = this.value; if (this.resolved) { return value; } value = supplier.get(); this.value = value; this.resolved = true; return value; }

Target:
How about sticking following the `Optional` `orElse(…)` pattern? Staying with Java's names and `Optional` idioms gives more flexibility and it's a bit more familiar to users.
Source:
private Optional<MethodExecutor> getMethodExecutor(EvaluationContextExtensionAdapter adapter, String name, List<TypeDescriptor> argumentTypes) { FunctionsMap functions = adapter.getFunctions(); Optional<Function> function = functions.get(name, argumentTypes); return function.map(FunctionMethodExecutor::new); }

Target:
Inline `function`?
Source:
public Writing(ConvertiblePair convertiblePair, Function<? super S, ? extends T> function) { super(convertiblePair, function); }

Target:
Is public visibility modifier required?
Source:
Class<?> getRepositoryInterfaceFrom(BeanDefinition beanDefinition) { if (beanDefinition instanceof ScannedGenericBeanDefinition) { try { return ((ScannedGenericBeanDefinition) beanDefinition).resolveBeanClass(beanClassLoader); } catch (ClassNotFoundException e) { throw new IllegalStateException("Could not resolve bean class.", e); } } else { return getRepositoryInterfaceFromFactory(beanDefinition); } }

Target:
Can this stay private?
Source:
private RootBeanDefinition createBeanDefinition() { RootBeanDefinition beanDefinition = new RootBeanDefinition("com.acme.MyRepository"); ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues(); constructorArgumentValues.addGenericArgumentValue(MyRepository.class); beanDefinition.setConstructorArgumentValues(constructorArgumentValues); return beanDefinition; }

Target:
Static?
Source:
public DefaultRepositoryMetadata(Class<?> repositoryInterface) { super(repositoryInterface); Assert.isTrue(Repository.class.isAssignableFrom(repositoryInterface), MUST_BE_A_REPOSITORY); Class<? extends Serializable> idType = resolveIdType(repositoryInterface); Class<?> domainType = resolveDomainType(repositoryInterface); Assert.notNull(idType, "IdType must not be null!"); Assert.notNull(domainType, "DomainType must not be null!"); this.idType = idType; this.domainType = domainType; }

Target:
Could be assigned to the field directly.
Source:
public Optional<SolrConfiguration> getSolrConfiguration() { return null; }

Target:
Why not Optional.empty()?
Source:
public String renderArticle(HttpServletRequest request, Model model, @SiteParam Site site, RequestedDoiVersion articleId) throws IOException { ArticlePointer articlePointer = articleMetadataFactory.get(site, articleId) .validateVisibility("article") .populate(request, model) .fillAmendments(model) .getArticlePointer(); XmlContent xmlContent = getXmlContent(site, articlePointer); model.addAttribute("articleText", xmlContent.html); model.addAttribute("references", xmlContent.references); model.addAttribute("isArticlePage", true); return site + "/ftl/article/article"; }

Target:
I would rather not involve controller code in this fix if we can help it. Could we just put ``` html <#assign isArticlePage = true /> ``` near the top of `article.ftl` instead? Also, won't this create inconsistency between the main article body tab and all the other article pages? As currently implemented, I think we would get "Journal Title: Journal Slogan" on non-article pages, "Article Title" on the main body tab, and "Journal Title: Article Title" on the other article pages.
Source:
private String getParentArticleDoiFromComment(Map<String, Object> comment) { return (String) ((Map<String, Object>) ((Map<String, Object>) comment.get("parentArticle")).get("doi")).get("doiName"); }

Target:
Yep, I poked around a little and it looks like we've just never serialized a `Doi` object before, apparently because we usually start with model classes that don't use the `Doi` wrapper. The best route here is probably just a global Gson adapter that serializes `Doi` to a primitive `JsonElement` (rather than an object). See `AdapterRegistry` and let me know if you'd like some help getting it wired.
Source:
public Map<?, ?> lookupArticlesByDois(List<String> dois) throws IOException { String doiQueryString = Joiner.on(" OR ").join(dois); ArticleSearchQuery.Builder query = ArticleSearchQuery.builder() .setQuery(doiQueryString) .setStart(0) .setRows(dois.size()) .setDateRange(SolrSearchApiImpl.SolrEnumeratedDateRange.ALL_TIME); return search(query.build()); }

Target:
do we even need to set the dateRange?
Source:
public CategoryView findCategory(CategoryView parentCategoryView, String category) throws IOException { String cacheKey = "singleCategory:" + CacheParams.createKeyHash(category + parentCategoryView.hashCode()); return CacheUtil.getOrCompute(cache, cacheKey, () -> findCategoryWithoutCache(parentCategoryView, category)); }

Target:
`CategoryView.hashCode()` just returns the `hashCode` of its `name` field, and `String.hashCode()` is not collision-resistant. Meaning, there is a small chance (but not astronomically small as with SHA-1) that the cache key could collide with another parent of the same category. `CacheParams` already provides a way to make a collision-resistant key out of two strings. I recommend ``` java String cacheKey = "singleCategory:" + CacheParams.createKeyHash(category, parentCategoryView.getName()); ```
Source:
private boolean isSimpleSearch(String query) { return Arrays.stream(AdvancedSearchTerms.class.getEnumConstants()) .noneMatch(e -> query.contains(e.text)); }

Target:
Based on this documentation https://docs.oracle.com/javase/tutorial/reflect/special/enumMembers.html you can use values() instead of "class.getEnumConstants()", which I think is cleaner.
Source:
public SiteRequestCondition(SiteResolver siteResolver, Set<String> validSites){ this.siteResolver = Preconditions.checkNotNull(siteResolver); this.validSites = ImmutableSet.copyOf(Preconditions.checkNotNull(validSites)); }

Target:
You don't need the `checkNotNull` here. `ImmutableSet.copyOf` checks for null arguments on its own.
Source:
public SiteRequestCondition combine(SiteRequestCondition other) { Set<String> combinedIncludedSites = new ImmutableSet.Builder<String>() .addAll(includedSites) .addAll(other.includedSites) .build(); Set<String> combinedExcludedSites = new ImmutableSet.Builder<String>() .addAll(excludedSites) .addAll(other.excludedSites) .build(); return new SiteRequestCondition(siteSet, siteResolver, combinedIncludedSites, combinedExcludedSites); }

Target:
I'm less than 100% clear on how Spring uses this method, but do we need to guard here against `combinedIncludedSites` and `combinedExcludedSites` ending up with overlapping elements? (For that matter, maybe we should check that in the constructor also.)
Source:
public List<Object> getArticles(HomeController context, SectionSpec section, Site site, int start) throws IOException { Map<?, ?> result = context.solrSearchService.getHomePageArticles( Collections.singletonList(site.getJournalKey()), start, section.resultCount, SolrSearchService.SolrSortOrder.DATE_NEWEST_FIRST); return sanitizeSolrResults(result); }

Target:
Instead of altering these method signatures, would it be more readable if we had an overloaded method signature that accepts a singular site?
Source:
HtmlElementTransformation(String tagName, String attributeName) { this.matchingTagName = tagName; this.matchingAttributeName = attributeName; }

Target:
Similarly to the `static enum` thing, I subjectively like to make enum constructors explicitly `private` even though there's no practical difference. Any particular rationale for this change?
Source:
private CacheParams(String cacheKey, Optional<Integer> timeToLive) { this.cacheKey = Preconditions.checkNotNull(cacheKey); this.timeToLive = timeToLive; }

Target:
Just to be really style-conscious, `Preconditions.checkNotNull` would be good on `timeToLive` as well. Or you could move the `Optional.fromNullable` to this line and change the constructor argument from `Optional<Integer>` to `Integer`.
Source:
private void addPatternToIndex(TripPattern tripPattern) { for (Stop stop: tripPattern.getStops()) { if (!patternsForStop.containsEntry(stop, tripPattern)) { patternsForStop.put(stop, tripPattern); } } }

Target:
This conditional is probably not necessary, even from a performance point of view. The meaning might be clearer with only the put() call and no conditional.
Source:
private void assertOperators(Collection<Operator> operators) { Operator o = list(operators).get(0); assertEquals("RUT:Operator:130c", o.getId().getId()); assertEquals("Ruter", o.getName()); assertNull( o.getUrl()); assertNull(o.getPhone()); assertEquals(1, operators.size()); }

Target:
I find the body more readable if the size is asserted first, because the Collection is not ordered, so the get(0) operation does not appear deterministic until you know its length is one.
Source:
public static String convertStreamToString(java.io.InputStream is) { java.util.Scanner scanner = null; String result=""; try { scanner = new java.util.Scanner(is).useDelimiter("\\A"); result = scanner.hasNext() ? scanner.next() : ""; scanner.close(); } finally { if(scanner!=null) scanner.close(); } return result; }

Target:
`public`?
Source:
public void setWhiteListedRoutes(String s) { if (s != null && !s.equals("")) whiteListedRoutes = RouteMatcher.parse(s); else whiteListedRoutes = RouteMatcher.emptyMatcher(); }

Target:
The canonical way of performing the second check is `String.isEmpty()`. If we are going to check for equality with the empty string, note that by reversing the comparison we can elide the null check: `!("".equals(string))`
Source:
public String getFeedId() { if (code != null && code.length() > 0) { // The key stored in patternForId is the pattern code that is constructed as. // Agency:RouteId:DirectionId:PatternNumber, the first part is the feed id. return code.substring(0, code.indexOf(':')); } // If we cant obtain the feed id from the code, we can get it from the route. return route.getId().getAgencyId(); }

Target:
What if code is non-empty, but doesn't have a ':' character?
Source:
public synchronized void trimMemory(int level) { if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_BACKGROUND) { clearMemory(); } else if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) { evictToSize(maxSize / 2); } else if (level == android.content.ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL) { evictToSize(maxSize / 2); } }

Target:
Use || instead of duplicating the size logic.
Source:
private static boolean isLowMemoryDevice(ActivityManager activityManager) { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && activityManager.isLowRamDevice(); }

Target:
Didn't we have some problems with shortcutting vs Build.VERSION before?
Source:
public void testSetModulesEnabledFalse() throws Exception { // teaDown glide instance first so we have a clean slate and not the Glide.get() call in setUp Glide.tearDown(); Glide.setModulesEnabled(false); try { Glide glide = Glide.get(getContext()); List<ModelLoader<GlideUrl, ?>> modelLoaders = glide.getRegistry().getModelLoaders(mock(GlideUrl.class)); // With modules disabled, SetupModule below should not have been initialized, // so the default modelLoader should remain assertEquals(1, modelLoaders.size()); assertTrue(modelLoaders.get(0) instanceof HttpGlideUrlLoader); } finally { Glide.setModulesEnabled(true); } }

Target:
I think this should be part of Glide.tearDown, it resets Glide to pre-initialized state, which IMO includes both static variables. (It should probably even reset ViewTarget.tagId)
Source:
public int getDelay(int n) { int delay = -1; if (0 <= n && n < header.frameCount) { delay = header.frames.get(n).delay; } return delay; }

Target:
nit: I prefer the other ordering for <= or ==, it's easier for me to read "n is greater than or equal to 0" than it is "0 is less than or equal to n".
Source:
public CalibratedPredictiveModel(Classifier wrappedPredictiveModel, PoolAdjacentViolatorsModel PAVFunction) { Preconditions.checkArgument(!(wrappedPredictiveModel instanceof CalibratedPredictiveModel)); this.wrappedPredictiveModel = wrappedPredictiveModel; this.pavFunction = PAVFunction; }

Target:
Seems a little over-cautious, there might be a reason to do a double-wrapped PM.
Source:
private boolean newValidationSetExists() { if (currentTrainingSetSize >= allTrainingData.size()) { return false; } else return true; }

Target:
You can just return the inverse of your conditional: return currentTrainingSetSize < allTrainingData.size();
Source:
public static Collection<Integer> getSupportedCountryCodes() { final Set<Integer> supportedCountryCodes = new HashSet<>(); final PhoneNumberUtil pnUtil = PhoneNumberUtil.getInstance(); for (final String region : pnUtil.getSupportedRegions()) { supportedCountryCodes.add(pnUtil.getCountryCodeForRegion(region)); } return supportedCountryCodes; }

Target:
Semantic change! We do not want duplicates here.
Source:
public void bbCodesWithTextThatShouldFail(String postBody, String messageIfTestFails) throws Exception { info("Running a test case [" + messageIfTestFails + "]"); try { Topics.postAnswer(TEST_TOPIC, new Post(postBody)); //should throw exception if validation failed fail(messageIfTestFails); } catch (ValidationException e) { //if validation error happened, then the test passed } catch (CouldNotOpenPageException e) { fail("Something went wrong and user was thrown out of topic."); } }

Target:
Why do you catch this kind of exception if the only thin you do is re-throwing an exception?
Source:
public void bbCodesWithTextThatShouldPass(String postBody, String messageIfTestFails) throws Exception { info("Running a test case [" + messageIfTestFails + "]"); try { Topics.postAnswer(TEST_TOPIC, new Post(postBody)); //should throw exception if validation failed } catch (ValidationException e) { fail(messageIfTestFails); //if validation error happened, then the test failed } catch (CouldNotOpenPageException e) { fail("Something went wrong and user was thrown out of topic."); } }

Target:
I don't see any reason to catch the exception if you still are going to throw it..
Source:
public static void removePmFromOutbox(PrivateMessage pm) { info("Start to remove PM from outbox folder"); mainPage.openPrivateMessages(); info("Opening outbox folder"); pmPage.clickOpenOutboxMessages(); removePm(pm); }

Target:
Can be moved inside `pmPage.clickOpenOutboxMessages()`
Source:
public static void savePrivateMessageAsDraft(PrivateMessage pm) throws NoSuchElementException, ValidationException { composeMessage(pm); if (pmPage.isSaveButtonEnabled()) { info("Clicking Save PM button"); try { pmPage.clickSaveButton(); } catch (NoSuchElementException e) { info("No such button found!"); throw new NoSuchElementException("Couldn't find Save button."); } } assertFormValid(); info("Draft had to be saved"); }

Target:
Either re-throw the very same exception: `throw e` or add the root exception to the newly created: `throw new NoSuchElementException("blah-blah", e)`
Source:
private static void composeMessage(PrivateMessage pm) { info("Opening private messages page"); mainPage.openPrivateMessages(); info("Clicking compose button"); pmPage.clickComposeMessage(); info("Start filling PM fields."); pmPage.fillPrivateMessageFields(pm); }

Target:
Shouldn't this kind of messages be placed inside of `pmPage.clickComponseMessage()`?
Source:
public void createTopicWithTitleAndMessage_ShouldPass_JC_13() throws Exception { Users.signUpAndSignIn(); Topic topic = new Topic().withTitle("subject").withBody("message"); Topic createdTopic = Topics.createTopic(topic); Assert.assertTrue(Topics.isCreated(createdTopic)); }

Target:
just new Topic() so that subject and body get random
Source:
public void viewUserProfile_shouldPass() throws Exception { User user = Users.signUpAndSignIn(); Users.viewProfile(user); Users.viewProfile(); }

Target:
What do we check in this TC? And what should two "viewProfile" methods do?
Source:
public Qualifiers(Qualifiers other) { this.resolvers.addAll(other.resolvers); this.registry = null; }

Target:
Should be package private
Source:
private ReflectionMappers(ReflectionMappers that) { columnNameMatchers.addAll(that.columnNameMatchers); strictMatching = that.strictMatching; }

Target:
Should use the `CopyOnWriteArrayList(Collection)` copy constructor, which reuses the underlying array if the collection is another `CopyOnWriteArrayList`. Then you actually get the copy-on-write benefit.
Source:
public MapEntryMappers() { keyColumn = null; valueColumn = null; }

Target:
This constructor does nothing.
Source:
public JdbiImmutables registerImmutable(Iterable<Class<?>> specs) { specs.iterator().forEachRemaining(this::registerImmutable); return this; }

Target:
Iterable already has a forEach IIRC
Source:
public <R, X extends Exception> R inTransaction(HandleCallback<R, X> callback) throws X { if (isInTransaction()) { return callback.withHandle(this); } return transactions.inTransaction(this, callback); }

Target:
Nitpick: I think a ternary would be nice here. This reads a lot like a guard block, while it's really just a binary decision.
Source:
private TemporalUnitOffset getAllowableOffset() { // PostgreSQL seems to not have as much precision on Windows as it does on Linux. if (SystemUtils.IS_OS_WINDOWS) { return within(0, ChronoUnit.MICROS); } else { return within(0, ChronoUnit.NANOS); } }

Target:
Can we just use the more lenient comparison window always, and get rid of the OS detection? We are not really intending to test the system clock here at all, and OS-specific behavior should be avoided whenever possible.
Source:
public String locate(Class<?> sqlObjectType, Method method, ConfigRegistry config) { Function<String, String> valueOrMethodNameToSql = key -> { String filename = key.isEmpty() ? method.getName() : key; return org.jdbi.v3.core.locator.ClasspathSqlLocator.findSqlOnClasspath(sqlObjectType, filename); }; return SqlAnnotations.getAnnotationValue(method, valueOrMethodNameToSql) .orElseThrow(() -> new IllegalStateException(String.format("method %s has no query annotations", method))); }

Target:
Can't this be an import and short reference now?
Source:
public E map(ResultSet rs, int columnNumber, StatementContext ctx) throws SQLException { String name = ctx.findColumnMapperFor(String.class) .orElseThrow(() -> new UnableToProduceResultException("a String column mapper is required to map Enums from names", ctx)) .map(rs, columnNumber, ctx); return name == null ? null : nameValueCache.computeIfAbsent(name.toLowerCase(), lowercased -> getValueByName(enumClass, name, ctx)); }

Target:
I wonder if the cost of lowercasing outweighs the cost of duplicate entries. Previously I'd operated under the assumption that most users, even if the casing is wrong, will tend to be at least consistently wrong - in which case you'd have few if any truly redundant entries. And even if they aren't, the extra cache entries may well be cheaper than repeatedly lowercasing. Part of the reason for adding this cache in the first place is to avoid case sensitive operations. I worry that this may be a performance regression if that is indeed the common case.
Source:
public SqlStatements define(String key, Object value) { synchronized (this) { attributes.put(key, value); } return this; }

Target:
Prefer using a private field for a mutex to prevent outside code from being able to hold our lock: ```java private final Object mutex = new Object(); public SqlStatement define(String key, Object value) { synchronized (mutex) { attributes.put(key, value); } return this; } ```
Source:
public SqlStatements defineMap(final Map<String, ?> values) { if (values != null) { synchronized (this) { attributes.putAll(values); } } return this; }

Target:
Ditto for mutex
Source:
public static Type resolveType(Type type, Type contextType) { return GenericTypeReflector.resolveType(GenericTypeReflector.annotate(type), GenericTypeReflector.annotate(contextType)).getType(); }

Target:
Please use `GenericTypeReflector.resolveType(Type, Type)` instead of wrapping first using `annotate`. The end result is the same, but it avoids one extra traversal through the type structure, so it should be somewhat faster. Details, in case you care: When calling `GenericTypeReflector.resolveType(AnnotatedType, AnnotatedType)`, the `contextType` first gets its generics expanded (so that each `Class` with type parameters gets wrapped into a `ParameterizedType`), and when calling `GenericTypeReflector.resolveType(Type, Type)` this is done at the same time the `Type` is wrapped into an `AnnotatedType`, so one traversal is skipped.
Source:
public Jackson2Config createCopy() { return new Jackson2Config().setMapper(mapper); }

Target:
perhaps a copy constructor to be consistent with all other Config classes? Would be a shame to divert from the pattern and have to refactor it later anyway.
Source:
public static <T> Optional<T> findFirstPresent(Supplier<Optional<T>>... suppliers) { return Stream.of(suppliers) .flatMap(supplier -> toStream(supplier.get())) .findFirst(); }

Target:
Duplicates `JdbiStreams.toStream(Optional<T>)`. Although I'd be okay folding that method into this class.
Source:
protected BeanMapper(Class<T> type, String prefix) { this(type, (PojoProperties<T>) BeanPropertiesFactory.propertiesFor(type), prefix); }

Target:
Could be package private
Source:
public void setUp() { h = dbRule.getSharedHandle(); h.registerRowMapper(ImmutablesMapperFactory.mapImmutable(Train.class, ImmutableTrain.class, ImmutableTrain::builder)); h.execute("create table train (name varchar, carriages int, observation_car boolean)"); dao = h.attach(Dao.class); }

Target:
Feels like we want annotations to register Immutables mappers, e.g. `@RegisterImmutablesMapper(value = Train.class)` annotation. The impl and builder method name could be default attributes that look for `Immutable*` and `Immutable*.builder()`, respectively.
Source:
public static <T, B> Function<Type, PojoProperties<T>> immutable(Class<T> defn, Supplier<B> builder) { return t -> (PojoProperties<T>) IMMUTABLE_PROPERTIES.computeIfAbsent(t, x -> new ImmutablePojoProperties<>(t, defn, builder)); }

Target:
I'm not sure what this indirection with the `t ->` business buys us
Source:
public SqlStatements define(String key, Object value) { if (value != null) { attributes.put(key, value); } return this; }

Target:
Should probably `remove(key)` if `value == null`.
Source:
public static File findTemplateDirectory(Class<?> type) { try { String classFolder = type.getName().replace(".", "/"); URL resource = type.getClassLoader().getResource(classFolder); if (resource != null) { return new File(resource.toURI()); } } catch (URISyntaxException ignored) return null; }

Target:
Some issues with mixed tabs and spaces? Please configure your IDE project for spaces only.
Source:
public void setUp() throws Exception { Jdbi jdbi = Jdbi.create("jdbc:sqlite::memory:"); jdbi.installPlugin(new SQLitePlugin()); handle = jdbi.open(); handle.useTransaction(handle -> { handle.execute("DROP TABLE IF EXISTS foo"); handle.execute("CREATE TABLE foo(url URL);"); }); }

Target:
I don't think `foo` can ever exist here, right, since the above opens a unique in-memory db?
Source:
public void setUp() throws Exception { Jdbi jdbi = Jdbi.create("jdbc:sqlite::memory:"); jdbi.installPlugin(new SQLitePlugin()); handle = jdbi.open(); handle.useTransaction(handle -> { handle.execute("CREATE TABLE foo(url URL);"); }); }

Target:
Single statements also are implicitly in a transaction, so it might be entirely redundant.
Source:
public static void closeIfNeeded(Handle handle) { if (UNMANAGED_HANDLES.contains(handle)) { handle.close(); } }

Target:
this looks like a memory leak, should this be `remove`?
Source:
public static Method lookupMethod(String methodName, Class<?>... parameterTypes) { return lookup0(initData().extensionType, methodName, parameterTypes); }

Target:
should we add suppressions for `unused` on methods only called from reflective code? Better indicates current state on one hand, but adds maintenance to code changes on the other.
Source:
public void testMapMapperOrdering() throws Exception { h.execute("insert into something (id, name) values (?, ?)", 1, "hello"); h.execute("insert into something (id, name) values (?, ?)", 2, "world"); List<Map<String, Object>> rs = h.createQuery("select id, name from something") .setMaxRows(1) .mapToMap() .list(); assertThat(rs).hasSize(2); assertThat(rs).hasOnlyElementsOfType(LinkedHashMap.class); }

Target:
This max rows disagrees with the assertion, which is why the test is failing.
Source:
private Comparator<Class<? extends Annotation>> createDecoratorComparator(DecoratorOrder order) { List<Class<? extends Annotation>> ordering = Arrays.asList(order.value()); ToIntFunction<Class<? extends Annotation>> indexOf = type -> { int index = ordering.indexOf(type); return index == -1 ? ordering.size() : index; }; return Comparator.comparingInt(indexOf::applyAsInt); }

Target:
I think the lambda expression could be passed directly to `Comparator.comparingInt`
Source:
private static BoundCustomizer defaultParameterCustomizer(Class<?> type, Method method, Parameter parameter, Integer i) { return (stmt, args) -> getDefaultParameterCustomizerFactory(stmt) .createForParameter(null, type, method, parameter, i) .apply(stmt, args[i]); }

Target:
I'd rather we introduce a separate factory interface for the default customizer, similar to what #754 is doing with default handlers. It feels weird to pass a `null` for the annotation, when the use case is specifically for when there _is_ no annotation. e.g. ```java interface DefaultParameterCustomizerFactory { SqlStatementParameterCustomizer createForParameter(Class<?> sqlObjectType, Method method, Parameter param, int index); } ```
Source:
public void testInvalidDuration() { handle.createQuery("select foo from intervals where id=?") .bind(0, 5) .mapTo(Duration.class) .findOnly(); }

Target:
Here is an example of a test that is difficult to understand in isolation, because the critical data (what is in interval id=5?) is in `IntervalTestCommon` instead of in a setup method or a one-off in the test itself.
Source:
public Optional<ColumnMapper<?>> build(Type type, ConfigRegistry config) { Class<?> erasedType = GenericTypes.getErasedType(type); if (ImmutableList.class.equals(erasedType)) { return GenericTypes.findGenericParameter(type, ImmutableList.class) .flatMap(t -> config.get(ColumnMappers.class).findFor(type, config)) .map(ImmutableListArrayColumnMapper::new); } return Optional.empty(); }

Target:
This might be splitting hairs, but it should probably be `findFor(t, config)` (`t` instead of `type`)
Source:
public OracleReturning(RowMapper<ResultType> mapper) { this.mapper = mapper; try { this.oraclePS = Class.forName("oracle.jdbc.OraclePreparedStatement"); this.registerReturnParameter = oraclePS.getMethod("registerReturnParameter", new Class[]{int.class, int.class}); this.getReturnResultSet = oraclePS.getMethod("getReturnResultSet"); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
Do we still need to do all this reflective bullshit now that it's in a separate artifact?
Source:
public Handler buildHandler(Class<?> sqlObjectType, Method method) { return (obj, m, args, handle) -> { return "foo"; }; }

Target:
couldn't this just be `-> "foo"` ?
Source:
public <T> T getColumn(String column, GenericType<T> type) { return (T) getColumn(column, (Type) type); }

Target:
Ditto: should be `type.getType()`
Source:
public void testMapperForDelegatesToRegistry() { ColumnMapper<?> mapper = new FooMapper(); JdbiConfig config = new JdbiConfig(); config.mappingRegistry.addColumnMapper(mapper); final StatementContext context = new StatementContext(config); assertThat(context.findColumnMapperFor(Foo.class).get()).isEqualTo(mapper); }

Target:
`Assertions` has an `Optional<T>` variant you could use: ``` assertThat(context.findColumnMapperFor(Foo.class)).hasValue(mapper); ```
Source:
public void testCorrectExceptionOnSQLException() throws Exception { Jdbi dbi = Jdbi.create(() -> { throw new SQLException(); }); try { dbi.open(); fail("Should have raised an exception"); } catch (UnableToObtainConnectionException e) { assertThat(e).isNotNull(); } }

Target:
This assertion is probably not buying us anything
Source:
public void testHelpfulErrorOnNothingSet() throws Exception { try { h.createQuery("select * from something where name = :name").list(); fail("should have raised exception"); } catch (UnableToExecuteStatementException e) { assertThat(e).isNotNull(); } catch (Exception e) { fail("Raised incorrect exception"); } }

Target:
Redundant assertion
Source:
public void testThrowingRuntimeExceptionPercolatesOriginal() throws Exception { Handle h = db.openHandle(); try { h.inTransaction((handle, status) -> { throw new IllegalArgumentException(); }); } catch (JdbiException e) { fail("Should have thrown a straight RuntimeException"); } catch (IllegalArgumentException e) { assertThat(e).isNotNull(); } catch (Exception e) { fail("Should have been caught at IllegalArgumentException"); } }

Target:
Redundant assertion
Source:
public boolean nameMatches(String propertyName, String sqlColumnName) { return sqlColumnName.replace("_", "").toLowerCase(locale).equals(propertyName.toLowerCase(locale)); }

Target:
In the absence of a demonstrated problem the other way, let's go with the simple solution. We can always enhance it later to use locales.
Source:
public void testSomethingByIterableHandleNullWithEmptyList() { final SomethingByIterableHandleNull s = handle.attach(SomethingByIterableHandleNull.class); final List<Something> out = s.get(new ArrayList<Object>()); Assert.assertEquals(4, out.size()); }

Target:
I expect `out` to be empty here, yes?
Source:
public void testSomethingByIterableHandleNullWithNull() { final SomethingByIterableHandleNull s = handle.attach(SomethingByIterableHandleNull.class); final List<Something> out = s.get(null); Assert.assertEquals(4, out.size()); }

Target:
This might be considered a programming error -- should we really assume `null` is `empty list` instead of a coding error?