auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected 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; }

Target:
not useful, you are not using this method outside of the AbstractEEFLifecycleManager
Source:
protected 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; }

Target:
not useful, you are not using this method outside of the AbstractEEFLifecycleManager
Source:
public static boolean hasPackageJson(IProject project){ IFile packageJsonFile = project.getFile(NodeConstants.PACKAGE_JSON); if (packageJsonFile != null && packageJsonFile.isAccessible()) { return true; } return false; }

Target:
Does it really need to be 'public static'? Is this method used from somewhere outside?
Source:
public static 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; }

Target:
Does it really need to be 'public static'? Is this method used from somewhere outside?
Source:
public NewExecutableDialog( Shell parentShell, NewExecutableInfo info ) { super( parentShell ); setShellStyle( getShellStyle() | SWT.RESIZE ); fInfo = info != null ? info : new NewExecutableInfo(SessionType.LOCAL); }

Target:
The new call on this line is unreachable.
Source:
public void testCallStackRequirements() { /* Test optional requirement */ LttngUstCallStackAnalysisRequirement req = new LttngUstCallStackAnalysisRequirement(ILttngUstEventLayout.DEFAULT_LAYOUT); for (TestData item: TestData.values()) { assertEquals(item.isValid(), req.test(item.getTrace())); } }

Target:
change to: assertEquals(item.name(), item.isValid(), req.test(item.getTrace())); In case it fails then we would know which one in loop failed.
Source:
public @Nullable String toString() { return String.valueOf(fValue); }

Target:
String.valueof(String).toString();? why not just return the string, it's final.
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 (cancelingMethod != null); }

Target:
Redundant parentheses.
Source:
protected Control createContents(Composite parent) { final Composite composite = createComposite(parent); System.out.println(composite.getBackground()); createAutoSaveCheckbox(composite); createAutoSaveGroup(composite); createIntervalPart(); createMessagesPart(); return composite; }

Target:
Please remove such debug/log lines.
Source:
public void addDisposeListener(Consumer<ISideEffect> disposalConsumer) { checkRealm(); if (isDisposed()) { return; } if (this.disposeListeners == null) { this.disposeListeners = new CopyOnWriteArrayList<>(); } this.disposeListeners.add(disposalConsumer); }

Target:
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).
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; } return list.toArray(new @NonNull String[0]); }

Target:
While changing this code, here instead of String[0], it should be 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(); } } catch (IOException e) { } return null; }

Target:
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?
Source:
public CpuUsageXYViewer(Composite parent) { super(parent, Messages.CpuUsageXYViewer_Title, Messages.CpuUsageXYViewer_TimeXAxis, Messages.CpuUsageXYViewer_CpuYAxis); setResolution(RESOLUTION); getSwtChart().getTitle().setVisible(true); getSwtChart().getLegend().setVisible(false); }

Target:
did you mean false here? The title is still getting displayed
Source:
private Point getPreferredSize(SWTGridCell gridCell) { return gridCell.getPreferredSize() != null ? gridCell.getPreferredSize() : SWTGridCell.DEFAULT_PREFERRED_SIZE; }

Target:
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
Source:
public static void loadBasicInformation(GerritClient gerrit, ChangeInfo toRefresh) { ChangeInfo newChangeInfo = QueryHelpers.queryBasicInformation(gerrit, toRefresh.getId()); mergeNewInformation(toRefresh, newChangeInfo); QueryHelpers.loadRevisionDetails(gerrit, toRefresh.getUserSelectedRevision()); }

Target:
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
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); if (sourceElement != null) javaElement = getJavaElement(sourceElement); } return javaElement; }

Target:
You don't need this null-check, the getJavaElement method already does that.
Source:
public Properties getProviderSpecificProperties() { return null; }

Target:
returning an empty list by default would be nicer here IMHO, no need for null check on the invoker side.
Source:
public ViewerTestCase(String name) { super(name); disableTestsBug347491 = Util.isCocoa(); final String GTK_VERSION_PROPERTY = "org.eclipse.swt.internal.gtk.version"; String value = System.getProperty(GTK_VERSION_PROPERTY); if (value != null) { if (value.startsWith("3")) { disableTestsBug493357 = true; } } }

Target:
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$
Source:
public void dispose() { super.dispose(); fBuildThreadMap.values().forEach(buildThread -> { buildThread.cancel(); }); if (fZoomThread != null) { fZoomThread.cancel(); } ResourcesPlugin.getWorkspace().removeResourceChangeListener(this); getSite().getPage().removePartListener(fPartListener); }

Target:
this needs to be synchronized. I got a java.util.ConcurrentModificationException when closing the view while right after opening a trace.
Source:
public SmartImportRootWizardPage(SmartImportWizard wizard, File initialSelection, Set<IWorkingSet> initialWorkingSets) { super(SmartImportRootWizardPage.class.getName()); this.potentialProjects = Collections.emptyMap(); this.selection = initialSelection; this.workingSets = initialWorkingSets; if (this.workingSets == null) { this.workingSets = new HashSet<>(); } setWizard(wizard); }

