auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public PathVariablesGroup(boolean multiSelect, int variableType) { this.multiSelect = multiSelect; this.variableType = variableType; pathVariableManager = ResourcesPlugin.getWorkspace() .getPathVariableManager(); removedVariableNames = new HashSet(); Collator ignoreCaseComparator = Collator.getInstance(); START ignoreCaseComparator.setStrength(Collator.TERTIARY); END tempPathVariables = new TreeMap(ignoreCaseComparator); // initialize internal model initTemporaryState(); } Is there a reason to set the strength? None of the Platform/UI nor JDT code does so.

Target:
public PathVariablesGroup(boolean multiSelect, int variableType) { this.multiSelect = multiSelect; this.variableType = variableType; pathVariableManager = ResourcesPlugin.getWorkspace() .getPathVariableManager(); removedVariableNames = new HashSet(); Collator ignoreCaseComparator = Collator.getInstance(); tempPathVariables = new TreeMap(ignoreCaseComparator); // initialize internal model initTemporaryState(); }
Source:
protected void paintFigure(final Graphics g) { g.setBackgroundColor(getBackgroundColor()); g.setForegroundColor(getForegroundColor()); g.setLineWidth(getLineWidth()); START g.setLineStyle(getLineStyle()); END final PointList points = calculatePoints(new Rectangle(getBounds())); g.fillPolygon(points); g.drawPolygon(points); } Line dash / line attributes ?

Target:
protected void paintFigure(final Graphics g) { g.setBackgroundColor(getBackgroundColor()); g.setForegroundColor(getForegroundColor()); g.setLineWidth(getLineWidth()); final PointList points = calculatePoints(new Rectangle(getBounds())); g.fillPolygon(points); g.drawPolygon(points); }
Source:
public ChooseWorkspaceDialog(Shell parentShell, ChooseWorkspaceData launchData, boolean suppressAskAgain, boolean centerOnMonitor) { super(parentShell); this.launchData = launchData; this.suppressAskAgain = suppressAskAgain; this.centerOnMonitor = centerOnMonitor; // Bug 462707 - [WorkbenchLauncher] dialog not closed on ESC this.parentShell = parentShell; this.keyListener = new Listener() { @Override public void handleEvent(Event event) { START if (event.character == SWT.ESC) END cancelPressed(); } }; parentShell.getDisplay().addFilter(SWT.KeyDown, keyListener); } style nit: can you add braces around if block?

Target:
public ChooseWorkspaceDialog(Shell parentShell, ChooseWorkspaceData launchData, boolean suppressAskAgain, boolean centerOnMonitor) { super(parentShell); this.launchData = launchData; this.suppressAskAgain = suppressAskAgain; this.centerOnMonitor = centerOnMonitor; // Bug 462707 - [WorkbenchLauncher] dialog not closed on ESC this.parentShell = parentShell; this.keyListener = new Listener() { @Override public void handleEvent(Event event) { if (event.character == SWT.ESC) { cancelPressed(); } } }; parentShell.getDisplay().addFilter(SWT.KeyDown, keyListener); }
Source:
public void emptyLine() { String html = parseToHtml(" "); START assertEquals(html, ""); END } should reverse order as follows: assertEquals("",html)

Target:
public void emptyLine() { String html = parseToHtml(" "); assertEquals("", html); }
Source:
public void strong() { String html = parseToHtml("*foo bar*"); assertEquals(html,"<p><strong>foo bar</strong></p>\n"); START } END Should also have tests for strong with preceding character content, and following character content. (those are areas where we've had troubles before)

Target:
public void strong() { String html = parseToHtml("*foo bar*"); assertEquals("<p><strong>foo bar</strong></p>\n", html); }
Source:
public void disconnect() { if (fExplicitConnect) { START fHost.close(); END } } We should also set the variable to false, so we only close the connection once.

Target:
public void disconnect() { if (fExplicitConnect) { fHost.close(); fExplicitConnect = false; } }
Source:
private static String extractScriptStackTrace(RhinoException e) { START String st = e.getScriptStackTrace(); END if (st.equals("")) return null; return st; } return (e.getScriptStackTrace().isEmpty() ? null : e.getScriptStackTrace();

Target:
private static String extractScriptStackTrace(RhinoException e) { String st = e.getScriptStackTrace(); if (st.isEmpty()) return null; return st; }
Source:
private static void checkIfSessionIsAssociatedWithProject(SessionId sessionId, ProjectId projectId) throws AccessControlException { final EList<Adapter> eAdapters = sessionId.eAdapters(); for (final Adapter adapter : eAdapters) { if (ShareProjectAdapter.class.isInstance(adapter)) { final ShareProjectAdapter shareAdapter = (ShareProjectAdapter) adapter; final boolean didRemove = shareAdapter.removeProject(projectId); if (!didRemove) { START throw new AccessControlException(Messages.AdminEmfStoreImpl_IllegalRequestToAddInitialRole); END } return; } } throw new AccessControlException(Messages.AdminEmfStoreImpl_IllegalRequestToAddInitialRole); } Logic is weird here, I would change it to: if (didRemove) { return }

Target:
private static void checkIfSessionIsAssociatedWithProject(SessionId sessionId, ProjectId projectId) throws AccessControlException { final EList<Adapter> eAdapters = sessionId.eAdapters(); for (final Adapter adapter : eAdapters) { if (ShareProjectAdapter.class.isInstance(adapter)) { final ShareProjectAdapter shareAdapter = (ShareProjectAdapter) adapter; final boolean didRemove = shareAdapter.removeProject(projectId); if (didRemove) { return; } throw new AccessControlException(Messages.AdminEmfStoreImpl_IllegalRequestToAddInitialRole); } } // no ShareProjectAdapter with the correct project found throw new AccessControlException(Messages.AdminEmfStoreImpl_IllegalRequestToAddInitialRole); }
Source:
public boolean isQualifiedNameDisplay(View labelView) { boolean QNDisplayed; String depth = NotationUtils.getStringValue(labelView, StereotypeDisplayUtils.STEREOTYPE_LABEL_DEPTH, StereotypeDisplayUtils.DEFAULT_DEPTH_VALUE); START QNDisplayed = StereotypeDisplayUtils.DEPTH_MAX.equals(depth); END return QNDisplayed; } Return directly the evaluation value.

Target:
public boolean isQualifiedNameDisplay(View labelView) { String depth = NotationUtils.getStringValue(labelView, StereotypeDisplayUtils.STEREOTYPE_LABEL_DEPTH, StereotypeDisplayUtils.DEFAULT_DEPTH_VALUE); return StereotypeDisplayUtils.DEPTH_MAX.equals(depth); }
Source:
void initialize() { START fgKeys= new HashMap<String, Integer>(); END Integer k= new Integer(KEY); for (String word : fgKeywords) fgKeys.put(word, k); } No need for type here.

Target:
void initialize() { fgKeys= new HashMap<>(); Integer k= new Integer(KEY); for (String word : fgKeywords) fgKeys.put(word, k); }
Source:
START String getQualifier(Date timestamp) throws MojoFailureException { END String qualifier = format.format(timestamp); // parse an empty version with the given qualifier to check if the qualifier is valid try { Version.parseVersion(Version.emptyVersion + "." + qualifier); } catch (IllegalArgumentException e) { throw new MojoFailureException("Invalid build qualifier format '" + format.toPattern() + "', it does not match the OSGi qualifier constraint ([0..9]|[a..zA..Z]|'_'|'-')"); } return qualifier; } in calculateQualifiedVersion(), there are other ways to set the qualifier which are not being validated. rather pull this out into a dedicated validateQualifer method and call it after qualifier was determined.

Target:
String getQualifier(Date timestamp) { return format.format(timestamp); }
Source:
public String getOSRecommendedFolder() { try { return _get_os_recommended_folder(); } catch (UnsatisfiedLinkError e) { if (!libraryLoaded) { loadLibrary(); START return _get_os_recommended_folder(); END } return null; } } I know the effect is the same but just to be consistent with the rest of the code in this class, may be this statement can be changed to 'return getOSRecommendedFolder()' - wdyt? I'm fine if you don't want to change but decided to ask anyway...

Target:
public String getOSRecommendedFolder() { try { return _get_os_recommended_folder(); } catch (UnsatisfiedLinkError e) { if (!libraryLoaded) { loadLibrary(); return getOSRecommendedFolder(); } return null; } }
Source:
private static void checkTerminateFailures() { synchronized (fTestFailedToTerminate) { START while (fTerminateThreadsRunning > 0) { END try { fTestFailedToTerminate.wait(500); } catch (InterruptedException e) { } } if (fTestFailedToTerminate.isEmpty() == false) { StringBuffer buffer = new StringBuffer(); for (String failedName : fTestFailedToTerminate) { buffer.append("\nTermination failed for test " + failedName); } fTestFailedToTerminate.clear(); Assert.assertTrue(buffer.toString(), false); } } } Can this cause an infinite loop?

Target:
private static void checkTerminateFailures() { synchronized (fTestFailedToTerminate) { while (fTerminateThreadsRunning > 0) { try { fTestFailedToTerminate.wait(500); } catch (InterruptedException e) { } } if (fTestFailedToTerminate.isEmpty() == false) { StringBuilder buffer = new StringBuilder(); for (String failedName : fTestFailedToTerminate) { buffer.append("\nTermination failed for test " + failedName); } fTestFailedToTerminate.clear(); Assert.assertTrue(buffer.toString(), false); } } }
Source:
public Repository open(HttpServletRequest req, String name) throws RepositoryNotFoundException, ServiceNotEnabledException { if (!name.equals(repoName)) START throw new RepositoryNotFoundException(name); END Repository db = repo.getRepository(); db.incrementOpen(); return db; } Done. (Copy-paste)

Target:
public Repository open(HttpServletRequest req, String name) throws RepositoryNotFoundException, ServiceNotEnabledException { if (!name.equals(repoName)) { throw new RepositoryNotFoundException(name); } Repository db = repo.getRepository(); db.incrementOpen(); return db; }
Source:
public IRemoteProcess getCommandShell(int flags) throws IOException { START return new JSchProcessBuilder(getRemoteConnection(), "shell").start(flags); END } This should either use the one argument constructor, or the one argument constructor should be removed as it is not being used. If this is kept, then it is missing //$NON-NLS-$

Target:
public IRemoteProcess getCommandShell(int flags) throws IOException { return new JSchProcessBuilder(getRemoteConnection()).start(flags); }
Source:
public <T extends IRemoteConnection.Service> T getService(IRemoteConnection connection, Class<T> service) { if (IRemoteCommandShellService.class.equals(service)) { return (T) new JSchCommandShellService(connection); } else { START return null; END } } else is redundant.

Target:
public <T extends IRemoteConnection.Service> T getService(IRemoteConnection connection, Class<T> service) { if (IRemoteCommandShellService.class.equals(service)) { return (T) new JSchCommandShellService(connection); } return null; }
Source:
protected void doWakeUp() { IJobManager START jobManager = END Job.getJobManager(); jobManager.wakeUp(TestJob.FAMILY_TEST_JOB); } Why not just replace Platform with Job? Same below.

Target:
protected void doWakeUp() { Job.getJobManager().wakeUp(TestJob.FAMILY_TEST_JOB); }
Source:
public long getBucketStartTime(int index) { // .5 for rounding START return fFirstBucketTime + (long) (index * fBucketDuration + .5); END } Remove rounding... 3rd strike ;)

Target:
public long getBucketStartTime(int index) { return fFirstBucketTime + (long) (index * fBucketDuration); }
Source:
protected boolean batchValidate(EObject eObject, DiagnosticChain diagnostics, Map<Object, Object> context) { IStatus status = Status.OK_STATUS; // no point in validating if we can't report results if (diagnostics != null) { // if EMF Mode Validation Service already covered the sub-tree, // which it does for efficient computation and error reporting, // then don't repeat (the Diagnostician does the recursion // externally). If there is no context map, then we can't // help it if (!hasProcessed(eObject, context)) { START if (canCompareUpperGeLower(eObject)) { END status = batchValidator.validate( eObject, new NullProgressMonitor()); processed(eObject, context, status); appendDiagnostics(status, diagnostics); } } } return status.isOK(); } Only the Lower/Upper constraint should be disabled. In this case, unrelated constraints on the same element will be ignored too

Target:
protected boolean batchValidate(EObject eObject, DiagnosticChain diagnostics, Map<Object, Object> context) { IStatus status = Status.OK_STATUS; // no point in validating if we can't report results if (diagnostics != null) { // if EMF Mode Validation Service already covered the sub-tree, // which it does for efficient computation and error reporting, // then don't repeat (the Diagnostician does the recursion // externally). If there is no context map, then we can't // help it if (!hasProcessed(eObject, context)) { status = batchValidator.validate( eObject, new NullProgressMonitor()); processed(eObject, context, status); appendDiagnostics(status, diagnostics); } } return status.isOK(); }
Source:
public int draw(GC gc, long nanosec, Rectangle rect) { String stime; START synchronized (formats) { END stime = YEAR_FORMAT.format(new Date(nanosec / MILLISEC_IN_NS)); } return Utils.drawText(gc, stime, rect, true); } You only need synchronized (YEAR_FORMAT) { here. And it will block with the .setTimeZone() calls above.

Target:
public int draw(GC gc, long nanosec, Rectangle rect) { String stime; synchronized (YEAR_FORMAT) { stime = YEAR_FORMAT.format(new Date(nanosec / MILLISEC_IN_NS)); } return Utils.drawText(gc, stime, rect, true); }
Source:
public int getAvailableWidth(int requestedOffset) { START int totalWidth = fTimeAlignedComposite.getSize().x; END int availableWidth = totalWidth - requestedOffset; return availableWidth; } inline this maybe?

Target:
public int getAvailableWidth(int requestedOffset) { return fTimeAlignedComposite.getSize().x - requestedOffset; }
Source:
public ISchedulingRule getSchedulingRule() { START return RuleUtil.getRuleForContainers(Collections.<IPath> emptySet()); END } can't you just return null ?

Target:
public ISchedulingRule getSchedulingRule() { return null; }
Source:
public static void handleIssue(int severity, String message, Throwable throwable, boolean show) { IStatus status = new Status(severity, getPluginId(), message, throwable); int style = StatusManager.LOG; START if (show) END style |= StatusManager.SHOW; StatusManager.getManager().handle(status, style); } missing braces

Target:
public static void handleIssue(int severity, String message, Throwable throwable, boolean show) { IStatus status = new Status(severity, getPluginId(), message, throwable); int style = StatusManager.LOG; if (show) { style |= StatusManager.SHOW; } StatusManager.getManager().handle(status, style); }
Source:
public boolean isSupported() { START return version.compareTo(MINIMUM_SUPPORTED_VERSION) >= 0 && version.compareTo(MAXIMUM_SUPPORTED_VERSION) < 0; END } Shouldnt this be <= ? Is it possible you haven't pulled latest changes? I think this was changed to < 2_12_0 but <= 2_11_0 would be equivalent (and maintain the appropriate value of MAXIMUM_SUPPORTED_VERSION)

Target:
public boolean isSupported() { return version.compareTo(MINIMUM_SUPPORTED_VERSION) >= 0 && version.compareTo(MAXIMUM_SUPPORTED_VERSION) <= 0; }
Source:
START boolean shouldReactToChildVisibilityChanges(MUIElement END theElement) { return (theElement instanceof MPartSashContainer || theElement instanceof MPartStack); } The method should probably be made static.

Target:
private static boolean shouldReactToChildVisibilityChanges(MUIElement theElement) { return (theElement instanceof MPartSashContainer || theElement instanceof MPartStack); }
Source:
public void activate() { if (!isActive()) { final IPermissionAuthority auth = PermissionAuthorityRegistry.getDefault().getPermissionAuthority(getEditingDomain().getResourceSet()); auth.addAuthorityListener(this.getEditPartAuthorityListener()); super.activate(); DiagramElementEditPartOperation.activate(this); } START EditPartAuthorityListener editModeUpdater = getEditPartAuthorityListener(); if (editModeUpdater.shouldRefresh()) { editModeUpdater.refreshEditMode(); } END } why do you not do this in DiagramElementEditPartOperation.activate(this); ?

Target:
public void activate() { if (!isActive()) { final IPermissionAuthority auth = PermissionAuthorityRegistry.getDefault().getPermissionAuthority(getEditingDomain().getResourceSet()); auth.addAuthorityListener(this.getEditPartAuthorityListener()); super.activate(); DiagramElementEditPartOperation.activate(this); } }
Source:
public CompositeMenuBuilder(final String label, final Collection<AbstractMenuBuilder> menus) { this.label = label; this.menus = menus; AbstractMenuBuilder firstMenu = (AbstractMenuBuilder) START menus.toArray()[0]; END priority = firstMenu.getPriority(); } A little dangerous to access an array index without checking its validity.

Target:
public CompositeMenuBuilder(final String label, final Collection<AbstractMenuBuilder> menus) { this.label = label; this.menus = menus; if (menus != null && menus.toArray().length > 0) { AbstractMenuBuilder firstMenu = (AbstractMenuBuilder) menus.toArray()[0]; priority = firstMenu.getPriority(); } }
Source:
START public static void updateDefaultFormats() { END fDefaultTimeFormat = new TmfTimestampFormat( TmfTimePreferences.getTimePattern(), TmfTimePreferences.getTimeZone(), TmfTimePreferences.getLocale()); fDefaultIntervalFormat = new TmfTimestampFormat(TmfTimePreferences.getIntervalPattern()); } synchronized here

Target:
public static synchronized void updateDefaultFormats() { fDefaultTimeFormat = new TmfTimestampFormat( TmfTimePreferences.getTimePattern(), TmfTimePreferences.getTimeZone(), TmfTimePreferences.getLocale()); fDefaultIntervalFormat = new TmfTimestampFormat(TmfTimePreferences.getIntervalPattern()); }
Source:
public void setHeight(int height) { START int oldHeight = this.fHeight; END this.fHeight = height; if (oldHeight != height) { getParent().layout(new Control[] { this }); } } Could avoid this local variable if you store fHeight inside the if clause, if you feel like it (also, this. unnecessary).

Target:
public void setHeight(int height) { if (fHeight != height) { fHeight = height; getParent().layout(new Control[] { this }); } }
Source:
public int compareTo(FileAndName o) { int retVal = getFile().compareTo(o.getFile()); if (retVal == 0) { if (getTraceTypeId() != null) { START if (o.getTraceTypeId() != null) { END retVal = getTraceTypeId().compareTo(o.getTraceTypeId()); } } } return retVal; } While at it, you could merge the if's together: if (retVal == 0 && getTraceTypeId() != null && o.getTraceTypeId() != null) { retVal = .... } Technically, if getTraceTypeId() returns a mutable value, it'd be safer to extract it to a local variable first, because the value could change between the if check and using it in the compareTo() below since there is more than one condition in the if. But I don't think the trace type ID is supposed to change once we're here so that's probably fine.

Target:
public int compareTo(FileAndName o) { int retVal = getFile().compareTo(o.getFile()); if (retVal == 0) { if (getTraceTypeId() != null && o.getTraceTypeId() != null) { retVal = getTraceTypeId().compareTo(o.getTraceTypeId()); } } return retVal; }
Source:
private void lruRemove(final Slot e) { Slot p = e.lruPrev; Slot n = e.lruNext; START if (p != null) END p.lruNext = n; else lruHead = n; if (n != null) n.lruPrev = p; else lruTail = p; } So braces here, I guess.

Target:
private void lruRemove(final Slot e) { Slot p = e.lruPrev; Slot n = e.lruNext; if (p != null) { p.lruNext = n; } else { lruHead = n; } if (n != null) { n.lruPrev = p; } else { lruTail = p; } }
Source:
public static void parallel(String task, Iterable<Job> jobs) { IProgressMonitor group = getProgressGroup(); try { group.beginTask(task, size(jobs)); for (Job job : jobs) { job.setProgressGroup(group, 1); job.schedule(); } for (Job job : jobs) { START job.join(); END } } catch (InterruptedException e) { // ignore } finally { group.done(); } } wouldn't join block the caller?

Target:
public static IProgressMonitor parallel(String task, Iterable<Job> jobs) { IProgressMonitor group = getProgressGroup(); try { group.beginTask(task, size(jobs)); for (Job job : jobs) { job.setProgressGroup(group, 1); job.schedule(); } for (Job job : jobs) { job.join(); } } catch (InterruptedException e) { // ignore } finally { group.done(); } return group; }
Source:
public void dispose() { super.dispose(); if (this.tabFolder != null) { this.tabFolder.dispose(); this.tabFolder = null; } tabItems.clear(); for (ModelExplorerTabDescriptor tabDescriptor : ModelExplorerTabRegistry.getRegisteredExtensions()) { IModelExplorerTabExtension tab = tabDescriptor.getTabExtension(); if (tab != null) { tab.dispose(); } } START lockDecorationUpdater.unregister(); END } Should be set to null, especially as LockDecorationUpdater has not all its fields set to null on unregister() call.

Target:
public void dispose() { super.dispose(); if (this.tabFolder != null) { this.tabFolder.dispose(); this.tabFolder = null; } tabItems.clear(); for (ModelExplorerTabDescriptor tabDescriptor : ModelExplorerTabRegistry.getRegisteredExtensions()) { IModelExplorerTabExtension tab = tabDescriptor.getTabExtension(); if (tab != null) { tab.dispose(); } } lockDecorationUpdater.unregister(); lockDecorationUpdater = null; }
Source:
public void testDeactivateDoesNotRestoreForNoOpenTasks() { taskActivityManager.activateTask(task1); taskActivityManager.deactivateTask(task1); assertNoTaskOrTextEditorsOpen(); taskActivityManager.activateTask(task1); START assertEquals(Collections.emptyList(), getOpenEditorsByType(TaskEditor.class)); END } Should we just call assertNoTaskOrTextEditorsOpen again?

Target:
public void testDeactivateDoesNotRestoreForNoOpenTasks() { taskActivityManager.activateTask(task1); taskActivityManager.deactivateTask(task1); assertNoTaskOrTextEditorsOpen(); taskActivityManager.activateTask(task1); assertNoTaskOrTextEditorsOpen(); }
Source:
START public static IConsole[] findConsole(IRemoteConnection connection) { END return new TerminalConsoleFactory().findConsole(connection); } Done

Target:
public static List<IConsole> findConsole(IRemoteConnection connection) { return new TerminalConsoleFactory().findConsole(connection); }
Source:
private TreeItem thisOrFirstItem(TreeItem item) { START return item != null ? item : getFirstItemInTree(); END } I know that checkstyle is disabled for this project (not sure why actually), but the EMF Compare checkstyle config discourages ternary expressions, so I'd replace this with a common if statement here.

Target:
private TreeItem thisOrFirstItem(TreeItem item) { if (item != null) { return item; } return getFirstItemInTree(); }
Source:
public WordUpdateChange updateWordArtifacts(WordUpdateData data) { WordUpdateArtifact updateArt = new WordUpdateArtifact(logger, orcsApi); WordUpdateChange change = null; try { validate(data); change = updateArt.updateArtifacts(data, atsServer); START } catch (Exception ex) { END throw new OseeWebApplicationException(Status.INTERNAL_SERVER_ERROR, "Exception in updateWordArtifacts", ex); } return change; } don't catch, but instead allow the ExceptionMapper to handle it

Target:
public WordUpdateChange updateWordArtifacts(WordUpdateData data) { WordUpdateArtifact updateArt = new WordUpdateArtifact(logger, orcsApi); validate(data); return updateArt.updateArtifacts(data, atsServer); }
Source:
private AbstractTreeIterator getTreeIterator(String name) throws IOException { final ObjectId id = db.resolve(name); if (id == null) throw new IllegalArgumentException(name); final CanonicalTreeParser p = new CanonicalTreeParser(); START try (final ObjectReader or = db.newObjectReader()) { END p.reset(or, new RevWalk(db).parseTree(id)); return p; } } (optional) likewise

Target:
private AbstractTreeIterator getTreeIterator(String name) throws IOException { final ObjectId id = db.resolve(name); if (id == null) throw new IllegalArgumentException(name); final CanonicalTreeParser p = new CanonicalTreeParser(); try (ObjectReader or = db.newObjectReader()) { p.reset(or, new RevWalk(db).parseTree(id)); return p; } }
Source:
public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (selection == null || part instanceof GenericHistoryView) { return; } IStructuredSelection structuredSelection = SelectionUtils .getStructuredSelection(selection); System.out.println("selectionChanged[" + part + "]: " //$NON-NLS-1$ //$NON-NLS-2$ START + structuredSelection.size()); END if (structuredSelection.isEmpty()) { return; } setSelection(structuredSelection); } Argh, thanks for noticing! ;-)

Target:
public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (selection == null || part instanceof GenericHistoryView) { return; } IStructuredSelection structuredSelection = SelectionUtils .getStructuredSelection(selection); if (structuredSelection.isEmpty()) { return; } setSelection(structuredSelection); }
Source:
protected FS() { START gitSystemConfig = new Holder<File>(discoverGitSystemConfig()); END } It would be better to evaluate gitSystemConfig lazily in getGitSystemConfig(), so a call to discoverGitSystemConfig() can be avoided completely if gitSystemConfig has been set 'manually' before. discoverGitSystemConfig() is possibly slow and may even hang if the bash configuration is screwed up.

Target:
protected FS() { // Do nothing by default. }
Source:
START protected View getView() { END if (getHost().getModel() instanceof View) { if (((View) getHost().getModel()) instanceof View) { return (View) ((View) getHost().getModel()); } return null; } return null; } Multi return is forbidden.

Target:
protected View getView() { View view = null; if (getHost().getModel() instanceof View) { if (((View) getHost().getModel()) instanceof View) { view = (View) ((View) getHost().getModel()); } } return view; }
Source:
public ITopic[] getSubtopics() { START return subTopics.toArray(new ITopic[subTopics.size()]); END } You could just do 'return subTopics.toArray(new ITopic[0]);'

Target:
public ITopic[] getSubtopics() { return subTopics.toArray(new ITopic[0]); }
Source:
START public long END getCountOfLoadedCommits() { return countOfLoadedCommits; } s/public// This type is not visible, so the methods aren't visible even if you declared them public. In such cases we avoid public to make it less confusing.

Target:
long getCountOfLoadedCommits() { return countOfLoadedCommits; }
Source:
public InputStream getInputStream(GzipEntry entry) { if START (entry.equals(fEntry)) END { return fInternalEntryStream; } throw new IllegalArgumentException(); } I think the == is right here. You don't want two "equivalent" entries from a different Gzipfile to return the inputstream from this file.

Target:
public InputStream getInputStream(GzipEntry entry) { if (entry != fEntry) { throw new IllegalArgumentException(); } return fInternalEntryStream; }
Source:
public Builder hostname(final String hostname) { START if (hostname != null && !hostname.isEmpty()) { END this.hostname = hostname; } return this; } This means both .hostname("").hostname("wonka") .hostname("wonka").hostname("") result in hostname being "wonka" ? That seems inconsistent. Why is this needed ?

Target:
public Builder hostname(final String hostname) { this.hostname = hostname; return this; }
Source:
public Builder cmd(final List<String> cmd) { START if (cmd != null && !cmd.isEmpty()) { END this.cmd = new ArrayList<String>(cmd); } return this; } same, why not set what is coming in here ?

Target:
public Builder cmd(final List<String> cmd) { this.cmd = cmd; return this; }
Source:
public Builder entryPoint(final String entrypoint) { START if (entrypoint != null && !entrypoint.isEmpty()) { END return entryPoint(entrypoint.split(" ")); } return this; } so how do make the entryPoint be empty ?

Target:
public Builder entryPoint(final String entrypoint) { if (entrypoint != null && !entrypoint.isEmpty()) { return entryPoint(entrypoint.split(" ")); } else { this.entrypoint = null; } return this; }
Source:
public void setSelectedTime(long time, boolean ensureVisible) { /* if there is a pending time selection, ignore this one */ synchronized (fListenerNotifierLock) { START if (fListenerNotifier != null && fListenerNotifier.hasTimeSelected()) { END return; } } setSelectedTimeInt(time, ensureVisible, false); } idem

Target:
public void setSelectedTime(long time, boolean ensureVisible) { /* if there is a pending time selection, ignore this one */ if (fListenerNotifier != null && fListenerNotifier.hasTimeSelected()) { return; } setSelectedTimeInt(time, ensureVisible, false); }
Source:
public void setSelectionRange(long beginTime, long endTime) { /* if there is a pending time selection, ignore this one */ synchronized (fListenerNotifierLock) { START if (fListenerNotifier != null && fListenerNotifier.hasTimeSelected()) { END return; } } fSelectionBegin = Math.max(fTime0Bound, Math.min(fTime1Bound, beginTime)); fSelectionEnd = Math.max(fTime0Bound, Math.min(fTime1Bound, endTime)); fTimeGraphCtrl.redraw(); fTimeScaleCtrl.redraw(); } idem

Target:
public void setSelectionRange(long beginTime, long endTime) { /* if there is a pending time selection, ignore this one */ if (fListenerNotifier != null && fListenerNotifier.hasTimeSelected()) { return; } fSelectionBegin = Math.max(fTime0Bound, Math.min(fTime1Bound, beginTime)); fSelectionEnd = Math.max(fTime0Bound, Math.min(fTime1Bound, endTime)); fTimeGraphCtrl.redraw(); fTimeScaleCtrl.redraw(); }
Source:
protected boolean hasShortcuts() { START return true; END } sollte false nicht default sein?

Target:
protected boolean hasShortcuts() { return false; }
Source:
public Option<String> getNewFragment(String uriFragment) { boolean contains = false; String newUriFragment = uriFragment; // do not directly do a replaceAll on "@firstModelOperations" to avoid // an infinite loop if (uriFragment.endsWith("@firstModelOperations")) { contains = true; newUriFragment = newUriFragment + ".0"; START } if (uriFragment.contains("@firstModelOperations/")) END { contains = true; newUriFragment = newUriFragment.replaceAll("@firstModelOperations/", "@firstModelOperations.0/"); } if (contains) { return Options.newSome(newUriFragment); } else { return super.getNewFragment(uriFragment); } } Could be an "else if" to make it more obvious these are exclusive cases.

Target:
public Option<String> getNewFragment(String uriFragment) { boolean contains = false; String newUriFragment = uriFragment; // do not directly do a replaceAll on "@firstModelOperations" to avoid // an infinite loop if (uriFragment.endsWith("@firstModelOperations")) { contains = true; newUriFragment = newUriFragment + ".0"; } else if (uriFragment.contains("@firstModelOperations/")) { contains = true; newUriFragment = newUriFragment.replaceAll("@firstModelOperations/", "@firstModelOperations.0/"); } if (contains) { return Options.newSome(newUriFragment); } else { return super.getNewFragment(uriFragment); } }
Source:
public boolean launchConfigurationChanged(ILaunchConfiguration configuration) throws CoreException { if (ownsLaunchConfiguration(configuration)) { // we have to ignore notifications from working copies, otherwise // we will be adding them here and not removing destroying the proper cache // change event will be sent to original configuration later START if (configuration.isWorkingCopy()) END return true; // clear cache, target could have changed launchConfigurationRemoved(configuration); return addLaunchConfiguration(configuration); } else if (ownedConfigs.contains(configuration)) { // something changed that will cause us to loose ownership of this // configuration. Remove and add it back in. ILaunchBarManager manager = getManager(); manager.launchConfigurationRemoved(configuration); manager.launchConfigurationAdded(configuration); return true; } else { return false; } } Shouldn't this check be at the top of this method. Should we ignore working copies all the time?

Target:
public boolean launchConfigurationChanged(ILaunchConfiguration configuration) throws CoreException { if (ownsLaunchConfiguration(configuration)) { // clear cache, target could have changed launchConfigurationRemoved(configuration); return addLaunchConfiguration(configuration); } else if (ownedConfigs.contains(configuration)) { // something changed that will cause us to loose ownership of this // configuration. Remove and add it back in. ILaunchBarManager manager = getManager(); manager.launchConfigurationRemoved(configuration); manager.launchConfigurationAdded(configuration); return true; } else { return false; } }
Source:
START public boolean accept(final Object element) { END if (element instanceof ILabelProviderContextElementWrapper) { final Object object = ((ILabelProviderContextElementWrapper) element).getObject(); if (object instanceof ITreeItemAxis) { ITreeItemAxis curr = (ITreeItemAxis) object; Object el = curr.getElement(); if (el instanceof TreeFillingConfiguration) { final IAxis axis = ((TreeFillingConfiguration) el).getAxisUsedAsAxisProvider(); return axis instanceof EOperation || axis instanceof EOperationAxis; } } } return false; } Multi returns are to avoid.

Target:
public boolean accept(final Object element) { boolean result = false; if (element instanceof ILabelProviderContextElementWrapper) { final Object object = ((ILabelProviderContextElementWrapper) element).getObject(); if (object instanceof ITreeItemAxis) { ITreeItemAxis curr = (ITreeItemAxis) object; Object el = curr.getElement(); if (el instanceof TreeFillingConfiguration) { final IAxis axis = ((TreeFillingConfiguration) el).getAxisUsedAsAxisProvider(); result = axis instanceof EOperation || axis instanceof EOperationAxis; } } } return result; }
Source:
private String getLabelProviderContextForTreeFillingConfiguration(final Table table, final Object listenObject) { START if (listenObject instanceof EStructuralFeature) { END return Constants.HEADER_LABEL_PROVIDER_TREE_FILLING_FEATURE_CONFIGURATION_CONTEXT; } else if (listenObject instanceof EOperation) { return Constants.HEADER_LABEL_PROVIDER_TREE_FILLING_OPERATION_CONFIGURATION_CONTEXT; } else { // TODO return ""; //$NON-NLS-1$ } } Multi return is to avoid?

Target:
private String getLabelProviderContextForTreeFillingConfiguration(final Table table, final Object listenObject) { String result = ""; //$NON-NLS-1$ if (listenObject instanceof EStructuralFeature) { result = Constants.HEADER_LABEL_PROVIDER_TREE_FILLING_FEATURE_CONFIGURATION_CONTEXT; } else if (listenObject instanceof EOperation) { result = Constants.HEADER_LABEL_PROVIDER_TREE_FILLING_OPERATION_CONFIGURATION_CONTEXT; } return result; }
Source:
private RGB getRGBFromTheme(String value) { if (Platform.getBundle("org.eclipse.e4.ui.css.swt.theme") != null) { String backgroundColor = E4ThemeColor.getCssValueFromTheme(display, value); if (backgroundColor != null) { RGB themeColor = E4ThemeColor.getRGBFromCssString(backgroundColor); if (themeColor != null) { return themeColor; } } } START return getImpliedBackground().getRGB(); END } It's odd for getRGBFromTheme to call getImpliedBackground. Instead we should have a method getBackground that calls getRGBFromTheme and getImpliedBackground.

Target:
private RGB getRGBFromTheme(String value) { if (Platform.getBundle("org.eclipse.e4.ui.css.swt.theme") != null) { String backgroundColor = E4ThemeColor.getCssValueFromTheme(display, value); if (backgroundColor != null) { RGB themeColor = E4ThemeColor.getRGBFromCssString(backgroundColor); if (themeColor != null) { return themeColor; } } } return null; }
Source:
public synchronized void setLocation(ITmfLocation location) { if (location != null) { CtfIterator iterator = getIterator(); START iterator.seek(((CtfLocation) location).getLocationInfo()); END fCurLocation = iterator.getLocation(); } else { fCurLocation = null; } } could we instanceof here?? just a thought?

Target:
public synchronized void setLocation(ITmfLocation location) { if (location instanceof CtfLocation) { CtfIterator iterator = getIterator(); iterator.seek(((CtfLocation) location).getLocationInfo()); fCurLocation = iterator.getLocation(); } else { fCurLocation = null; } }
Source:
protected View getView() { EditPart host = getHost(); if (host == null) { return null; } Object hostView = host.getModel(); if (hostView instanceof View) { // The mask have to be applied on the label and not on the parent START if (((View) getHost().getModel()) instanceof View) { END return (View) ((View) getHost().getModel()); } return null; } return null; } Casting to View before checking instanceof is highly suspicious

Target:
protected View getView() { EditPart host = getHost(); if (host == null) { return null; } Object hostView = host.getModel(); if (hostView instanceof View) { // The mask have to be applied on the label and not on the parent return (View) hostView; } return null; }
Source:
public void testAtsProgramInsertionBadProgramIdRestCall() throws Exception { START String result = END doRequestString("/ats/program/" + getSawTeam().getArtId() + "/insertion", HttpMethod.GET, null, javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Assert.assertTrue(result.contains("SERVER_ERROR")); } use .getUuid instead of getArtId, which will go away

Target:
public void testAtsProgramInsertionBadProgramIdRestCall() throws Exception { String result = doRequestString("/ats/program/" + getSawTeam() + "/insertion", HttpMethod.GET, null, javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Assert.assertTrue(result.contains("SERVER_ERROR")); }
Source:
START public boolean hasVisibleCompartment(View comment) { END boolean empty = true; if (isStereotypeComment(comment)) { Iterator<?> childrenIterator = comment.getChildren().iterator(); while (childrenIterator.hasNext() && empty) { Object child = childrenIterator.next(); if (isStereotypeCompartment(child)) { empty = !((View) child).isVisible(); } } } return !empty; } 'final' is missing

Target:
public boolean hasVisibleCompartment(View comment) { boolean empty = true; if (isStereotypeComment(comment)) { Iterator<?> childrenIterator = comment.getChildren().iterator(); while (empty && childrenIterator.hasNext()) { Object child = childrenIterator.next(); if (isStereotypeCompartment(child)) { empty = !((View) child).isVisible(); } } } return !empty; }
Source:
public void removeListener() { if (!stereotypeList.isEmpty()) { START if (comment != null) { END for (Stereotype stereotype : stereotypeList) { getDiagramEventBroker().removeNotificationListener(helper.getStereotypeCompartment(comment, stereotype), this); getDiagramEventBroker().removeNotificationListener(helper.getStereotypeBraceCompartment(comment, stereotype), this); } } } } 'null !=' is preferably used

Target:
public void removeListener() { if (!stereotypeList.isEmpty()) { if (null != comment) { for (Stereotype stereotype : stereotypeList) { getDiagramEventBroker().removeNotificationListener(helper.getStereotypeCompartment(comment, stereotype), this); getDiagramEventBroker().removeNotificationListener(helper.getStereotypeBraceCompartment(comment, stereotype), this); } } } }
Source:
protected void executeAppliedStereotypeCommentDeletion(final TransactionalEditingDomain domain, final View commentNode) { START if (commentNode != null) { END Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { // because it is asynchronous the comment node's domain maybe become null if (TransactionUtil.getEditingDomain(commentNode) == domain) { DeleteCommand command = new DeleteCommand(commentNode); try { GMFUnsafe.write(domain, command); } catch (Exception e) { Activator.log.error(e); } } } }); } } null or constant must be first for operations.

Target:
protected void executeAppliedStereotypeCommentDeletion(final TransactionalEditingDomain domain, final View commentNode) { if (null != commentNode) { Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { // because it is asynchronous the comment node's domain maybe become null if (TransactionUtil.getEditingDomain(commentNode) == domain) { DeleteCommand command = new DeleteCommand(commentNode); try { GMFUnsafe.write(domain, command); } catch (Exception e) { Activator.log.error(e); } } } }); } }
Source:
protected boolean isStereotypedElement(final View view) { boolean result = false; START if (view.getElement() instanceof Element && !((Element) view.getElement()).getAppliedStereotypes().isEmpty()) { END result = true; } return result; } Why do you not return directly the value of condition ?

Target:
protected boolean isStereotypedElement(final View view) { return (view.getElement() instanceof Element && !((Element) view.getElement()).getAppliedStereotypes().isEmpty()); }
Source:
public void setAccelerator (int accelerator) { checkWidget(); if (this.accelerator == accelerator) return; long /*int*/ accelGroup = getAccelGroup (); if (accelGroup != 0) removeAccelerator (accelGroup); this.accelerator = accelerator; START if (accelGroup != 0) { addAccelerator (accelGroup); } } END I like this re-factoring. But you haven't made any changes in this function other than this refactoring. I would recommend to submit as a separate re-factoring patch. This patch is already very long. Also, if you're doing it here, you should ideally do this if-separation across the whole widget in a 2nd refactoring patch (or across all of menu-item ideally). Also, you touch this line, but don't change the near identical line if statement above it (L 900) which makes this function look a bit inconsistent.

Target:
public void setAccelerator (int accelerator) { checkWidget(); if (this.accelerator == accelerator) return; long /*int*/ accelGroup = getAccelGroup (); if (accelGroup != 0) removeAccelerator (accelGroup); this.accelerator = accelerator; if (accelGroup != 0) addAccelerator (accelGroup); }
Source:
public static <E> ListDiff<E> createListDiff( final List<ListDiffEntry<E>> differences) { final ListDiffEntry<?>[] differencesArray START = END differences .toArray(new ListDiffEntry[differences.size()]); return new ListDiff<E>() { @Override public ListDiffEntry<?>[] getDifferences() { return differencesArray; } }; } Better to break after the equal sign.

Target:
public static <E> ListDiff<E> createListDiff(final List<ListDiffEntry<E>> differences) { final ListDiffEntry<E>[] differencesArray = differences.toArray(new ListDiffEntry[differences.size()]); return new ListDiff<E>() { @Override public ListDiffEntry<E>[] getDifferences() { return differencesArray; } }; }
Source:
private T getLiveValue() { for (Option option : options) { if START (Boolean.TRUE.equals(option.observable.getValue())) END return option.value; } return null; } This code can be simplified to rely on autounboxing.

Target:
private T getLiveValue() { for (Option option : options) { if (option.observable.getValue()) return option.value; } return null; }
Source:
protected void doSetValue(Object value) { int index = indexOfValue(value); try { updating = true; for (int i = 0; i < options.size(); i++) { START options.get(i).observable.setValue(i == index ? Boolean.TRUE : Boolean.FALSE); END } } finally { updating = false; } notifyIfChanged(index); } This code can be simplified to rely on autoboxing.

Target:
protected void doSetValue(Object value) { int index = indexOfValue(value); try { updating = true; for (int i = 0; i < options.size(); i++) { options.get(i).observable.setValue(i == index); } } finally { updating = false; } notifyIfChanged(index); }
Source:
public boolean addAll(Collection<? extends E> c) { boolean changed = false; for START (Iterator<? END extends E> iterator = c.iterator(); iterator.hasNext();) { E element = iterator.next(); changed |= wrappedSet.add(IdentityWrapper.wrap(element)); } return changed; } Better: E element : c

Target:
public boolean addAll(Collection<? extends E> c) { boolean changed = false; for (E element : c) { changed |= wrappedSet.add(IdentityWrapper.wrap(element)); } return changed; }
Source:
protected Boolean doGetValue() { return START tracked.isStale() ? Boolean.TRUE : Boolean.FALSE; END } The code can be simplified to rely on autoboxing.

Target:
protected Boolean doGetValue() { return tracked.isStale(); }
Source:
boolean containsValue(Object value) { for START (Iterator<DelegateCache> END it = delegateCaches.values().iterator(); it .hasNext();) { DelegateCache cache = it.next(); if (cache.containsValue(value)) return true; } return false; } Better: DelegateCache cache : delegateCache.values()

Target:
boolean containsValue(Object value) { for (DelegateCache cache : delegateCaches.values()) { if (cache.containsValue(value)) return true; } return false; }
Source:
public void removeTable(Table tableInstance) { START getResource().getContents().remove(tableInstance); END } Same here; will probably not work with controlled models

Target:
public void removeTable(Table tableInstance) { if (getResource() != null) { getResource().getContents().remove(tableInstance); } }
Source:
public void addCommand(ReceiveCommand cmd, String rawLine) { START received = true; END commands.add(cmd); rawCommands.append(rawLine); } not for addCommand, see below

Target:
public void addCommand(ReceiveCommand cmd, String rawLine) { commands.add(cmd); rawCommands.append(rawLine); }
Source:
public void addCommand(String rawLine) { START received = true; END commands.add(parseCommand(chomp(rawLine))); rawCommands.append(rawLine); } No, not for addCommand. The caller runs this if push cert is enabled, but the client didn't send a push cert.

Target:
public void addCommand(String rawLine) { commands.add(parseCommand(chomp(rawLine))); rawCommands.append(rawLine); }
Source:
public int hashCode() { int hashCode = 0; if (this.isSystemLibrary()) { hashCode++; } for (int i = 0; i < this.entries.length; i++) { START hashCode = hashCode * 17 + this.entries.hashCode(); END } return hashCode; } there is a bug here, reported to JDT (470535)

Target:
public int hashCode() { int hashCode = 0; if (this.isSystemLibrary()) { hashCode++; } for (int i = 0; i < this.entries.length; i++) { hashCode = hashCode * 17 + this.entries[i].hashCode(); } return hashCode; }
Source:
RGB acquireCurrentColorSelectionGtk3(long /*int*/ handle, GdkRGBA rgba) { int red = 0; int green = 0; int blue = 0; OS.gtk_color_chooser_get_rgba (handle, rgba); red = (int) (rgba.red * 255); green = (int) (rgba.green * 255); blue = (int) (rgba.blue * 255); START rgb = new RGB (red, green, blue); END return rgb; } You are assigning 'rgb' a new value, then you return rgb and then you re-assign rgb it's own value that get's returned. This duplicate assignment is somewhat strange code. Instead consider simply returning a new RGB object without touching 'rgb' in this call and just leave the assignment in the parent method.

Target:
RGB acquireCurrentColorSelectionGtk3(long /*int*/ handle, GdkRGBA rgba) { int red = 0; int green = 0; int blue = 0; OS.gtk_color_chooser_get_rgba (handle, rgba); red = (int) (rgba.red * 255); green = (int) (rgba.green * 255); blue = (int) (rgba.blue * 255); return new RGB (red, green, blue); }
Source:
START public void setReviewInput(ReviewInput reviewInput) { fReviewInput.setLabels(reviewInput.getLabels()); fReviewInput.setMessage(reviewInput.getMessage()); } END can you just use fReviewInput = reviewInput

Target:
public void setReviewInput(ReviewInput reviewInput) { fReviewInput = reviewInput; }
Source:
private static List<Variable> removeDuplicates(List<Variable> typeMatches) { START HashSet<Variable> set END = new HashSet<>(); set.addAll(typeMatches); return Arrays.asList(set.toArray(new Variable[set.size()])); } Simpler: return new ArrayList<>(new HashSet<>(typeMatches));

Target:
private static List<Variable> removeDuplicates(List<Variable> typeMatches) { return new ArrayList<>(new HashSet<>(typeMatches)); }
Source:
private static CEditor getCEditor(IEditorPart editorPart) { if (editorPart instanceof CEditor) { return (CEditor) editorPart; } START else { END return null; } } Redundant "else"

Target:
private static CEditor getCEditor(IEditorPart editorPart) { if (editorPart instanceof CEditor) { return (CEditor) editorPart; } return null; }
Source:
public Variable(String name, VariableType variableType, int positionScore, char[] triggerChars, ImageDescriptor descriptor) { this.name = name; this.variableType = variableType; this.positionScore = positionScore; this.triggerChars = triggerChars; this.descriptor = descriptor; this.alreadyMatched = START false; END } Redundant initialization.

Target:
public Variable(String name, VariableType variableType, int positionScore, char[] triggerChars, ImageDescriptor descriptor) { this.name = name; this.variableType = variableType; this.positionScore = positionScore; this.triggerChars = triggerChars; this.descriptor = descriptor; }