auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Diff getPrimeRefining() { Diff main = null; if (primeRefining != null) { main = primeRefining; } else { for (Diff refBy : this.getRefinedBy()) { if (refBy instanceof ReferenceChange) { ReferenceChange rc = (ReferenceChange)refBy; if (rc.getReference().isContainment() && (this.getDiscriminant() == rc.getValue())) { main = rc; break; } } } } return main; }

Target:
you should replace the test by (primeRefining == null) and execute statements from the else block. Then always return primeRefining field after the "if", the main local variable is not useful
Source:
StoreIndexDescriptor( StoreIndexDescriptor indexDescriptor ) { super( indexDescriptor ); this.id = indexDescriptor.id; this.owningConstraintId = indexDescriptor.owningConstraintId; this.name = indexDescriptor.name; }

Target:
This constructor should delegate to other constructor
Source:
public Void delete(@PathParam(RestParameter.ID) Long id) { ratingDao.delete(id); return null; }

Target:
You should return void instead of Void, so you won't have to return null
Source:
protected AbstractXmlApplicationContext createApplicationContext() { String version = Version.getCurrentVersion(); ClassPathXmlApplicationContext applicationContext = null; if (version.startsWith("2") && (version.contains("2.5") || version.contains("2.4"))) { applicationContext = new ClassPathXmlApplicationContext(new String("org/apache/camel/component/cxf/jaxrs/CxfRsSpringEndpointBeans.xml")); } else { applicationContext = new ClassPathXmlApplicationContext(new String("org/apache/camel/component/cxf/jaxrs/CxfRsSpringEndpointBeans-2.6.xml")); } emulateBeanRegistrationProgrammatically(applicationContext); return applicationContext; }

Target:
This version check could be removed as we already move to 2.6.x
Source:
private void handlePendingScenario(ITmfEvent event, boolean isInputValid) { if (fConsuming && isEventConsumed()) { return; } if ((fInitialStateId.equals(TmfXmlState.INITIAL_STATE_ID) || isInputValid) && fPendingScenario != null) { @NonNull TmfXmlScenario scenario = fPendingScenario; handleScenario(scenario, event); if (!scenario.isPending()) { addActiveScenario(scenario); fPendingScenario = null; } } }

Target:
You should extract to local variable before the if and use this variable to null-check in the if
Source:
public boolean isRestricted() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. }

