auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean prepareConnectHostToStoragePoolServers(ConnectHostToStoragePoolServersParameters parameters, List<StorageServerConnections> connections) { List<StorageServerConnections> res = updateIfaces(connections, parameters.getVds().getId()); connections.clear(); connections.addAll(res); return true; }

Target:
What's the point of this return value if it's always true?
Source:
public HibernateErrorReportingServiceDao() { this.errorOccurrenceConverter = new ErrorOccurrenceConverter(); }

Target:
I am not sure that converter should be part of DAO. Given we still using save on single entity I would suggest i would move that code to Service layer.
Source:
public JettyConfig getJettyConfig() { if(jettyConfig != null) { return jettyConfig; } else { return new DefaultJettyConfig(); } }

Target:
Would much rather use the ternary operator here. Or even Optional, since we're on Java8 now. ``` Optional.ofNullable(jettyConfig).orElse(() -> new DefaultJettyConfig()); ```
Source:
public void setNumThreads(final Integer numThreads) { m_threads = ConfigUtils.assertNotNull(numThreads, "threads"); }

Target:
Why do we not allow this field to be null?
Source:
public String getModeName() { String header = getHeader(); return header.substring(0, header.indexOf('"') - 1); }

Target:
change to private
Source:
private List<RequestInfo> pollForRequests() { // these are ids that were successfully put for an operation that eventually failed idsToDelete.clear(); putManager.getIdsToDelete(idsToDelete); // this is a best effort to delete ids for cleanup purposes (these may fail and we will // not do anything about it at this time). for (String blobId : idsToDelete) { // possibly add a batch api going forward. deleteManager .submitDeleteBlobOperation(operationIdGenerator.incrementAndGet(), blobId, new FutureResult<Void>(), null); } List<RequestInfo> requests = new ArrayList<RequestInfo>(); putManager.poll(requests); getManager.poll(requests); deleteManager.poll(requests); return requests; }

Target:
If you make the getIdsToDelete() to return a list of blob Ids, we can avoid idsToDelete.clear(). We can just call idsToDelete = putManager.getIdsToDelete() everytime.
Source:
public InternalAggregationFunction specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionManager functionManager) { Type type = boundVariables.getTypeVariable("E"); MethodHandle compareMethodHandle = functionManager.getScalarFunctionImplementation( functionManager.resolveOperator(operatorType, TypeSignatureProvider.fromTypes(ImmutableList.of(type, type)))).getMethodHandle(); return generateAggregation(type, compareMethodHandle); }

Target:
Static import `fromTypes`.
Source:
public AccountInfo getAccountInfo() throws IOException { CoingiBalances coingiBalances; try { coingiBalances = getCoingiBalance(); } catch (CoingiException e) { throw CoingiErrorAdapter.adapt(e); } return CoingiAdapters.adaptAccountInfo( coingiBalances, exchange.getExchangeSpecification().getUserName()); }

Target:
it would be easier to read if would surround the entire method with this type of try / catch like: ``` @Override public AccountInfo getAccountInfo() throws IOException { try { CoingiBalances coingiBalances = getCoingiBalance(); return CoingiAdapters.adaptAccountInfo( coingiBalances, exchange.getExchangeSpecification().getUserName()); } catch (CoingiException e) { throw CoingiErrorAdapter.adapt(e); } } ``` please apply this hint to all the methods that have this type of try catch
Source:
public IdentityHashMap<TableScanNode, Void> visitPlan(PlanNode node, Void context) { IdentityHashMap<TableScanNode, Void> ret = new IdentityHashMap<>(); node.getSources().forEach(source -> ret.putAll(source.accept(this, context))); return ret; }

