auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static final HostThread readHostThread(ISafeByteBufferReader buffer) { /* the first short = the size to read */ short valueSize = buffer.getShort(); byte[] array = new byte[valueSize]; buffer.get(array); String host = new String(array, CHARSET); /* Confirm the 0'ed byte at the end */ if (buffer.get() != 0) { throw new IllegalStateException("Host thread's host could not be correctly serialized / deserialized"); //$NON-NLS-1$ } int tid = buffer.getInt(); return new HostThread(host, tid); }

Target:
buffer.getString()?
Source:
public void setFocus() { StyledText widget = fSourceViewer.getTextWidget(); if (fSourceViewer != null && widget != null && !widget.isDisposed()) { widget.setFocus(); } }

Target:
That could be null ;-). Also note, that Text uses compact assignment.
Source:
private Method getConditionMethod(Class<?> clazz) { for (Method checkMethod : clazz.getMethods()) { if (checkMethod.getName().equals("getCondition") && (checkMethod.getModifiers() & Modifier.STATIC) != Modifier.STATIC && checkParameterTypes(checkMethod.getParameterTypes())) { return checkMethod; } } return null; }

Target:
We are looking for a static method here, so this should be an == check.
Source:
default String getPreferenceKey() { return getClass().getCanonicalName(); }

Target:
Actually should be getName(), because getCanonicalName() can return null for an anonymous class.
Source:
private static String getPath(ITimeGraphPresentationProvider presentationProvider, StateItem stateItem) { String stateTypeName = String.valueOf(presentationProvider.getId()); String stateName = stateItem.getStateString(); if (isLink(stateItem)) { return PREFIX + stateTypeName + SEPARATOR + LINK + stateName; } return PREFIX + stateTypeName + SEPARATOR + stateName; }

Target:
id?
Source:
public static boolean isGerritVersion(String verString) { return verString != null && GERRIT_SSHD_REPLY.matcher(verString).matches(); }

Target:
if you move the test to package org.eclipse.egit.core.op this method doesn't need to be public
Source:
public void setFetchAtomic(final boolean atomic) { this.fetchAtomic = Optional.of(atomic); }

Target:
nit. unnecessary 'final'
Source:
protected void registerChanges(final TextEditBasedChangeManager manager) throws CoreException { CompilationUnitRewrite rewrite= null; Set<Entry<ICompilationUnit, CompilationUnitRewrite>> entrySet= fCompilationUnitRewrites.entrySet(); for (Entry<ICompilationUnit, CompilationUnitRewrite> entry : entrySet) { ICompilationUnit unit= entry.getKey(); rewrite= entry.getValue(); if (rewrite != null) { final CompilationUnitChange change= rewrite.createChange(true); if (change != null) manager.manage(unit, change); } } }

Target:
Variable entrySet seems to be unnecessary? Could be replaced by fCompilationUnitRewrites.entrySet() directly, without loss of efficiency or clarity.
Source:
public void setArch(String arch) { incrementSequenceNumber(); fArch = arch; if (fRoot != null && arch != null && arch.length() > 0) { Element archNode = TargetDefinitionDocumentTools.getChildElement(fRoot, TargetDefinitionPersistenceHelper.ENVIRONMENT, TargetDefinitionPersistenceHelper.ARCH); archNode.setTextContent(arch); } else { removeElement(TargetDefinitionPersistenceHelper.ENVIRONMENT, TargetDefinitionPersistenceHelper.ARCH); } }

Target:
Please use !string.isEmpty().
Source:
public void setName(String name) { fName = name; if (fRoot != null) { if (name != null && name.length() > 0) { fRoot.setAttribute(TargetDefinitionPersistenceHelper.ATTR_NAME, name); } else { fRoot.removeAttribute(TargetDefinitionPersistenceHelper.ATTR_NAME); } } }

Target:
Please use !string.isEmpty().
Source:
static void flushUIEvents() { final Display display = Display.getCurrent(); for (;;) { if (!display.readAndDispatch()) { break; } } }

Target:
why not use a simple while loop? thus removing the for and the if
Source:
private static boolean isValid(@Nullable Object element) { if (element instanceof ITmfTrimmableTrace) { return true; } if (!(element instanceof ITmfTrace)) { return false; } ITmfTrace trace = (ITmfTrace) element; List<ITmfEventProvider> children = trace.getChildren(); if (children.isEmpty()) { return false; } for (ITmfEventProvider child : children) { if (!isValid(child)) { return false; } } return true; }

Target:
Here you refuse trimming if any trace is non-trimmable, but later you get the subset of trimmable traces for the operation... Should it be allowed if at least one is trimmable? Then you could get away with !getValid().isEmpty()...
Source:
private void activateContextService() { if (!fActiveContexts.isEmpty()) { deactivateContextService(); } fActiveContexts.add(fContextService.activateContext(CONTEXT)); }

Target:
I think it would be good enough to just do nothing if it's already active?
Source:
public GridTableViewerComposite build() { final GridTableViewerComposite viewerComposite = new GridTableViewerComposite(getComposite(), getSwtStyleBits(), getInput(), getCustomization(), getTitle(), getTooltip()); TableConfigurationUtil.setTableConfiguration(viewerComposite, getCustomization().getTableConfiguration()); return viewerComposite; }

Target:
why move it out? why not let the composite set the config itself?
Source:
public void bundleChanged(BundleEvent event) { int eventType = event.getType(); // Note: no calls to any non-trivial Eclipse code outside this class // should be made inside the synchronized block below. Such calls // can cause deadlocks on startup, see bug 502095. // Progress monitor calls *are* non-trivial. synchronized (this) { if (eventType == BundleEvent.STARTED) { progressMonitor.split(4); String symbolicName = event.getBundle().getSymbolicName(); String taskName = NLS.bind(WorkbenchMessages.Startup_Loading, symbolicName); progressMonitor.subTask(taskName); } } }

Target:
Why 4? I don't think we have 25% early startup bundles in any Eclipse. How expensive would it be to obtain up front the correct number? Is that possible at all without undue effort?
Source:
final public Ref exactRef(String name) throws IOException { return getRefDatabase().exactRef(name); }

Target:
public final
Source:
public File resolve(File dir, String name) { final File abspn = createFile(name); if (abspn.isAbsolute()) return abspn; return createFile(dir, name); }

Target:
missing braces
Source:
private static void appendBodyColorsRule(StringBuilder buffer, RGB fgRGB, RGB bgRGB) { StringBuilder fg= new StringBuilder(); appendColor(fg, fgRGB); StringBuilder bg= new StringBuilder(); appendColor(bg, bgRGB); buffer.append("body {color:"); //$NON-NLS-1$ appendColor(buffer, fgRGB); buffer.append("; background-color:"); //$NON-NLS-1$ appendColor(buffer, bgRGB); buffer.append(";}"); //$NON-NLS-1$ }

Target:
But now these 4 lines above can be deleted.
Source:
private String insanelyHugeCommitMessage() { StringBuilder b = new StringBuilder(HUGE_SIZE); // Give the message a real header; otherwise even writing the reflog // message may run into troubles because RevCommit.getShortMessage() // will return the whole message. b.append("An insanely huge commit message\n\n"); String oneLine = "012345678901234567890123456789012345678901234567890123456789\n"; while (b.length() < HUGE_SIZE) { b.append(oneLine); } return b.toString(); }

Target:
This is calculating the character count in each iteration. Would it be better to calculate the required size in advance?
Source:
public static ResourceSet loadResourceWithProxies(URI resourceURI, final ResourceSet resourceSet) { try { if (addResourceToSet(resourceSet, resourceURI)) { return resourceSet; } } catch (final IOException ex) { Activator.getDefault().getReportService().report( new StatusReport(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex))); } return null; }

Target:
why not call the new method with null as third parameter?
Source:
public static boolean isInvalidBranchName(String branchName) { if (HEAD.equals(branchName)) { return true; } if ((R_HEADS + HEAD).equals(branchName)) { return true; } return branchName.startsWith("-"); //$NON-NLS-1$ }

Target:
optional: I think it would be easier to understand if reversed, to be isValidBranchName. That would be more consistent with Repository#isValidRefName, too.
Source:
protected void doReset() { allCommandsRetrieved = false; idToCommand = null; if (currentSnapshot instanceof ExpressionContext) { ((ExpressionContext) currentSnapshot).eclipseContext.dispose(); } currentSnapshot = null; }

Target:
I would clear the map. Having some field be null leads in such code to NPE's sooner or later.
Source:
public QuickAccessElement[] getElements() { if (!allCommandsRetrieved) { ICommandService commandService = getCommandService(); Collection<String> commandIds = commandService.getDefinedCommandIds(); for (String commandId : commandIds) { retrieveCommand(commandId); } allCommandsRetrieved = true; } return idToCommand.values().toArray( new QuickAccessElement[idToCommand.values().size()]); }

Target:
please guard the map for concurrent access. Iterator used in values() call will cry if the map is changed ifrom another thread, like in retrieveCommand below (which IS called from different threads)
Source:
public static final int headerEnd(final byte[] b, int ptr) { final int sz = b.length; while (ptr < sz) { final byte c = b[ptr++]; if (c == '\n' && (ptr == sz || b[ptr] != ' ')) return ptr - 1; } return ptr - 1; }

Target:
Missing curly braces.
Source:
public File createFile(String pathname, Config config) { if (config != null && isNfsSupportEnabled(config)) { return new NFSFile(pathname, config); } return new File(pathname); }

Target:
you could put the check for config==null into isNfsSupportEnabled. If config==null then isNfsSupportEnabled would return false
Source:
private void setNotFoundBackgroundColor() { patternField.setData(CCS_CLASS_KEY, NO_RESULTS_CLASS); patternField.reskin(SWT.ALL); patternField.update(); noResults = true; }

Target:
Is this necessary? If I remove the update line everything seems still to work.
Source:
private void setNormalBackgroundColor() { if (noResults) { Color currentColor = patternField.getBackground(); patternField.setData(CCS_CLASS_KEY, null); patternField.reskin(SWT.ALL); patternField.update(); if (currentColor.equals(patternField.getBackground())) { // If the theme has no definition for the text field's // background, it remains unchanged. Reset it to the SWT default // in that case. patternField.setBackground(null); } noResults = false; } }

Target:
Is this necessary? If I remove the update line everything seems still to work.
Source:
private boolean checkAppElementByBundleSymbolicNameAndClass(String bundleSymbolicName, String className) { Collection<BundleWiring> wirings = findWirings(bundleSymbolicName, bundleContext); if (!isBundleClassAvailable(wirings, className)) { // remove application element, if there is not wiring available // or if the class cannot be found return false; } return true; }

Target:
Return of boolean literal statements wrapped into if-then-else ones should be simplified. Noncompliant Code Example if (expression) { return true; } else { return false; } Compliant Solution return expression;
Source:
private boolean isChildObjectRemoved(Set<Object> children, Set<Object> childrenFromTreeContextEntry, int notificationType) { return !children.containsAll(childrenFromTreeContextEntry) && (Notification.REMOVE == notificationType || Notification.REMOVE_MANY == notificationType); }

Target:
Should we turn this around? I guess that the type check is faster than a containsAll
Source:
protected void viewerSelectionChanged(SelectionChangedEvent event) { actionBar.updateControls(); }

Target:
don't we need to check for the actionbar being null?
Source:
ActionConfigurationBuilder() { }

Target:
both constructors can be private right?
Source:
public Collection<Action> getActions() { return Collections.unmodifiableCollection(configuration.getActions()); }

Target:
why do we need this?
Source:
public void addControl(String id, Control control) { if (controls.containsKey(id)) { throw new IllegalArgumentException( MessageFormat.format("A control with id {0} already exists", id)); //$NON-NLS-1$ } controls.put(id, control); }

Target:
why is this public?
Source:
public ViewerActionContext<? extends Viewer> getActionContext() { return actionContext; }

Target:
Could this be protected as well?
Source:
public void testShallowCommitParse() throws Exception { RevCommit a = commit(); RevCommit b = commit(a); createShallowFile(b); rw = createRevWalk(); b = rw.parseCommit(b); markStart(b); assertCommit(b, rw.next()); assertNull(rw.next()); }

Target:
Leaks an ObjectReader.
Source:
private void createShallowFile(ObjectId... shallowCommits) throws IOException { // Reset the RevWalk since the new shallow file invalidates the existing // RevWalk's shallow state. rw = createRevWalk(); StringBuilder builder = new StringBuilder(); for (ObjectId commit : shallowCommits) { builder.append(commit.getName() + "\n"); } JGitTestUtil.write(new File(db.getDirectory(), "shallow"), builder.toString()); }

Target:
not a new issue, but seems worth fixing anyway: this leaks an ObjectReader.
Source:
private boolean isArgumentFileSupported() { return (JavaCore.compareJavaVersions(javaVersion, JavaCore.VERSION_9) >= 0); }

Target:
Please remove redundant braces
Source:
public void propertyChange(PropertyChangeEvent event) { if(event.getSource() == serverChoice && event.getProperty() == FieldEditor.VALUE) { String changedLSLocation = CPPStreamConnectionProvider.getDefaultLSLocation((String) event.getNewValue()).getAbsolutePath(); if(changedLSLocation != null) { serverPath.setStringValue(changedLSLocation); } } }

Target:
This null check is too late: if getDefaultLSLocation() returns null, the call to getAbsolutePath() on the previous line will already throw a NullPointerException.
Source:
public SiriusGraphQLPlugin() { super(new ResourceLocator[0]); }

Target:
private
Source:
public RegistrationWindows() { registryWriter = new RegistryWriter(); }

Target:
just call the other constructor here
Source:
public static void classSetup() { originalEclipseHomeLocation = System.getProperty("eclipse.home.location", ""); System.setProperty("eclipse.home.location", "file:/C:/Users/Test/"); originalEclipseLauncher = System.getProperty("eclipse.launcher", ""); System.setProperty("eclipse.launcher", "C:\\Users\\Test\\eclipse.exe"); }

Target:
same is done in setUp, therefor its not needed
Source:
public void testHandleSchemesForOneScheme() { RegistrationWindows registrationWindows = new RegistrationWindows(registryWriter); SchemeInformation schemeInformation = new SchemeInformation("schemeToTest", "ThisSchemeisJustForTesting", System.getProperty("eclipse.launcher")); registrationWindows.handleSchemes(Arrays.asList(schemeInformation), Arrays.asList(schemeInformation)); assertEquals(null, registryWriter.getRegisteredHandlerPath("schemeToTest")); }

Target:
this method does add and remove the same scheme. the name of the method does not reflect this.
Source:
public void test() { Resource vgql = getResource(PROJECT_NAME, fileName); VqlCodeGenerator vqlGenerator = new VqlCodeGenerator(); EObject root = vgql.getContents().get(0); String vql = vqlGenerator.generate((PatternPackage) root); printVQL(vql); vql = removeWhitespace(vql); String cleanExpectedOutput = removeWhitespace(expectedOutput); assertEquals(cleanExpectedOutput, vql); }

Target:
Remove the printVQL call and the corresponding method.
Source:
public ITmfTrace getTrace() { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { for (ITmfTrace t : TmfTraceManager.getTraceSetWithExperiment(trace)) { if (getResource().equals(t.getResource()) && (t instanceof TmfExperiment)) { return t; } } } return null; }

Target:
I think we can avoid going through the trace set altogether, the experiment can only be found in the opened traces collection.
Source:
public void suspendedLineDifferStaysSuspendedAfterDocumentRewriteSession() throws Exception { // given fLineDiffer.connect(fDocument); fLineDiffer.suspend(); // when fDocument.startRewriteSession(SEQUENTIAL); fDocument.stopRewriteSession(fDocument.getActiveRewriteSession()); // then assertFalse(fLineDiffer.isSuspended()); assertFalse(fLineDiffer.isSynchronized()); }

Target:
"The differ stays suspended" seems to be the opposite of what you're testing here. Shouldn't it be assertTrue?
Source:
private boolean isIncluded(Location reference, Location included) { return reference.getUri().equals(included.getUri()) && !isSameRange(reference.getRange(), included.getRange()) && isAfter(reference.getRange().getStart(), included.getRange().getStart()) && isAfter(included.getRange().getEnd(), reference.getRange().getEnd()); }

Target:
Doesn't reference.equals(included) work?
Source:
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { PresentationReconcilerCPP.this.setupDocument(newInput); }

Target:
It is sufficient to write: setupDocument(newInput);
Source:
public IVariable getVariable(int offset) throws DebugException { if (offset >= getLength()) { requestFailed(JDIDebugModelMessages.JDIArrayValue_6, new IndexOutOfBoundsException()); } return new JDIArrayEntryVariable(getJavaDebugTarget(), getArrayReference(), offset, fLogicalParent); }

Target:
Here and below: please add requested offset value like: throw new IndexOutOfBoundsException(Integer.toString(offset));
Source:
protected void assertEvaluationIsError() throws Exception { IValue value = getValue(); assertEquals(value, IntegralValue.ERROR); }

Target:
I'm not sure how much value there is in distinguishing these two cases. It may be simpler to just have a single function, assertEvaluationIsError(), which checks for either.
Source:
public PcapTimestampScale getTimestampPrecision() { if (getTsResolNg(fInterfaceID - 1) == 6) { return PcapTimestampScale.MICROSECOND; } return PcapTimestampScale.NANOSECOND; }

Target:
This method does not belong in PcapNgFile because there is no global timestamp precision per file.
Source:
public static PcapFile getPcapFile(Path filePath) throws IOException, BadPcapFileException { if (filePath.getFileName().toString().endsWith(PCAPNG_EXTENSION)) { try (PcapFile dummy = new PcapNgFile(filePath)) { return dummy; } } try (PcapFile dummy = new PcapOldFile(filePath)) { return dummy; } }

Target:
I think you should just return the file and the caller will handle the close. if (filePath.getFileName().toString().endsWith(PCAPNG_EXTENSION)) { return new PcapNgFile(filePath); } return new PcapOldFile(filePath);
Source:
public @NonNull ByteBuffer getBody() { return fBody; }

Target:
Remove @NonNull annotation.
Source:
protected static String getLineDelimiterPreference(IFile file) { IScopeContext[] scopeContext; if (file != null) { ITextFileBufferManager manager = FileBuffers.getTextFileBufferManager(); ITextFileBuffer buffer = manager.getTextFileBuffer(file.getFullPath(), LocationKind.IFILE); return TextUtilities.getDefaultLineDelimiter(buffer.getDocument()); } // workspace preference scopeContext = new IScopeContext[] { InstanceScope.INSTANCE }; return Platform.getPreferencesService().getString(Platform.PI_RUNTIME, Platform.PREF_LINE_SEPARATOR, null, scopeContext); }

Target:
Please note, that this ignores product default settings, which is not good.
Source:
private void updateEnableStates() { boolean enabledCodeMining= getCheckBox(PREF_CODEMINING_ENABLED).getSelection(); if (enabledCodeMining) { // Show references checkboxes boolean showReferences= getCheckBox(PREF_SHOW_REFERENCES).getSelection(); getCheckBox(PREF_SHOW_REFERENCES_ON_CLASSES).setEnabled(showReferences); getCheckBox(PREF_SHOW_REFERENCES_ON_FIELDS).setEnabled(showReferences); getCheckBox(PREF_SHOW_REFERENCES_ON_METHODS).setEnabled(showReferences); // Show implementations checkboxes boolean showImplementations= getCheckBox(PREF_SHOW_IMPLEMENTATIONS).getSelection(); } else { atLeastOneCheckBox.setEnabled(false); fFilteredPrefTree.setEnabled(false); } }

Target:
The local variable is never used and results in a warning.
Source:
private void handlePropertyChangeEvent(PropertyChangeEvent event) { if (fPreferenceStore == null) { return; // Uninstalled during event notification } if (fEditor != null && fEditor.affectsJavaCodeMining(event, false)) { if (isJavaCodeMiningEnabled()) { enable(); } else { disable(); } } }

Target:
I think it'd be better to directly use fEditor.affectsJavaCodeMining(event.getPropertyName())
Source:
public static Resource getResource(final ResourceSet resourceSet, final URI resourceURI) { Resource resource = null; try { resource = resourceSet.getResource(resourceURI, true); } catch (WrappedException e) { SiriusPlugin.getDefault().getLog().log(new Status(IStatus.WARNING, SiriusPlugin.ID, e.getMessage(), e)); } return resource; }

Target:
Should be private, no reason to expose this helper more than strictly necessary.
Source:
public int getVersion() { return 2; }

Target:
Version 3 I think ?
Source:
protected boolean mergeImpl() throws IOException { if (implicitDirCache) { dircache = nonNullRepo().lockDirCache(); } if (!inCore) { checkoutMetadata = new HashMap<>(); } try { return mergeTrees(mergeBase(), sourceTrees[0], sourceTrees[1], false); } finally { if (implicitDirCache) { dircache.unlock(); } checkoutMetadata = null; } }

Target:
Would it make sense to move above the unlock call? Could unlock throw and then not properly unset this?
Source:
public static Set<Bundle> getBundlesBySymbolicName(BundleContext bundleContext, String symbolicName) { return Arrays.stream(bundleContext.getBundles()) .filter(bundle -> bundle.adapt(BundleRevision.class).getSymbolicName().equals(symbolicName)) .collect(toSet()); }

Target:
This will NPE if BundleRevision.getSymbolicName() returns null, I would reverse the equals target to be symbolicName.equals(bundle.adapt(BundleRevision.class).getSymbolicName()) This does not scale well if you have large numbers of bundles. If this is a hotspot of your code you can consider using org.osgi.framework.wiring.FrameworkWiring.findProviders(Requirement) using an "osgi.identity" namespace requirement. If I recall correctly virgo uses Equinox regions. That can end up hiding bundles from a BundleContext perspective. Using FrameworkWiring.findProviders would bypass the equinox region hooks so you need to be aware of that.
Source:
private CommunicationChannel getComChannel(boolean local, Event sourceEvent, Connection connection) { CommunicationChannel channel = communicationModel.getChannels().get(sourceEvent); if (channel == null) { if(connection instanceof EventConnection) { //currently only add a channel if an event, data connection should attach to existing channels channel = new CommunicationChannel(); channel.setSourceEvent(sourceEvent); channel.setLocal(local); communicationModel.getChannels().put(sourceEvent, channel); } } else if (!local) { //force non local if needed channel.setLocal(false); } return channel; }

Target:
not sure if this coding rule also applies to our Java code, but null should be lhs
Source:
File getActiveFile() { IWorkbenchPage workbenchPage = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getService(IWorkbenchPage.class); IEditorPart activeEditor = workbenchPage.getActiveEditor(); if (activeEditor == null) return null; IEditorInput editorInput = activeEditor.getEditorInput(); return Adapters.adapt(editorInput, File.class); }

Target:
missing braces
Source:
public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException { RefactoringStatus refactoringStatus = RefactoringStatus.create(Resources.checkInSync(fResource)); if (!refactoringStatus.isOK()) { boolean autoRefresh= Platform.getPreferencesService().getBoolean(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PREF_LIGHTWEIGHT_AUTO_REFRESH, false, null); if (autoRefresh) { fResource.refreshLocal(IResource.DEPTH_INFINITE, pm); refactoringStatus= RefactoringStatus.create(Resources.checkInSync(fResource)); } } return refactoringStatus; }

Target:
I think refactoringStatus can be null as we see in org.eclipse.ltk.core.refactoring.RefactoringStatus.merge(RefactoringStatus)
Source:
public static boolean isShowingEntireContents(StyledText widget) { if (widget.getTopPixel() != 0) // more efficient shortcut return false; int lastVisiblePixel= computeLastVisiblePixel(widget); int bottom= widget.getLineIndex(lastVisiblePixel); if (bottom + 1 < widget.getLineCount()) // There's definitely more lines below return false; // Check whether the last line is fully visible int bottomLastPixel= getLinePixel(widget, bottom + 1) - 1; return bottomLastPixel <= lastVisiblePixel; }

Target:
What's the policy on curly braces in JFace? In EGit we would require them.
Source:
public static void markAsLinkNote(View view) { EAnnotation specificStyles = view.getEAnnotation(ViewQuery.SPECIFIC_STYLES); if (specificStyles == null) { specificStyles = EcoreFactory.eINSTANCE.createEAnnotation(); specificStyles.setSource(ViewQuery.SPECIFIC_STYLES); specificStyles.getDetails().put(SiriusNoteEditPart.LINK_NOTE_STYLE, null); view.getEAnnotations().add(specificStyles); } else { specificStyles.getDetails().put(SiriusNoteEditPart.LINK_NOTE_STYLE, null); } }

Target:
if (specificStyles == null) { specificStyles = EcoreFactory.eINSTANCE.createEAnnotation(); specificStyles.setSource(ViewQuery.SPECIFIC_STYLES); view.getEAnnotations().add(specificStyles); } specificStyles.getDetails().put(SiriusNoteEditPart.LINK_NOTE_STYLE, null);
Source:
protected void decorateView(View containerView, View view, IAdaptable semanticAdapter, String semanticHint, int index, boolean persisted) { EObject element = view.getElement(); if (element instanceof DRepresentationDescriptor) { markAsLinkNote(view); } super.decorateView(containerView, view, semanticAdapter, semanticHint, index, persisted); }

Target:
I think it is better to call the super..decorateView in first
Source:
public void run() { count--; AbstractContributionItem[] copy = itemsToUpdateLater.toArray(new AbstractContributionItem[] {}); itemsToUpdateLater.clear(); for (AbstractContributionItem it : copy) { it.updateItemEnablement(); } }

Target:
-- or set to zero?
Source:
private ProjectTrackerPreferenceSnapshot takeSnapshot() { String branch = getBranch(); if (StringUtils.isEmptyOrNull(branch)) return null; List<String> projectPaths = getAssociatedProjectsPaths(); if (projectPaths == null) return null; return new ProjectTrackerPreferenceSnapshot(repository, branch, projectPaths); }

Target:
What about projectPaths.isEmpty()? Maybe use @NonNull List<String> getAssociatedProjectsPaths() returning Collections.emptyList() instead of null and then test here for projectPaths.isEmpty().
Source:
private void handleMultipleRepositoryCheckoutError( Map<Repository, CheckoutResult> results) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { @Override public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); new MultiBranchOperationResultDialog(shell, results).open(); } }); }

Target:
Lambda?
Source:
private boolean allBranchOperationsSucceeded( final @NonNull Map<Repository, CheckoutResult> results) { return results.entrySet().stream() // .map(Map.Entry::getValue) // .allMatch(r -> r.getStatus() == CheckoutResult.Status.OK); }

Target:
How about results.values().stream().allMatch(...) ?
Source:
private boolean anyRepositoryIsInDetachedHeadState( final @NonNull Map<Repository, CheckoutResult> results) { return results.entrySet().stream() // .map(Map.Entry::getKey) // .anyMatch(RepositoryUtil::isDetachedHead); }

Target:
Same here: results.keySet().stream().anyMatch(...)
Source:
public List<Ref> getRefsByPrefix(String... prefixes) throws IOException { List<Ref> result = new ArrayList<>(); if (prefixes.length == 0) { result.addAll(getRefsByPrefix(ALL)); } else { for (String prefix : prefixes) { result.addAll(getRefsByPrefix(prefix)); } } return Collections.unmodifiableList(result); }

Target:
Do we need this special case? Why not use the 'else' case unconditionally (so that calling getRefsByPrefix(new String[]{}) would produce an empty list)?
Source:
public void testGetRefsByPrefixes() throws IOException { List<Ref> refs = db.getRefDatabase().getRefsByPrefix("refs/heads/p", "refs/tags/A"); assertEquals(3, refs.size()); checkContainsRef(refs, db.exactRef("refs/heads/prefix/a")); checkContainsRef(refs, db.exactRef("refs/heads/pa")); checkContainsRef(refs, db.exactRef("refs/tags/A")); }

Target:
A few more cases discussed during review: * can we have a test for getRefsByPrefix()? * what about ordering of the result? It seems like it's well defined, so should this use something like assertArrayEquals? * what happens with overlapping prefixes?
Source:
public void setMessage (String message) { checkWidget (); if (message == null) error (SWT.ERROR_NULL_ARGUMENT); this.message = message; if (GTK.GTK_VERSION >= OS.VERSION (3, 4, 0)) { if ((style & SWT.SINGLE) != 0) { byte buffer = Converter.wcsToMbcs (message, true); GTK.gtk_entry_set_placeholder_text (handle, buffer); return; } } redraw (false); }

Target:
SWT requires 3.4 already so the guard can be removed.
Source:
protected void createDefaultEditPolicies() { super.createDefaultEditPolicies(); installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE, new DefaultSemanticEditPolicy()); installEditPolicy(AppliedStereotypeLabelDisplayEditPolicy.STEREOTYPE_LABEL_POLICY, new AppliedStereotypeLinkLabelDisplayEditPolicy()); installEditPolicy(EditPolicy.CONNECTION_ENDPOINTS_ROLE, new DurationConstraintLinkSelectionHandlesEditPolicy(this, getEditingDomain())); }

Target:
Modifying generated code is risky. We should extend the EditParts (with a CustomDurationConstraintLinkEditPart), and instantiate these custom parts in org.eclipse.papyrus.uml.diagram.sequence.providers.CustomEditPartProvider Also, DurationObservationLinkEditPart should be modified in the same way
Source:
public void setDefaults(ILaunchConfigurationWorkingCopy configuration, boolean isJUnit) { configuration.setAttribute(IPDELauncherConstants.CONFIG_CLEAR_AREA, !isJUnit); boolean useDefaultArea = !isJUnit || LaunchArgumentsHelper.getDefaultJUnitWorkspaceIsContainer(); configuration.setAttribute(IPDELauncherConstants.CONFIG_USE_DEFAULT_AREA, useDefaultArea); String location; if (isJUnit && !useDefaultArea) { location = LaunchArgumentsHelper.getDefaultJUnitConfigurationLocation(); } else { location = DEFAULT_DIR + configuration.getName(); } configuration.setAttribute(IPDELauncherConstants.CONFIG_LOCATION, location); }

Target:
please just seto to true. Before: true for tests but false for users. After it should be just true by default for all.
Source:
private static List<? extends ICodeMining> logCodeMiningProviderException(Throwable e) { String PLUGIN_ID= "org.eclipse.jface.text"; //$NON-NLS-1$ ILog log= Platform.getLog(Platform.getBundle(PLUGIN_ID)); log.log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, e.getMessage(), e)); return new ArrayList<>(); }

Target:
Still, I don't think this method should return a value. Without the context of usage, it's not clear why there is a return value.
Source:
public static Collection<Stereotype> getAllSuperStereotypes(Stereotype stereotype) { Set<Stereotype> result = new HashSet<>(); if (stereotype != null) { getAllSuperStereotypes(stereotype, result); } return result; }

Target:
type!
Source:
private void createPaintListener(final Table rawTable) { // Tell SWT we will completely handle painting for some columns. // rawTable.addListener(SWT.EraseItem, new Listener() { @Override public void handleEvent(final Event event) { if (0 <= event.index && event.index <= 5) event.detail &= ~SWT.FOREGROUND; } }); rawTable.addListener(SWT.PaintItem, new Listener() { @Override public void handleEvent(final Event event) { doPaint(event); } }); }

Target:
Why the heck are we painting all columns ourselves? We only need to draw column 1 containing the graphical commit tree. This suggests a nice two-liner to fix this: replace above by event.index == 1 and...
Source:
public int getLineVerticalIndent(int index) { checkWidget(); if (index < 0 || index > content.getLineCount()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } return isListening(ST.LineGetStyle) ? 0 : renderer.getLineVerticalIndent(index, verticalIndent); }

Target:
Throws AIOOB exception when called with index = line count.
Source:
private String hostName(String host, int port) { if (port == SSH_PORT) { return host; } return String.format("[%s]:%d", host, port); }

Target:
static?
Source:
private void enableAllFields() { languageLabel.setEnabled(true); if(algorithmGroup != null) algorithmGroup.setEnabled(true); commentLabel.setEnabled(true); commentText.setEnabled(true); languageCombo.setEnabled(true); }

Target:
better make these methods protected and move the algorithmGroup soly to the algorithmgroup class and override the methods where it is used here
Source:
public synchronized void addChild(AbstractCalledFunction child, AggregatedCalledFunction aggregatedChild) { // Update the child's statistics with itself fSelfTime -= aggregatedChild.getDuration(); if (child.getDepth() >= 0) { aggregatedChild.getFunctionStatistics().update(child); } AggregatedCalledFunction node = fChildren.get(aggregatedChild.getSymbol()); if (node == null) { fChildren.put(aggregatedChild.getSymbol(), aggregatedChild); } else { merge(node, aggregatedChild); } }

Target:
The self time should also not be decremented.
Source:
public FsckError check(ProgressMonitor pm) throws IOException { if (pm == null) { pm = NullProgressMonitor.INSTANCE; } FsckError errors = new FsckError(); if (!connectivityOnly) { checkPacks(pm, errors); } checkConnectivity(pm, errors); objChecker.reset(); return errors; }

Target:
In the spirit of defensive programming, I think it would be easiest to have this reset() call to right before checkPacks. (Fewer hard-to-reproduce issues due to a caller leaving some state in the objChecker.)
Source:
public static void assertValidSubmoduleUri(String uri) throws SubmoduleValidationException { if (uri.startsWith("-")) { //$NON-NLS-1$ throw new SubmoduleValidationException( MessageFormat.format( JGitText.get().submoduleUrlInvalid, uri), ObjectChecker.ErrorType.GITMODULES_URL); } }

Target:
Ack
Source:
Object doConvert(BoxedValue input) throws CoreException { if (input instanceof EclString) { String value = ((EclString) input).getValue(); if (value.equals("inf") || value.equals("+inf")) { return Double.POSITIVE_INFINITY; } if (value.equals("-inf")) { return Double.NEGATIVE_INFINITY; } } return BoxedValues.toDouble(input); }

Target:
Lets check if Java allows uppercase literals and if so accept them too.
Source:
protected @Nullable String getSegmentType(@NonNull ISegment segment) { if (segment instanceof ICalledFunction) { ICalledFunction calledFunction = (ICalledFunction) segment; // FIXME work around this trace ITmfTrace trace = TmfTraceManager.getInstance().getActiveTrace(); if (trace != null) { Object symbol = calledFunction.getSymbol(); return String.valueOf(symbol); } } return null; }

Target:
why do you need the trace here?
Source:
public void testFirstWantValidCapabilityNames() throws PackProtocolException { List<String> validNames = Arrays.asList( "c", "cap", "C", "CAP", "1", "1cap", "cap-64k_test", "-", "-cap", "_", "_cap", "agent=pack.age/Version", "cap(this_is_valid!)"); for (String capability: validNames) { FirstWant r = FirstWant.fromLine(makeFirstWantLine(capability)); assertEquals(r.getCapabilities().size(), 1); assertTrue(r.getCapabilities().contains(capability)); } }

Target:
I don't think this example is valid.
Source:
public DsfGdbAdaptor(GdbTrace trace, String gdbExec, String traceFile, String tracedExecutable) { this.fGdbTrace = trace; this.gdb72Executable = gdbExec; this.fTraceFilePath = traceFile; this.fTraceFile = traceFile.substring(traceFile.lastIndexOf(IPath.SEPARATOR) + 1); this.tracedExecutable = tracedExecutable; try { launchDGBPostMortemTrace(); } catch (CoreException e) { GdbTraceCorePlugin.logError(CORE_EXCEPTION, e); } }

Target:
e.getMessage()
Source:
public void dispose() { if (fLaunch != null && fLaunch.canTerminate() && !isTerminating) { isTerminating = true; try { fLaunch.terminate(); } catch (DebugException e) { GdbTraceCorePlugin.logError(GDB_EXCEPTION, e); } fLaunch = null; } }

Target:
e.getMessage()
Source:
public void dispose() { fCurrentEntries = checkNotNull(Collections.emptyList()); fTableViewer = null; fComparator = null; }

Target:
Can remove checkNotNull, we have external @NonNull annotation on Collections.emptyList().
Source:
public int findCloseOffset(String line, int lineOffset) { if (nestedBlock == null) { return findCloseOffset(line, lineOffset); } return nestedBlock.findCloseOffset(line, lineOffset); }

Target:
This line is untested. Can this ever happen? Looks like this could result in a stack overflow since it calls itself with the same parameters.
Source:
private UriSchemeHandlerPreferencePage openPreferenceAndGetPage() { Shell shell = Display.getCurrent().getActiveShell(); this.dialog = PreferencesUtil.createPreferenceDialogOn(shell, "org.eclipse.ui.preferencePages.General.LinkHandlers", null, null); this.dialog.setBlockOnOpen(false); this.dialog.open(); return (UriSchemeHandlerPreferencePage) this.dialog.getSelectedPage(); }

Target:
What about new Shell(); Does this work?
Source:
Builder addClientCapabilities(Collection<String> clientCapabilities) { for (String cap: clientCapabilities) { // TODO(ifrade): Do this is done on parse time if (cap.startsWith("agent=")) { //$NON-NLS-1$ setAgent(cap.substring("agent=".length())); //$NON-NLS-1$ } else { clientCaps.add(cap); } } clientCaps.addAll(clientCapabilities); return this; }

Target:
This adds the caps a second time.
Source:
private static boolean canMatchPacket(final ITmfEvent event) { /* Make sure all required fields are present to match with this event */ ITmfEventField content = event.getContent(); return ((content.getFieldValue(Long.class, TcpEventStrings.SEQ) == null) || (content.getFieldValue(Long.class, TcpEventStrings.ACKSEQ) == null) || (content.getFieldValue(Long.class, TcpEventStrings.FLAGS) == null)); }

Target:
Shouldn't the whole expression be negated?
Source:
private static boolean isVisibleEventColumn(TableColumn column) { if (column.getData(Key.ASPECT) == TmfMarginColumn.MARGIN_ASPECT) { return false; } return (!column.getResizable() && column.getWidth() == 0); }

Target:
needs to be negated, right?
Source:
protected boolean verifyChildrenSpecific(N parent, int index, N child) { return (parent.getChildStart(index) != child.getNodeStart() && parent.getChildEnd(index) != child.getNodeEnd()); }

Target:
OOPS!
Source:
private boolean isBinaryEquivalent(IntegerDeclaration other) { if (fAlignment != other.fAlignment) { return false; } if (fLength != other.fLength) { return false; } if (fSigned != other.fSigned) { return false; } // no need for base // no need for encoding // no need for clock // byte inversion is ok on byte order if the element is one byte long return !(fLength == BYTE_ALIGN) && fByteOrder.equals(other.fByteOrder); }

Target:
This is not equivalent.
Source:
private static boolean canMatchPacket(final ITmfEvent event) { /* Make sure all required fields are present to match with this event */ ITmfEventField content = event.getContent(); return ((content.getFieldValue(Long.class, TcpEventStrings.SEQ) != null) || (content.getFieldValue(Long.class, TcpEventStrings.ACKSEQ) != null) || (content.getFieldValue(Long.class, TcpEventStrings.FLAGS) != null)); }

Target:
This is not equivalent. || should be &&
Source:
protected boolean checkLevelExists(int level) { return !(level < levelQuarks.size() || level >= 0); }

Target:
This is not equivalent
Source:
private static boolean isVisibleEventColumn(TableColumn column) { if (column.getData(Key.ASPECT) == TmfMarginColumn.MARGIN_ASPECT) { return false; } return (column.getResizable() && column.getWidth() > 0); }

Target:
This is not equivalent
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } HistogramBucket other = (HistogramBucket) obj; if (fNbEvents != other.fNbEvents) { return false; } return (fNbEvents == 0 && Arrays.equals(fEvents, other.fEvents)); }

Target:
This is not equivalent. && should be ||
Source:
protected SimpleName getNewName(ASTRewrite rewrite) { AST ast= rewrite.getAST(); SimpleName nameNode= ast.newSimpleName(String.valueOf("provider")); //$NON-NLS-1$ // TypeConstants.PROVIDER return nameNode; }

Target:
Is this a left-over from trying to use the char[] constant from jdt.core? I suggest to make it a regular String constant in this class.
Source:
protected IStatus validateItem(Object item) { for (int i = 0; i < fdisabledModels.length; i++) { if (((IPluginModelBase) item).equals(fdisabledModels[i])) { return new Status(IStatus.CANCEL, IPDEUIConstants.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ } } return new Status(IStatus.OK, IPDEUIConstants.PLUGIN_ID, 0, "", null); //$NON-NLS-1$ }

Target:
cast not needed for equals
Source:
private TemplateStoreInitializer getTemplateStoreInitializer() { if (fJavaPluginInitializer == null) { fJavaPluginInitializer = new TemplateStoreInitializer(); fJavaPluginInitializer.activate(); } return fJavaPluginInitializer; }

Target:
Shouldn't this be synchronized?
Source:
public long getValueReference() { if (getFmiVariable() != null){ return (int)getFmiVariable().getValueReference(); } return super.getValueReference(); }

Target:
I do not know the code but are you sure of the cast ? Since the result type is long it could be good but I am not sure
Source:
public long getValueReference() { if (getFmiVariable() != null) { return (int) getFmiVariable().getValueReference(); } return super.getValueReference(); }

Target:
idem
Source:
private static List<String> mapValuesToListIgnoreCase(String keyName, Map<String, List<String>> m) { List<String> fields = new LinkedList<>(); m.entrySet().stream().filter(e -> keyName.equalsIgnoreCase(e.getKey())) .forEach(e -> fields.addAll(e.getValue())); return fields; }

Target:
Are we sure that we can never have e.getValue() == null ?
Source:
private void checkAlignment(String errorMessage, int expectedAlignment, int actualAlignment) { switch (expectedAlignment) { case PositionConstants.LEFT: assertEquals("wrong text wrap alignment.", PositionConstants.LEFT, actualAlignment); break; case PositionConstants.RIGHT: assertEquals("wrong text wrap alignment.", PositionConstants.RIGHT, actualAlignment); break; case PositionConstants.CENTER: assertEquals("wrong text wrap alignment.", PositionConstants.CENTER, actualAlignment); break; default: break; }; }

Target:
use this parameter to replace hard coded texts
Source:
public JavaReferenceCodeMining(IJavaElement element, JavaEditor editor, IDocument document, ICodeMiningProvider provider, boolean showReferencesAtLeastOne) throws JavaModelException, BadLocationException { super(element, document, provider, null); this.showReferencesAtLeastOne= showReferencesAtLeastOne; action= e -> new FindReferencesAction(editor).run(element); }

Target:
Shouldn't it be set in the doResolve instead?
Source:
public Consumer<MouseEvent> getAction() { if (refCount > 0) { return action; } return null; }

Target:
If action is set in the doResolve depending on the refCount: * refCount can remain a variable instead of a field * the condition become useless and you can just return `action`
Source:
public JavaImplementationCodeMining(IType element, JavaEditor editor, IDocument document, ICodeMiningProvider provider, boolean showImplementationsAtLeastOne) throws JavaModelException, BadLocationException { super(element, document, provider, e -> new FindImplementorsAction(editor).run(element)); this.showImplementationsAtLeastOne= showImplementationsAtLeastOne; }

Target:
This should only be set if the number of implementation is not 0. I suggest you set this in the doResolve() according to the result.
Source:
private void notifyClick(final Point p) { notify(SWT.MouseEnter); notify(SWT.Activate); notify(SWT.FocusIn); notify(SWT.Selection); notify(SWT.MouseDown, createMouseEvent(p.x, p.y, 1, SWT.NONE, 1)); notify(SWT.MouseUp, createMouseEvent(p.x, p.y, 1, SWT.BUTTON1, 1)); }

Target:
I don't see a SWT.Selection event when I click, except if there was a non-empty selection before, then clicking clears the selection.
Source:
public void test() { final HelloWorld hello = new HelloWorld(); assertTrue("Hello World".equals(hello.test())); }

Target:
Couldn't we use assertEquals(...) here instead for better reports in case of failur?
Source:
private static ClassLoader createCombinedClassLoader(String testPlugin) throws BundleException { ClassLoader testClassLoader = getBundleClassLoader(testPlugin); ClassLoader contextFinder = Thread.currentThread().getContextClassLoader(); ClassLoader surefireClassLoader = ForkedBooter.class.getClassLoader(); return new CombinedClassLoader(testClassLoader, new TychoContextFinder(contextFinder.getParent()), surefireClassLoader); }

Target:
I think context finder should be the last in the list because classloading happens in this order
Source:
public synchronized void dispose() { synchronized (this) { if (fFileInput != null) { try { fFileInput.close(); } catch (IOException e) { Activator.getInstance().logError("Error disposing trace. File: " + getPath(), e); //$NON-NLS-1$ } } } super.dispose(); }

Target:
I think it's unnecessary, method is synchronized?
Source:
public Object run(Object object) throws Exception { String[] args = Platform.getCommandLineArgs(); // https://bugs.eclipse.org/bugs/show_bug.cgi?id=540222: log stack traces when we are nearing the test timeout String timeoutParameter = getParameterValue(args, "-timeout"); //$NON-NLS-1$ if (timeoutParameter != null) { DumpStackTracesTimer.startStackDumpTimeoutTimer(timeoutParameter); } return Integer.valueOf(OsgiSurefireBooter.run(args)); }

Target:
Couldn't we have the timeout check implmented in the OsgiSurefireBooter (or a parent) instead? It would most likely allow easier reuse.
Source:
public void run() { CompoundCommand updateCmd = new CompoundCommand(); for(Object obj : getSelectedObjects()){ if (obj instanceof AbstractFBNElementEditPart) { UpdateFBTypeCommand cmd; cmd = new UpdateFBTypeCommand(((AbstractFBNElementEditPart) obj).getModel(), entry); if (cmd.canExecute()) { updateCmd.add(cmd); } } } execute(updateCmd); }

Target:
that could be merged into one line
Source:
protected HttpURLConnection createConnection(String uri) throws IOException { URL url = new URL(createUri(uri)); if (proxy != null) return (HttpURLConnection) url.openConnection(proxy); return (HttpURLConnection) url.openConnection(); }

Target:
Please add curly braces {}, also for single-line bodies. I know, old code doesn't have this, but for new code we require it since several years. We add it where we change things anyway, so don't change all the other ifs in this source.
Source:
private ACUser findUser(String name) throws ESException { ACUser result = null; for (final ACUser user : adminBroker.getUsers()) { if (user.getName().equals(name)) { result = user; } } return result; }

Target:
We could break here (applies to findGroup as well)
Source:
public String getName() { return fName.get(0); }

Target:
possible exception
Source:
public ICleanUpFix createFix(CleanUpContext context) throws CoreException { ICleanUpFixCore fixCore= coreCleanUp.createFixCore(context); return fixCore == null ? null : new CleanUpFixWrapper(coreCleanUp.createFixCore(context)); }

Target:
Could this just be 'fixCore' instead of creating the object twice ?
Source:
private void changeExperimentName(TracePackageExperimentElement experimentElement) { String currentName = experimentElement.getImportName(); int nameSuffixIndex = 1; while (experimentExists(experimentElement)) { String newName = currentName + " (" + nameSuffixIndex + ')'; //$NON-NLS-1$ experimentElement.setImportName(newName); nameSuffixIndex++; } }

Target:
Should start at 2
Source:
public void testResolveTipSha1() throws IOException { ObjectId masterId = db.resolve("refs/heads/master"); Set<Ref> resolved = db.getRefDatabase().resolveTipSha1(masterId); assertEquals(resolved.size(), 2); checkContainsRef(resolved, db.exactRef("refs/heads/master")); checkContainsRef(resolved, db.exactRef("HEAD")); assertEquals(db.getRefDatabase() .resolveTipSha1(ObjectId.zeroId()).size(), 0); }

Target:
The arguments here are in the opposite order to previous uses, for example at L347. Which order is correct? If it's this one, we should do a cleanup of the others.
Source:
public void setGetterName(String name) { Assert.isNotNull(fGetterName); fGetterName= name; fCreateGetter= !fGetterName.isEmpty(); }

Target:
This could probably be an assert since it is invalid and shouldn't get passed. The Encapsulate Field dialog doesn't allow an empty string and shows an error (though the message is not properly referenced and shows the id instead of the message).