Target:
Oops.
Source:
private Guid getTargetClusterId(Action action) { if (action.isSetCluster() && (action.getCluster().isSetId() || action.getCluster().isSetName())) { return getClusterId(action); } // means use the cluster of the provided host return null; }

Target:
I think that this check makes more sense in the "getClusterId" method. Can we move it there?
Source:
public Object[] factory() { List testsToRun = new ArrayList<>(); testsToRun.add(new DistributedMultimapCacheTest().fromOwner(false).cacheMode(CacheMode.DIST_SYNC).transactional(false)); testsToRun.add(new DistributedMultimapCacheTest().fromOwner(true).cacheMode(CacheMode.DIST_SYNC).transactional(false)); return testsToRun.toArray(); }

Target:
do you have any trouble with array initializers?
Source:
private boolean isNimbus(Subject who) { Set<Principal> principals = null; boolean isNimbusInstance = false; if (who != null) { principals = who.getPrincipals(); for (Principal principal : principals) { if (principal instanceof NimbusPrincipal) { isNimbusInstance = true; } } } return isNimbusInstance; }

Target:
unnecessary assignment, actually it can be moved into if
Source:
ILogData read(long address) { if (!runtime.getParameters().isCacheDisabled()) { // The VersionLockedObject and the Transaction layer will generate // undoRecord(s) during a transaction commit, or object sync. These // undo records are stored in transient fields and are not persisted. // A missing undo record can cause a NoRollbackException, thus forcing // a complete object rebuild that generates a "scanning" behavior // which affects the LRU window. In essence, affecting other cache users // and making the VersionLockedObject very sensitive to caching behavior. // A concrete example of this would be unsynchronized readers/writes: // 1. Thread A starts replicating write1 // 2. Thread B discovers the write (via stream tail query) and // tries to read write1 // 3. Thread B's read results in a cache miss and the reader thread // starts loading the value into the cache // 4. Thread A completes its write and caches it with undo records // 5. Thread B finishes loading and caches the loaded value replacing // the cached value from step 4 (i.e. loss of undo records computed // by thread A) ILogData data = readCache.getIfPresent(address); if (data == null) { final ILogData loadedVal = fetch(address); data = readCache.asMap().computeIfAbsent(address, (k) -> loadedVal); } return data; } return fetch(address); }

Target:
Return just here.
Source:
public void tearDown() { closeAllRuntimeException(queryRunner); queryRunner = null; }

Target:
Why not just `queryRunner.close();`?
Source:
public AuditLogType getAuditLogTypeValue() { UserProfile existingProfile = getUserProfile(); if (existingProfile != null && isSSHPublicKeyUpdate(existingProfile)) { return getSucceeded() ? AuditLogType.USER_UPDATE_PROFILE : AuditLogType.USER_UPDATE_PROFILE_FAILED; } else { return getSucceeded() ? AuditLogType.USER_ADD_PROFILE : AuditLogType.USER_ADD_PROFILE_FAILED; } }

Target:
since this method is called after the validate method, you can make the check shorter as you did in the executeCommand method
Source:
public ConfigurationBuilder getDefaultCacheBuilder() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.memory().storageType(StorageType.OFF_HEAP); // Off heap and compatibility don't work together configurationBuilder.compatibility().disable(); return configurationBuilder; }

Target:
Aren't there any test methods that require compatibility?
Source:
public boolean counter(String key, int magnitude) { String stat = String.format(Locale.ENGLISH, "%s:%d|c", key, magnitude); return maybeAppend(stat); }

Target:
UTF8?
Source:
public FunctionMetadata getFunctionMetadata(FunctionHandle functionHandle) { checkArgument(functionHandle.getCatalogSchemaName().equals(STATIC_FUNCTION_NAMESPACE_CATALOG_SCHEMA_NAME), "Expect static function namespace"); return staticFunctionNamespace.getFunctionMetadata((StaticFunctionHandle) functionHandle); }

Target:
Maybe a static helper function `isStaticFunctionNamespace(functionHandle)`; also, why not `functionHandle instanceof StaticFunctionHandle`?
Source:
public void waitForValueToBePresentInElementsAttributeByCss(String selector, String attribute, String value) { changeImplicitWait(250, TimeUnit.MILLISECONDS); try { waitFor.until(CommonExpectedConditions.valueToBePresentInElementsAttribute( By.cssSelector(selector), attribute, escapeHtml(value))); } finally { restoreDeaultImplicitWait(); } }

Target:
I don't think we should escape on this level, we should explicitly escape title of a video when passing to a method, not in here. Let's move it to `verifyVideoAdded(String videoTitle)` in `SpecialVideosPageObject`
Source:
public String parse() { StringBuilder myCommandBuilder = new StringBuilder(""); for (String argument:mArgs) { myCommandBuilder.append(argument+" "); } return myCommandBuilder.toString(); }

Target:
А вообще надо два append() делать
Source:
public void testUseMetaAfterCreate() throws IOException { DataFileWriter<?> w = new DataFileWriter<>(new GenericDatumWriter<>()); w.create(Schema.create(Type.NULL), new ByteArrayOutputStream()); w.setMeta("foo", "bar"); w.close(); }

Target:
Can we use a try-with-resource pattern here?
Source:
public LabelMetadataBuilder setOrigin(String origin) { this.origin = origin; return this; }

Target:
Is the fluent required here? could we just a have a basic setter instead?
Source:
public long cyclesToNanos(long cycles) { // CTFTrace adds the clock offset in cycles to the input CTFTrace trace = fTrace; if (trace != null) { CTFClock clock = trace.getClock(); return trace.timestampCyclesToNanos(cycles - trace.getOffset()) + clock.getClockOffsetNs(); } return 0; }

Target:
This method is a simple converter that is only dependent on frequency and not dependent on clock offset. It should return cycles * clock.getScale(), or cycles if clock is null.
Source:
private Document createDocument() { Document document = null; try { DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); document = documentBuilder.newDocument(); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } return document; }

Target:
dont do this but let the exception be propagated back up so we can have a better error reporting about not possible to generate jacoco report due to .... Also these methods can be static methods
Source:
public ConnectDocumentToLanguageServerSetupParticipant() { ITextFileBufferManager.DEFAULT.addFileBufferListener(new FileBufferListenerAdapter() { @Override public void bufferDisposed(IFileBuffer buffer) { Job job = locationMap.get(buffer.getLocation()); if (job != null) { job.cancel(); } locationMap.remove(buffer.getLocation()); } }); }

Target:
You can directly invoke Job job = locationMap.remove(buffer.getLocation()); if (job != null) { job.cancel(); }
Source:
public void createAndSetPhoneHome() { this.phoneHome = new PhoneHome(node); }

Target:
Can it be `protected`?
Source:
protected void verifySafeObject(final AnyObjectId id, final int type, final byte[] data) { try { super.verifySafeObject(id, type, data); } catch (CorruptObjectException e) { // catch the exception and continue parse the pack file CorruptObject o = new CorruptObject(id.toObjectId(), type, e.getErrorType()); corruptObjects.add(o); } }

Target:
Can simplify by avoiding the temporary: corruptObjects.add(new CorruptObject(...));
Source:
public KeyValuePairValidation() { this.allowAlsoKey = false; }

Target:
Nit-pick: to have more consistent constructor behavior, I'd prefer to do this(false)
Source:
public String getNameTokenWithClass() { if (nameTokenPsiClass == null) { return ""; } String s = nameTokenPsiClass.getName().replace(".java", "") + "." + nameToken; return s; }

Target:
nl and return directly
Source:
public void setGrantType(String grantType) { setProperty(GRANT_TYPE, grantType); }

Target:
the sole appropriate grantType must be an `stormpath_token` therefore please assert that the parameter is always `stormpath_token`. Additionally it should not be `public` (`protected` at the minimum), it should be just invoked internally when this class is created.
Source:
private static <T> void printIndented(Iterable<T> strings) { for (T extension : strings) { System.out.println(" " + extension); } }

Target:
other name (for example item) instead of extension?
Source:
public int getMaxDamage() { if (itemMaterial == null) { return 0; } else { return itemMaterial.getMaxDamage(); } }

Target:
Can be simplified to ```java return itemMaterial == null ? 0 : itemMaterial.getMaxDamage(); ```
Source:
public Response handle() throws Exception { ServerSideSession session = getDriver().getSession(getRequest().getSession()); JSONObject payload = getRequest().getPayload(); String type = payload.getString("type"); WebDriverLog log = (WebDriverLog) session.getLogManager().getLog(type); List<LogEntry> entries = (log == null ? null : log.getAndClearEntries()); return createResponse(entries); }

Target:
Return empty list (ImmutableList.of()), not null, if log == null
Source:
public Cursor selectAll() { return select("", new String[] {}, null); }

Target:
Could these params just be null, null, null?
Source:
public int getId() { try { return id; } catch (RuntimeException e) { throw logAndPrepareForRethrow(e); } catch (Error e) { throw logAndPrepareForRethrow(e); } catch (Throwable t) { throw logAndPrepareForRethrow(t); } }

Target:
Well I think at least here we do not need all this try/catch stuff ))
Source:
public ADBInfo(HashMap<String,String> env) { this.env = env; try { String dockerHost = env.get("DOCKER_HOST"); URI url = new URI(dockerHost); String h = url.getHost(); openshiftHost = "https://" + h; } catch(URISyntaxException murle) { murle.printStackTrace(); } }

Target:
Why should this be catched? Shouldn't this make it to the caller that then can react accordingly?
Source:
public void testStrlen() { assertExpr("strlen(x)", 3L); assertExpr("strlen(nonexistent)", NullHandling.defaultLongValue()); assertExprFail("strlen(a)", AssertionError.class, null); }

Target:
This test should be adjusted since you removed the strlen change.
Source:
public boolean deleteFile(File file, boolean recursive) { if (recursive) { return this.deleteRecursive(file); } return file.delete(); }

Target:
deleteFile(file)
Source:
public ArrayList<Brick> getBricksRequiringResources(int resource) { ArrayList<Brick> resourceBrickList = new ArrayList<Brick>(); for (Brick brick : brickList) { if ((brick.getRequiredResources() & resource) > 0) { resourceBrickList.add(brick); } } return resourceBrickList; }

Target:
> program to an interface, not to an implementation. Please use `List` instead of `ArrayList` everywhere. I'm just mentioning it here once.
Source:
public static ServerManager getInstance( final WorkspaceStatus wsStatus ) { if (instance == null) { instance = new ServerManager(); } instance.setWorkspaceStatus(wsStatus); return instance; }

Target:
Should this line be moved up into the above block where the `ServerManager` instance is being created? And maybe just code it like `instance.wsStatus = wsStatus` and get rid of the `setWorkspaceStatus` method. I am assuming the status would only need to be set whenever the server variable is `null`. Is that true?
Source:
public WebAccess addUserAgent(String userAgent) { if (Objects.nonNull(userAgent)) this.userAgent = userAgent; return this; }

Target:
Meiner Meinung nach ist die Überprüfung überflüssig. ```userAgent``` darf null sein und es mag auch Fälle geben, wo ein Request *ohne* userAgent gemacht werden soll. Die Abfrage ```addUserAgent(null)``` ist m.E. ein gültiger Verwendung.
Source:
public void setPromiscuousBinding(IBinding binding) { promiscuousBinding = binding; }

Target:
Make final.
Source:
public synchronized void clear() { fZoom.setFullRange(0L, 0L); fZoom.setNewRange(0L, 0L); fZoom.stop(); super.clear(); }

Target:
the null check is necessary because clear is called by the super class in the constructor.
Source:
public List<Object> getSortedObjects() { Set<Object> sorted = newSetFromMap(new LinkedHashMap<>(objectCount)); for (List<Object> bucket : buckets) { if (bucket != null) { sorted.addAll(bucket); } } return new ArrayList<>(sorted); }

Target:
what's the point of doing this?
Source:
public void setOS(String os) { incrementSequenceNumber(); fOS = os; if (fRoot != null && os != null && os.length() > 0) { Element nlNode = TargetDefinitionDocumentTools.getChildElement(fRoot, TargetDefinitionPersistenceHelper.ENVIRONMENT, TargetDefinitionPersistenceHelper.OS); nlNode.setTextContent(os); } else { removeElement(TargetDefinitionPersistenceHelper.ENVIRONMENT, TargetDefinitionPersistenceHelper.OS); } }

Target:
Please use !string.isEmpty().
Source:
public ScriptEntryData getScriptEntryData() { return new BukkitScriptEntryData( hitBy.isPlayer() ? hitBy.getDenizenPlayer() : (entity.isPlayer() ? entity.getDenizenPlayer() : null), hitBy.isCitizensNPC() ? hitBy.getDenizenNPC() : (entity.isCitizensNPC() ? entity.getDenizenNPC() : null) ); }

Target:
Stray doublenewline ^ Also the newlines on the individual parts I'm confused why this isn't formatted exactly the same as the EntityDamaged event, which I think is what you were referencing anyway? ```java return new BukkitScriptEntryData(damager != null && damager.isPlayer() ? damager.getDenizenPlayer() : entity.isPlayer() ? entity.getDenizenPlayer() : null, damager != null && damager.isCitizensNPC() ? damager.getDenizenNPC() : entity.isCitizensNPC() ? entity.getDenizenNPC() : null); ```
Source:
public Void visit(Boolean inTailPosition, New newExpr) { for (Declaration decl : newExpr.getDecls()) { decl.acceptVisitor(this, inTailPosition); } return null; }

Target:
This doesn't really matter because Val- and Var-Declaration pass "false" for inTailPosition, but it might be better conceptually to also pass "false" here.
Source:
public ReflectionMappers setColumnNameMatchers(List<ColumnNameMatcher> columnNameMatchers) { synchronized (lock) { this.columnNameMatchers.clear(); this.columnNameMatchers.addAll(columnNameMatchers); } return this; }

Target:
What's the expected benefit for this change? This method is typically called at most once per VM--let's prioritize simplicity for low-traffic methods like this.
Source:
private static MessageType getProjection(MessageType schema, Collection<SchemaPath> projectionColumns, List<SchemaPath> columnsNotFound) { projectionColumns = adaptColumnsToParquetSchema(projectionColumns, schema); List<SchemaPath> schemaColumns = getAllColumnsFrom(schema); Set<SchemaPath> selectedSchemaPaths = matchProjectionWithSchemaColumns(projectionColumns, schemaColumns, columnsNotFound); MessageType projection = convertSelectedColumnsToMessageType(schema, selectedSchemaPaths); return projection; }

Target:
nit: `projection` variable may be avoided.
Source:
private FileObject ingestFileObject(ContentObject parent, Resource parentResc, Resource childResc) throws DepositException, IOException { if (skipResumed(childResc)) { return null; } // TODO add ACLs WorkObject work = (WorkObject) parent; FileObject obj = addFileToWork(work, childResc); // Add ingestion event for file object addIngestionEventForChild(obj); addPremisEvents(obj); // add MODS addDescription(work); // Increment the count of objects deposited addClicks(1); log.info("Created file object for deposit {}", obj.getPid(), getDepositPID()); return obj; }

Target:
Can you remove the return types for ingest methods since they aren't being used now?
Source:
public int hashCode() { return hash(getHost(), getPort(), getPassword(), getUsername(), getNonProxyHosts(), ntlmDomain); }

Target:
shouldn't this be `hash(super.hashCode, ntlmDomain)`... if you do it like this, any changes in the super class will break here.
Source:
public void subscribe(Subscriber<? super RecordsRetrieved> s) { subscriber = s; ++subscriptionTryCount; s.onSubscribe(new Subscription() { @Override public void request(long n) { if (subscriptionTryCount == 1) { } else { send(n); } } @Override public void cancel() { requested = 0; } }); }

Target:
Would it be simpler to rewrite this block as just `if (subscriptionTryCount != 1)`?
Source:
protected static boolean canAttachPrestartedVmToUser(Guid vmId) { // check that there isn't another user already attached to this VM: boolean returnValue = !vmAssignedToUser(vmId, new java.util.ArrayList<String>()); // Make sure the Vm is running stateless returnValue = returnValue && vmIsRunningStateless(vmId); return returnValue; }

Target:
please remove the 'java.util.'
Source:
public void setInput(Object inputElement) { fInputElement = inputElement; ITimeGraphEntry[] input = fTimeGraphContentProvider.getElements(inputElement); synchronized (fListenerNotifierLock) { fListenerNotifier = null; } if (fTimeGraphCtrl != null) { setTimeRange(input); setTopIndex(0); fSelectionBegin = SWT.DEFAULT; fSelectionEnd = SWT.DEFAULT; fSelectedEntry = null; refreshAllData(input); } }

Target:
The state of the reference is part of "this" object. The monitor of "fListenerNotifierLock" should be used to cover states in that object, not in "this". You could remove the synchronized block here, and extract to a local variable below.
Source:
public void onAttachOrDetach(AttachEvent event) { if (event.isAttached()) { index = 0; displayCurrent(); $(contents).on(TRANSITION_END, new Function() { @Override public void f() { GQuery.console.log("TRANSITION_END"); activeAnimation = false; $("[data-remove]", contents).remove(); } }); } else { $(contents).off(TRANSITION_END); } }

Target:
You should remove console outputs for production
Source:
public int prepare(Xid xid) throws XAException { if (LOG.isTraceEnabled()) { LOG.trace("DummyXAResource.prepare(xid=" + xid + ")"); } return 0; }

Target:
can be info
Source:
public void update(RuleBaseElementId name, String newCode) throws RuleBaseException { RuleBaseElement newBean = new RuleBaseElement(name, newCode); Map<String, String> metaData = newBean.toMetadata(); RuleBaseConfiguration conf = new RuleBaseConfiguration(metaData, newBean); try { rulePersistence.persist(conf); } catch (PersistenceException e) { throw new RuleBaseException(e); } builder.reloadPackage(name.getPackageName()); }

Target:
Why not using here the Constructor where you only pass the RuleBaseElement?
Source:
@Override public Pair<SqlNode, RelDataType> validateAndGetType(SqlNode sqlNode) throws ValidationException { final SqlNode validatedNode = this.validate(sqlNode); final RelDataType type = m_validator.getValidatedNodeType(validatedNode); return Pair.of(validatedNode, type); }

Target:
superfluous `this`
Source:
public Object inject(Object instance) throws InjectionProviderException { return instance; }

Target:
I think this should just return null, similar to the default MyFaces implementation of InjectionProvider.
Source:
private void validateVnicMappings(Action action) { if (!(action.isSetVnicProfileMappings() && action.getVnicProfileMappings().isSetVnicProfileMappings())) { return; } action.getVnicProfileMappings().getVnicProfileMappings().forEach(this::validateVnicProfileMapping); }

Target:
please negate condition and move #121 into the 'then-clause'
Source:
public Drawable getDrawable(Context context) { final PackageManager packageManager = context.getPackageManager(); Resources resources; try { if (shortcutPojo.icon != null) { return new BitmapDrawable(shortcutPojo.icon); } resources = packageManager.getResourcesForApplication(shortcutPojo.packageName); final int id = resources.getIdentifier(shortcutPojo.resourceName, null, null); return resources.getDrawable(id); } catch (NameNotFoundException e) { } return null; }

Target:
you can try this from outside the try catch, before getting an instance to the packagemanager
Source:
protected boolean handlePreloadPackage(String packagePath, String libsPath) { Log.d(TAG, "Preload package ********************************************************"); Log.d(TAG, "WebView package = " + packagePath); return false; }

Target:
Dianne will tell you to remove this. This is logspam.
Source:
public boolean equals(Object o) { Grant grant = (Grant) o; if (!group.equals(grant.group)) return false; if (!pattern.equals(grant.pattern)) return false; return true; }

Target:
Style-nit: We don't cuddle onto the same line. But really isn't this shorter? Grant grant = (Grant)o; return group.equals(grant.group) && pattern.equals(grant.pattern);
Source:
public void onValueChanged(final Consumer<Event> onValueChanged) { input.onkeyup = null; input.onkeyup = event -> { onValueChanged.accept(event); return this; }; }

Target:
Is this two step handler change needed to avoid some memory leak? Isn't enough just to assign new value?
Source:
public boolean isEntryRemovedInContext(Object key) { throw new CacheException("This context is immutable"); }

Target:
So if the context is immutable why not just return false?
Source:
protected ITmfTreeColumnDataProvider getColumnDataProvider() { return () -> { return ImmutableList.of( createColumn(Messages.AbstractSegmentStoreScatterView_Type, Comparator.comparing(TmfGenericTreeEntry::getName)), new TmfTreeColumnData(Messages.AbstractSegmentStoreScatterView_Legend)); }; }

Target:
remove curly braces
Source:
public void buttonStateChanged(VRControllerState_t stateBefore, VRControllerState_t stateAfter, int handIndex) { cachedStateBefore = stateBefore; cachedStateAfter = stateAfter; queuedActions.add(new ControllerAction(InputType.CONTROLLER_BUTTON.getInput(ControllerId.X_AXIS), "OpenVR", ButtonState.DOWN, 1.0f)); if (handIndex == 0) { handleController0(); } else { handleController1(); } }

Target:
This seems odd here. What is this for?
Source:
protected void cancelled() { logger.debug("Subscriber cancelled, ignoring the rest of the body"); try { future.done(); } catch (Exception t) { // Never propagate exception once we know we are done. logger.error(t.getMessage(), t); } // The subscriber cancelled early - this channel is dead and should be closed. channelManager.releaseChannelLock(future.getPartitionKey()); channelManager.closeChannel(channel); channel.pipeline().remove(StreamedResponsePublisher.class); }

Target:
Now that we close the channel, I think it's useless to remove the publisher from the pipeline. The channel will be garbage collected.
Source:
public static List<String> getAuthenticatedUserRoles(IdentityProvider identityProvider) { List<String> roles = identityProvider.getRoles(); if (roles == null || roles.isEmpty()) { roles = new ArrayList<>(); roles.add(""); } return roles; }

Target:
There should be a null check on the identityProvider, prior to calling its getRoles method. Maybe something like... `List<String> roles = (identityProvider != null) ? identityProvider.getRoles():null;`
Source:
public void initializeDataSource(ITmfTrace trace) { TmfAbstractAnalysisModule module = createStatisticsAnalysiModule(); if (!(module instanceof AbstractSegmentStatisticsAnalysis)) { // null or not a segment analysis module return; } try { module.setTrace(trace); module.schedule(); if (fModule != null) { fModule.dispose(); } fModule = (AbstractSegmentStatisticsAnalysis) module; } catch (TmfAnalysisException e) { Activator.getDefault().logError("Error initializing statistics analysis module", e); //$NON-NLS-1$ } }

Target:
legacy extensions might not use abstractSegmentStatisticsAnalysis
Source:
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Bundle extras = intent.getExtras(); if (ACTION_AIRPLANE_MODE_CHANGED.equals(action)) { if (extras != null) { dispatchAirplaneModeChange(extras.getBoolean(EXTRA_AIRPLANE_STATE, false)); } } else if (CONNECTIVITY_ACTION.equals(action)) { dispatchNetworkStateChange(connectivityManager.getActiveNetworkInfo()); } }

Target:
formatting here is off.
Source:
public void onDelete(@NonNull ReadingList readingList) { showDeleteListUndoSnackbar(readingList); ReadingList.DAO.removeList(readingList); funnel.logDeleteList(readingList, readingLists.size()); updateLists(); if (callback() != null) { callback().onReadingListModified(); } }

Target:
Instead of adding a callback, consider using a ContentObserver wherever changes must be observed (I think SavePageSyncService does this?). This likely allow you to remove the tab change logic as well.
Source:
public RelationTypeSchemaDescriptor( int relTypeId, int... propertyIds ) { this.relTypeId = relTypeId; this.propertyIds = propertyIds; }

Target:
I'm pretty certain there is a factory for making these, no public constructor required. (Took a lot of refactoring to achieve that, let's uphold the flag.)
Source:
public Map<String, Object> introspect(String token) { TokenIntrospectionSuccessResponse response = Optional.of(this.requestEntityConverter.convert(token)) .map(this::makeRequest) .map(this::adaptToNimbusResponse) .map(this::parseNimbusResponse) .map(this::castToNimbusSuccess) // relying solely on the authorization server to validate this token (not checking 'exp', for example) .filter(TokenIntrospectionSuccessResponse::isActive) .orElseThrow(() -> new OAuth2IntrospectionException("Provided token [" + token + "] isn't active")); return convertClaimsSet(response); }

Target:
What would you think of ```suggestion TokenIntrospectionSuccessResponse response = Optional.of(token) .map(this.requestEntityConverter::convert) ```
Source:
private boolean isColdReboot() { boolean coldReboot = (getVm().isRunOnce() && !getVm().isVolatileRun()) || getVm().isNextRunConfigurationExists(); log.info("VM '{}' is performing reboot; run once: '{}', running as volatile: '{}', has next run configuration: '{}'", getVm().getName(), coldReboot ? "cold" : "warm", getVm().isRunOnce(), getVm().isVolatileRun(), getVm().isNextRunConfigurationExists()); return coldReboot; }

Target:
shouldn't we perform cold reboot for volatile runs?
Source:
public void updateVisibility() { super.updateVisibility(); messageLabel.setVisible(false); subnetTab.setVisible(exportEditor.asCheckBox().getValue()); }

Target:
Again, I don't understand why this is needed? Isn't it the same thing that happens in AbstractNetworkPopupPresenterWidget?
Source:
protected void executeVdsBrokerCommand() { _result = getBroker().getStorageDomainStats(getParameters().getStorageDomainId().toString()); proceedProxyReturnValue(); StorageDomain domain = buildStorageDynamicFromXmlRpcStruct(_result.storageStats); domain.setId(getParameters().getStorageDomainId()); setReturnValue(domain); }

Target:
Could you please rename also _result?
Source:
Boolean canEditColumns() { final String permission = WorkbenchFeatures.GUIDED_DECISION_TABLE_EDIT_COLUMNS; final User user = sessionInfo.getIdentity(); return authorizationManager.authorize(permission, user); }

Target:
```Boolean``` for a reason (vs ```boolean```)? Just asking.. Use of ```Boolean``` in my mind always makes me think this is a tri-value ```boolean``` (```true```, ```false```, ```null```)..
Source:
public CommandCallback getCallback() { return isCinderDisksExist() ? null : new ConcurrentChildCommandsExecutionCallback(); }

Target:
This is a bug, if cinder disks exists return the call back (not null). Also use the parameter you have added in the previous patch
Source:
private Config loadHazelcastConfig(GeoServerResourceLoader rl) throws IOException{ Resource hzf = getConfigFile(HAZELCAST_FILENAME, HzCluster.class); InputStream hzIn = hzf.in(); try { return new XmlConfigBuilder(hzIn).build(); } finally { hzIn.close(); } }

Target:
@NielsCharlier try-with-resources?
Source:
public void testDeserialize() throws Exception { String data = getFixture("/v1/accounts/acct_123"); Account resource = APIResource.GSON.fromJson(data, Account.class); assertNotNull(resource); assertNotNull(resource.getId()); }

Target:
we likely want specific edge-case as fixtures to ensure deserialization works as needed.
Source:
public VdcQueryParametersBase(String sessionId) { this.sessionId = sessionId; refresh = true; }

Target:
Why not flip this around, have the constructor with the sessionId call the constructor without the parameter? That way you don't have to pass null into the constructor. Functionally it makes no difference, just reads a little nicer IMO.
Source:
private int onSpinMisses(int spins) { if (UPDATE_STATISTICS) spinMisses.increment(); if (spins == YIELD_SPINS) { spins = 0; Thread.yield(); } else { spins++; JDKSpecific.onSpinWait(); } return spins; }

Target:
I'm concerned that this might not be inlined.
Source:
private static String resolveKafkaService() { final StringBuilder sb = new StringBuilder() .append(resolve(KAFKA_SERVICE_HOST)) .append(":") .append(resolve(KAFKA_SERVICE_PORT)); return sb.toString(); }

Target:
No need to assign to a variable
Source:
public void onBackPressed() { if (referencesViewPager.getCurrentItem() > 0) { referencesViewPager.setCurrentItem(referencesViewPager.getCurrentItem() - 1, true); } }

Target:
This correctly cycles back through the pager when the Back button is pressed. However, when the first position is reached, the Back button has no effect (i.e. the dialog should close when Back is pressed). To handle the final Back case, you could add an `else` here and say the following: else { super.onBackPressed(); }
Source:
public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (sqlObjectType != null ? sqlObjectType.hashCode() : 0); result = 31 * result + (sqlObjectMethod != null ? sqlObjectMethod.hashCode() : 0); return result; }

Target:
ditto on readability here: ``` int result = name == null ? 0 : name.hashCode(); ```
Source:
public Implementation() { plugin = this; pageRegistry = new PageRegistry(); pageRegistry.addPageProvider(new DefaultPageProvider()); }

Target:
Should be done inside start().
Source:
public Symbol cast(DataType<?> targetType, boolean tryCast) { if (targetType.equals(valueType())) { return this; } else if (ArrayType.unnest(targetType).equals(DataTypes.UNTYPED_OBJECT) && valueType().id() == DataTypes.UNTYPED_OBJECT.id()) { return this; } return CastFunctionResolver.generateCastFunction(this, targetType, tryCast); }

Target:
Looks better to me to have it here :+1:
Source:
public static boolean validate() { boolean valid = true; for (Map.Entry<String, String> entry : toMap().entrySet()) { String propertyName = entry.getKey(); if (!PropertyKey.isValid(propertyName)) { LOG.warn("Unsupported property {}" + propertyName); valid = false; } } return valid; }

Target:
`LOG.warn("Unsupported property {}", propertyName);`
Source:
public String BuildJSON() { if (swagger != null) { updateHostAndBasePath(); } else { synchronized (this) { log.info("Initiating Swagger specification creation"); toggleLogs(RestConstants.SWAGGER_LOGS_OFF); try { initSwagger(); addPaths(); addDefaultDefinitions(); // addSubclassOperations(); //FIXME uncomment after fixing the method } catch (Exception e) { log.error("Error while creating Swagger specification", e); } finally { toggleLogs(RestConstants.SWAGGER_LOGS_ON); log.info("Swagger specification creation complete"); } } } return createJSON(); }

Target:
Wrapping the else body in a new method will make it even cleaner.
Source:
static List<TypeName> list(Type[] types) { List<TypeName> result = new ArrayList<>(types.length); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < types.length; i++) { result.add(get(types[i])); } return result; }

Target:
This is bytecode equivalent to using the for-each syntax on an array.
Source:
private boolean loadDataInMemory() { String value = Optional.ofNullable(GeoServerExtensions.getProperty("WMTS_HISTOGRAM_IN_MEMORY")) .orElse("false"); return Boolean.getBoolean(value); }

Target:
If ``value`` is ``NULL``, ``Boolean.getBoolean(value)`` will return ``FALSE`` anyway, but I understand that this is more explicit.
Source:
public Map<String, Integer> getRemainingQueries() { synchronized (this) { Map<String, Integer> queriesInfo = new HashMap<String, Integer>(); queriesInfo.put("queriesCount", queries.size()); queriesInfo.put("fragmentsCount", runningFragments.size()); return queriesInfo; } }

Target:
Since the entire body is synchronized, put the `synchronized` on the method itself.
Source:
public void next() { RadioDroidApp radioDroidApp = (RadioDroidApp) this.getApplication(); DataRadioStation station = radioDroidApp.getFavouriteManager().getNextById(currentStationID); if (station != null) new RadioDroidBrowserService.GetRealLinkAndPlayTask(itsContext, station, itsBinder).execute(); }

Target:
You may remove `this.`
Source:
public void connectDisconnect() throws IOException { final FtpFacade facade = FtpFacadeTest.mockFacade(); final FTPClient ftp = new FTPClient(); try { facade.listen(); ftp.connect("localhost"); final int reply = ftp.getReplyCode(); MatcherAssert.assertThat( FTPReply.isPositiveCompletion(reply), Matchers.equalTo(true) ); MatcherAssert.assertThat( ftp.logout(), Matchers.equalTo(true) ); } finally { facade.close(); } }

Target:
please inline this variable
Source:
@Override public void close() { EndpointGroup endpointGroup = EndpointGroupRegistry.get("elasticsearch"); if (endpointGroup != null) { endpointGroup.close(); EndpointGroupRegistry.unregister("elasticsearch"); } factory.close(); }

Target:
Could put this in a `finally` or local try-with-resources in case `endpointGroup.close()` throws for some reason, though it's extremely careful.
Source:
void doPrefetch(long relativeOffset, long size) throws IOException { long sizeToRead = Math.min(size, getMessageInfo().getSize() - relativeOffset); prefetchedData = ByteBuffer.allocate((int) sizeToRead); getChannel().position(offset.getOffset() + relativeOffset); getChannel().read(prefetchedData); prefetchedDataRelativeOffset = relativeOffset; }

Target:
I'm not sure this will work in a concurrent environment. Isn't this a shared channel? Can you instead use [this](https://docs.oracle.com/javase/8/docs/api/java/nio/channels/FileChannel.html#read-java.nio.ByteBuffer-long-)?
Source:
public ProcessorExpressionRoute(String expression, Processor processor) { super(processor); requireNonNull(expression, "expression can't be null"); this.expression = expression; }

Target:
this returns the expression, you can combine this line and the next
Source:
public CachingHasher build() throws IllegalArgumentException { List<long[]> cache = new ArrayList<long[]>(); for (byte[] buff : buffers) { long[] result = new long[2]; result[0] = function.apply(buff, 0); result[1] = function.apply(buff, 1) - result[0]; cache.add(result); } return new CachingHasher(function, cache); }

Target:
use final
Source:
public Object merge( Object parent ) { if (parent == null) { return this; } if (parent instanceof MockHttpServletRequestBuilder) { this.mergeable = (Mergeable) parent; return this.mergeable; } else { throw new IllegalArgumentException("Cannot merge with [" + parent.getClass().getName() + "]"); } }

Target:
Remove extra space for consistent formatting ```suggestion public Object merge(Object parent ) { ```
Source:
public Parser<I, Stream<A>, E> repeat1() { return bind(a -> repeat().map(new F<Stream<A>, Stream<A>>() { public Stream<A> f(final Stream<A> as) { return as.cons(a); } })); }

Target:
Lambda here?
Source:
public String getLanguage() { if (null == this.language) { return ""; //$NON-NLS-1$ } return this.language; }

Target:
You can do it in one line. More lisibility.
Source:
public boolean execute(short a, BlockComponentHolder b) { try { for (Component c : b.values()) { c.onAttached(); } } catch (Exception e) { Spout.getLogger().log(Level.SEVERE, "Unhandled exception attaching block component", e); } return true; }

Target:
Formatting is off here, try should be around each onAttached() so that 1 bad component does not break all of the components.
Source:
protected static double averageMetricOverOperations(ASTClassOrInterfaceDeclaration node, OperationMetricKey key, MetricVersion version, boolean includeNested) { List<ASTMethodOrConstructorDeclaration> operations = findOperations(node, includeNested); double total = 0; for (ASTMethodOrConstructorDeclaration op : operations) { double val = Metrics.get(key, op, version); total += val == Double.NaN ? 1 : val; } return total / operations.size(); }

Target:
Is the "1" here correct? I guess, it should be the same like in "sumMetricOverOperations" -> 0 if there is no value?
Source:
public void setupSelectComponent(final DataTypeSelect typeSelect) { type.innerHTML = ""; HTMLElement element = typeSelect.getElement(); if (element instanceof HTMLDivElement) { new MenuInitializer((HTMLDivElement) element, ".btn-group").init(); } type.appendChild(typeSelect.getElement()); }

Target:
I think we could add a final here: ```suggestion final HTMLElement element = typeSelect.getElement(); ```
Source:
public boolean isTriggerExpired() { isExpired = isExpired || expireCondition.isMet(); return isExpired; }

Target:
This is counterintuitive. Why do we need to reassign `isExpired`? Can `expireCondition.isMet()` become `false` after returning `true`?
Source:
public void setMonitorEventTypes(String monitorEventTypes) { HazelcastIntegrationDefinitionValidator.validateEnumType( ClusterMonitorType.class, monitorEventTypes); final Set<String> monitorTypes = StringUtils .commaDelimitedListToSet(monitorEventTypes); Assert.notEmpty(monitorTypes, "'monitorTypes' must have elements"); this.monitorTypes = monitorTypes; }

Target:
I think `validate...` method can return the `Set<ClusterMonitorType>` already avoiding double `commaDelimitedListToSet` call. In addition I think we should add `vararg` methods for the Java Config convenience. But that should be done in the separate JIRA.
Source:
final AbstractInsnNode skipNonOpcodes(AbstractInsnNode cursor) { while (cursor != null && (cursor.getType() == AbstractInsnNode.FRAME || cursor.getType() == AbstractInsnNode.LABEL || cursor.getType() == AbstractInsnNode.LINE)) { cursor = cursor.getNext(); } return cursor; }

Target:
As this method does not change state (unlike the others) I would prefer to declare it `static`.
Source:
public boolean isValid() { if (this.urlString == null || httpMethod == null) { return true; } else { return false; } }

Target:
`return this.urlString == null || httpMethod == null;`
Source:
public UnitOfWorkAspect newAspect(ImmutableMap<String, SessionFactory> sessionFactories) { return new UnitOfWorkAspect(this.sessionFactories); }

Target:
Shouldn't it be `sessionFactories` instead of `this.sessionFactories`? If yes, would it be possible to overload `newAspect` instead of changing its signature?
Source:
public boolean isMarshallable(Object o) { // Protostream can handle all of these type as well if (o instanceof String || o instanceof Long || o instanceof Integer || o instanceof Double || o instanceof Float || o instanceof Boolean || o instanceof byte[] || o instanceof Enum) { return true; } return getSerializationContext().canMarshall(o.getClass()); }

Target:
Enum should not be handled here, should be left to `SerializationContext.canMarshall()` because it needs to check that a custom marshaller was defined for the Enum.
Source:
private void resetScope() { MortarScope root = Mortar.createRootScope(false, ObjectGraph.create(new ModuleAndBlueprint("root"))); activityScope = Mortar.requireActivityScope(root, new ModuleAndBlueprint("activity")); }

Target:
static import of createRootScope, and requireActivityScope below?
Source:
public Builder withOutputFileset(String fileset){ this.outputFilesets.add(fileset); return this; }

Target:
can you add safety checks against `null` or empty strings, plz?
Source:
public String getDeepRepresentation(CtElement elem) { EqualVisitor prThis = new EqualVisitor(); prThis.scan(elem); return prThis.getRepresentation(); }

Target:
This doesn't work. e.g., when you want build the deep representation of a method like this one: ``` java public void toProvider(Provider<? extends T> provider) { } ``` The result of `getDeepRepresentation` will be: `void toProvider(javax.inject.Provider,)voidprovider{}`.
Source:
public KSyntax2GrammarStatesFilter(Context context) { super(KSyntax2GrammarStatesFilter.class.getName(), context); // create a NonTerminal for every declared sort for (String sort : context.definedSorts) { NonTerminal nt = new NonTerminal(new NonTerminalId(sort)); grammar.add(nt); } }

Target:
Can you please check to verify that definedSorts is computed by means of processing every production in the definition? Otherwise this might not work as expected.
Source:
protected void clearContent() { fXYPresentationProvider.clear(); getSwtChart().getAxisSet().getXAxis(0).getTick().setFormat(null); super.clearContent(); }

Target:
The order of colors is changed when the content is changed (e.g. checking/unchecking a counter).
Source:
protected void onNewIntent(Intent intent) { // This is called when the user press Home again while already browsing MainActivity // onResume() will be called right after, hiding the kissbar if any. // http://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent) // Animation can't happen in this method, since the activity is not resumed yet, so they'll happen in the onResume() // https://github.com/Neamar/KISS/issues/569 if (!searchEditText.getText().toString().isEmpty()) { Log.i(TAG, "Clearing search field"); searchEditText.setText(""); } // Hide kissbar when coming back to kiss if (isViewingAllApps()) { displayKissBar(false); } // Close the backButton context menu MainActivity.this.closeContextMenu(); }

Target:
why not just call directly `closeContextMenu()`?
Source:
private void validateRetentionPolicy(String retentionPolicy) throws FalconException { if (!retentionPolicy.equalsIgnoreCase("delete")) { throw new FalconException("Retention policy \"" + retentionPolicy + "\" is invalid"); } }

Target:
Make the method static
Source:
public byte[] getData() { Object base = slice.getBase(); checkState(base instanceof byte[], "unexpected serialization type %s", base.getClass()); byte[] bytes = (byte[]) base; if (slice.isCompact()) { return bytes; } // do a copy return slice.getBytes(); }

Target:
Should this above three lines actually happen in this `if` branch? I don't see why we would need to get `base` if the slice is not compact.
Source:
public HeaderExtension getAbsoluteSendTimeExtension(RawPacket packet) { if( packet.getExtensionBit() && packet.getHeaderExtensionType() == getAbsSendTimeExtensionID() ) { return packet.getHeaderExtension(getAbsSendTimeExtensionID()); } return null; }

Target:
We should check whether the AbsSendTimeEngine is configured with an extension ID (e.g. getExtensionID() != -1).
Source:
public RedisPublishingMessageHandler(RedisConnectionFactory connectionFactory) { Assert.notNull(connectionFactory, "connectionFactory must not be null"); this.template = new RedisTemplate(); this.template.setConnectionFactory(connectionFactory); this.template.setEnableDefaultSerializer(false); this.template.afterPropertiesSet(); }

Target:
`@SuppressWarnings("rawtypes")`
Source:
public AnnotationCommandTargetResolver build() { try { return resolver; } finally { resolver = null; // builder can only be used once. } }

Target:
I think it's nicer to call the `AnnotationCommandTargetResolver` constructor here, with, as suggested earlier, `this` as the sole parameter, so that the `AnnotationCommandTargetResolver` constructor can pull the `identifierAnnotation` and `versionAnnotation` from it.
Source:
protected void doPoll(SourcePollingChannelAdapter adapter) { try { Method method = AbstractPollingEndpoint.class.getDeclaredMethod("doPoll"); method.setAccessible(true); method.invoke(adapter); } catch (Exception e) { e.printStackTrace(); fail("Failed to invoke doPoll(): " + e.toString()); } }

Target:
No `e.printStackTrace()`, please, at all. It doesn't provide much info and just pollutes logs on CI builds
Source:
public CLOption(String opt, String val, String param) { super(); this.opt = opt; this.val = val; this.param = param; }

Target:
nitpick: redundant
Source:
private RemoteCacheManager createExecClient() { org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = super.createHotRodClientConfigurationBuilder(servers.get(0).getPort()); clientBuilder.marshaller(new UTF8StringMarshaller()); clientBuilder.protocolVersion(getProtocolVersion()); return new InternalRemoteCacheManager(clientBuilder.build()); }

Target:
Method deprecated. Use `clientBuilder.version()` instead.
Source:
static synchronized Iterable<TerminalInfoView> getViews() { return new ArrayList<TerminalInfoView>(views); }

Target:
Visibility missing. Synchronized comes before static Why return an Iterable here? It would be better just to return a List<TerminatlInfoView>
Source:
private void setWidgetsEnabled(final boolean enabled, final Control... controls) { for (Control control : controls) { control.setEnabled(enabled); } // set the focus on the fist element of the group. if (controls.length > 0 && enabled) { for (Control control : controls) { if (control instanceof Text) { control.setFocus(); break; } } } }

Target:
This might as well become if (enable) since the for loop will end gracefully whether it's > 0 or not.
Source:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object object = method.invoke(producer, args); if (method.getName().equals("produce") && spiedClasses.contains(object.getClass())) { object = spy(object); } return object; }

Target:
oh yea. A spy :)
Source:
private boolean filterInvalid(Position position) { return filterInvalid && !position.getValid() || position.getLatitude() > 90 || position.getLongitude() > 180 || position.getLatitude() < -90 || position.getLongitude() < -180; }

Target:
You should only filter if the filter is enabled. Please be very careful and test your code before submitting anything.
Source:
public CreateDDiagramElementCommand(final TransactionalEditingDomain domain, final EObject semantic, final EdgeMapping mapping, final EdgeTarget source, final EdgeTarget target) { this(domain, semantic); edgeCandidate = new DEdgeCandidate(mapping, semantic, source, target, RefreshIdsHolder.getOrCreateHolder(getParentDiagram())); /* store source as container to retrieve later parent diagram */ this.container = (DragAndDropTarget) source; }

Target:
getparentDiagram() will be null.. you have to set the container before calling the method.