Target:
Such general initialization should go along with the field declaration, otherwise it gets lost when adding another constructor.
Source:
private static @Nullable Long nullableNumberToLong(@Nullable Number number) { return number == null ? null : Long.valueOf(number.longValue()); }

Target:
parentheses please ;) 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$ } return null; }

Target:
Again here, empty string or "null" might be preferable?
Source:
private static @Nullable Long nullableNumberToLong(@Nullable Number number) { if (number == null) { return null; } return Long.valueOf(number.longValue()); }

Target:
elvis notation?
Source:
public static ArrayList<State> getStates(Region region) { ArrayList<State> states = new ArrayList<>(); for (Vertex vertex : region.getSubvertices()) { if (vertex instanceof State) { states.add((State) vertex); } } return states; }

Target:
Same here, why using ArrayList<>?
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 (callEvent.getOperation() != null && callEvent.getOperation().equals(operation)) { result = callEvent; break; } } } } return result; }

Target:
what about operation.equals(callEvent.getOperation()) ?
Source:
private void handleUnknownFeatures(final EObject owner, final FeatureMap featureMap) { final Iterator<FeatureMap.Entry> iter = featureMap.iterator(); List<FeatureMap.Entry> entryList = Lists.newArrayList(); while (iter.hasNext()) { entryList.add(iter.next()); } // 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()); } }

Target:
Can be replaced by List<FeatureMap.Entry> entryList = Lists.newArrayList(featureMap.iterator());
Source:
public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + fChannels.hashCode(); result = prime * result + (fDomain.equals(DomainEnum.KERNEL) ? 1231 : 1237); result = prime * result + ((fBufferType == null) ? 0 : (fBufferType.ordinal() + 1)); return result; }

Target:
result = prime * result + ((fDomain == null) ? 0 : (fDomain.ordinal() + 1));
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); initializeToolBar(); initializeMenu(); }

Target:
Are the toolbar and menu initialization calls really required? Especially as we are not using Actions but Commands.
Source:
public long getCleanupDelay() { if (cleanupDelayMillis > 0) { return cleanupDelayMillis; } else { return Math.min(expireAfterMillis / 10, TimeUnit.MINUTES.toMillis(10)); } }

Target:
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.
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}; for (int i = 0; i < cases.length; i++) scrolledComposite = new ScrolledComposite(shell, cases[i]); }

Target:
Please use for blocks.
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); saveables.removeModelLifecycleListener(saveablesTracker); currentPart = null; currentSelection = null; pinPropertySheetAction = null; }

Target:
check for non 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(); return compare(date1.getEndDate(), date2.getEndDate(), sortDirection); } return 0; }

Target:
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?
Source:
protected void tearDown() throws Exception { super.tearDown(); if (oldFont != null) { changeDefaultFontName(oldFont); } }

Target:
This must be done before super.teadDown() as it clean all variables (included oldFont that will be set to null).
Source:
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) { return "Alrighty!"; }

Target:
This creates a deprecated warning. Why not using non-deprecated API?
Source:
public boolean remove(String id) { return this.id2descriptors.removeAll(id) != null; }

Target:
Why not return "!this.id2descriptors.removeAll(id).isEmpty();" like in LegacyPropertyContributorRegistry.java?
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())) { legacyPropertyTypeMapper = ((LegacyPropertyContributorItemDescriptor) itemDescriptor).getTypeMapper(); } } } return legacyPropertyTypeMapper; }

Target:
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)?
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, ConfigConstants.CONFIG_KEY_FF, null); } return ffMode != null ? FastForwardMode.valueOf(ffMode) : null; }

Target:
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.
Source:
protected void resetAll() { try { m_organizedTable.setTableChanging(true); // m_organizedTable.resetColumns(); m_organizedTable.removeUserRowFilters(); 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(); }

Target:
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?
Source:
public void setParent(CalledFunction parent) { fParent = parent; }

Target:
private
Source:
public boolean canExecute(ITmfTrace trace) { return !Iterables.isEmpty(getDependentAnalyses()); }

Target:
replace with true at the moment, discussed with Genevieve
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 handles; }

Target:
I'd inline this variable.
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) { ids.add(ref.getPeeledObjectId()); } } return ids; }

Target:
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?
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()); } return updateLocation == null ? module.getLocation() : updateLocation; }

Target:
Due to the null test above, you do not need to retest for null in the return statement.
Source:
public Function<@NonNull ISegment, @Nullable Long> getMapper() { return (o) -> { return o.getStart(); }; }

Target:
for short, you can just do return o -> o;
Source:
public List<ChartSeries> getChartSeries() { return checkNotNull(ImmutableList.copyOf(fSeries)); }

Target:
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.
Source:
public void accept(Object obj) { for (XYSeriesConsumer consumer : fSeries) { consumer.accept(obj); } }

