auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean isResolved() { START return resolveFuture == null || resolveFuture.isDone() || label != null; END } That's not very clear: if doResolve does return null, it most likely means that the CodeMining doesn't require resolution, so isResolved should be true. The implementation seems erroneous here. This may be caused by `resolveFuture == null` which can mean 2 different things: either the future wasn't requested yet, or the future was requested and null was returned (ie no resolution required). I believe you need some more details or another state variable in the class to distinguish both cases.

Target:
public boolean isResolved() { return (resolveFuture != null && resolveFuture.isDone()); }
Source:
public void testNoDefaulColortMenuInAppearancePropertyViewFromContainerMappingFontColor() { selectAndCheckEditPart(NODE_CONTAINER, DNodeContainerEditPart.class); bot.viewByTitle("Properties").setFocus(); SWTBotSiriusHelper.selectPropertyTabItem("Appearance"); try { bot.viewByTitle("Properties").bot().buttonInGroup("Fonts and Colors:", 0).click().contextMenu(DEFAULT_COLOR); fail(); } catch (WidgetNotFoundException e) { START assertTrue(true); END } } All of these are completely useless.

Target:
public void testNoDefaulColortMenuInAppearancePropertyViewFromContainerMappingFontColor() { selectAndCheckEditPart(NODE_CONTAINER, DNodeContainerEditPart.class); bot.viewByTitle("Properties").setFocus(); SWTBotSiriusHelper.selectPropertyTabItem("Appearance"); try { bot.viewByTitle("Properties").bot().buttonInGroup("Fonts and Colors:", 0).click().contextMenu(DEFAULT_COLOR); fail(); } catch (WidgetNotFoundException e) { // Expected exception, do nothing. } }
Source:
public void setProgressMonitor(ProgressMonitor monitor) { if (monitor == null) { START monitor = END NullProgressMonitor.INSTANCE; } this.monitor = monitor; } `this.monitor` to avoid confusion with the parameter of the same name optional: this whole block could be a ternary: this.monitor = monitor != null ? monitor : NullProgressMonitor.INSTANCE;

Target:
public void setProgressMonitor(ProgressMonitor monitor) { this.monitor = monitor != null ? monitor : NullProgressMonitor.INSTANCE; }
Source:
public void cleanup() { fModule.dispose(); START fTrace.dispose(); CtfTmfTestTraceUtils.dispose(getTestTrace()); END } they both disposing the same trace. Keep the second call

Target:
public void cleanup() { fModule.dispose(); CtfTmfTestTraceUtils.dispose(getTestTrace()); }
Source:
private static ImportDeclaration getProblematicImport(IProblem problem, CompilationUnit cu) { ASTNode coveringNode= new NodeFinder(cu, problem.getSourceStart(), START problem.getSourceEnd() - problem.getSourceStart()).getCoveringNode(); END if (coveringNode != null) { ASTNode importNode= ASTNodes.getParent(coveringNode, ASTNode.IMPORT_DECLARATION); if (importNode instanceof ImportDeclaration) { return (ImportDeclaration) importNode; } } return null; } Check the old code where: fLength= problem.getSourceEnd() - fOffset + 1; Here, +1 is missing.

Target:
private static ImportDeclaration getProblematicImport(IProblem problem, CompilationUnit cu) { ASTNode coveringNode= new NodeFinder(cu, problem.getSourceStart(), problem.getSourceEnd() - problem.getSourceStart() + 1).getCoveringNode(); if (coveringNode != null) { ASTNode importNode= ASTNodes.getParent(coveringNode, ASTNode.IMPORT_DECLARATION); if (importNode instanceof ImportDeclaration) { return (ImportDeclaration) importNode; } } return null; }
Source:
public void setStatusLineManager(IStatusLineManager statusLineManager) { if (fStatusLineManager != null && statusLineManager == null) { START fStatusLineManager.setMessage(""); END //$NON-NLS-1$ } fStatusLineManager = statusLineManager; } according to the docs, you are supposed to pass null to clear the message

Target:
public void setStatusLineManager(IStatusLineManager statusLineManager) { if (fStatusLineManager != null && statusLineManager == null) { fStatusLineManager.setMessage(null); } fStatusLineManager = statusLineManager; }
Source:
public Object addInheritableProperty(String key, Object value) { if (getNonInheritableProperties().containsKey(key)) { START final Object oldValue = getNonInheritableProperties().get(key); END getNonInheritableProperties().removeKey(key); getInheritableProperties().put(key, value); return oldValue; } return getInheritableProperties().put(key, value); } removeKey returns the value already no need to fetch it first

Target:
public Object addInheritableProperty(String key, Object value) { if (getNonInheritableProperties().containsKey(key)) { // removes the entry with the given key (due to EMap interface instead of Map) final Object oldValue = getNonInheritableProperties().removeKey(key); getInheritableProperties().put(key, value); return oldValue; } return getInheritableProperties().put(key, value); }
Source:
public START @Nullable String END getRemoteBranchName() { return remoteBranchName; } Move to a separate commit

Target:
public String getRemoteBranchName() { return remoteBranchName; }
Source:
START public int getWidth() { END return width; } Shouldn't we make it final in a 1st iteration or do you have use-cases that need to override it?

Target:
public final int getWidth() { return width; }
Source:
START public void setWidth(int width) { END this.width= width; } Does this need to be public? It seems to me this would only be useful to call from subclasses, so it could be protected. Shouldn't we make it final in a 1st iteration or do you have use-cases that need to override it?

Target:
protected final void setWidth(int width) { this.width= width; }
Source:
public static synchronized @Nullable SegmentStoreScatterDataProvider START create(ITmfTrace END trace, @Nullable ISegmentStoreProvider provider) { if (provider == null) { return null; } SegmentStoreScatterDataProvider dataProvider = PROVIDER_MAP.get(provider); if (dataProvider != null) { return dataProvider; } if (provider instanceof IAnalysisModule) { ((IAnalysisModule) provider).schedule(); dataProvider = new SegmentStoreScatterDataProvider(trace, provider); PROVIDER_MAP.put(provider, dataProvider); } return null; } rename smth like getOrCreate?

Target:
public static synchronized @Nullable SegmentStoreScatterDataProvider create(ITmfTrace trace, @Nullable ISegmentStoreProvider provider) { if (provider == null) { return null; } SegmentStoreScatterDataProvider dataProvider = PROVIDER_MAP.get(provider); if (dataProvider != null) { return dataProvider; } dataProvider = new SegmentStoreScatterDataProvider(trace, provider); PROVIDER_MAP.put(provider, dataProvider); if (provider instanceof IAnalysisModule) { ((IAnalysisModule) provider).schedule(); } return dataProvider; }
Source:
public void dispose() { menuManager.dispose(); if (toolbarManager != null) { START ((ToolBarManager) toolbarManager).dispose(); END } super.dispose(); } could be removed if the field will have right type

Target:
public void dispose() { menuManager.dispose(); if (toolbarManager != null) { toolbarManager.dispose(); } super.dispose(); }
Source:
public int compare(String o1, String o2) { String name1 = tocNames.get(o1); String name2 = tocNames.get(o2); if (name1 == null) { return START -1; END } if (name2 == null) { return 1; } return Collator.getInstance().compare(name1, name2); } case not handled when both are null name2 != null ? -1 : 0

Target:
public int compare(String o1, String o2) { String name1 = tocNames.get(o1); String name2 = tocNames.get(o2); if (name1 == null) { return (name2 != null) ? -1 : 0; } if (name2 == null) { return 1; } return Collator.getInstance().compare(name1, name2); }
Source:
private static void loadXmlFile() { XmlUtils.addXmlFile(TmfXmlTestFiles.CONDITION_FILE.getFile()); XmlUtils.addXmlFile(TmfXmlTestFiles.VALID_TIMEGRAPH_VIEW_ELEMENT_FILE.getFile()); START File xmlFile = XmlUtils.getXmlFilesPath().addTrailingSeparator().append(TmfXmlTestFiles.VALID_TIMEGRAPH_VIEW_ELEMENT_FILE.getFile().getName()).toFile(); XmlUtils.preloadXmlAnalysesOutput(xmlFile); END XmlAnalysisModuleSource.notifyModuleChange(); } What bugs me is that you have to worry about the file path before calling this, this shouldn't be... You should be able to just call the preload with the same File as the one in addXmlFile.

Target:
private static void loadXmlFile() { XmlUtils.addXmlFile(TmfXmlTestFiles.CONDITION_FILE.getFile()); XmlUtils.addXmlFile(TmfXmlTestFiles.VALID_TIMEGRAPH_VIEW_ELEMENT_FILE.getFile()); XmlAnalysisModuleSource.notifyModuleChange(); }
Source:
public static int determineModularClasspathProperty(IClasspathEntry entry) { return Arrays.stream(entry.getExtraAttributes()) START .anyMatch(p -> p.getName().equals(IClasspathAttribute.MODULE) && p.getValue().equals("true")) END ? IRuntimeClasspathEntry.MODULE_PATH : IRuntimeClasspathEntry.CLASS_PATH; } "true".equals(p.getValue()) if getValue() can yield null

Target:
public static int determineModularClasspathProperty(IClasspathEntry entry) { return Arrays.stream(entry.getExtraAttributes()) .anyMatch(p -> p.getName().equals(IClasspathAttribute.MODULE) && "true".equals(p.getValue())) ? IRuntimeClasspathEntry.MODULE_PATH : IRuntimeClasspathEntry.CLASS_PATH; }
Source:
public boolean isMergerFor(Diff target) { START final Conflict conflict = target.getConflict(); END return conflict != null && conflict.getKind() == ConflictKind.PSEUDO; } I'll take this occasion to mention this. This kind of variable extraction does nothing for performance and often hinders readability. please avoid them (they're cluttering most of these "performance" patches). Simple getters like this are only highlighted by profilers because of the instrumentation.

Target:
public boolean isMergerFor(Diff target) { return target.getConflict() != null && target.getConflict().getKind() == ConflictKind.PSEUDO; }
Source:
public boolean equals(Object obj) { if (!(obj instanceof DependencyEvent)) { return false; } DependencyEvent other = (DependencyEvent) obj; return START Objects.equals(fTrace, END other.fTrace) && Objects.equals(fTimestamp, other.fTimestamp); } Objects.equals is safe though.

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof DependencyEvent)) { return false; } DependencyEvent other = (DependencyEvent) obj; return Objects.equals(fTrace, other.fTrace) && Objects.equals(fTimestamp, other.fTimestamp); }
Source:
protected void okPressed() { boolean copyAsLink = false; START if(fCopyLinkButton != null) { END copyAsLink = fCopyLinkButton.getSelection(); } IResource trace = copyTrace(fNewTraceName.getText(), copyAsLink); if (trace == null) { return; } setSelectionResult(new IResource[] { trace }); super.okPressed(); } Missing space. Or could be shortened as: copyAsLink = not null && is selected;

Target:
protected void okPressed() { boolean copyAsLink = fCopyLinkButton != null ? fCopyLinkButton.getSelection() : false; IResource trace = copyTrace(fNewTraceName.getText(), copyAsLink); if (trace == null) { return; } setSelectionResult(new IResource[] { trace }); super.okPressed(); }
Source:
public FtraceEvent(ITmfTrace trace, long rank, FtraceField field) { super(trace, rank, TmfTimestamp.fromNanos(field.getTs()), FtraceEventTypeFactory.get(field.getName()), field.getContent()); fField = field; fName = field.getName(); START fLogLevel = Level.INFO; END fCallsite = null; } Do we need this?

Target:
public FtraceEvent(ITmfTrace trace, long rank, FtraceField field) { super(trace, rank, TmfTimestamp.fromNanos(field.getTs()), FtraceEventTypeFactory.get(field.getName()), field.getContent()); fField = field; fName = field.getName(); fCallsite = null; }
Source:
public Stream<Tuple> getAllMatches(Object[] parameters) { START return matchAll(parameters, notNull(parameters)).stream(); END } matchAll will internally still copy the entire match set, so in case of hybrid matching, this will not perform as expected

Target:
public Stream<Tuple> getAllMatches(Object[] parameters) { return matchAll(parameters, notNull(parameters)); }
Source:
START private void END checkCanceled(IProgressMonitor pm) { if (pm.isCanceled()) throw new OperationCanceledException(); } static

Target:
private static void checkCanceled(IProgressMonitor pm) { if (pm.isCanceled()) throw new OperationCanceledException(); }
Source:
START private ITypeHierarchy END createHierarchyOfTypes(IProgressMonitor pm, WorkingCopyOwner owner, Stream<IType> types) throws JavaModelException { IRegion region= JavaCore.newRegion(); for (Iterator<IType> iter= types.iterator(); iter.hasNext(); ) { IType type= iter.next(); region.add(type); } return JavaCore.newTypeHierarchy(region, owner, pm); } static

Target:
private static ITypeHierarchy createHierarchyOfTypes(IProgressMonitor pm, WorkingCopyOwner owner, Stream<IType> types) throws JavaModelException { IRegion region= JavaCore.newRegion(); for (Iterator<IType> iter= types.iterator(); iter.hasNext(); ) { IType type= iter.next(); region.add(type); } return JavaCore.newTypeHierarchy(region, owner, pm); }
Source:
private static void checkCanceled(IProgressMonitor pm) { START if (pm.isCanceled()) END throw new OperationCanceledException(); } can you please use for if block. I know the old code doesn't use this always, but in the new code we can do better.

Target:
private static void checkCanceled(IProgressMonitor pm) { if (pm.isCanceled()) { throw new OperationCanceledException(); } }
Source:
public OperationReport getOperationSummary() { String operationSummaryJson = artifact.getSoleAttributeAsString(DispoConstants.OperationSummary, "{}"); START try { return DispoUtil.jsonObjToOperationSummary(operationSummaryJson); } catch (Exception ex) { throw new OseeCoreException("Could not parse Operation Summary Json", ex); } END } move try-catch to DispoUtil.jsonObjToOperationSummary

Target:
public OperationReport getOperationSummary() { String operationSummaryJson = artifact.getSoleAttributeAsString(DispoConstants.OperationSummary, "{}"); return DispoUtil.jsonObjToOperationSummary(operationSummaryJson); }
Source:
private void ensureAllSet(EventTester tester) { String[] unfiredIds = tester.getAttIds(false); if (unfiredIds.length > 0) { START StringBuilder msg = new StringBuilder("No event fired:" + unfiredIds); END for (int i = 0; i < unfiredIds.length; i++) { msg.append(' ' + unfiredIds[i]); } fail(msg.toString()); } } use append instead of +

Target:
private void ensureAllSet(EventTester tester) { String[] unfiredIds = tester.getAttIds(false); if (unfiredIds.length > 0) { StringBuilder msg = new StringBuilder("No event fired:").append(unfiredIds); for (int i = 0; i < unfiredIds.length; i++) { msg.append(' ').append(unfiredIds[i]); } fail(msg.toString()); } }
Source:
public String getName() { // String name = ""; //$NON-NLS-1$ StringBuilder name = new StringBuilder(); for (int i = 0; i < (input.length - 1); i++) { START name.append(input[i].getName() + "/"); //$NON-NLS-1$ END } name.append(input[input.length - 1].getName()); return name.toString(); } use append instead of +

Target:
public String getName() { StringBuilder name = new StringBuilder(); for (int i = 0; i < (input.length - 1); i++) { name.append(input[i].getName()).append("/"); //$NON-NLS-1$ } name.append(input[input.length - 1].getName()); return name.toString(); }
Source:
public boolean setSubtreeChecked(Object element, boolean state) { START IPreCheckStateListener preCheckStateListener = fPreCheckStateListener; END if (preCheckStateListener != null && preCheckStateListener.setSubtreeChecked(element, state)) { // uncheck the root element setChecked(element, false); return false; } checkSubtree(element, state); return fCheckboxTreeViewer.setSubtreeChecked(element, state); } This doesn't get executed in our case because TriStateFilteredCheckboxTree overrides setSubtreeChecked().

Target:
public boolean setSubtreeChecked(Object element, boolean state) { checkSubtree(element, state); return fCheckboxTreeViewer.setSubtreeChecked(element, state); }
Source:
private AbstractSelectTreeViewer(Composite parent, TriStateFilteredCheckboxTree checkboxTree, int legendIndex, String id) { super(parent, checkboxTree.getViewer()); TreeViewer treeViewer = checkboxTree.getViewer(); treeViewer.setComparator(COMPARATOR); if (treeViewer instanceof CheckboxTreeViewer) { ((CheckboxTreeViewer) treeViewer).addCheckStateListener(new CheckStateChangedListener()); } fCheckboxTree = checkboxTree; fLegendIndex = legendIndex; fId = id; START checkboxTree.setPreCheckStateListener(new ManyEntriesSelectedDialogPreCheckedListener(checkboxTree)); END } I would prefer if the listener was added in TmfChartView.coupleSelectViewer(). The Many... listener should also go in that package. AbstractSelectTreeViewer would need either a addPreCheckListener() or getFilteredCheckboxTree() method.

Target:
private AbstractSelectTreeViewer(Composite parent, TriStateFilteredCheckboxTree checkboxTree, int legendIndex, String id) { super(parent, checkboxTree.getViewer()); TreeViewer treeViewer = checkboxTree.getViewer(); treeViewer.setComparator(COMPARATOR); if (treeViewer instanceof CheckboxTreeViewer) { ((CheckboxTreeViewer) treeViewer).addCheckStateListener(new CheckStateChangedListener()); } fCheckboxTree = checkboxTree; fLegendIndex = legendIndex; fId = id; }
Source:
START public boolean isInVisibleLines() { END return support.isInVisibleLines(this); } Does this one have to be public? As an extender of such annotation, I don't think this is something I would need to invoke directly and I'd expect the underlying framework to do the necssary optimizations.

Target:
protected boolean isInVisibleLines() { return support.isInVisibleLines(this); }
Source:
START public boolean isInVisibleLines(AbstractInlinedAnnotation annotation) { END return visibleLines.isInVisibleLines(annotation); } Does it have to be public? Couldn't it be package visible only?

Target:
boolean isInVisibleLines(AbstractInlinedAnnotation annotation) { return visibleLines.isInVisibleLines(annotation); }
Source:
protected final Collection<DRepresentation> getRepresentationsByName(final String representationName) { final Collection<DRepresentation> representations = START DialectManager.INSTANCE.getAllLoadedRepresentations(session).stream().filter(rep -> rep.getName().equals(representationName)) END .collect(Collectors.toList()); return representations; } representationName.equals(rep -> rep.getName())

Target:
protected final List<DRepresentation> getRepresentationsByName(final String representationName) { final List<DRepresentation> representations = DialectManager.INSTANCE.getAllLoadedRepresentations(session).stream().filter(rep -> representationName.equals(rep.getName())) .collect(Collectors.toList()); return representations; }
Source:
public boolean canExecute(ITmfTrace trace) { if (!(trace instanceof TmfExperiment)) { throw new START IllegalStateException(); END } return super.canExecute(trace); } you can just return false here, even better : return trace instanceof TmfExperiment && super.canExecute(trace);

Target:
public boolean canExecute(ITmfTrace trace) { return (trace instanceof TmfExperiment) && super.canExecute(trace); }
Source:
public void after() { START fTrace.dispose(); END } technically, you should null check here

Target:
public void after() { if (fTrace == null) { fTrace.dispose(); } }
Source:
public static PackIndex open(final File idxFile) throws IOException { try (SilentFileInputStream fd = new SilentFileInputStream( idxFile)) { START try { END return read(fd); } catch (IOException ioe) { throw new IOException( MessageFormat.format(JGitText.get().unreadablePackIndex, idxFile.getAbsolutePath()), ioe); } } } unnecessary nested try block

Target:
public static PackIndex open(final File idxFile) throws IOException { try (SilentFileInputStream fd = new SilentFileInputStream( idxFile)) { return read(fd); } catch (IOException ioe) { throw new IOException( MessageFormat.format(JGitText.get().unreadablePackIndex, idxFile.getAbsolutePath()), ioe); } }
Source:
public @NonNull String getPresetFilterName(String presetFilterId) { String presetFilterName = START null; END if (fPresetFilterName != null) { presetFilterName = fPresetFilterName.get(presetFilterId); } if (presetFilterName == null && fPresetFilter != null) { presetFilterName = fPresetFilter.get(fPresetFilter.indexOf(presetFilterId)); } return presetFilterName == null ? "" : presetFilterName; //$NON-NLS-1$ } "" to remove the last ternary

Target:
public @NonNull String getPresetFilterName(String presetFilterId) { String presetFilterName = presetFilterId; if (fPresetFilterName != null) { presetFilterName = fPresetFilterName.get(presetFilterId); } return presetFilterName == null ? "" : presetFilterName; //$NON-NLS-1$ }
Source:
public START int getIndex() END { return findex; } long

Target:
public long getIndex() { return findex; }
Source:
private static final HostThread readHostThread(ISafeByteBufferReader buffer) { /* the first short = the size to read */ START 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$ } END int tid = buffer.getInt(); return new HostThread(host, tid); } buffer.getString()?

Target:
private static final HostThread readHostThread(ISafeByteBufferReader buffer) { String host = buffer.getString(); int tid = buffer.getInt(); return new HostThread(host, tid); }
Source:
public void setFocus() { StyledText widget = START fSourceViewer.getTextWidget(); END if (fSourceViewer != null && widget != null && !widget.isDisposed()) { widget.setFocus(); } } That could be null ;-). Also note, that Text uses compact assignment.

Target:
public void setFocus() { if (fSourceViewer != null) { StyledText widget = fSourceViewer.getTextWidget(); if (widget != null && !widget.isDisposed()) { widget.setFocus(); } } }
Source:
private Method getConditionMethod(Class<?> clazz) { for (Method checkMethod : clazz.getMethods()) { if (checkMethod.getName().equals("getCondition") && (checkMethod.getModifiers() & Modifier.STATIC) START != Modifier.STATIC END && checkParameterTypes(checkMethod.getParameterTypes())) { return checkMethod; } } return null; } We are looking for a static method here, so this should be an == check.

Target:
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; }
Source:
default String getPreferenceKey() { return START getClass().getCanonicalName(); END } Actually should be getName(), because getCanonicalName() can return null for an anonymous class.

Target:
default String getPreferenceKey() { return getClass().getName(); }
Source:
private static String getPath(ITimeGraphPresentationProvider presentationProvider, StateItem stateItem) { String START stateTypeName = END String.valueOf(presentationProvider.getId()); String stateName = stateItem.getStateString(); if (isLink(stateItem)) { return PREFIX + stateTypeName + SEPARATOR + LINK + stateName; } return PREFIX + stateTypeName + SEPARATOR + stateName; } id?

Target:
private static String getPath(ITimeGraphPresentationProvider presentationProvider, StateItem stateItem) { String id = String.valueOf(presentationProvider.getId()); String stateName = stateItem.getStateString(); if (isLink(stateItem)) { return PREFIX + id + SEPARATOR + LINK + stateName; } return PREFIX + id + SEPARATOR + stateName; }
Source:
START public static boolean isGerritVersion(String verString) { END return verString != null && GERRIT_SSHD_REPLY.matcher(verString).matches(); } if you move the test to package org.eclipse.egit.core.op this method doesn't need to be public

Target:
static boolean isGerritVersion(String verString) { return verString != null && GERRIT_SSHD_REPLY.matcher(verString).matches(); }
Source:
public void START setFetchAtomic(final boolean END atomic) { this.fetchAtomic = Optional.of(atomic); } nit. unnecessary 'final'

Target:
public void setFetchAtomic(final boolean atomic) { this.fetchAtomic = atomic; }
Source:
protected void registerChanges(final TextEditBasedChangeManager manager) throws CoreException { CompilationUnitRewrite rewrite= null; Set<Entry<ICompilationUnit, CompilationUnitRewrite>> entrySet= fCompilationUnitRewrites.entrySet(); START for (Entry<ICompilationUnit, CompilationUnitRewrite> entry : entrySet) { END ICompilationUnit unit= entry.getKey(); rewrite= entry.getValue(); if (rewrite != null) { final CompilationUnitChange change= rewrite.createChange(true); if (change != null) manager.manage(unit, change); } } } Variable entrySet seems to be unnecessary? Could be replaced by fCompilationUnitRewrites.entrySet() directly, without loss of efficiency or clarity.

Target:
protected void registerChanges(final TextEditBasedChangeManager manager) throws CoreException { CompilationUnitRewrite rewrite= null; for (Entry<ICompilationUnit, CompilationUnitRewrite> entry : fCompilationUnitRewrites.entrySet()) { ICompilationUnit unit= entry.getKey(); rewrite= entry.getValue(); if (rewrite != null) { final CompilationUnitChange change= rewrite.createChange(true); if (change != null) manager.manage(unit, change); } } }
Source:
public void setArch(String arch) { incrementSequenceNumber(); fArch = arch; if (fRoot != null && arch != null && START arch.length() > 0) { END Element archNode = TargetDefinitionDocumentTools.getChildElement(fRoot, TargetDefinitionPersistenceHelper.ENVIRONMENT, TargetDefinitionPersistenceHelper.ARCH); archNode.setTextContent(arch); } else { removeElement(TargetDefinitionPersistenceHelper.ENVIRONMENT, TargetDefinitionPersistenceHelper.ARCH); } } Please use !string.isEmpty().

Target:
public void setArch(String arch) { incrementSequenceNumber(); fArch = arch; if (fRoot != null && arch != null && !arch.isEmpty()) { Element archNode = TargetDefinitionDocumentTools.getChildElement(fRoot, TargetDefinitionPersistenceHelper.ENVIRONMENT, TargetDefinitionPersistenceHelper.ARCH); archNode.setTextContent(arch); } else { removeElement(TargetDefinitionPersistenceHelper.ENVIRONMENT, TargetDefinitionPersistenceHelper.ARCH); } }
Source:
public void setName(String name) { fName = name; if (fRoot != null) { if (name != null && START name.length() > 0) { END fRoot.setAttribute(TargetDefinitionPersistenceHelper.ATTR_NAME, name); } else { fRoot.removeAttribute(TargetDefinitionPersistenceHelper.ATTR_NAME); } } } Please use !string.isEmpty().

Target:
public void setName(String name) { fName = name; if (fRoot != null) { if (name != null && !name.isEmpty()) { fRoot.setAttribute(TargetDefinitionPersistenceHelper.ATTR_NAME, name); } else { fRoot.removeAttribute(TargetDefinitionPersistenceHelper.ATTR_NAME); } } }
Source:
static void flushUIEvents() { final Display display = Display.getCurrent(); START for (;;) { END if (!display.readAndDispatch()) { break; } } } why not use a simple while loop? thus removing the for and the if

Target:
static void flushUIEvents() { final Display display = Display.getCurrent(); while (display.readAndDispatch()) { // Nothing to do } }
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)) { START return false; END } } return true; } 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()...

Target:
private static boolean isValid(@Nullable Object element) { if (element instanceof ITmfTrimmableTrace) { return true; } if (!(element instanceof ITmfTrace)) { return false; } ITmfTrace trace = (ITmfTrace) element; if (trace.getChildren().isEmpty()) { return false; } for (ITmfEventProvider child : trace.getChildren()) { if (!isValid(child)) { return false; } } return true; }
Source:
private void activateContextService() { if (!fActiveContexts.isEmpty()) { deactivateContextService(); START } END fActiveContexts.add(fContextService.activateContext(CONTEXT)); } I think it would be good enough to just do nothing if it's already active?

Target:
private void activateContextService() { if (fActiveContexts.isEmpty()) { fActiveContexts.add(fContextService.activateContext(CONTEXT)); } }
Source:
public GridTableViewerComposite build() { final GridTableViewerComposite viewerComposite = new GridTableViewerComposite(getComposite(), getSwtStyleBits(), getInput(), getCustomization(), getTitle(), getTooltip()); START TableConfigurationUtil.setTableConfiguration(viewerComposite, getCustomization().getTableConfiguration()); END return viewerComposite; } why move it out? why not let the composite set the config itself?

Target:
public GridTableViewerComposite build() { return new GridTableViewerComposite(getComposite(), getSwtStyleBits(), getInput(), getCustomization(), getTitle(), getTooltip()); }
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) { START progressMonitor.split(4); END String symbolicName = event.getBundle().getSymbolicName(); String taskName = NLS.bind(WorkbenchMessages.Startup_Loading, symbolicName); progressMonitor.subTask(taskName); } } } 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?

Target:
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. if (eventType == BundleEvent.STARTED) { progressMonitor.split(10); String symbolicName = event.getBundle().getSymbolicName(); String taskName = NLS.bind(WorkbenchMessages.Startup_Loading, symbolicName); progressMonitor.subTask(taskName); } }
Source:
START final public Ref END exactRef(String name) throws IOException { return getRefDatabase().exactRef(name); } public final