Target:
`Map<TableScanNode, Void> result = new IdentityHashMap<>();`
Source:
protected RevCommit findHead(Repository repo) { try (RevWalk walk = new RevWalk(repo)) { try { ObjectId head = repo.resolve(HEAD); return walk.parseCommit(head); } catch (RevisionSyntaxException e) { throw new RuntimeException(e); } catch (AmbiguousObjectException e) { throw new RuntimeException(e); } catch (IncorrectObjectTypeException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }

Target:
you handle all these exceptions in the same way so you can use multi-catch: } catch (RevisionSyntaxException | AmbiguousObjectException | IncorrectObjectTypeException | IOException e) {
Source:
public void process(EquivalentContentUpdatedMessage message) throws RecoverableException { Id contentId = message.getContentRef().getId(); log.debug("Processing message on id {}, took PT{}S, message: {}", contentId, getTimeToProcessInSeconds(message)); Timer.Context time = timer.time(); try { Content content = getContent(contentId); neo4JContentStore.writeContent(content); time.stop(); } catch (Exception e) { failureMeter.mark(); throw Throwables.propagate(e); } }

Target:
You're not passing in the message even though you have a marker there. Think that might throw weird RTEs.
Source:
public String apply(String dimValue) { if (dimValue == null) return null; Matcher matcher = pattern.matcher(dimValue); return matcher.find() ? dimValue : null; }

Target:
Internally Druid treats nulls and empty strings as similar values. So I think one workaround here is to do dimValue == null ? "" : dimValue Druid's handling of nulls and empty strings could definitely be better though.
Source:
private void writeSubscribeCommands( String repoName, List<SubscribeCommand> commands) throws IOException { write("repository " + repoName); for (SubscribeCommand cmd : commands) { switch (cmd.getCommand()) { case SUBSCRIBE: write("want " + cmd.getSpec()); break; case UNSUBSCRIBE: write("stop " + cmd.getSpec()); break; } } }

Target:
default: throw new IllegalArgumentException...
Source:
private Set<GlusterServerInfo> fetchServers(VDS upServer, List<VDS> existingServers) { Set<GlusterServerInfo> fetchedServers = null; while (fetchedServers == null && existingServers.size() > 0) { fetchedServers = fetchServers(upServer); if (fetchedServers == null) { logServerMessage(upServer, AuditLogType.GLUSTER_SERVERS_LIST_FAILED); // Couldn't fetch servers from the up server. Mark it as non-operational setNonOperational(upServer); existingServers.remove(upServer); upServer = getNewUpServer(existingServers, upServer); } } return fetchedServers; }

Target:
consider !existingServes.isEmpty()
Source:
public static String sanitizeSecondCachedKey(final Contentlet vanityUrl) throws DotDataException, DotRuntimeException, DotSecurityException { Host host = hostAPI.find(vanityUrl.getStringProperty(VanityUrlContentType.SITE_FIELD_VAR), APILocator.systemUser(), false); return sanitizeSecondCacheKey(host.getIdentifier(), vanityUrl.getLanguageId()); }

Target:
![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') Remove the redundant '!unknownSymbol!' thrown exception declaration(s). [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://sonarcloud.io/coding_rules#rule_key=squid%3ARedundantThrowsDeclarationCheck)
Source:
void remove(I key) { Integer prev = this.identityMap.remove(key); if (prev != null) this.objectList.set(prev, null); }

Target:
please keep the body of an `if` on its own line
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof TaskPropertyType)) { return false; } TaskPropertyType that = (TaskPropertyType) o; if (!name.equals(that.name)) { return false; } return true; }

Target:
This is always FALSE. since name is `static final`
Source:
protected long obtainEntityId() { return nextEntityId++; }

Target:
This could be `private` right?
Source:
public void markInCatalog() { exportLog.info("ExportDataSource for table " + m_tableName + " partition " + m_partitionId + " marked as in catalog."); m_isInCatalog = true; }

Target:
I'm not sure that this INFO message is helpful to users.
Source:
private static boolean canConvert(ParameterDefinition def, ParameterValue v) { return def instanceof SimpleParameterDefinition && !(def instanceof StringParameterDefinition) && v instanceof StringParameterValue; }

Target:
This results conversion will be applyed also to subclass of `StringParameterValue`. It would be better applied to exact `StringParameterValue`.
Source:
public void setUp() { deviceHandler = new EventHandlerTest(); passingHandler = new FilterHandler(); filtingHandler = new FilterHandler(); filtingHandler.setFilterInvalid(true); filtingHandler.setFilterZero(true); filtingHandler.setFilterDuplicate(true); filtingHandler.setFilterFuture(true); filtingHandler.setFilterApproximate(true); filtingHandler.setFilterStatic(true); filtingHandler.setFilterDistance(10); filtingHandler.setFilterLimit(10); }

Target:
Why are you using `EventHandlerTest` here? It has nothing to do with filtering.
Source:
public void download(String url, String downloadPath) { InputStream in = null; try { in = new URL(url).openStream(); FileUtils.writeByteArrayToFile(new File(downloadPath), IOUtils.toByteArray(in)); System.out.println(IOUtils.toString(in)); } catch (IOException e) { log.error(e); } finally { IOUtils.closeQuietly(in); } }

Target:
The connector setup should fail when an exception occurs.
Source:
private boolean getOldChildStale(IObservable child) { Boolean oldChildValue = staleMap.get(child); boolean oldChildStale = oldChildValue == null ? false : oldChildValue .booleanValue(); return oldChildStale; }

Target:
Simpler: oldChildValue != && oldChildValue.booleanValue()
Source:
public void invoke(@NotNull final Project project, final Editor editor, PsiFile file, DataContext dataContext) { if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) return; if (editor.getSettings().isVariableInplaceRenameEnabled()) { final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor); if (templateState != null && !templateState.isFinished()) return; } performAction(new GoIntroduceOperation(project, editor, file)); }

Target:
Add tooltip
Source:
private List<String> getListOfIsoFiles(File directory, OVirtNodeInfo info) { List<String> isoFileList = new ArrayList<String>(); File[] filterOvirtFiles = filterOvirtFiles(directory, getIsoPattern(info)); for (File file : filterOvirtFiles) { isoFileList.add(file.getName()); } return isoFileList; }

Target:
but you removed the static from there as well.
Source:
EWAHCompressedBitmap getBitmap() { // Fast path to immediately return the expanded result. Object r = bitmapContainer; if (r instanceof EWAHCompressedBitmap) return (EWAHCompressedBitmap) r; // Expand the bitmap and cache the result. XorCompressedBitmap xb = (XorCompressedBitmap) r; EWAHCompressedBitmap out = xb.bitmap; while (true) { r = xb.xorBitmap.bitmapContainer; if (r instanceof EWAHCompressedBitmap) { bitmapContainer = out = out.xor((EWAHCompressedBitmap) r); return out; } xb = (XorCompressedBitmap) r; out = out.xor(xb.bitmap); } }

Target:
nit: jgit spells this for (;;)
Source:
public AbstractCorrelatingMessageHandler(MessageGroupProcessor processor, MessageGroupStore store, CorrelationStrategy correlationStrategy, ReleaseStrategy releaseStrategy) { Assert.notNull(processor); Assert.notNull(store); setMessageStore(store); this.outputProcessor = processor; this.correlationStrategy = correlationStrategy == null ? new HeaderAttributeCorrelationStrategy(IntegrationMessageHeaderAccessor.CORRELATION_ID) : correlationStrategy; this.releaseStrategy = releaseStrategy == null ? new SequenceSizeReleaseStrategy() : releaseStrategy; super.messagingTemplate.setSendTimeout(DEFAULT_SEND_TIMEOUT); sequenceAware = this.releaseStrategy instanceof SequenceSizeReleaseStrategy; }

Target:
??? `this.` of course. That's why I said to revert those all changes for the `messagingTemplate` and PR is becoming clear
Source:
public Statement createBootstrapScriptForGroup(String group, @Nullable String nodeName) { return groupToBootScript.apply(group, null); }

Target:
Hmmm this is wrong now? There should be two methods, one passing null and the other one passing the nodeName.
Source:
public boolean create(Personname personnameRecord) { LOG.trace("PersonnameDAO.create() - Begin"); boolean result = true; if (personnameRecord != null) { result = super.create(personnameRecord); } LOG.trace("PersonnameDAO.create() - End"); return result; }

Target:
No need for result variable
Source:
public void handleInvocation(EJBClientInvocationContext context) throws Exception { log.info("In the client interceptor handleInvocation : " + this.getClass().getName() + " " + context.getViewClass() + " " + context.getLocator()); context.getContextData().put("ClientInterceptorInvoked", this.getClass().getName() + " " + context.getViewClass() + " " + context.getLocator()); // Must make this call context.sendRequest(); }

Target:
Please only log at debug or trace
Source:
public void edit(final NewExternalSubnetModel subnet) { driver.edit(subnet); if (subnet.getNetwork().getEntity() != null){ networkEditor.asValueBox().setValue(subnet.getNetwork().getEntity().getName()); } }

Target:
If I'm not mistaken, it shouldn't be possible for subnet.getNetwork() to be null, so you can drop the check.
Source:
protected AddVmFromTemplateCommand<AddVmParameters> createCommand() { initVM(); AddVmParameters param = new AddVmParameters(vm); return new AddVmFromTemplateCommand<>(param, null); }

Target:
this is probably simple enough to be inlined...
Source:
public void testGetNameFromPath() { String path1 = "/group1"; String path2 = "/group1/group2/group3"; String emptyPath = ""; String nullPath = null; String rootPath = "/"; assertEquals(HDF5Utils.getNameFromPath(path1), "group1"); assertEquals(HDF5Utils.getNameFromPath(path2), "group3"); assertEquals(HDF5Utils.getNameFromPath(emptyPath), ""); assertNull(HDF5Utils.getNameFromPath(nullPath)); assertEquals(HDF5Utils.getNameFromPath(rootPath), ""); }

Target:
Please split this test into several, testing each case separately.
Source:
@Override public GlusterLocalLogicalVolumeListReturn glusterLogicalVolumeList() { JsonRpcRequest request = new RequestBuilder("GlusterHost.logicalVolumeList").build(); Map<String, Object> response = new FutureMap(this.client, request).withIgnoreResponseKey(); return new GlusterLocalLogicalVolumeListReturn(response); }

Target:
Coding conventions: Let's have the @Override on its own line please
Source:
public String toString() { return "TypedByteArray[length=" + length() + "]"; }

Target:
needs `@Override`
Source:
public void onEntityDestroyed(EntityRef entity) { if (!entity.isPersistent()) { return; // ignore } entityDeltas.remove(entity.getId()); destroyedEntities.add(entity.getId()); }

Target:
Not an issue, but could be rewritten as ``` java if (entity.isPersistent()) { // do stuff } ``` to avoid multiple points of return from the method (and save a line of code).
Source:
private OrganizationalUnit getOU( String ouIdentifier, Collection<OrganizationalUnit> organizationalUnits ) { Optional<OrganizationalUnit> targetOU = organizationalUnits.stream() .filter( p -> p.getIdentifier().equalsIgnoreCase( ouIdentifier ) ).findFirst(); if ( targetOU.isPresent() ) { return targetOU.get(); } return null; }

Target:
Isn't this use of `Optional` and returning `null` contradictory? Surely checking `isPresent(..)` in `getDefaultOrganizationalUnit(..)` would be better?
Source:
public void testPutAsync() throws Exception { // put Future<String> f = c.putAsync("k", "v"); testFuture(f, null); testK("v"); f = c.putAsync("k", "v2"); testFuture(f, "v"); assertEquals("v2", c.get("k")); }

Target:
to keep code consistency, you may use `testK("v2");`
Source:
public boolean isReady(TaskActionClient taskActionClient) throws Exception { return false; }

Target:
should this return true instead ?
Source:
static Map<String, EntryValue> convertBeanToEntryMap(Object bean) { Map<String, Object> buildAttributeValueMap = BeanUtilsExtended.buildObjectAttributeMap(bean); return Maps.transformEntries(buildAttributeValueMap, new ObjectToEntryValueTransformer()); }

Target:
why not public
Source:
public RequestHeader(Struct struct, short headerVersion) { this.data = new RequestHeaderData(struct, headerVersion); this.headerVersion = headerVersion; }

Target:
nit: replace with `this(new RequestHeaderData(struct, headerVersion), headerVersion)`. Consolidates c'tor logic to one place.
Source:
public void accountSession(String username, String password) throws TmdbInvalidParametersException { if (username == null || password==null) throw new TmdbInvalidParametersException(401,"Username and Password may not be null"); this.username = username; this.password = password; hasAccountSession = true; }

Target:
Please add braces to conditionals (like `if { }`).
Source:
public void setProjectName(String projectName) { fProjectName = projectName; // If remote directory field is empty if(fLocationText.getText().equals(EMPTY_STRING)) { fRemoteDirSelected = false; } // If remote directory was not selected yet if (fRemoteDirSelected == false) { fLocationText.setText(getDefaultPathDisplayString()); } }

Target:
Use if (!fRemoteDirSelected) {
Source:
public void testAddChildCycle3() { assertNotNull(fFixture); assertNotNull(f42Fixture); assertNotNull(fHiFixture); ((CalledFunction) f42Fixture).addChild(fHiFixture); assertEquals(Collections.singletonList(fHiFixture), f42Fixture.getChildren()); }

Target:
unreachable. Maybe you should remove.
Source:
private char formatFieldFirstCharacterToFitDroolsCoreStandards(final String fieldName) { if (fieldName.length() > 2 && Character.isLowerCase(fieldName.charAt(0)) && Character.isUpperCase(fieldName.charAt(1))) { return fieldName.charAt(0); } else { return Character.toUpperCase(fieldName.charAt(0)); } }

Target:
I think the condition needs top start as `fieldName.length() > 1` instead of `fieldName.length() > 2 `. I think the generated code getters/setters has same rules for fields **aField** and **aF**. Or am I wrong?
Source:
public void start() { logger.debug("start()"); for (final Class<?> stepDefinitionType : cachedStepsInstances.keySet()) { cachedStepsInstances.put(stepDefinitionType, createStepsInstance(stepDefinitionType)); } }

Target:
Are these logging statements really needed?
Source:
private WorkingSetDescriptor getSelectedWorkingSet() { IStructuredSelection selection = typesListViewer.getStructuredSelection(); WorkingSetDescriptor descriptor = null; if (!selection.isEmpty()) { descriptor = (WorkingSetDescriptor) selection.getFirstElement(); } return descriptor; }

Target:
I don't have the code now but if the contract od sselection is to return null on getFirstElement() if sselection is empty, the code can be changed to simply return the first element, without the if.
Source:
public void evaluate() throws Throwable { if (null != previous) { previous.evaluate(); } for (FrameworkMethod before : befores) { before.invokeExplosively(target); } next.evaluate(); }

Target:
Is it reasonable for the caller to pass in a null value for previous into the constructor? If not, then the constructor should throw a `NullPointerException` if it is null.
Source:
public Response add(OpenStackVolumeProvider provider) { validateParameters(provider, "name"); StoragePool storagePool = provider.isSetDataCenter() ? getStoragePool(provider.getDataCenter()) : new StoragePool(); provider.setDataCenter(DataCenterMapper.map(storagePool, null)); return performCreate( VdcActionType.AddProvider, new ProviderParameters(map(provider)), new QueryIdResolver<Guid>(VdcQueryType.GetProviderById, IdQueryParameters.class) ); }

Target:
It is a bit weird to create here an empty "StoragePool" to indicate that there is no storage pool to use. Can't we just pass "null" to the backend in that case?
Source:
protected void doStoreUsers() { try { usersFileManager.store(new UsersDto(new HashSet<>(userMap.values()))); } catch (IOException e) { throw new UndeclaredThrowableException(e); } }

Target:
private
Source:
public void tearDown() throws IOException, SQLException { try { globalScheduler.shutdown(); } catch (Exception e) { } cleanup(); tearDownOnce(); }

Target:
Why is this needed now?
Source:
private CloudMachineNamer getCloudMachineNamer(ConfigBag config) { String namerClass = config.get(LocationConfigKeys.CLOUD_MACHINE_NAMER_CLASS); if (namerClass != null) { try { return (CloudMachineNamer) getManagementContext().getCatalog().getRootClassLoader().loadClass(namerClass) .getDeclaredConstructor(ConfigBag.class).newInstance(config); } catch (Exception e) { throw Exceptions.propagate(e); } } else { return new JcloudsMachineNamer(getAllConfigBag()); } }

Target:
This shouldn't call `getAllConfigBag()`. It should use the `config` passed in, otherwise we lose the local values passed in to the obtain() method. Do you agree?
Source:
public IllustratedSelectItem(Object value, String label, String image) { super(value, label); this.image = image; }

Target:
Missing JavaDoc.
Source:
private boolean layerGroupContainmentCheckRequired() { // first, is it WMS? Request request = Dispatcher.REQUEST.get(); if(request == null) { return false; } // layer groups are used only in WMS final String service = request.getService(); boolean isMapService = "WMS".equalsIgnoreCase(service) || "gwc".equalsIgnoreCase(service); if(!isMapService) { return false; } return true; }

Target:
The last six lines can be squashed into: return "WMS".equalsIgnoreCase(service) || "gwc".equalsIgnoreCase(service);
Source:
public ResteasyUriInfo(final String absoluteUri, final String contextPath, final InitData initData) { initialize(absoluteUri, contextPath, InitData.canBeCached(absoluteUri) ? initData : null); }

Target:
I would do this instead: ``initialize(absoluteUri, contextPath, (initData != null && InitData.canBeCached(absoluteUri)) ? initData : null);`` IOW, no point in spending time on checking if the cache can be used if there's no ``initData`` provided.
Source:
private void buildUnaryExpression(UnaryExpressionTree tree) { if(tree.is(Tree.Kind.PREFIX_DECREMENT, Tree.Kind.PREFIX_INCREMENT)) { build(tree.expression()); currentBlock.elements.add(tree); } else { currentBlock.elements.add(tree); build(tree.expression()); } }

Target:
@benzonico The fact that postfix operators return value before modification shouldn't change order in CFG, because loading of value should anyway happen before operation, i.e. order should be the same.
Source:
public Class getRealClass() { return testNGMethod.getRealClass(); }

Target:
Class<?>
Source:
private KeyStore getSecretsStore() { final File secretStoreFile = createStoreIfNeeded(); try { final KeyStore keyStore = KeyStore.getInstance(SECRETS_STORE_KEYSTORE_TYPE); try (InputStream inputStream = Files.newInputStream(secretStoreFile.toPath())) { keyStore.load(inputStream, loadStorePassword()); } return keyStore; } catch (Exception e) { Logger.warn(this.getClass(), "unable to load secrets store " + SECRETS_STORE_FILE + ": " + e); throw new DotRuntimeException(e); } }

Target:
Good it is the way
Source:
public AnonymousSpec anonymous(){ if (this.anonymous == null) { this.anonymous = new AnonymousSpec(); } return this.anonymous.authorities("ROLE_USER"); }

Target:
This should be ROLE_ANONYMOUS. However given the defaults in AnonymousSpec you should just delete it
Source:
public int getNumWaiters() { return this.connectionPool.getNumActive(); }

Target:
```suggestion return this.connectionPool.getNumWaiters(); ```
Source:
private void store() throws IOException { byte[] serialized = state.toCbor().serialize(); System.out.println("Writing "+ serialized.length +" bytes to "+ statePath); Files.write( statePath, serialized, StandardOpenOption.CREATE); }

Target:
can we do this atomically?
Source:
private static void initFacets(@CheckForNull Fingerprint fingerprint){ if (fingerprint==null) return; for (FingerprintFacet facet : fingerprint.facets) facet._setOwner(fingerprint); }

Target:
Please add curlies here
Source:
public Map<FactoryContainer, Attributes> getEnabledContainers() { Map<FactoryContainer, Attributes> map = new LinkedHashMap<>(); synchronized(_path) { for (Entry<FactoryContainer, Attributes> entry : getReversed(_path.entrySet())) { Attributes attr = entry.getValue(); if (attr.isEnabled()) { Attributes attrClone = new Attributes(attr); map.put(entry.getKey(), attrClone); } } } return map; }

Target:
For clarity it's preferable: Map.Entry
Source:
private FileListCacheValue getFileList() { readLock.lock(); try { FileListCacheValue fileList = (FileListCacheValue) cache.get(fileListCacheKey); if (fileList == null) { fileList = new FileListCacheValue(); FileListCacheValue prev = (FileListCacheValue) cache.putIfAbsent(fileListCacheKey, fileList); if (prev != null) { fileList = prev; } } if (trace) log.trace("Refreshed file listing view"); return fileList; } finally { readLock.unlock(); } }

Target:
I'm concerned about this lock.. it doesn't seem necessary as each operation invoking this private method is guarded already, and whenever a thread needs to acquire two locks I have an alarm bell ringing in my head.
Source:
public long size() { build(); return body.length() + partBoundary.length + partHeader.length; }

Target:
What happens when one of these `TypedOutput` instances return `-1` because they don't know their length?
Source:
public boolean canStreamToNextPipe() { return super.canStreamToNextPipe() && !isCollectResults(); // when collectResults is false, streaming is not necessary or useful }

Target:
Performance gezien is het natuurlijk handiger eerst een boolean check te hebben en dan extra logica..
Source:
public FoundViewHolder getFoundViewHolder(JFieldRef idRef, AbstractJClass viewClass) { String idRefString = idRef.name(); FoundViewHolder foundViewHolder = (FoundViewHolder) foundHolders.get(idRefString); if (foundViewHolder == null) { foundViewHolder = createFoundViewAndIfNotNullBlock(idRef, viewClass); foundHolders.put(idRefString, foundViewHolder); } return foundViewHolder; }

Target:
Where do you handle this now?
Source:
public void tearDown() { try { queryRunner.close(); } finally { queryRunner = null; } }

Target:
`finally` is not really needed. If `close` throws the test will fail anyway and we won't care whether `queryRunner` is `null` or not.
Source:
private CommitConfig(Config rc) { commitTemplatePath = rc.getString(ConfigConstants.CONFIG_COMMIT_SECTION, null, ConfigConstants.CONFIG_KEY_COMMIT_TEMPLATE); String i18nCommitEncoding = rc.getString( ConfigConstants.CONFIG_SECTION_I18N, null, ConfigConstants.CONFIG_KEY_COMMIT_ENCODING); if (i18nCommitEncoding != null) { commitMessageEncoding = Charset.forName(i18nCommitEncoding); } }

Target:
What if this throws an exception? Should probably be mapped to a ConfigInvalidException, and the caller should report the error.
Source:
public int decompress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength) throws MalformedInputException { try { Inflater inflater = new Inflater(true); inflater.setInput(input, inputOffset, inputLength); int resultLength = inflater.inflate(output, outputOffset, maxOutputLength); inflater.end(); return resultLength; } catch (DataFormatException e) { throw Throwables.propagate(e); } }

Target:
What's broken (add some details in the commit message)? This is not very obvious.
Source:
public List<OutputLine> getLog() { return this.log; }

Target:
we should return an ImmutableList if we don't intend for users of this method to edit the list.
Source:
protected void doInit() { super.doInit(); if (!this.evaluationContextSet) { this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory()); } Assert.state(this.closeStreamAfterSend ? this.isSingleUse : true, "Single use connection needed with closeStreamAfterSend"); }

Target:
`!this.closeStreamAfterSend || this.isSingleUse` ?
Source:
public ExtensionElementsConverter(XStream xStream, List<DMNExtensionRegister> extensionRegisters) { super(xStream); this.extensionRegisters = new ArrayList<DMNExtensionRegister>(); if(extensionRegisters != null && extensionRegisters.size() > 0) this.extensionRegisters.addAll(extensionRegisters); }

Target:
I'm reworking this code in the context of the class, also to avoid potential NPE if the extensionRegisters field might have not been initialized, from the no-args constructor.
Source:
public void executeBatch(OperationsQueue operationsQueue) { log.tracef( "Executing batch" ); try { if ( GridDialects.hasFacet( getGridDialect(), BatchableGridDialect.class ) || GridDialects.hasFacet( getGridDialect(), GroupingByEntityDialect.class ) ) { super.executeBatch( operationsQueue ); } } catch ( TupleAlreadyExistsException taee ) { // TODO: Ideally, we should log the entity name + id here; For now we trust the datastore to provide this // information via the original exception; It'd require a fair bit of changes to obtain the entity name here // (we'd have to obtain the persister matching the given entity key metadata which in turn would require // access to the session factory which is not easily available here) throw log.mustNotInsertSameEntityTwice( taee.getMessage(), taee ); } }

Target:
Maybe we should move that inside the `if` body, since we won't always execute the batch... ?
Source:
public int hashCode() { return (((startCommit.hashCode() * 31) + numbers.length) * 31) + getNumber(); }

Target:
nit-pick: startCommit.hashCode can just be xored/added in since it is well distributed
Source:
private void prepareAuthForBrokerCall() throws NoSuchAlgorithmException { AuthenticationSettings.INSTANCE.setUseBroker(true); }

Target:
can this function now throw NoSuchAlgorithmException
Source:
public boolean isWrapperFor(Class<?> iface) { if (gridCoverage instanceof Wrapper) return ((Wrapper) gridCoverage).isWrapperFor(iface); else if (iface.isInstance(gridCoverage)) return true; else return false; }

Target:
I woudl remove this else, if the gridCoverage is a wrapper and says "false" but iface is "GridCoverage2D" you want to fall back on the isInstance check anyways.
Source:
DataSegment uploadDataSegment( DataSegment segment, final int binaryVersion, final long size, final File compressedSegmentData, final String azurePath ) throws StorageException, IOException, URISyntaxException { azureStorage.uploadBlob(compressedSegmentData, config.getContainer(), azurePath); final DataSegment outSegment = segment .withSize(size) .withLoadSpec(this.makeLoadSpec(new URI(azurePath))) .withBinaryVersion(binaryVersion); log.info("Deleting file [%s]", compressedSegmentData); compressedSegmentData.delete(); return outSegment; }

Target:
Would you change the log level to debug? it doesn't look worth to be the info level.
Source:
public EEFButtonLifecycleManager(EEFButtonDescription description, IVariableManager variableManager, IInterpreter interpreter, TransactionalEditingDomain editingDomain) { super(description, variableManager, interpreter, editingDomain); this.description = description; }

Target:
not done
Source:
private static boolean isProbablyLog4jFormatterLogger(MethodInvocationTree mit, String formatString) { return mit.symbol().owner().type().is(ORG_APACHE_LOGGING_LOG4J_LOGGER) && (!formatString.contains("{}") && formatString.contains("%")); }

Target:
useless parenthesis
Source:
void setMarker(TextMarker marker, int length) { this.marker = marker; numSkipLines = length; if (checkAndUpdateArrows()) { upArrow.setHTML(PatchUtil.M.expandBefore(NUM_ROWS_TO_EXPAND)); downArrow.setHTML(PatchUtil.M.expandAfter(NUM_ROWS_TO_EXPAND)); } skipNum.setText(PatchUtil.C.patchSkipRegion(Integer .toString(length))); }

Target:
PatchUtil.M
Source:
public ExtendedEmailPublisherContext(ExtendedEmailPublisher publisher, AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { this.publisher = publisher; this.run = build; this.workspace = build.getWorkspace(); this.launcher = launcher; this.listener = listener; }

Target:
Wouldn't be better to directly call the new constructor? Just for easier maintenance in the future.
Source:
public void testWrongFormatNumber() throws Exception { NumberCellEditor editor; editor = new NumberCellEditor(shell, Integer.class); //empty string editor.setValue(" "); editor.getValue(); assertNull(editor.getValue() ); //not parsable number editor.setValue("aa"); editor.getValue(); assertNull(editor.getValue() ); }

Target:
this might be obsolete if `isValueValid`is implemented...
Source:
public void onReloadPlugin(Plugin oldPlugin, Plugin newPlugin) { if (hasAvatarProvider(newPlugin)) { avatarSupport = true; } else { if (avatarSupport && hasAvatarProvider(oldPlugin)) { avatarSupport = false; } } }

Target:
else if on one line.
Source:
public Class getRealClass() { return clazz; }

Target:
`Class<?>`
Source:
private String read(String resourcePath) throws IOException { InputStream is = getClass().getResourceAsStream(resourcePath); try { return Util.read(is); } finally { if (is != null) { is.close(); } } }

Target:
I suppose close() is already done in Util.read(..)
Source:
public static String getModelFileWithGAV(ReleaseId releaseId) { ReleaseIdImpl releaseIdImpl = (ReleaseIdImpl) releaseId; return Paths.get(MODEL_FILE_DIRECTORY, releaseIdImpl.getGroupId(), releaseIdImpl.getArtifactId(), releaseIdImpl.getVersion(), MODEL_FILE_NAME).toString(); }

Target:
I don't see why I need this cast. The group and artifact IDs are accessible even at interface level. Also the version is accessible, but I don't think you should add it here: this is for multimodule project compilaton and afaik you cannot have different modules with same GA and different version in the same project.
Source:
void removeConnection(String connectionId) { if (availableConnections.remove(connectionId)) { availableCount--; } poolCount--; }

Target:
This operation can be O(n), though the size of the list may be small. Making sense to use a set instead?
Source:
private Map<Long, ISegmentAspect> getAspectsFromColumnsId(List<Long> desiredColumns) { Map<Long, ISegmentAspect> aspects = new LinkedHashMap<>(); if (!desiredColumns.isEmpty()) { for (Long columnsId : desiredColumns) { ISegmentAspect segmentAspect = fAspectMap.get(columnsId); if (segmentAspect != null) { aspects.put(columnsId, segmentAspect); } } return aspects; } return fAspectMap; }

Target:
return before instantiating the map?
Source:
static boolean isValidMining(ICodeMining mining) { return Objects.nonNull(mining) && mining.getLabel() != null && !mining.getLabel().isEmpty(); }

Target:
Why Objects.nonNull instead of != null?
Source:
public void addInput(Page page) { verify(probe == null); probe = page; probePosition = 0; joinAddresses = null; joinAddressIndex = 0; }

Target:
`-1` would be more correct. AFAIC you can skip this.
Source:
public DescriptorImpl() { super(ThrottleJobProperty.class); synchronized(propertiesByCategoryLock) { load(); // Explictly drop queue items loaded from 1.8.1 version if (!propertiesByCategory.isEmpty()) { propertiesByCategory = new HashMap<String,Map<ThrottleJobProperty,Void>>(); save(); // Save the configuration to remove obsolete data } } }

Target:
Simpler to just rename the field. Then XStream will discard the old data automatically.
Source:
public String toString() { // Since the static data arrives from external source it's not guarenteed not to be null so a null check is // mandatory in order to avoid NPE when invoking toString by the logger String domainName = staticData.getName() == null ? "null" : staticData.getName(); String domainId = staticData.getId() == null ? "null" : staticData.getId().toString(); return "StorageDomain[" + domainName + ", " + domainId + "]"; }

Target:
you don't need this. the "+" operator does this for you.
Source:
Predicate<Entry<Key,Value>> getScanPredicate() { final Range range = getRange(); return input -> { if (range != null && !range.contains(input.getKey())) return false; return true; }; }

Target:
Can this be simplified to: ```java return input -> range == null || range.contains(input.getKey()); ```
Source:
public AlluxioHiveMetastore(TableMasterClient client) { requireNonNull(client, "client is null"); this.client = client; }

Target:
nit ```java this.client = requireNonNull(client, "client is null");
Source:
private void addWorkPackageCriteria() { if (isWorkPackageSpecified()) { ArtifactId workPackArt = atsApi.getQueryService().getArtifactOrSentinel(workPackageId); if (isColorTeamMatch(workPackArt)) { if (workPackArt.isValid()) { queryAnd(AtsAttributeTypes.WorkPackageReference, workPackArt.getIdString()); } } } }

Target:
Should this be above "isColorTeamMatch"? For example, on line #755.
Source:
private void sendToSocket(Socket socket, String cmdString) throws IOException { // remove spaces at beginning and end and replace double spaces in // string with single space byte[] sendBytes = ("A" + cmdString.trim().replaceAll("\\s+", " ") + "\n").getBytes(); socket.getInputStream().skip(tcpSocket.getInputStream().available()); socket.getOutputStream().write(sendBytes); socket.getOutputStream().flush(); AstericsErrorHandling.instance.reportInfo(this, "IRTrans sent data: " + cmdString); }

Target:
you directly use the member variable tcpSocket, but shouldnt it be the parameter socket?
Source:
public int hashCode() { return getClass().hashCode(); }

Target:
can you explain why this is necessary?
Source:
private void reset() { setId( next = NO_ID ); }

Target:
i do not think we need to save this line better make it more readable
Source:
public String getActualDowntime() { return (actualDowntime == null) ? "(N/A)" : actualDowntime.toString() + "ms"; }

Target:
so now you can drop the "toString()"
Source:
String resolveTemplatePath(final Context context, final Writer writer, final RenderParams params, final String argument) { if (argument.contains("/")) { }else{ return (params.live) ? "/live/" + argument + "." + EXTENSION : "/working/" + argument + "." + EXTENSION; } }

Target:
@wezell , missing return statement... This is breaking when compiling the code
Source:
public DispoConfig findDispoConfig(DispoProgram program) { ArtifactReadable config = getQuery().fromBranch(program.getUuid()).andNameEquals("Program Config").getResults().getOneOrNull(); if (config == null) { DispoUtil.getDefaultConfig(); } return DispoUtil.configArtToConfigData(new DispoConfigArtifact(config)); }

Target:
andNameEquals is un-needed and probably undesired incase name ever changes
Source:
public boolean hasMatchingOpSig(String name, JavaOperationSigMask mask) { // Indexing on signatures optimises this type of request for (Entry<JavaOperationSignature, Set<String>> entry : operations.entrySet()) { if (mask.covers(entry.getKey())) { if (operations.get(entry.getKey()).contains(name)) { return true; } } } return false; }

Target:
This is wrong, should be `entry.getValue()`
Source:
IonSqlQueryBuilder(TypeManager typeManager) { this.typeManager = requireNonNull(typeManager, "typeManager is null"); }

Target:
Make these methods public since they are part of the public API of the class. If we want to restrict access to the class, we would make the class itself package private.
Source:
protected OperationController getOperationController() { return ocList.get(ThreadLocalRandom.current().nextInt(ocList.size())); }

Target:
Should we abstract this. I mean the way we choose the operation controller. What in case in future, we wish to choose the one which is less loaded compared to others?
Source:
public List<JDK> getJDKs() { if(jdks==null) jdks = new ArrayList<JDK>(); return jdks; }

Target:
So I believe the only way this could be null is if a configuration was saved without the <jdks> entry and then reloaded. I don't see how that could happen - but there may be some old version of Jenkins that could have done it. Would probably make sense to modify a `readResolve()` to set it to an empty list and remove this check and the theoretical possibility?
Source:
public boolean addAll(int index, Collection<? extends T> c) { Collection<T> uniqueValuesToAdd = getUniqueValues(c); if (uniqueValuesToAdd.isEmpty()) { return false; } try { return super.addAll(index, uniqueValuesToAdd); } catch (IndexOutOfBoundsException ioobException) { comparingSet.removeAll(uniqueValuesToAdd); throw new IndexOutOfBoundsException(); } }

Target:
same as above: please pass on the original exception so that we retain the stacktrace and message.
Source:
public Context getContext() { if (sdkName == null) { sdkName = this.getClass().getPackage().getName(); } return new Context("Sdk-Name", sdkName) .addData("Sdk-Version", SDK_VERSION); }

Target:
why sdk version hardcoded?
Source:
public void setSelectedDevices(List<StorageDevice> selectedDevices) { getStorageDevices().setSelectedItems(selectedDevices); }

Target:
Can this be protected. I assume only the ListModel is using it
Source:
private JsonObject toJson(Timer timer, TimeUnit rateUnit, TimeUnit durationUnit) { Snapshot snapshot = timer.getSnapshot(); JsonObject json = new JsonObject(); // Meter populateMetered(json, timer, rateUnit); // Snapshot double factor = 1.0 / durationUnit.toNanos(1); populateSnapshot(json, snapshot, factor); // Duration rate String duration = durationUnit.toString().toLowerCase(Locale.US); json.putString("durationRate", duration); return json; }

Target:
Why US?
Source:
protected void delete(LogEntry delegate, String reason, RequestContext context) throws ResourceDoesNotSupportOperationException { throw new UnsupportedOperationException("delete not supported"); }

Target:
Should be ResourceDoesNotSupportOperationException
Source:
protected void setConsumerBatchEnabled(boolean consumerBatchEnabled) { this.consumerBatchEnabled = consumerBatchEnabled; }

Target:
Why is this `protected` ? Are you going to detect this option internally by the `@RabbitListener(Handler)` method signature?
Source:
public int getLevel() { return data.optInt("toclevel"); }

Target:
old code seems to indicate this should be "level" not "toclevel"? Could be causing failure of getLevel() calls being compared in SectionsFetchTask.processResult?
Source:
private void setPagesRecycler(OnThisDayCard card) { if (card.pages() != null) { RecyclerAdapter recyclerAdapter = new RecyclerAdapter(card.pages(), card.wiki(), true, (Activity) this.getContext()); recyclerAdapter.setCallback(new ItemCallback()); pagesRecycler.setAdapter(recyclerAdapter); } else { pagesRecycler.setVisibility(GONE); } }

Target:
use getContext() instead of this.getContext() ?
Source:
public String getExtendedLabelForVSM(String providedShapeURI) { for (IConfigurationElement configurationElement : extensions) { String identifier = ((ExtensionHandle) configurationElement.getParent()).getSimpleIdentifier(); if (identifier != null && identifier.equals(providedShapeURI)) { return configurationElement.getAttribute(LABEL_ATTRIBUTE) + " - " + configurationElement.getNamespaceIdentifier(); //$NON-NLS-1$ } } return "Unknown URI"; //$NON-NLS-1$ }

Target:
Add a getExtendedLabelsForVSM(IConfigurationElement) method to avoid duplication
Source:
public void stopServer() { if (server instanceof GrizzlyServer) { ((GrizzlyServer) server).setCleanIdleConnections(); } server.stop(); }

Target:
I would not use setCleanIdleConnections as the name of the function without parmeters. Maybe add a parameter.
Source:
protected Supplier<Operation> createOperationSupplier() { return () -> new DistributedObjectDestroyOperation(parameters.serviceName, parameters.name); }

Target:
We can make `DestroyProxyMessageTask` implement the Supplier, so that this method will no create a lamda but return `this` instead.
Source:
public <C extends CtTypedElement> C setType(CtTypeReference<T> type) { if (type != null) { type.setParent(this); } // even if the setter delegates to getExecutable, it makes sense to create an event getFactory().getEnvironment().getModelChangeListener().onObjectUpdate(this, TYPE, type, getExecutable().getType()); if (getExecutable() != null) { getExecutable().setType(type); } return (C) this; }

Target:
So model change listener will be called twice for single modification? I do not like it. @monperrus Could you explain why it is good?
Source:
public static AuthenticationProfileRepository getInstance() { return instance; }

Target:
I do not understand the above two... but for ut it will be hell.
Source:
public HttpRequest filterKey(HttpRequest request) throws HttpException { request = replaceDateHeader(request); String signature = calculateSignature(createStringToSign(request)); request = replaceAuthorizationHeader(request, signature); return request; }

Target:
```suggestion ```
Source:
public ScreenshotSize get() { if (config.getScreenshotSize() == ScreenshotSize.DOUBLE_SIZE) { return ScreenshotSize.DOUBLE_SIZE; } else if (config.getScreenshotSize() == ScreenshotSize.NORMAL_SIZE) { return ScreenshotSize.NORMAL_SIZE; } else if (config.getScreenshotSize() == ScreenshotSize.HALF_SIZE) { return ScreenshotSize.HALF_SIZE; } else if (config.getScreenshotSize() == ScreenshotSize.QUARTER_SIZE) { return ScreenshotSize.QUARTER_SIZE; } else { return ScreenshotSize.NORMAL_SIZE; } }

Target:
Again, should just return the value if not null.
Source:
public String canonicalID() { return canonical; }

Target:
Why make this non-final? Given how important this method is for its serialization/internal representation, it's pretty important that it not be overridden.
Source:
protected void close() { try { m_sout.flush(); m_sout.close(); } catch (IOException ex) { } }

Target:
close does an implicit flush
Source:
protected boolean isProcessed(ChronicleLogOffsetTracker tracker, long offset) { long last = tracker.readLastCommittedOffset(); return (last > 0) && (last >= offset); }

Target:
No need for parentheses.
Source:
public EList<Diff> getDifferences() { return new BasicEList<Diff>(this.diffs); }

Target:
Please don't create a new list on every call of getDifferences(), but create the list once, e.g., on the first call, and then return the same instance. You might want to use an UnmodifiableEList instead, to fail early, if someone tries to modify it.
Source:
public IOWorkers.Selector getWorkerSelector() { return workerSelector; }

Target:
@clevertension Why do we need to expose `IOWorkers.Selector`? Looks completely unnecessary to me.
Source:
public Iterable<Tree> children() { List<Tree> result = new ArrayList<>(); if(openParenToken != null) { result.add(openParenToken); } for (Tree tree : super.children()) { result.add(tree); } if(closeParenToken != null) { result.add(closeParenToken); } return result; }

Target:
`super.children().forEach(res::add);` ?
Source:
public void setName(String name) { Objects.requireNonNull(name); this.name = name; }

Target:
`requireNonNull` could be on same line than affectation.
Source:
public Query existsQuery(QueryShardContext context) { if (hasDocValues()) { return new DocValuesFieldExistsQuery(name()); } else if (omitNorms()) { return new TermQuery(new Term(FieldNamesFieldMapper.NAME, name())); } else { return new NormsFieldExistsQuery(name()); } }

Target:
I believe it should be `omitNorms() || indexOptions() != IndexOptions.NONE`
Source:
private void handleYieldExpression(SubscriptionContext ctx, PyYieldExpressionTree yieldExpr) { if (yieldExpr.fromKeyword() == null && yieldExpr.expressions().size() == 1) { yieldExpr.expressions().forEach(e -> checkExpr(e, ctx, "yield")); } }

Target:
This method should be static
Source:
private void importLdif(InMemoryDirectoryServer directoryServer) throws LDAPException { if (StringUtils.hasText(this.ldif)) { try { Resource resource = locateResource(); try (InputStream inputStream = resource.getInputStream()) { directoryServer.importFromLDIF(false, new LDIFReader(inputStream)); } } catch (Exception ex) { throw new IllegalStateException("Unable to load LDIF " + this.ldif, ex); } } }

Target:
We do not need to declare that this throws an `LDAPException`.
Source:
public XSSFTableColumn(XSSFTable table, CTTableColumn ctTableColumn) { this.table = table; this.ctTableColumn = ctTableColumn; }

Target:
I would insist in having all methods that use a `CT*` parameter to be annotated as `@Internal` when they are not private.
Source:
private boolean isDateSelectable(Date date) { if (isCheckDayInSelectableCals && !containsDate(selectableCals, date)) return false; return dateConfiguredListener == null || dateConfiguredListener.isDateSelectable(date); }

Target:
We'd use `{` and `}` here or just fold the conditional into a single `return` statement.
Source:
public void updatePathGroup(List<Variable> variables, IPath node, IPath selection) { final int segmentsSelection = selection.segmentCount(); for (final Variable variable : variables) if (variable.getPath().uptoSegment(segmentsSelection).equals(selection.makeAbsolute())) { final IPath oldPath = variable.getPath(); final int count = selection.segmentCount(); variable.setPath(buildPath(oldPath, node, count)); } }

Target:
make static