Target:
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.
Source:
public ScatterStringConsumer(IStringResolver<Object> resolver) { fResolver = resolver; fMap = checkNotNull(HashBiMap.create()); }

Target:
annotate this instead
Source:
private void resolveImpl(PackList packList, AbbreviatedObjectId id, boolean noGarbage, HashSet<ObjectId> matches) throws IOException { if (MAX_RESOLVE_MATCHES <= matches.size()) { return; } for (DfsPackFile pack : packList.packs) { if (noGarbage && pack.isGarbage()) { continue; } pack.resolve(this, matches, id, MAX_RESOLVE_MATCHES); if (MAX_RESOLVE_MATCHES <= matches.size()) { break; } } }

Target:
This seems unnecessary. The caller invokes us once on an empty set, and then again only if matches.size() < MAX_RESOLVE_MATCHES so we shouldn't need this redundant check.
Source:
public boolean matchDestination(final String r) { if (allowMismatchedWildcards && getDestination() == null) { return match(r, getSource()); } return match(r, getDestination()); }

Target:
This would be equally convenient when !allowMismatchedWildcards, but alas it would be an API change. So I think it would be more consistent for the caller to be responsible for handling this. (Or in a followup change to have a method that sets the destination from src if unset, to make this more convenient.)
Source:
public String getExtractedToolbarGroupConfiguration() { String toolbarGroupConfiguration = getToolbarGroupConfiguration().trim(); if( !toolbarGroupConfiguration.startsWith( CKEDITOR_CONFIG_TOOLBAR_GROUPS ) || !toolbarGroupConfiguration.endsWith( ";" ) ) { throw new RuntimeException( "Invalid CKEditor toolbarGroups configuration" ); } int equalSignIndex = toolbarGroupConfiguration.indexOf( '=' ); int lastSemicolonIndex = toolbarGroupConfiguration.lastIndexOf( ';' ); return toolbarGroupConfiguration.substring( equalSignIndex + 1, lastSemicolonIndex ).trim(); }

Target:
This method should not be API as it doesn't exist in SWT Nebula RichTextEditor. The ONLY public method here is toString.
Source:
private boolean isInLayoutingMode(GraphicalEditPart graphicalEditPart) { View notationView = graphicalEditPart.getNotationView(); if (notationView != null) { Diagram diagram = notationView.getDiagram(); if (diagram != null) { EObject element = diagram.getElement(); if (element instanceof DDiagram && ((DDiagram) element).isIsInLayoutingMode()) { return true; } } } return false; }

Target:
return element instanceof DDiagram && ((DDiagram) element).isInLayoutingMpode();
Source:
private boolean isThreadSuspended(IExecutionDMContext ctx) { assert ctx != null; IRunControl runControl = getServicesTracker().getService(IRunControl.class); return runControl.isSuspended(ctx); }

Target:
You should check for null just in case
Source:
protected void createAndDispatchGDBFocusChangedEvent() { fCommandControl.getSession().dispatchEvent(new GDBFocusChangedEvent(fCurrentThreadCtx), fCommandControl.getProperties()); }