Target:
public final Ref exactRef(String name) throws IOException { return getRefDatabase().exactRef(name); }
Source:
public File resolve(File dir, String name) { final File abspn = createFile(name); START if (abspn.isAbsolute()) END return abspn; return createFile(dir, name); } missing braces

Target:
public File resolve(File dir, String name) { final File abspn = createFile(name); if (abspn.isAbsolute()) { return abspn; } return createFile(dir, name); }
Source:
private static void appendBodyColorsRule(StringBuilder buffer, RGB fgRGB, RGB bgRGB) { StringBuilder fg= new StringBuilder(); appendColor(fg, fgRGB); StringBuilder bg= new StringBuilder(); START appendColor(bg, bgRGB); END 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$ } But now these 4 lines above can be deleted.

Target:
private static void appendBodyColorsRule(StringBuilder buffer, RGB fgRGB, RGB 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$ }
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 START (b.length() < END HUGE_SIZE) { b.append(oneLine); } return b.toString(); } This is calculating the character count in each iteration. Would it be better to calculate the required size in advance?

Target:
private String insanelyHugeCommitMessage() { final String oneLine = "012345678901234567890123456789012345678901234567890123456789\n"; StringBuilder b = new StringBuilder(HUGE_SIZE + oneLine.length()); // 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"); while (b.length() < HUGE_SIZE) { b.append(oneLine); } return b.toString(); }
Source:
public static ResourceSet loadResourceWithProxies(URI resourceURI, final ResourceSet resourceSet) { try { START if (addResourceToSet(resourceSet, resourceURI)) { END return resourceSet; } } catch (final IOException ex) { Activator.getDefault().getReportService().report( new StatusReport(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex))); } return null; } why not call the new method with null as third parameter?

