auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START static ISideEffectFactory createFactory() { END ICompositeSideEffect compositeSideEffect = ICompositeSideEffect.create(); return new SideEffectFactory(compositeSideEffect::add); } Oh, I was thinking that the 0-argument version shouldn't create an ICompositeSideEffect at all. You'd use the 0-arg one to obtain an ISideEffectFactory that does exactly the same thing as the static methods on ISideEffect. I'd suggest calling the default constructor on SideEffectFactory here.

Target:
static ISideEffectFactory createFactory() { return new SideEffectFactory(); }
Source:
public boolean intersects(long timestamp) { START return (start <= timestamp && end >= timestamp); END } Unrelated to this patch. Again this is a good change, but it adds diff noise.

Target:
public boolean intersects(long timestamp) { if (start <= timestamp) { if (end >= timestamp) { return true; } } return false; }
Source:
private String getCombinedLabels(IThreadDMContext processDmc, IMIExecutionDMContext execDmc) { // get the process label IThreadDMData processData = getData(processDmc); String label = getLabel(processData); // get the execution (thread) context label if (execDmc != null) { START int threadId; END try { threadId = Integer.parseInt(execDmc.getThreadId()); label += !label.isEmpty() ? ": " : ""; //$NON-NLS-1$//$NON-NLS-2$ label += "Thread [" + Integer.toString(threadId) + "]"; //$NON-NLS-1$//$NON-NLS-2$ } catch (NumberFormatException e) { // No additional label adjustments } } return label; } In this block, you could avoid doing two conversions(String -> int, int -> String), and use directly the String value returned by execDmc.getThreadId()? That way this code will be ready to handle the "new" thread ids without change.

Target:
private String getCombinedLabels(IThreadDMContext processDmc, IMIExecutionDMContext execDmc) { // get the process label IThreadDMData processData = getData(processDmc); String label = getLabel(processData); // get the execution (thread) context label if (execDmc != null) { String threadId = execDmc.getThreadId(); label += !label.isEmpty() ? ": " : ""; //$NON-NLS-1$//$NON-NLS-2$ label += "Thread [" + threadId + "]"; //$NON-NLS-1$//$NON-NLS-2$ } return label; }
Source:
START public synchronized static void storeOnImageRegistry(String key, ImageDescriptor descriptor) { END getImageRegistry().put(key, descriptor); } can now go back to private

Target:
private synchronized static void storeOnImageRegistry(String key, ImageDescriptor descriptor) { getImageRegistry().put(key, descriptor); }
Source:
START public void tearDown() throws Exception { END LogReaderService logReaderService = appContext.get(LogReaderService.class); logReaderService.removeLogListener(listener); if (wb != null) { wb.close(); } appContext.dispose(); } I think "throws Exception" is unnecessary

Target:
public void tearDown() { LogReaderService logReaderService = appContext.get(LogReaderService.class); logReaderService.removeLogListener(listener); if (wb != null) { wb.close(); } appContext.dispose(); }
Source:
public boolean isEmpty() { START return this.toProcess.isEmpty(); END } synchronize

Target:
public boolean isEmpty() { synchronized (this.toProcess) { return this.toProcess.isEmpty(); } }
Source:
private Session getOrOpenTargetSession(final URI sessionResourceUri) { Session session = SessionManager.INSTANCE.getExistingSession(sessionResourceUri); if (session == null) { // Try to open a session. ModelingProjectManager.INSTANCE.loadAndOpenRepresentationsFile(sessionResourceUri, true); // Wait the end of the loading of the representations file try { Job.getJobManager().join(AbstractRepresentationsFileJob.FAMILY, new NullProgressMonitor()); } catch (InterruptedException e) { START throw new RuntimeException(e); END } session = SessionManager.INSTANCE.getExistingSession(sessionResourceUri); } return session; } Before, with waitOtherJobs, we "Do nothing" in case of InterruptedException. Why do you change that? Have you test the difference?

Target:
private Session getOrOpenTargetSession(final URI sessionResourceUri) { Session session = SessionManager.INSTANCE.getExistingSession(sessionResourceUri); if (session == null) { // Try to open a session. ModelingProjectManager.INSTANCE.loadAndOpenRepresentationsFile(sessionResourceUri, true); // Wait the end of the loading of the representations file try { Job.getJobManager().join(AbstractRepresentationsFileJob.FAMILY, new NullProgressMonitor()); } catch (InterruptedException e) { // Do nothing; } session = SessionManager.INSTANCE.getExistingSession(sessionResourceUri); } return session; }
Source:
public TypedElementBoundsRenderer(VControl vElement, ViewModelContext viewContext, ReportService reportService, EMFFormsDatabinding emfFormsDatabinding, EMFFormsLabelProvider emfFormsLabelProvider, VTViewTemplateProvider vtViewTemplateProvider) { super(vElement, viewContext, reportService, emfFormsDatabinding, emfFormsLabelProvider, vtViewTemplateProvider); START dbc = new EMFDataBindingContext(); END } you can use the databindingcontext from the super class

Target:
public TypedElementBoundsRenderer(VControl vElement, ViewModelContext viewContext, ReportService reportService, EMFFormsDatabinding emfFormsDatabinding, EMFFormsLabelProvider emfFormsLabelProvider, VTViewTemplateProvider vtViewTemplateProvider) { super(vElement, viewContext, reportService, emfFormsDatabinding, emfFormsLabelProvider, vtViewTemplateProvider); }
Source:
StackItemsModelChangeListener(Map<VStackLayout, Setting> stackToSetting) { this.stackToSetting = new LinkedHashMap<VStackLayout, EStructuralFeature.Setting>(); START this.stackToSetting.putAll(stackToSetting); END } why not simply assign?

Target:
StackItemsModelChangeListener(Map<VStackLayout, Setting> stackToSetting) { this.stackToSetting = stackToSetting; }
Source:
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) throws CoreException { fAdditionalContentTypesIDs = new String[0]; if (data != null) { START if (data instanceof String && data.toString().length() > 0) { END fAdditionalContentTypesIDs = StringUtils.unpack(data.toString()); } } } This is a bit puzzling. Is instanceof really necessary?

Target:
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) throws CoreException { fAdditionalContentTypesIDs = new String[0]; if (data instanceof String && data.toString().length() > 0) { fAdditionalContentTypesIDs = StringUtils.unpack(data.toString()); } }
Source:
START private ICPPEvaluation deref(ICPPEvaluation ptr, boolean isRef, ActivationRecord record, ConstexprEvaluationContext context) { END ICPPEvaluation derefEval = new EvalUnary(ICPPASTUnaryExpression.op_star, ptr, null, context.getPoint()).computeForFunctionCall(record, context); if(isRef) { return derefEval; } else { return new EvalFixed(derefEval.getType(null), derefEval.getValueCategory(null), derefEval.getValue(null)); } } This can be static like isEqual().

Target:
private static ICPPEvaluation deref(ICPPEvaluation ptr, boolean isRef, ActivationRecord record, ConstexprEvaluationContext context) { ICPPEvaluation derefEval = new EvalUnary(ICPPASTUnaryExpression.op_star, ptr, null, context.getPoint()).computeForFunctionCall(record, context); if(isRef) { return derefEval; } else { return new EvalFixed(derefEval.getType(context.getPoint()), derefEval.getValueCategory(context.getPoint()), derefEval.getValue(context.getPoint())); } }
Source:
public ICPPEvaluation[] getAll() { START return new ICPPEvaluation[] {this.getEvaluation()}; END } "this" is redundant here

Target:
public ICPPEvaluation[] getAll() { return new ICPPEvaluation[] { getEvaluation() }; }
Source:
public static IoOperationType getType(int rwbs) { START if (rwbs % 2 == 0) { END return READ; } return WRITE; } return ((rwbs & 1) == 0) ? READ:WRITE; ?

Target:
public static IoOperationType getType(int rwbs) { /* Even is a "read", odd is a "write" */ return (rwbs % 2 == 0) ? READ : WRITE; }
Source:
public boolean isModelerResource() { START if (resource.getURI() != null) { END return new FileQuery(resource.getURI().fileExtension()).isVSMFile(); } return false; } Looks like we might need the same try catch here.

Target:
public boolean isModelerResource() { try { if (resource.getURI() != null) { return new FileQuery(resource.getURI().fileExtension()).isVSMFile(); } } catch (IllegalStateException e) { // Silent catch: if an issue occurred while getting this Resource's // URI, then it will not be considered as a representation resource } return false; }
Source:
protected final void activate(BundleContext bundleContext) { START databindingServiceReference = bundleContext.getServiceReference(EMFFormsDatabindingEMF.class); END if (databindingServiceReference == null) { throw new IllegalStateException( "The org.eclipse.emfforms.spi.core.services.databinding.emf.EMFFormsDatabindingEMF Service is not available!"); //$NON-NLS-1$ } setEMFFormsDatabinding(bundleContext.getService(databindingServiceReference)); } should be loaded lazy

Target:
protected final void activate(BundleContext bundleContext) { this.bundleContext = bundleContext; }
Source:
public void init(Composite parent, String viewerName, ITmfTrace trace) { super.init(parent, viewerName); // Increment a counter to make sure the tree ID is unique. fCountInstance++; fInstanceNb = fCountInstance; fTrace = trace; // The viewer will process all events if he is assigned to an experiment fProcessAll = (trace instanceof TmfExperiment); initContent(parent); initInput(); START fSash.addDisposeListener(new DisposeListener() { END @Override public void widgetDisposed(DisposeEvent e) { internalDispose(); } }); } lambda?

Target:
public void init(Composite parent, String viewerName, ITmfTrace trace) { super.init(parent, viewerName); // Increment a counter to make sure the tree ID is unique. fCountInstance++; fInstanceNb = fCountInstance; fTrace = trace; // The viewer will process all events if he is assigned to an experiment fProcessAll = (trace instanceof TmfExperiment); initContent(parent); initInput(); fSash.addDisposeListener((e) -> { internalDispose(); }); }
Source:
public synchronized IndexWriter getTimestampsWriter() { if (fTimestampsWriter == null) { try { Directory indexDir = FSDirectory .open(Paths.get(fIndexRoot.append(fContainerId) START .append(TIMESTAMPS_DIR).toOSString())); END IndexWriterConfig config = new IndexWriterConfig( new SimpleAnalyzer()); config.setOpenMode(OpenMode.CREATE_OR_APPEND); fTimestampsWriter = new IndexWriter(indexDir, config); } catch (IOException e) { Logger.logException(e); } } return fTimestampsWriter; } as Lucene works with java7 Path, then IPath from eclipse is probably not needed, fIndexRoot can be declared as string, and then: Paths.get(fIndexRoot, fContainerId, TIMESTAMPS_DIR) (similar code in a few places)

Target:
public synchronized IndexWriter getTimestampsWriter() { if (fTimestampsWriter == null) { try { Directory indexDir = FSDirectory.open( Paths.get(fIndexRoot, fContainerId, TIMESTAMPS_DIR)); IndexWriterConfig config = new IndexWriterConfig( new SimpleAnalyzer()); config.setOpenMode(OpenMode.CREATE_OR_APPEND); fTimestampsWriter = new IndexWriter(indexDir, config); } catch (IOException e) { Logger.logException(e); } } return fTimestampsWriter; }
Source:
protected EEFWidgetStyle getWidgetStyle(EEFConditionalStyle conditionalStyle) { START return ((EEFButtonConditionalStyle) conditionalStyle).getStyle(); END } if (conditionalStyle instanceof EEFButtonConditionalStyle) { ... } Even if given the state of the code we could safely say today that we will not have a class cast exception, I can't condone casting something without testing its type first.

Target:
protected EEFWidgetStyle getWidgetStyle(EEFConditionalStyle conditionalStyle) { if (conditionalStyle instanceof EEFButtonConditionalStyle) { return ((EEFButtonConditionalStyle) conditionalStyle).getStyle(); } return null; }
Source:
public void setInstallLocation(File installLocation) { if (installLocation != null && START !installLocation.equals(fInstallLocation)) { END fInstallLocation= installLocation; } } Why is the equals needed here?

Target:
public void setInstallLocation(File installLocation) { fInstallLocation = installLocation; }
Source:
public void setJSRuntimeArguments(String runtimeArgs) { START if (fRuntimeArgs == null) { END if (runtimeArgs == null) { // No change return; } } else if (fRuntimeArgs.equals(runtimeArgs)) { // No change return; } fRuntimeArgs = runtimeArgs; } Is there a reason for not trying to update the fRuntimeArgs value if there are not changes?

Target:
public void setJSRuntimeArguments(String runtimeArgs) { fRuntimeArgs = runtimeArgs; }
Source:
private static Integer getSelectionIndex(SWTBotView viewBot) { final TimeGraphControl timegraph = viewBot.bot().widget(WidgetOfType.widgetOfType(TimeGraphControl.class)); START return UIThreadRunnable.syncExec(new IntResult() { END @Override public Integer run() { return timegraph.getSelectedIndex(); } }); } lambda

Target:
private static Integer getSelectionIndex(SWTBotView viewBot) { final TimeGraphControl timegraph = viewBot.bot().widget(WidgetOfType.widgetOfType(TimeGraphControl.class)); return UIThreadRunnable.syncExec(() -> { return timegraph.getSelectedIndex(); }); }
Source:
public void run() { FindTarget findTarget = fFindTarget; if (findTarget == null) { return; } checkShell(findTarget); if (fDialog == null) { fDialog = new TimeGraphFindDialog(findTarget.getShell()); } if (fDialog != null) { fDialog.update(findTarget); fDialog.open(); START fDialog.getShell().setMinimumSize(SHELL_MINIMUM_SIZE, SHELL_MINIMUM_SIZE); END } } This would better belong in TimeGraphFindDialog.create(), once you have a Shell but before it is made visible. Also, the minimumSize should be set using the result of computeTrim() to which you pass these values. I intermittently get a minimum height that is too small by the height of the trim, this might be the reason.

Target:
public void run() { FindTarget findTarget = fFindTarget; if (findTarget == null) { return; } checkShell(findTarget); if (fDialog == null) { fDialog = new TimeGraphFindDialog(findTarget.getShell()); } if (fDialog != null) { fDialog.update(findTarget); fDialog.open(); } }
Source:
public Repository open(HttpServletRequest req, String name) throws RepositoryNotFoundException, ServiceNotEnabledException { if (!name.equals(repoName)) throw new RepositoryNotFoundException(name); START final Repository END db = repo.getRepository(); db.incrementOpen(); return db; } unnecessary

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 String getMessage(EObject eObject, String value) { URI uri = START eObject.eResource().getURI(); END if (uri != null && uri.isPlatformPlugin() && uri.segmentCount() > 1) { // Segment 0 is the scheme // Segment 1 is the bundle Bundle bundle = Platform.getBundle(uri.segment(1)); return MessageTranslator.INSTANCE.getMessage(bundle, value); } return value; } Possible NPE if we're passed an EObject which is not part of a Resource.

Target:
public String getMessage(EObject eObject, String value) { if (eObject.eResource() != null) { URI uri = eObject.eResource().getURI(); if (uri != null && uri.isPlatformPlugin() && uri.segmentCount() > 1) { // Segment 0 is the scheme // Segment 1 is the bundle Bundle bundle = Platform.getBundle(uri.segment(1)); return MessageTranslator.INSTANCE.getMessage(bundle, value); } } return value; }
Source:
protected void tearDown() throws Exception { START Locale.getDefault(); END Locale.setDefault(default_language); sessionAirdResource = null; localSession = null; editor = null; super.tearDown(); } Why is this needed?

Target:
protected void tearDown() throws Exception { Locale.setDefault(default_language); sessionAirdResource = null; localSession = null; editor = null; super.tearDown(); }
Source:
protected Supplier<String> internalGetAttribute(String attr) { if ("type".equals(attr)) { return () -> START attributeType; END } return super.internalGetAttribute(attr); } This is unsafe, since attributeType is protected and can be set to null, but the contract is to return supplier only on non null values. This must be rewritten to check for the null value first.

Target:
protected Supplier<String> internalGetAttribute(String attr) { if ("type".equals(attr)) { return () -> attributeType != null ? attributeType : ""; } return super.internalGetAttribute(attr); }
Source:
START protected String END getFontName(String fontNameExpression, EAttribute eAttribute, FontData defaultFontData) { String fontName = defaultFontData.getName(); Eval eval = new Eval(interpreter, variableManager); if (fontNameExpression != null && !fontNameExpression.isEmpty()) { String fontNameValue = eval.get(eAttribute, fontNameExpression, String.class); if (fontNameValue != null) { // Get font name fontName = fontNameValue; } } return fontName; } not useful, you are not using this method outside of the AbstractEEFLifecycleManager

Target:
private String getFontName(String fontNameExpression, EAttribute eAttribute, FontData defaultFontData) { String fontName = defaultFontData.getName(); Eval eval = new Eval(interpreter, variableManager); if (fontNameExpression != null && !fontNameExpression.isEmpty()) { String fontNameValue = eval.get(eAttribute, fontNameExpression, String.class); if (fontNameValue != null) { // Get font name fontName = fontNameValue; } } return fontName; }
Source:
START protected int END getFontSize(String fontSizeExpression, EAttribute eAttribute, FontData defaultFontData) { int fontSize = defaultFontData.getHeight(); if (fontSizeExpression != null && !fontSizeExpression.isEmpty()) { Eval eval = new Eval(interpreter, variableManager); Integer fontSizeValue = eval.get(eAttribute, fontSizeExpression, Integer.class); if (fontSizeValue != null && fontSizeValue.intValue() != fontSize) { fontSize = fontSizeValue; } } return fontSize; } not useful, you are not using this method outside of the AbstractEEFLifecycleManager

Target:
private int getFontSize(String fontSizeExpression, EAttribute eAttribute, FontData defaultFontData) { int fontSize = defaultFontData.getHeight(); if (fontSizeExpression != null && !fontSizeExpression.isEmpty()) { Eval eval = new Eval(interpreter, variableManager); Integer fontSizeValue = eval.get(eAttribute, fontSizeExpression, Integer.class); if (fontSizeValue != null && fontSizeValue.intValue() != fontSize) { fontSize = fontSizeValue; } } return fontSize; }
Source:
START public static END boolean hasPackageJson(IProject project){ IFile packageJsonFile = project.getFile(NodeConstants.PACKAGE_JSON); if (packageJsonFile != null && packageJsonFile.isAccessible()) { return true; } return false; } Does it really need to be 'public static'? Is this method used from somewhere outside?

Target:
private boolean hasPackageJson(IProject project){ IFile packageJsonFile = project.getFile(NodeConstants.PACKAGE_JSON); if (packageJsonFile != null && packageJsonFile.isAccessible()) { return true; } return false; }
Source:
START public static END boolean isValidFile(IFile file) { // File must be a js file String fileExtension = file.getFileExtension(); if (!fileExtension.equals(JS_EXT)) { return false; } // File must exists and be accessible if (file.exists() && file.isAccessible()) { String filePath = file.getFullPath().toOSString(); // Js file cannot be inside node_modules or bower_components if (filePath != null && !filePath.contains(NODE_MODULES_FOLDER) && !filePath.contains(BOWER_COMPONENTS_FOLDER)) { return true; } } return false; } Does it really need to be 'public static'? Is this method used from somewhere outside?

Target:
private boolean isValidFile(IFile file) { // File must be a js file String fileExtension = file.getFileExtension(); if (!fileExtension.equals(JS_EXT)) { return false; } // File must exists and be accessible if (file.exists() && file.isAccessible()) { String filePath = file.getFullPath().toOSString(); // Js file cannot be inside node_modules or bower_components if (filePath != null && !filePath.contains(NODE_MODULES_FOLDER) && !filePath.contains(BOWER_COMPONENTS_FOLDER)) { return true; } } return false; }
Source:
public NewExecutableDialog( Shell parentShell, NewExecutableInfo info ) { super( parentShell ); setShellStyle( getShellStyle() | SWT.RESIZE ); START fInfo = info != null ? info : new NewExecutableInfo(SessionType.LOCAL); END } The new call on this line is unreachable.

Target:
public NewExecutableDialog( Shell parentShell, NewExecutableInfo info ) { super( parentShell ); assert info != null; setShellStyle( getShellStyle() | SWT.RESIZE ); fInfo = info; }
Source:
public void testCallStackRequirements() { /* Test optional requirement */ LttngUstCallStackAnalysisRequirement req = new LttngUstCallStackAnalysisRequirement(ILttngUstEventLayout.DEFAULT_LAYOUT); for (TestData item: TestData.values()) { START assertEquals(item.isValid(), req.test(item.getTrace())); END } } change to: assertEquals(item.name(), item.isValid(), req.test(item.getTrace())); In case it fails then we would know which one in loop failed.

Target:
public void testCallStackRequirements() { LttngUstCallStackAnalysisRequirement req = new LttngUstCallStackAnalysisRequirement(ILttngUstEventLayout.DEFAULT_LAYOUT); for (TestData item: TestData.values()) { assertEquals(item.name(), item.isValid(), req.test(item.getTrace())); } }
Source:
public @Nullable String toString() { START return String.valueOf(fValue); END } String.valueof(String).toString();? why not just return the string, it's final.

Target:
public @Nullable String toString() { return fValue; }
Source:
private boolean isJobOverridingCancelingMethod() { Method cancelingMethod = null; try { cancelingMethod = currentJob.getClass().getDeclaredMethod("canceling"); //$NON-NLS-1$ } catch (NoSuchMethodException | SecurityException e) { return false; } // sufficient as InternalJob and Job classes are abstract, // currentJob.getClass cannot be one or the other. return START (cancelingMethod != null); END } Redundant parentheses.

Target:
private boolean isJobOverridingCancelingMethod() { Method cancelingMethod = null; try { cancelingMethod = currentJob.getClass().getDeclaredMethod("canceling"); //$NON-NLS-1$ } catch (NoSuchMethodException | SecurityException e) { return false; } // Sufficient as InternalJob and Job classes are abstract, // currentJob.getClass cannot be one or the other. return cancelingMethod != null; }
Source:
protected Control createContents(Composite parent) { final Composite composite = createComposite(parent); START System.out.println(composite.getBackground()); END createAutoSaveCheckbox(composite); createAutoSaveGroup(composite); createIntervalPart(); createMessagesPart(); return composite; } Please remove such debug/log lines.

Target:
protected Control createContents(Composite parent) { final Composite composite = createComposite(parent); createAutoSaveCheckbox(composite); createAutoSaveGroup(composite); createIntervalPart(); createMessagesPart(); return composite; }
Source:
public void addDisposeListener(Consumer<ISideEffect> disposalConsumer) { checkRealm(); if (isDisposed()) { return; } if (this.disposeListeners == null) { this.disposeListeners = new START CopyOnWriteArrayList<>(); END } this.disposeListeners.add(disposalConsumer); } CopyOnWriteArrayList does unwanted synchronization, which is a performance problem. I'd suggest manually implementing the copy-on-write pattern using a normal ArrayList and a boolean to indicate if the list has been read (the copy can be omitted if there was no intervening read).

Target:
public void addDisposeListener(Consumer<ISideEffect> disposalConsumer) { checkRealm(); if (isDisposed()) { return; } if (this.disposeListeners == null) { this.disposeListeners = new ArrayList<>(); } this.disposeListeners.add(disposalConsumer); }
Source:
public @NonNull String @NonNull getFullAttribute() { LinkedList<String> list = new LinkedList<>(); Attribute curNode = this; /* Add recursive parents to the list, but stop at the root node */ while (curNode.parent != null) { list.addFirst(curNode.getName()); curNode = curNode.parent; } START return list.toArray(new @NonNull String[0]); END } While changing this code, here instead of String[0], it should be String[list.size()]

Target:
public @NonNull String @NonNull getFullAttribute() { LinkedList<String> list = new LinkedList<>(); Attribute curNode = this; /* Add recursive parents to the list, but stop at the root node */ while (curNode.parent != null) { list.addFirst(curNode.getName()); curNode = curNode.parent; } return list.toArray(new @NonNull String[list.size()]); }
Source:
private String resolveFile(Bundle bundle, String path) { String prefixedPath = getThemePrefixedPath(path); try { URL url = null; if (prefixedPath != null) { url = bundle.getEntry(prefixedPath); } if (url == null) { url = bundle.getEntry(path); } if (url != null) { URL localURL = FileLocator.toFileURL(url); return localURL.toString(); } START } catch (IOException e) { END } return null; } As per bug 487713#c11, the previous revision used to return the path in case of IOException. Do you think it makes sense to add that return statement?

Target:
private String resolveFile(Bundle bundle, String path) throws IOException { String prefixedPath = getThemePrefixedPath(path); URL url = null; if (prefixedPath != null) { url = bundle.getEntry(prefixedPath); } if (url == null) { url = bundle.getEntry(path); } if (url != null) { URL localURL = FileLocator.toFileURL(url); return localURL.toString(); } return null; }
Source:
public CpuUsageXYViewer(Composite parent) { super(parent, Messages.CpuUsageXYViewer_Title, Messages.CpuUsageXYViewer_TimeXAxis, Messages.CpuUsageXYViewer_CpuYAxis); setResolution(RESOLUTION); START getSwtChart().getTitle().setVisible(true); END getSwtChart().getLegend().setVisible(false); } did you mean false here? The title is still getting displayed

Target:
public CpuUsageXYViewer(Composite parent) { super(parent, Messages.CpuUsageXYViewer_Title, Messages.CpuUsageXYViewer_TimeXAxis, Messages.CpuUsageXYViewer_CpuYAxis); setResolution(RESOLUTION); getSwtChart().getTitle().setVisible(false); getSwtChart().getLegend().setVisible(false); }
Source:
private Point getPreferredSize(SWTGridCell gridCell) { START return gridCell.getPreferredSize() != null ? gridCell.getPreferredSize() : SWTGridCell.DEFAULT_PREFERRED_SIZE; END } the default preferred size is only used here, or? I would move this then to this class, as it is implementation specific that -1,-1 is treated as default

Target:
private Point getPreferredSize(SWTGridCell gridCell) { return gridCell.getPreferredSize() != null ? gridCell.getPreferredSize() : DEFAULT_PREFERRED_SIZE; }
Source:
public static void loadBasicInformation(GerritClient gerrit, ChangeInfo toRefresh) { ChangeInfo newChangeInfo = QueryHelpers.queryBasicInformation(gerrit, toRefresh.getId()); START mergeNewInformation(toRefresh, newChangeInfo); END QueryHelpers.loadRevisionDetails(gerrit, toRefresh.getUserSelectedRevision()); } Adding this code here pretty much reverts all attempts of performance improvements. As the name of the method implies, this should only load basic informations, and the detail about a revision is definitly not part of that

Target:
public static void loadBasicInformation(GerritClient gerrit, ChangeInfo toRefresh) { ChangeInfo newChangeInfo = QueryHelpers.queryBasicInformation(gerrit, toRefresh.getId()); mergeNewInformation(toRefresh, newChangeInfo); }
Source:
public static IJavaElement resolveJavaElement(Object object, ILaunch launch) throws CoreException { Object sourceElement = resolveSourceElement(object, launch); IJavaElement javaElement = getJavaElement(sourceElement); if (javaElement == null) { // fallback if default stratum does not provide a Java element sourceElement = resolveSourceElement(object, JAVA_STRATUM, launch); START if (sourceElement != null) END javaElement = getJavaElement(sourceElement); } return javaElement; } You don't need this null-check, the getJavaElement method already does that.

Target:
public static IJavaElement resolveJavaElement(Object object, ILaunch launch) throws CoreException { Object sourceElement = resolveSourceElement(object, launch); IJavaElement javaElement = getJavaElement(sourceElement); if (javaElement == null) { // fallback if default stratum does not provide a Java element sourceElement = resolveSourceElement(object, JAVA_STRATUM, launch); javaElement = getJavaElement(sourceElement); } return javaElement; }
Source:
public Properties getProviderSpecificProperties() { return START null; END } returning an empty list by default would be nicer here IMHO, no need for null check on the invoker side.

Target:
public Properties getProviderSpecificProperties() { return new Properties(); }
Source:
public ViewerTestCase(String name) { super(name); disableTestsBug347491 = Util.isCocoa(); final String START GTK_VERSION_PROPERTY = END "org.eclipse.swt.internal.gtk.version"; String value = System.getProperty(GTK_VERSION_PROPERTY); if (value != null) { if (value.startsWith("3")) { disableTestsBug493357 = true; } } } This should be a static and reduced to this: System.getProperty("org.eclipse.swt.internal.gtk.version", "").startsWith("3."); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$

Target:
public ViewerTestCase(String name) { super(name); disableTestsBug347491 = Util.isCocoa(); }
Source:
public void dispose() { super.dispose(); START fBuildThreadMap.values().forEach(buildThread -> { END buildThread.cancel(); }); if (fZoomThread != null) { fZoomThread.cancel(); } ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); getSite().getPage().removePartListener(fPartListener); } this needs to be synchronized. I got a java.util.ConcurrentModificationException when closing the view while right after opening a trace.

Target:
public void dispose() { super.dispose(); synchronized (fBuildThreadMap) { fBuildThreadMap.values().forEach(buildThread -> { buildThread.cancel(); }); } if (fZoomThread != null) { fZoomThread.cancel(); } ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); getSite().getPage().removePartListener(fPartListener); }
Source:
public SmartImportRootWizardPage(SmartImportWizard wizard, File initialSelection, Set<IWorkingSet> initialWorkingSets) { super(SmartImportRootWizardPage.class.getName()); START this.potentialProjects = Collections.emptyMap(); END this.selection = initialSelection; this.workingSets = initialWorkingSets; if (this.workingSets == null) { this.workingSets = new HashSet<>(); } setWizard(wizard); } Such general initialization should go along with the field declaration, otherwise it gets lost when adding another constructor.

Target:
public SmartImportRootWizardPage(SmartImportWizard wizard, File initialSelection, Set<IWorkingSet> initialWorkingSets) { super(SmartImportRootWizardPage.class.getName()); this.selection = initialSelection; this.workingSets = initialWorkingSets; if (this.workingSets == null) { this.workingSets = new HashSet<>(); } setWizard(wizard); }
Source:
private static @Nullable Long nullableNumberToLong(@Nullable Number number) { START return number == null ? null : Long.valueOf(number.longValue()); END } parentheses please ;) return (number == null ? null : Long.valueOf(number.longValue()));

Target:
private static @Nullable Long nullableNumberToLong(@Nullable Number number) { return (number == null ? null : Long.valueOf(number.longValue())); }
Source:
public @Nullable String toString() { Number startValue = fBegin.getValue(); Number endValue = fEnd.getValue(); // TODO: The string should probably include the low and // high limits here. if (startValue != null && endValue != null) { return "[" + String.valueOf(fBegin) + " - " + String.valueOf(fEnd) + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } START return null; END } Again here, empty string or "null" might be preferable?

Target:
public @Nullable String toString() { Long startValue = fBegin.getValue(); Long endValue = fEnd.getValue(); // TODO: The string should probably include the low and // high limits here. if (startValue != null && endValue != null) { return "[" + String.valueOf(fBegin) + " - " + String.valueOf(fEnd) + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } return null; }
Source:
private static @Nullable Long nullableNumberToLong(@Nullable Number number) { if (number == null) { return null; } START END return Long.valueOf(number.longValue()); } elvis notation?

Target:
private static @Nullable Long nullableNumberToLong(@Nullable Number number) { return number == null ? null : Long.valueOf(number.longValue()); }
Source:
START public static ArrayList<State> getStates(Region region) { END ArrayList<State> states = new ArrayList<>(); for (Vertex vertex : region.getSubvertices()) { if (vertex instanceof State) { states.add((State) vertex); } } return states; } Same here, why using ArrayList<>?

Target:
public static List<State> getStates(Region region) { List<State> states = new ArrayList<>(); for (Vertex vertex : region.getSubvertices()) { if (vertex instanceof State) { states.add((State) vertex); } } return states; }
Source:
public static CallEvent getCallEvent(Operation operation) { CallEvent result = null; Package nearestPackage = operation.getNearestPackage(); if (nearestPackage != null) { for (Element element : nearestPackage.getOwnedElements()) { if (element instanceof CallEvent) { final CallEvent callEvent = (CallEvent) element; if START (callEvent.getOperation() != null && callEvent.getOperation().equals(operation)) { END result = callEvent; break; } } } } return result; } what about operation.equals(callEvent.getOperation()) ?

Target:
public static CallEvent getCallEvent(Operation operation) { CallEvent result = null; Package nearestPackage = operation.getNearestPackage(); if (nearestPackage != null) { for (Element element : nearestPackage.getOwnedElements()) { if (element instanceof CallEvent) { final CallEvent callEvent = (CallEvent) element; if (operation.equals(callEvent.getOperation())) { result = callEvent; break; } } } } return result; }
Source:
private void handleUnknownFeatures(final EObject owner, final FeatureMap featureMap) { START final Iterator<FeatureMap.Entry> iter = featureMap.iterator(); List<FeatureMap.Entry> entryList = Lists.newArrayList(); while (iter.hasNext()) { entryList.add(iter.next()); } END // Don't call handleFeature when iterating the FeatureMap // Indeed, the handleFeature allows to set the value of the unknown // feature in // another feature. Doing this the FeatureMap is updated and may raise // concurrency if the Feature is being iterated. for (FeatureMap.Entry currentEntry : entryList) { handleFeature(owner, currentEntry.getEStructuralFeature(), currentEntry.getValue()); } } Can be replaced by List<FeatureMap.Entry> entryList = Lists.newArrayList(featureMap.iterator());

Target:
private void handleUnknownFeatures(final EObject owner, final FeatureMap featureMap) { // Don't call handleFeature when iterating the FeatureMap // Indeed, the handleFeature allows to set the value of the unknown // feature in // another feature. Doing this the FeatureMap is updated and may raise // concurrency if the Feature is being iterated. List<FeatureMap.Entry> entryList = Lists.newArrayList(featureMap.iterator()); for (FeatureMap.Entry currentEntry : entryList) { handleFeature(owner, currentEntry.getEStructuralFeature(), currentEntry.getValue()); } }
Source:
public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + fChannels.hashCode(); START result = prime * result + (fDomain.equals(DomainEnum.KERNEL) ? 1231 : 1237); END result = prime * result + ((fBufferType == null) ? 0 : (fBufferType.ordinal() + 1)); return result; } result = prime * result + ((fDomain == null) ? 0 : (fDomain.ordinal() + 1));

Target:
public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + fChannels.hashCode(); result = prime * result + ((fDomain == null) ? 0 : (fDomain.ordinal() + 1)); result = prime * result + ((fBufferType == null) ? 0 : (fBufferType.ordinal() + 1)); return result; }
Source:
public void createPartControl(Composite parent) { parent.setLayout(new FillLayout(SWT.HORIZONTAL)); Composite queryRegistryContainer = new Composite(parent, SWT.NONE); queryRegistryContainer.setLayout(new GridLayout(1, false)); initializeQueryTreeViewer(queryRegistryContainer); START initializeToolBar(); END initializeMenu(); } Are the toolbar and menu initialization calls really required? Especially as we are not using Actions but Commands.

Target:
public void createPartControl(Composite parent) { parent.setLayout(new FillLayout(SWT.HORIZONTAL)); Composite queryRegistryContainer = new Composite(parent, SWT.NONE); queryRegistryContainer.setLayout(new GridLayout(1, false)); initializeQueryTreeViewer(queryRegistryContainer); }
Source:
public long getCleanupDelay() { START if (cleanupDelayMillis > 0) { END return cleanupDelayMillis; } else { return Math.min(expireAfterMillis / 10, TimeUnit.MINUTES.toMillis(10)); } } This is wrong, it should be cleanupDelayMillis >= 0 otherwise it's impossible to disable clean up. Currently, if we set it to 0(NO_CLEANUP), getCleanupDelay returns 1/10 of expireAfterMillis instead of 0. Follow up change(https://git.eclipse.org/r/#/c/75060) is adding test cases and fix the problem. Please squash it into this change.

Target:
public long getCleanupDelay() { if (cleanupDelayMillis < 0) { return Math.min(expireAfterMillis / 10, TimeUnit.MINUTES.toMillis(10)); } return cleanupDelayMillis; }
Source:
public void test_ConstructorLorg_eclipse_swt_widgets_CompositeI() { try { scrolledComposite = new ScrolledComposite(null, 0); fail("No exception thrown"); } catch (IllegalArgumentException e) { } int[] cases = {SWT.H_SCROLL, SWT.V_SCROLL, SWT.BORDER, SWT.LEFT_TO_RIGHT, SWT.RIGHT_TO_LEFT}; START for (int i = 0; i < cases.length; i++) END scrolledComposite = new ScrolledComposite(shell, cases[i]); } Please use for blocks.

Target:
public void test_ConstructorLorg_eclipse_swt_widgets_CompositeI() { try { scrolledComposite = new ScrolledComposite(null, 0); fail("No exception thrown"); } catch (IllegalArgumentException e) { } int[] cases = {SWT.H_SCROLL, SWT.V_SCROLL, SWT.BORDER, SWT.LEFT_TO_RIGHT, SWT.RIGHT_TO_LEFT}; for (int i = 0; i < cases.length; i++){ scrolledComposite = new ScrolledComposite(shell, cases[i]); } }
Source:
public void dispose() { // run super. super.dispose(); // remove ourselves as a selection and registry listener getSite().getPage().removePostSelectionListener(this); RegistryFactory.getRegistry().removeListener(this); SaveablesList saveables = (SaveablesList) getSite().getService(ISaveablesLifecycleListener.class); START saveables.removeModelLifecycleListener(saveablesTracker); END currentPart = null; currentSelection = null; pinPropertySheetAction = null; } check for non null?

Target:
public void dispose() { // run super. super.dispose(); // remove ourselves as a selection and registry listener getSite().getPage().removePostSelectionListener(this); RegistryFactory.getRegistry().removeListener(this); SaveablesList saveables = (SaveablesList) getSite().getService(ISaveablesLifecycleListener.class); if (saveables != null) { saveables.removeModelLifecycleListener(saveablesTracker); } currentPart = null; currentSelection = null; pinPropertySheetAction = null; }
Source:
private int sortByScheduledDate(ITask task1, ITask task2, int sortDirection) { if (task1 instanceof AbstractTask && task2 instanceof AbstractTask) { DateRange date1 = ((AbstractTask) task1).getScheduledForDate(); DateRange date2 = ((AbstractTask) task2).getScheduledForDate(); START return compare(date1.getEndDate(), date2.getEndDate(), sortDirection); END } return 0; } Will this sort tasks scheduled for specific days next week before tasks scheduled for "next week" unless they are scheduled for the last day of the week, when they would have the same end date?

Target:
private int sortByScheduledDate(ITask task1, ITask task2, int sortDirection) { if (task1 instanceof AbstractTask && task2 instanceof AbstractTask) { DateRange date1 = ((AbstractTask) task1).getScheduledForDate(); DateRange date2 = ((AbstractTask) task2).getScheduledForDate(); return compare(date1, date2, sortDirection); } return 0; }
Source:
protected void tearDown() throws Exception { super.tearDown(); START if (oldFont != null) { changeDefaultFontName(oldFont); } END } This must be done before super.teadDown() as it clean all variables (included oldFont that will be set to null).

Target:
protected void tearDown() throws Exception { if (oldFont != null) { changeDefaultFontName(oldFont); } super.tearDown(); }
Source:
START public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { END return "Alrighty!"; } This creates a deprecated warning. Why not using non-deprecated API?

Target:
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { return null; }
Source:
public boolean remove(String id) { START return this.id2descriptors.removeAll(id) != null; END } Why not return "!this.id2descriptors.removeAll(id).isEmpty();" like in LegacyPropertyContributorRegistry.java?

Target:
public boolean remove(String id) { return !this.id2descriptors.removeAll(id).isEmpty(); }
Source:
public ITypeMapper getTypeMapper(String contributorId) { ITypeMapper legacyPropertyTypeMapper = null; Collection<IItemDescriptor> values = this.id2descriptors.values(); for (IItemDescriptor itemDescriptor : values) { if (itemDescriptor instanceof LegacyPropertyContributorItemDescriptor) { if (contributorId != null && contributorId.equals(itemDescriptor.getId())) { START legacyPropertyTypeMapper = ((LegacyPropertyContributorItemDescriptor) itemDescriptor).getTypeMapper(); END } } } return legacyPropertyTypeMapper; } Should we return/break early once we found the first match, or is it intended to continue and possibly find others (and only return the last one)?

Target:
public ITypeMapper getTypeMapper(String contributorId) { Collection<IItemDescriptor> values = this.id2descriptors.values(); for (IItemDescriptor itemDescriptor : values) { if (itemDescriptor instanceof LegacyPropertyContributorItemDescriptor) { if (contributorId != null && contributorId.equals(itemDescriptor.getId())) { return ((LegacyPropertyContributorItemDescriptor) itemDescriptor).getTypeMapper(); } } } return null; }
Source:
private FastForwardMode getFastForwardMode() { Config config = repo.getConfig(); Merge ffMode = config.getEnum(Merge.values(), ConfigConstants.CONFIG_PULL_SECTION, null, ConfigConstants.CONFIG_KEY_FF, null); if (ffMode == null) { ffMode = config.getEnum(Merge.values(), ConfigConstants.CONFIG_MERGE_SECTION, null, START ConfigConstants.CONFIG_KEY_FF, null); END } return ffMode != null ? FastForwardMode.valueOf(ffMode) : null; } Do we need this? MergeCommand should already fall back to the config... so it looks as if checking for pull.ff might be sufficient here.

Target:
private FastForwardMode getFastForwardMode() { Config config = repo.getConfig(); Merge ffMode = config.getEnum(Merge.values(), ConfigConstants.CONFIG_PULL_SECTION, null, ConfigConstants.CONFIG_KEY_FF, null); return ffMode != null ? FastForwardMode.valueOf(ffMode) : null; }
Source:
protected void resetAll() { try { m_organizedTable.setTableChanging(true); // m_organizedTable.resetColumns(); START m_organizedTable.removeUserRowFilters(); END m_organizedTable.applyRowFilters(); TableUserFilterManager m = m_organizedTable.getUserFilterManager(); if (m != null) { m.reset(); } ITableCustomizer cst = m_organizedTable.getTableCustomizer(); if (cst != null) { cst.removeAllColumns(); } } finally { m_organizedTable.setTableChanging(false); } getColumnsTableField().reloadTableData(); } Sollte sich gleich verhalten wie removeRowFilter(f). Der macht gleich ein applyRowFilter(). Ist sonst wahrscheinlich etwas verwirrend wenn sich die beiden Methoden in der Hinsicht unterschiedlich verhalten. Und noch ein Punkt: muss die Method tatsächlich auf dem Interface sein? Könnte man sie nicht einfach intern in der Impl. von resetColumns() aufrufen? Oder gibt es Fälle wo man resetColumns machen möchte, aber die UserFilter bewusst unangetastet lässt?

Target:
protected void resetAll() { try { m_organizedTable.setTableChanging(true); // m_organizedTable.resetColumns(); TableUserFilterManager m = m_organizedTable.getUserFilterManager(); if (m != null) { m.reset(); } ITableCustomizer cst = m_organizedTable.getTableCustomizer(); if (cst != null) { cst.removeAllColumns(); } } finally { m_organizedTable.setTableChanging(false); } getColumnsTableField().reloadTableData(); }
Source:
START public void END setParent(CalledFunction parent) { fParent = parent; } private

Target:
private void setParent(CalledFunction parent) { fParent = parent; }
Source:
public boolean canExecute(ITmfTrace trace) { START return !Iterables.isEmpty(getDependentAnalyses()); END } replace with true at the moment, discussed with Genevieve

Target:
public boolean canExecute(ITmfTrace trace) { /* * FIXME: change to !Iterables.isEmpty(getDependentAnalyses()) when * analysis dependencies work better */ return true; }
Source:
public boolean handle(TreeNode treeNode) { EObject data = treeNode.getData(); // we are interested only in the root match boolean handles = data instanceof Match && data.eContainer() instanceof Comparison; return START handles; END } I'd inline this variable.

Target:
public boolean handle(TreeNode treeNode) { EObject data = treeNode.getData(); // we are interested only in the root match return data instanceof Match && data.eContainer() instanceof Comparison; }
Source:
private static Set<ObjectId> refIdSet(Collection<Ref> refs) { Set<ObjectId> ids = new HashSet<ObjectId>(refs.size()); for (Ref ref : refs) { if (ref.getObjectId() != null) { ids.add(ref.getObjectId()); } if (ref.getPeeledObjectId() != null) { START ids.add(ref.getPeeledObjectId()); END } } return ids; } One implementation of Ref.getPeeledObjectId() (the one in SymbolicRef) seems to be so expensive that it would make sense to cache the result of ref.getPeeledObjectId() in a local variable. Or do you know we will never deal with symbolic refs here?

Target:
private static Set<ObjectId> refIdSet(Collection<Ref> refs) { Set<ObjectId> ids = new HashSet<ObjectId>(refs.size()); for (Ref ref : refs) { ObjectId id = ref.getObjectId(); if (id != null) { ids.add(id); } id = ref.getPeeledObjectId(); if (id != null) { ids.add(id); } } return ids; }
Source:
String getUpdateLocation0(Module module) { ModuleRevision current = module.getCurrentRevision(); Generation generation = (Generation) current.getRevisionInfo(); String updateLocation = generation.getHeaders().get(Constants.BUNDLE_UPDATELOCATION); if (updateLocation == null) { updateLocation = module.getLocation(); } if (updateLocation.startsWith(INITIAL_LOCATION)) { updateLocation = updateLocation.substring(INITIAL_LOCATION.length()); } START return updateLocation == null ? module.getLocation() : updateLocation; END } Due to the null test above, you do not need to retest for null in the return statement.

Target:
String getUpdateLocation0(Module module) { ModuleRevision current = module.getCurrentRevision(); Generation generation = (Generation) current.getRevisionInfo(); String updateLocation = generation.getHeaders().get(Constants.BUNDLE_UPDATELOCATION); if (updateLocation == null) { updateLocation = module.getLocation(); } if (updateLocation.startsWith(INITIAL_LOCATION)) { updateLocation = updateLocation.substring(INITIAL_LOCATION.length()); } return updateLocation; }
Source:
public Function<@NonNull ISegment, @Nullable Long> getMapper() { START return (o) -> { END return o.getStart(); }; } for short, you can just do return o -> o;

Target:
public Function<@NonNull ISegment, @Nullable Long> getMapper() { return o -> o.getStart(); }
Source:
public List<ChartSeries> getChartSeries() { START return checkNotNull(ImmutableList.copyOf(fSeries)); END } you should do the ImmutableList.copyOf() at the constructor, and here just return the list directly. This will ensure that the constrcutor's caller cannot modify the list stored in this class.

Target:
public List<ChartSeries> getChartSeries() { return fSeries; }
Source:
public void accept(Object obj) { for (XYSeriesConsumer consumer : fSeries) { consumer.accept(obj); START } END } You can use .forEach on a List directly: fSeries.forEach(consumer -> consumer.accept(obj)); Both work, not much difference, but the functional syntax would fit well with the rest imo.

Target:
public void accept(Object obj) { fSeries.forEach(consumer -> consumer.accept(obj)); }