Target:
Lets reduce the API and make this one private, It would also be better to assert fCurrentThreadCtx != null
Source:
protected IMIBackend createBackendGDBService(DsfSession session, ILaunchConfiguration lc) { if (compareVersionWith(GDB_7_12_VERSION) >= 0 || compareVersionWith("7.11.50") >= 0 // TODO remove once GDB 7.12 is released ) { return new GDBBackend_7_12(session, lc); } return new GDBBackend(session, lc); }

Target:
Remove the 7.11.50 condition as GDB 7.12 is now available
Source:
private IFrameDMContext createFrameContext(IExecutionDMContext execCtx, String frameNum) { assert execCtx != null && frameNum != null; if (execCtx == null || frameNum == null) { return null; } int intFrameNum = 0; try { intFrameNum = Integer.parseInt(frameNum); } catch (NumberFormatException e){ GdbPlugin.log(e); } return fStackService.createFrameDMContext(execCtx, intFrameNum); }

Target:
I've added a check for null, in case some extender has replaced our MIStack service and does not yet implement IGDBStack
Source:
public void update() { IDebuggerConsole[] consoles = getDebuggerConsoleManager().getConsoles(); setEnabled(consoles.length > 1); }

Target:
In the typical use-case, there will be a single session / console, so this will be disabled. The user might wonder why this button is there. So I wonder if it would be less confusing to enable the widget even if there is a single console? The caption "display selected console" doesn't shed much more light on the situation, since there appears to be nothing to select, in the single session case :)
Source:
public Direction getDirection(ITmfEvent event) { try { IKernelAnalysisEventLayout layout = TRACE_LAYOUTS.get(event.getTrace()); if (layout == null) { return null; } String evname = event.getName(); /* Is the event a tcp socket in or out event */ if (layout.eventsNetworkReceive().contains(evname)) { return Direction.EFFECT; } else if (layout.eventsNetworkSend().contains(evname)) { return Direction.CAUSE; } } catch (ExecutionException e) { } return null; }

Target:
You can do getUnchecked() if you know the load() method does not throw any exception. The ExecutionException is just a wrapper that allows catching potential exceptions that get thrown by load().
Source:
public List<String> getPushOptions() { if (allowPushOptions) { if (enabledCapabilities == null) { throw new RequestNotYetReadException(); } return pushOptions == null ? null : Collections.unmodifiableList(pushOptions); } else { throw new IllegalStateException(); } }

Target:
Can simplify by dealing with the exceptional case first: if (!allowPushOptions) { // Reading push options without a prior setAllowPushOptions(true) // call doesn't make sense. throw new IllegalStateException(); } if (enabledCapabilities == null) { // Push options are not available until receive() has been called. throw new RequestNotYetReadException(); } if (pushOptions == null) { // The client doesn't support push options. Return null to distinguish // this from the case where the client declared support for push // options and sent an empty list of them. return null; } return Collections.unmodifiableList(pushOptions);
Source:
protected boolean isHandledByDirectEditor(final EObject element) { return DirectEditorEditingSupport.getConfiguration(element) != null; }

Target:
null must be the first operande
Source:
private static String computeNewName(String str) { String fileExtension = ""; //$NON-NLS-1$ String fileNameNoExtension = str; Pattern p = Pattern.compile("[0-9]+$"); //$NON-NLS-1$ Matcher m = p.matcher(fileNameNoExtension); if (m.find()) { // String ends with a number: increment it by 1 int newNumber = Integer.parseInt(m.group()) + 1; String numberStr = m.replaceFirst(Integer.toString(newNumber)); return numberStr + fileExtension; } return fileNameNoExtension + "2" + fileExtension; //$NON-NLS-1$ }

Target:
fileExtension doesn't actually seem to be used?
Source:
public AbstractCounterAspect(String fieldName, String label) { Objects.requireNonNull(fieldName); fFieldName = fieldName; fLabel = label; }

Target:
put this on one line and add an exception message
Source:
public Object getParent(Object object, IMergeViewerItemProviderConfiguration configuration) { return ResourceAttachmentChangeMergeViewerItem.class.cast(object).getParent(); }

Target:
Please use the following syntax for casts, as is done everywhere else in the project: return ((ResourceAttachmentChangeMergeViewerItem)object).getParent();
Source:
public Object[] getChildren(Object object, IMergeViewerItemProviderConfiguration configuration) { return ResourceAttachmentChangeMergeViewerItem.class.cast(object).getChildren( configuration.getDifferenceGroupProvider(), configuration.getDifferenceFilterPredicate()); }

Target:
Done
Source:
public boolean hasChildren(Object object, IMergeViewerItemProviderConfiguration configuration) { return ResourceAttachmentChangeMergeViewerItem.class.cast(object).hasChildren( configuration.getDifferenceGroupProvider(), configuration.getDifferenceFilterPredicate()); }

Target:
Done
Source:
protected AbstractMergeViewer createMergeViewer(final Composite parent, final MergeViewerSide side) { final TreeMergeViewer mergeTreeViewer = new TreeMergeViewer(parent, side, this, getCompareConfiguration()); final IContentProvider contentProvider = createMergeViewerContentProvider(); mergeTreeViewer.setContentProvider(contentProvider); final IBaseLabelProvider labelProvider = new PapyrusTreeContentMergeViewerItemLabelProvider( getResourceBundle(), getAdapterFactory(), side); mergeTreeViewer.setLabelProvider(labelProvider); hookListeners(mergeTreeViewer); return mergeTreeViewer; }

Target:
We should think about if we also want to enable customizing the LabelProvider with this PS.
Source:
public IDEWorkflow(@Named(CTX_SERVERS) List<IServerDescriptor> endpoints, ILogEventsQueue queue, ISystemSettings settings, IEventBroker broker, MylynNotificationsSupport notificationSupport, UploadReportsScheduler uploadService, IEclipseContext context, @Named(IDEWorkflow.CTX_REPORT_PROCESSORS) List<IProcessorDescriptor> descriptors) { this.servers = endpoints; this.queue = queue; this.system = settings; this.broker = broker; this.notificationSupport = notificationSupport; this.uploadService = uploadService; this.context = context; this.descriptors = descriptors; }

Target:
please make fields final, if possible.
Source:
public <T> T getSoleAttributeValue(IAttributeType attributeType, DeletionFlag flag, T defaultValue) { T value = defaultValue; Attribute<T> attribute = null; try { attribute = getSoleAttribute(attributeType, flag); } catch (AttributeDoesNotExist ex) { // do nothing } if (attribute != null) { value = attribute.getValue(); } return value; }

Target:
move this to 244, then can get rid of extra if check
Source:
public void testIsDeleteD() { when(data.getModType()).thenReturn(ModificationType.DELETED); assertTrue(relation.isHardDeleted()); when(data.getModType()).thenReturn(ModificationType.ARTIFACT_DELETED); assertTrue(relation.isHardDeleted()); when(data.getModType()).thenReturn(ModificationType.MODIFIED); assertFalse(relation.isHardDeleted()); }

Target:
Is ARTIFACT_DELETED hard deleted? I thought from the modificationType file above, isDeleted was true when DELETED | ARTIFACT_DELETED, but isHardDeleted was when DELETED only.
Source:
public boolean isPending() { return fScenarioInfo.getStatus().equals(ScenarioStatusType.PENDING); }

Target:
Since these are enums, you can use == instead
Source:
private void joinConflicts(UMLRTDiff change1, UMLRTDiff change2, Comparison comparison) { final Conflict change2Conflict = change2.getConflict(); change1.getConflict().getDifferences().addAll(change2Conflict.getDifferences()); change1.getConflict().getDifferences().removeAll(change1.getRefinedBy()); change1.getConflict().getDifferences().removeAll(change2.getRefinedBy()); comparison.getConflicts().remove(change2Conflict); }

Target:
Why is this necessary? Shouldn't we "join" the refines as well? If removing refines is desired than it should be included in the test as well.
Source:
protected void updateURLInformation() { String url = serverUrlCombo.getText(); apiKey.setToolTipText( NLS.bind(Messages.BugzillaRestRepositorySettingsPage_Please_create_or_copy_the_API_Key_from, url)); apiKeyLabel.setToolTipText( NLS.bind(Messages.BugzillaRestRepositorySettingsPage_Please_create_or_copy_the_API_Key_from, url)); apikeyPreferenceLink.setText(url + userprefs); apikeyPreferenceLink .setToolTipText(NLS.bind(Messages.BugzillaRestRepositorySettingsPage_View_your_apikey_settings, url)); apikeyPreferenceLink.setEnabled(TasksUiInternal.isValidUrl(url + userprefs)); }

Target:
url = serverUrl + userprefs, shouldn't all these use the full URL to the place with the API key?
Source:
protected void doTearDown() throws Exception { super.doTearDown(); if (project.exists()) { project.delete(true, null); } }

Target:
super.tearDown should be executed after, not before this test code
Source:
private static IMarker[] getMarkersOfView(String viewId, IMarker[] markers) throws CoreException { if (null == viewId) // all markers should be shown return markers; ArrayList<IMarker> markersOfView = new ArrayList<>(); for (IMarker marker : markers) { if (viewId.equals(getViewId(marker))) markersOfView.add(marker); } return markersOfView.toArray(new IMarker[markersOfView.size()]); }

Target:
please add if(marker != null &&
Source:
public Object getImage(final Object object) { EObject element = EMFHelper.getEObject(object); if (element == null) { return null; } // Delegate to UML2 Edit providers to get localized and inferred names where applicable IItemLabelProvider provider = getDelegate(element); return (provider == null) ? null : provider.getImage(element); }

Target:
PLease invert operande
Source:
public static void selectFolder(SWTBot bot, boolean check, String... treePath) { SWTBotTree tree = bot.tree(); bot.waitUntil(Conditions.widgetIsEnabled(tree)); SWTBotTreeItem folderNode = SWTBotUtils.getTreeItem(bot, tree, treePath); if (check) { folderNode.check(); } else { folderNode.select(); } }

Target:
This checks the element but does not select it (so the file table doesn't show that folder's files). That doesn't seem like something that should be possible with the UI, I wonder if this should not be fixed in SWTBotTreeItem.setChecked()?
Source:
public IPath buildPath(IPath sourcePath, IPath targetPath, int count) { sourcePath = sourcePath.removeFirstSegments(count); return targetPath.append(sourcePath); }

Target:
make static
Source:
public void dragStart(DragSourceEvent event) { final IStructuredSelection selection = (IStructuredSelection) fTreeViewer.getSelection(); LocalSelectionTransfer.getTransfer().setSelection(selection); }

Target:
setSelection takes an ISelection, no need to cast what you get from the viewer. you also do not need a local variable
Source:
protected VariablesDropSupport(TreeViewer viewer, TestSuiteModel model) { super(viewer); fTreeViewer = viewer; fModel = model; }

Target:
if super() is already storing the viewer, do you need to store your own copy?
Source:
public void dragStart(DragSourceEvent event) { event.doit = !((event.data instanceof IPath) || (event.data instanceof Variable)); final IStructuredSelection selection = (IStructuredSelection) fTreeViewer.getSelection(); LocalSelectionTransfer.getTransfer().setSelection(selection); }

Target:
are there cases where this evaluates to false?
Source:
public void run() { try { fLaunch.terminate(); setImageDescriptor(GdbUIPlugin.getImageDescriptor(IConsoleImagesConst.IMG_CONSOLE_TERMINATE_DISABLED_COLOR)); } catch (DebugException e) { GdbUIPlugin.log(new Status(IStatus.ERROR, GdbUIPlugin.PLUGIN_ID, "Unable to terminate launch", e)); //$NON-NLS-1$ } }

Target:
We shoudn't change the active image but instead disable the action. Notice that after the terminate button is pressed, the icon currently becomes 'disabled' but one can still press the button. Calling setEnabled(false) will actually disable the action.
Source:
public void createPartControl(Composite parent) { super.createPartControl(parent); viewer = super.getViewer(); createFilterAction(); initToolBar(); }

Target:
I don't think that is necessary.
Source:
public static boolean isSystemProtocol(Collaboration element) { return (UMLUtil.getStereotypeApplication(element, SystemProtocol.class) != null) ? true : false; }

Target:
You don't need the ternary operator: the parenthesized boolean expression is already the result. Also, probably it should also be checked that the collaboration is a <<Protocol>> to start with.
Source:
public static String unlink(LinkType sourceLinkType, Artifact source, String content) throws OseeCoreException { LinkType linkType = checkLinkType(sourceLinkType); String modified = content; HashCollection<String, MatchRange> matchMap = parseOseeWordMLLinks(content); if (!matchMap.isEmpty()) { modified = modifiedContent(linkType, source, content, matchMap, true, null, null); } return modified; }

Target:
provide a method that does not require the caller to pass null for the presentationType
Source:
public void createControl(Composite parent, FormToolkit toolkit) { super.createControl(parent, toolkit, (getLayoutHint().rowSpan == RowSpan.MULTIPLE ? SWT.WRAP : SWT.NONE)); if (!isReadOnly() && isMultiSelect) { getText().setToolTipText("Separate multiple values with a comma"); //$NON-NLS-1$ } }

Target:
Need to check the hint is not null.
Source:
public String toString() { if (getName() == null) { return getPersonId(); } else { if (getPersonId() == null) { return ""; //$NON-NLS-1$ } else { if (getName().equals(getPersonId())) { return getName(); } else { return getName() + " <" + getPersonId() + ">"; //$NON-NLS-1$ //$NON-NLS-2$ } } } }

Target:
Why not return name in this case?
Source:
public String toString() { if (getName() == null) { return getPersonId(); } else { if (getPersonId() == null) { return getName(); } else { if (getName().equals(getPersonId())) { return getName(); } else { return getName() + " <" + getPersonId() + ">"; //$NON-NLS-1$ //$NON-NLS-2$ } } } }

Target:
Please avoid unnecessarily nesting if blocks. This method could be written as: if (getName() == null) { return getPersonId(); } else if (getPersonId() == null) { return getName(); } else if (getName().equals(getPersonId())) { return getName(); } else { return getName() + " <" + getPersonId() + ">"; //$NON-NLS-1$ //$NON-NLS-2$ }
Source:
public void beginTask(String name, int totalWork) { fTaskName = name; fSubTaskName = ""; //$NON-NLS-1$ updateLabel(); if ((totalWork == IProgressMonitor.UNKNOWN || totalWork == 0) && !fProgressIndicator.isDisposed()) { fProgressIndicator.beginAnimatedTask(); } else { fProgressIndicator.beginTask(totalWork); } if (fToolBar != null && !fToolBar.isDisposed()) { fToolBar.setVisible(true); fToolBar.setFocus(); } }

Target:
Why should we access thiss if the indicator is disposed? This will fail same way as the other if branch?
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((this.logEntry == null) ? 0 : this.logEntry.hashCode()); return result; }

Target:
Why not simply Objects.hashCode(logEntry)?
Source:
public GdbAutoTerminateAction() { super(ConsoleMessages.ConsoleAutoTerminateAction_name, IAction.AS_CHECK_BOX); setText(ConsoleMessages.ConsoleAutoTerminateAction_name); setToolTipText(ConsoleMessages.ConsoleAutoTerminateAction_description); // initialize state setChecked(readState()); }

Target:
Done
Source:
public void run() { // Toggle and update the new state boolean terminate = !readState(); setChecked(terminate); // Update preference store IEclipsePreferences preferences = InstanceScope.INSTANCE.getNode(GdbPlugin.PLUGIN_ID); if (preferences != null) { preferences.putBoolean(IGdbDebugPreferenceConstants.PREF_AUTO_TERMINATE_GDB, terminate); try { preferences.flush(); } catch (BackingStoreException e) { } } }

Target:
Done
Source:
private boolean canPerformInverseNavigation(EStructuralFeature feature){ return allowInverseNavigation && ( // Feature has opposite (this only possible for references) hasEOpposite(feature) || ( // Or // indexing is enabled, and the feature can be indexed (it's not a non-well-behaving derived feature) // and it's a reference TODO this constraint might not be needed. It shall be possible to find elements by an attribute value using the base indexer useIndex && modelComprehension.representable(feature) && (feature instanceof EReference) )); }

Target:
what is the point of disallowing cheap (eOpposite-based) inverse navigation? How about checking this switch only in case we have to rely on the index to navigate backards
Source:
public static void closeSecondaryShells(SWTWorkbenchBot bot) { SWTBotShell[] shells = bot.shells(); SWTBotShell mainShell = getMainShell(shells); if (mainShell == null) { return; } for (SWTBotShell shell : shells) { boolean visible = shell.isVisible(); if (shell != mainShell && visible) { shell.close(); } } }

Target:
Could a test spawn a separate shell that is actually visible (a new window?). Why not just close all the shells that are not the mainShell?
Source:
public AssertChecker(Dim[] dimensions) { fDimensions = new HashSet<Dim>(); fDimensions.addAll(Arrays.asList(dimensions)); }

Target:
This creates a warning.
Source:
private void unregisterAndCloseRepository(final Key location, Repository db) { synchronized (lockFor(location)) { if (isExpired(db)) { Repository oldDb = unregisterRepository(location); if (oldDb != null) { oldDb.doClose(); } } } }

Target:
this should be removed
Source:
protected IStatus run(IProgressMonitor monitor) { try { runnable.run(monitor); } catch (CoreException e) { IStatus st = e.getStatus(); return new Status(st.getSeverity(), st.getPlugin(), st.getCode(), st.getMessage(), e); } finally { monitor.done(); } return Status.OK_STATUS; }

Target:
The 'finally' block is not needed since calling monitor.done() is not required.
Source:
public void startup(IProgressMonitor monitor) { SubMonitor subMonitor = SubMonitor.convert(monitor, 1); Preferences preferences = ResourcesPlugin.getPlugin().getPluginPreferences(); preferences.addPropertyChangeListener(this); refreshJob = new RefreshJob(); monitors = new MonitorManager(workspace, this); boolean autoRefresh = preferences.getBoolean(ResourcesPlugin.PREF_AUTO_REFRESH); if (autoRefresh) manageAutoRefresh(autoRefresh, subMonitor.split(1)); subMonitor.setWorkRemaining(0); }

Target:
This method doesn't advance the monitor.
Source:
public int hashCode() { if (isEmpty()) { return Objects.hash(comparer); } int r; if (comparer != null) { r = 31 + comparer.hashCode(); for (Object e : elements) { r = 31 * r + (e == null ? 0 : comparer.hashCode(e)); } } else { r = Arrays.hashCode(elements); } return r; }

Target:
if isEmpty() and comparer==null, this will return the hash code of a null Object. - Is this the intended behavior? - Perhaps we could use getClass().hashCode() instead?
Source:
public int hashCode() { if (elements == null) { return Objects.hash(comparer); } int r = 1; if (comparer != null) { r = 31 + comparer.hashCode(); for (Object e : elements) { r = 31 * r + (e == null ? 0 : comparer.hashCode(e)); } } else { Arrays.hashCode(elements); } return r; }

Target:
assignment has no effect
Source:
protected Control createDialogArea(Composite parent) { Composite parent2 = (Composite) super.createDialogArea(parent); Composite composite = new Composite(parent2, SWT.NONE); composite.setLayout(new GridLayout(1, false)); GridDataFactory.fillDefaults().align(SWT.FILL, SWT.BEGINNING).applyTo(composite); createCenterArea(composite); composite.pack(); return parent; }

Target:
this should return parent2
Source:
protected ResourceBundle getPluginResourceBundle() { Bundle bundle = FrameworkUtil.getBundle(PDETemplateSection.class); return Platform.getResourceBundle(bundle); }

Target:
I think the result of this call will not change at any time. So we could improve the code by keeping the Bundle in an instance variable so it is not needed to request it everytime.
Source:
public void testCanContribute() { // if the test fails, a section is probably renamed in the configuration section assertTrue(processor.canContribute(mock(IStatus.class))); }

Target:
why not keep using hamcrest matchers?
Source:
private void recordSaveables(Saveable[] sourceSaveables) { if (knownSaveables == null) knownSaveables = new HashSet<Saveable>(); for (int i = 0; i < sourceSaveables.length; i++) { Saveable saveable = sourceSaveables[i]; knownSaveables.add(saveable); } }

Target:
Use new HashSet<>
Source:
public void start(BundleContext context) throws Exception { super.start(context); Hashtable<String, String> properties = new Hashtable<String, String>(2); properties.put(DebugOptions.LISTENER_SYMBOLICNAME, PLUGIN_ID); debugRegistration = context.registerService(DebugOptionsListener.class, Policy.DEBUG_OPTIONS_LISTENER, properties); ComparePlugin.getDefault().setCappingDisabled( getPreferenceStore().getBoolean( ComparePreferencePage.CAPPING_DISABLED)); }

Target:
Use new Hashtable<>
Source:
private static Map<IFile, Long> createModificationStampMap(List<IResource> files) { Map<IFile, Long> map= new HashMap<IFile, Long>(); for (Iterator<IResource> iter= files.iterator(); iter.hasNext(); ) { IFile file= (IFile)iter.next(); map.put(file, new Long(file.getModificationStamp())); } return map; }

Target:
Use modern for loop.
Source:
IgnoreCondition create() { checkConditionType(); try { return createCondition(); } catch (RuntimeException re) { throw Throwables.propagate(re); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
This can just be catch Exception.
Source:
protected static void setOverrideFileName(String... path) { String filePaths = Joiner.on(LIST_SEPARATOR).skipNulls().join(path); fOverridePath = filePaths == null ? null : filePaths.isEmpty() ? null : filePaths; fOverride = true; }

Target:
Should just store the String[] and for open() and getFileName() you return the first item in the array.
Source:
public void addPageTerminalControl(ITerminalControl terminalControl) { fTerminalPageControls.add(terminalControl); // write the currently available buffered history to this new terminal if (fHistoryBuffer.size() > 0) { new WriteHistoryJob(terminalControl).schedule(); } }

Target:
I wonder if we shouldn't finish the writing of the history before we add the new terminalControl to fTerminalPageControls? Couldn't we get new output written to the page by OutputReadJob before WriteHistoryJob is finished?
Source:
protected Point getSize() { if (size == null) { size = new Point(getBaseImageData().width, getBaseImageData().height); } return size; }

Target:
This triggers now baseImage.getImageData() if size was not specified for Image based constructors but would lead to NPE before. For descriptor-based data this creates a second ImageData object (parent has one).
Source:
public String generateModelElementId(EObject eObject, ESObjectContainer<ModelElementId> collection) { if (EGenericType.class.isInstance(eObject)) { final EGenericType eGeneric = EGenericType.class.cast(eObject); if (eGeneric.eContainer() != null && eGeneric.eContainer() != this && collection.contains(eGeneric.eContainer())) { final ModelElementId containerId = collection.getModelElementId(eGeneric.eContainer()); return containerId.getId() + ID_SUFFIX; } } return null; }

Target:
This is wrong, probably CP error :),this should check against collection NOT this.
Source:
private void clearAll() { for (int stage = 0; stage < 2; stage++) { for (Iterator<Map.Entry<Key, Reference<Repository>>> i = cacheMap .entrySet().iterator(); i.hasNext();) { final Map.Entry<Key, Reference<Repository>> e = i.next(); unregisterAndCloseRepository(e.getKey(), null); } } }

Target:
Could you explain a bit more detailled what's the purpose of this loop? Maybe I miss the bigger context: I haven't got the whole idea of how the cache intends to care about Repository refcount. Is it explained somewhere?
Source:
public boolean canHandleSelection(Object selection) { if (selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; Object element = structuredSelection.getFirstElement(); if (element instanceof SpecHierarchyImpl) { return true; } } return false; }

Target:
Are we sure that selection is not null? Otherwise, a null check before we call getFirstElement() is in order.
Source:
public Set<ModelElementId> getAllInvolvedModelElements(AbstractChangePackage changePackage) { final Set<ModelElementId> result = new LinkedHashSet<ModelElementId>(); final ESCloseableIterable<AbstractOperation> operations = changePackage.operations(); for (final AbstractOperation op : operations.iterable()) { result.addAll(op.getAllInvolvedModelElements()); } return result; }

Target:
must be closed?
Source:
public void testNoSetting() throws IOException, InterruptedException { Process start = processBuilder.start(); start.waitFor(); assertEquals( "http.proxyHost: null, http.proxyPort: null, https.proxyHost: null, https.proxyPort: null", getOutput(start)); }

Target:
Isn't it enough to declare Exception here? An exception will fail the test, regardless of the specific type.
Source:
protected ContentSecurityPolicy addOrAppend(String key, String value) { if (m_directives.containsKey(key)) { String existingSource = m_directives.get(key); // Only change directive, if the former value was not-null OR the new value is not null. // If existingSource and new value are both null, do not change directive, since StringUtility.join creates an empty string for two null values // Further check for duplicates and do not add new value, if value already is part of the existing source if ((existingSource != null || value != null) && !StringUtility.containsString(existingSource, value)) { m_directives.put(key, StringUtility.join(SOURCE_SEPARATOR, existingSource, value)); } } else { m_directives.put(key, value); } return this; }

Target:
Could we write that simpler? if (value == null) { return; } if (m_directives.containKey(key)) { ... if (!StringUtility.containsString(existingSource, value)) { ...
Source:
public String getModelPluginId(EPackage ePackage, ResourceSet set) { if (getProvidedMetamodels().contains(ePackage.getNsURI())) { GenPackage genPackage = getGenmodelRegistry().findGenPackage(ePackage.getNsURI(), set); getModelPluginId(genPackage); } return null; }

Target:
Should this method always return null? Inside the 'if' there is no return statement...