Target:
public static ResourceSet loadResourceWithProxies(URI resourceURI, final ResourceSet resourceSet) { try { if (addResourceToSet(resourceSet, resourceURI, null)) { return resourceSet; } } catch (final IOException ex) { Activator.getDefault().getReportService().report( new StatusReport(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage(), ex))); } return null; }
Source:
public static boolean START isInvalidBranchName(String END branchName) { if (HEAD.equals(branchName)) { return true; } if ((R_HEADS + HEAD).equals(branchName)) { return true; } return branchName.startsWith("-"); //$NON-NLS-1$ } optional: I think it would be easier to understand if reversed, to be isValidBranchName. That would be more consistent with Repository#isValidRefName, too.

Target:
public static boolean isInvalidBranchName(String branchName) { if (HEAD.equals(branchName)) { return true; } return branchName.startsWith("-"); //$NON-NLS-1$ }
Source:
protected void doReset() { allCommandsRetrieved = false; START idToCommand = END null; if (currentSnapshot instanceof ExpressionContext) { ((ExpressionContext) currentSnapshot).eclipseContext.dispose(); } currentSnapshot = null; } I would clear the map. Having some field be null leads in such code to NPE's sooner or later.

Target:
protected void doReset() { allCommandsRetrieved = false; idToCommand.clear(); if (currentSnapshot instanceof ExpressionContext) { ((ExpressionContext) currentSnapshot).eclipseContext.dispose(); } currentSnapshot = null; }
Source:
public QuickAccessElement[] getElements() { if (!allCommandsRetrieved) { ICommandService commandService = getCommandService(); Collection<String> commandIds = commandService.getDefinedCommandIds(); for (String commandId : commandIds) { retrieveCommand(commandId); } allCommandsRetrieved = true; } return START idToCommand.values().toArray( END new QuickAccessElement[idToCommand.values().size()]); } 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)

Target:
public QuickAccessElement[] getElements() { if (!allCommandsRetrieved) { ICommandService commandService = getCommandService(); Collection<String> commandIds = commandService.getDefinedCommandIds(); for (String commandId : commandIds) { retrieveCommand(commandId); } allCommandsRetrieved = true; } return idToCommand.values().stream().toArray(QuickAccessElement[]::new); }
Source:
public static final int headerEnd(final byte[] b, int ptr) { final int sz = b.length; while (ptr < sz) { final byte c = b[ptr++]; START if (c == '\n' && (ptr == sz || b[ptr] != ' ')) END return ptr - 1; } return ptr - 1; } Missing curly braces.

Target:
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; }
Source:
public File createFile(String pathname, Config config) { if START (config != null && isNfsSupportEnabled(config)) { END return new NFSFile(pathname, config); } return new File(pathname); } you could put the check for config==null into isNfsSupportEnabled. If config==null then isNfsSupportEnabled would return false

Target:
public File createFile(String pathname, Config config) { return isNfsSupportEnabled(config) ? new NFSFile(pathname, config) : new File(pathname); }
Source:
private void setNotFoundBackgroundColor() { patternField.setData(CCS_CLASS_KEY, NO_RESULTS_CLASS); patternField.reskin(SWT.ALL); START patternField.update(); END noResults = true; } Is this necessary? If I remove the update line everything seems still to work.

Target:
private void setNotFoundBackgroundColor() { patternField.setData(CCS_CLASS_KEY, NO_RESULTS_CLASS); patternField.reskin(SWT.ALL); noResults = true; }
Source:
private void setNormalBackgroundColor() { if (noResults) { Color currentColor = patternField.getBackground(); patternField.setData(CCS_CLASS_KEY, null); patternField.reskin(SWT.ALL); START patternField.update(); END 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; } } Is this necessary? If I remove the update line everything seems still to work.

Target:
private void setNormalBackgroundColor() { if (noResults) { Color currentColor = patternField.getBackground(); patternField.setData(CCS_CLASS_KEY, null); patternField.reskin(SWT.ALL); 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; } }
Source:
private boolean checkAppElementByBundleSymbolicNameAndClass(String bundleSymbolicName, String className) { Collection<BundleWiring> wirings = findWirings(bundleSymbolicName, bundleContext); START if (!isBundleClassAvailable(wirings, className)) { END // remove application element, if there is not wiring available // or if the class cannot be found return false; } return true; } 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;

Target:
private boolean checkAppElementByBundleSymbolicNameAndClass(String bundleSymbolicName, String className) { Collection<BundleWiring> wirings = findWirings(bundleSymbolicName, bundleContext); // remove application element, if there is not wiring available // or if the class cannot be found return isBundleClassAvailable(wirings, className); }
Source:
private boolean isChildObjectRemoved(Set<Object> children, Set<Object> childrenFromTreeContextEntry, int notificationType) { START return !children.containsAll(childrenFromTreeContextEntry) && (Notification.REMOVE == notificationType || Notification.REMOVE_MANY == notificationType); END } Should we turn this around? I guess that the type check is faster than a containsAll

Target:
private boolean isChildObjectRemoved(Set<Object> children, Set<Object> childrenFromTreeContextEntry, int notificationType) { return (Notification.REMOVE == notificationType || Notification.REMOVE_MANY == notificationType) && !children.containsAll(childrenFromTreeContextEntry); }
Source:
protected void viewerSelectionChanged(SelectionChangedEvent event) { START actionBar.updateControls(); END } don't we need to check for the actionbar being null?

Target:
protected void viewerSelectionChanged(SelectionChangedEvent event) { if (actionBar != null) { actionBar.updateControls(); } }
Source:
START ActionConfigurationBuilder() { END } both constructors can be private right?

Target:
private ActionConfigurationBuilder() { }
Source:
START public Collection<Action> getActions() { END return Collections.unmodifiableCollection(configuration.getActions()); } why do we need this?

Target:
protected Collection<Action> getActions() { return Collections.unmodifiableCollection(configuration.getActions()); }
Source:
START public void addControl(String id, Control control) { END if (controls.containsKey(id)) { throw new IllegalArgumentException( MessageFormat.format("A control with id {0} already exists", id)); //$NON-NLS-1$ } controls.put(id, control); } why is this public?

Target:
protected 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); }
Source:
START public ViewerActionContext<? END extends Viewer> getActionContext() { return actionContext; } Could this be protected as well?

Target:
protected ViewerActionContext<? extends Viewer> getActionContext() { return actionContext; }
Source:
public void testShallowCommitParse() throws Exception { RevCommit a = commit(); RevCommit b = commit(a); createShallowFile(b); START rw = createRevWalk(); END b = rw.parseCommit(b); markStart(b); assertCommit(b, rw.next()); assertNull(rw.next()); } Leaks an ObjectReader.

Target:
public void testShallowCommitParse() throws Exception { RevCommit a = commit(); RevCommit b = commit(a); createShallowFile(b); rw.close(); rw = createRevWalk(); b = rw.parseCommit(b); markStart(b); assertCommit(b, rw.next()); assertNull(rw.next()); }
Source:
private void createShallowFile(ObjectId... shallowCommits) throws IOException { // Reset the RevWalk since the new shallow file invalidates the existing // RevWalk's shallow state. START rw = createRevWalk(); END StringBuilder builder = new StringBuilder(); for (ObjectId commit : shallowCommits) { builder.append(commit.getName() + "\n"); } JGitTestUtil.write(new File(db.getDirectory(), "shallow"), builder.toString()); } not a new issue, but seems worth fixing anyway: this leaks an ObjectReader.

Target:
private void createShallowFile(ObjectId... shallowCommits) throws IOException { // Reset the RevWalk since the new shallow file invalidates the existing // RevWalk's shallow state. rw.close(); rw = createRevWalk(); StringBuilder builder = new StringBuilder(); for (ObjectId commit : shallowCommits) { builder.append(commit.getName() + "\n"); } JGitTestUtil.write(new File(db.getDirectory(), "shallow"), builder.toString()); }
Source:
private boolean isArgumentFileSupported() { return START (JavaCore.compareJavaVersions(javaVersion, END JavaCore.VERSION_9) >= 0); } Please remove redundant braces

Target:
private boolean isArgumentFileSupported() { return JavaCore.compareJavaVersions(javaVersion, JavaCore.VERSION_9) >= 0; }
Source:
public void propertyChange(PropertyChangeEvent event) { if(event.getSource() == serverChoice && event.getProperty() == FieldEditor.VALUE) { String changedLSLocation = CPPStreamConnectionProvider.getDefaultLSLocation((String) event.getNewValue()).getAbsolutePath(); START if(changedLSLocation != null) { END serverPath.setStringValue(changedLSLocation); } } } This null check is too late: if getDefaultLSLocation() returns null, the call to getAbsolutePath() on the previous line will already throw a NullPointerException.

Target:
public void propertyChange(PropertyChangeEvent event) { if(event.getSource() == serverChoice && event.getProperty() == FieldEditor.VALUE) { File changedLSLocation = CPPStreamConnectionProvider.getDefaultLSLocation((String) event.getNewValue()); if(changedLSLocation != null) { serverPath.setStringValue(changedLSLocation.getAbsolutePath()); } } }
Source:
START public SiriusGraphQLPlugin() END { super(new ResourceLocator[0]); } private

Target:
private SiriusGraphQLPlugin() { super(new ResourceLocator[0]); }
Source:
public RegistrationWindows() { START registryWriter = new RegistryWriter(); END } just call the other constructor here

Target:
public RegistrationWindows() { this(new RegistryWriter()); }
Source:
public static void classSetup() { originalEclipseHomeLocation = System.getProperty("eclipse.home.location", ""); START System.setProperty("eclipse.home.location", "file:/C:/Users/Test/"); END originalEclipseLauncher = System.getProperty("eclipse.launcher", ""); System.setProperty("eclipse.launcher", "C:\\Users\\Test\\eclipse.exe"); } same is done in setUp, therefor its not needed

Target:
public static void classSetup() { originalEclipseHomeLocation = System.getProperty("eclipse.home.location", ""); originalEclipseLauncher = System.getProperty("eclipse.launcher", ""); }
Source:
public void START testHandleSchemesForOneScheme() END { 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")); } this method does add and remove the same scheme. the name of the method does not reflect this.

Target:
public void testHandleSchemesForOneScheme() { SchemeInformation schemeInformation = new SchemeInformation("schemeToTest", "ThisSchemeisJustForTesting", System.getProperty("eclipse.launcher")); registrationWindows.handleSchemes(Arrays.asList(schemeInformation), Arrays.asList(schemeInformation)); assertEquals(null, registryWriter.getRegisteredHandlerPath("schemeToTest")); }
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); START printVQL(vql); END vql = removeWhitespace(vql); String cleanExpectedOutput = removeWhitespace(expectedOutput); assertEquals(cleanExpectedOutput, vql); } Remove the printVQL call and the corresponding method.

Target:
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); vql = removeWhitespace(vql); String cleanExpectedOutput = removeWhitespace(expectedOutput); assertEquals(cleanExpectedOutput, vql); }
Source:
public ITmfTrace getTrace() { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { START for (ITmfTrace t : TmfTraceManager.getTraceSetWithExperiment(trace)) { END if (getResource().equals(t.getResource()) && (t instanceof TmfExperiment)) { return t; } } } return null; } I think we can avoid going through the trace set altogether, the experiment can only be found in the opened traces collection.

Target:
public ITmfTrace getTrace() { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { if (getResource().equals(trace.getResource()) && (trace instanceof TmfExperiment)) { return trace; } } return null; }
Source:
public void suspendedLineDifferStaysSuspendedAfterDocumentRewriteSession() throws Exception { // given fLineDiffer.connect(fDocument); fLineDiffer.suspend(); // when fDocument.startRewriteSession(SEQUENTIAL); fDocument.stopRewriteSession(fDocument.getActiveRewriteSession()); // then START assertFalse(fLineDiffer.isSuspended()); END assertFalse(fLineDiffer.isSynchronized()); } "The differ stays suspended" seems to be the opposite of what you're testing here. Shouldn't it be assertTrue?

Target:
public void suspendedLineDifferStaysSuspendedAfterDocumentRewriteSession() throws Exception { // given fLineDiffer.connect(fDocument); fLineDiffer.suspend(); // when fDocument.startRewriteSession(SEQUENTIAL); fDocument.stopRewriteSession(fDocument.getActiveRewriteSession()); // then assertTrue(fLineDiffer.isSuspended()); }