auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected boolean updateSelection(IStructuredSelection selection) { BuildState buildState = BuildState.STOPPED; if (selection.getFirstElement() instanceof IBuildPlan) { IBuildPlan buildPlan = (IBuildPlan) selection.getFirstElement(); return buildPlan.getState() == BuildState.RUNNING; } return false; }

Target:
this is unused.
Source:
public void testCrash() throws Exception { IRunnableWithProgress operation = new CrashingRunnable(); try{ PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(true, false, operation); fail("Should have an invocation target exception"); } catch (InvocationTargetException e){ //We should get this } boolean interrupted = Thread.interrupted(); if (interrupted) { fail("Thread was interrupted at end of test"); } }

Target:
Why not inline this variable?
Source:
private StoredConfig loadUserConfig() throws IOException { FileBasedConfig c = SystemReader.getInstance().openUserConfig(null, FS.DETECTED); try { c.load(); } catch (ConfigInvalidException e1) { IOException e2 = new IOException(MessageFormat .format(LfsText.get().userConfigInvalid, c.getFile() .getAbsolutePath(), e1)); e2.initCause(e1); throw e2; } return c; }

Target:
This should not be necessary. IOException can take the cause as an argument. I.e. this entire block can be replaced with a single "throw new IOException(...) rather than creating the instance, setting the cause on it, and then throwing it. See for example the change I did here: https://git.eclipse.org/r/#/c/114363/4/org.eclipse.jgit/src/org/eclipse/jgit/gitrepo/ManifestParser.java
Source:
public boolean isDirty() { if (getTrace() == null) { return false; } TmfTraceContext ctx = TmfTraceManager.getInstance().getCurrentTraceContext(); long startTime = ctx.getWindowRange().getStartTime().toNanos(); long endTime = ctx.getWindowRange().getEndTime().toNanos(); // If the time graph control hasn't updated all the way to the end of // the window range then it's dirty. A refresh should happen later. if (getWindowStartTime() != startTime || getWindowEndTime() != endTime) { return true; } return false; }

Target:
how about a single return instead of an if?
Source:
private static Object iterateCompare(long startTime, long endTime, ISegmentStore<@NonNull ISegment> store, @NonNull Comparator<@NonNull ISegment> comparator) { Object shutupCompilerWarnings = null; for (ISegment elem : store.getIntersectingElements((endTime - startTime) / 2, comparator)) { shutupCompilerWarnings = elem; } return shutupCompilerWarnings; }

Target:
I LOVE THIS
Source:
public IBinding getPromiscuousBinding() { return promiscuousBinding; }

Target:
Make final.
Source:
private IBinding resolveBindingPromiscuous() { // If we haven't already resolved the non-promiscuous binding, do so now. if (fBinding == null) { try { CPPSemantics.disablePromiscuousBindingResolution(); resolveBindingNormal(); } finally { CPPSemantics.enablePromiscuousBindingResolution(); } } // If the non-promiscuous binding is not a ProblemBinding, the promiscuous // binding will be the same, so just return it. if (!(fBinding instanceof ProblemBinding)) { return fBinding; } // Otherwise, the non-promiscuous binding is a ProblemBinding. ProblemBinding problem = (ProblemBinding) fBinding; if (problem.getPromiscuousBinding() == null) { // Resolve the promiscuous binding, and store it in the ProblemBinding. IBinding promiscuous = resolveBindingNormal(); problem.setPromiscuousBinding(promiscuous); // Restore the cached ProblemBinding (which resolveBindingNormal() overwrote). fBinding = problem; } return problem.getPromiscuousBinding(); }

Target:
Better to write: IBinding promiscuous = problem.getPromiscuousBinding(); if (promiscuous == null) { ... } return promiscuous;
Source:
public void redraw() { if (fRelayoutRequired) { layout(true); return; } if (fCachedTextViewer != null && fCachedTextViewer.getTextWidget() != null && fCanvas != null && !fCanvas.isDisposed()) { if (VerticalRuler.AVOID_NEW_GC) { fCanvas.redraw(); fCanvas.update(); } else { GC gc= new GC(fCanvas); doubleBufferPaint(gc); gc.dispose(); } } }

Target:
can we please wrap this long condition, so it can be readable?
Source:
public EList<IBuildPlan> getPlanAndAllChildren() { return new BasicEList<IBuildPlan>( Stream.concat(Stream.of(this), getChildren().stream().flatMap(IBuildPlan::flattened)) .collect(Collectors.toList())); }

Target:
I don't think we need the EList.
Source:
private static void populate(int size, int[] fuzz, ISegmentStore<@NonNull ISegment> store, long count, INewSegment segmentCreator) { for (int i = 0; i < count; i++) { long start = i + fuzz[i % size]; store.add(segmentCreator.createSegment(start, start + 10, i)); } }

Target:
I had this line create overflows and Segments with negative start times (before the tree start)
Source:
public void setTimeGraphScale(TimeGraphScale timeGraphScale) { fTimeGraphScale = timeGraphScale; setHeaderHeight(timeGraphScale.getBounds().height); }

Target:
This shouldn't be necessary anymore.
Source:
public void paintControl(PaintEvent event) { if (fTextWidget != null) { try { handleDrawRequest(event.gc); } catch (IllegalStateException e) { // Do not allow the exception to escape this PaintListener method into the SWT code. // See http://bugs.eclipse.org/498907 String PLUGIN_ID= "org.eclipse.jface.text"; //$NON-NLS-1$ ILog log= Platform.getLog(Platform.getBundle(PLUGIN_ID)); log.log(new Status(IStatus.ERROR, PLUGIN_ID, JFaceTextMessages.getString("MatchingCharacterPainter.unexpected_error"), e)); //$NON-NLS-1$ return; } } }

Target:
Log messages are generally English strings and do not come from translation bundles. Messages written to the log are intended to be read by the Eclipse developers, not the end user.
Source:
public static int nvl(Integer value, int valueWhenNull) { if (value != null) { return value.intValue(); } else { return valueWhenNull; } }

Target:
Unnecessary "else" blocks, just return
Source:
public @NonNull ISegment createSegment(long start, long end) { return new BasicSegment(start, end); }

Target:
Should this be protected
Source:
private static void populate(int size, int[] fuzz, ISegmentStore<@NonNull ISegment> store, long low, long high) { for (int i = (int) low; i < high; i++) { long start = (long) i + fuzz[i % size]; store.add(new BasicSegment(start, start + 10)); } }

Target:
especially because of this. long->int->long
Source:
private static int[] fuzzyArray(int size){ int[] fuzz = new int[DEFAULT_SAMPLE]; Random rng = new Random(10); for (int i = 0; i < DEFAULT_SAMPLE; i++) { fuzz[i] = rng.nextInt(); } return fuzz; }

Target:
rng.nextInt(1000);
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { rebuildJob.cancel(); rebuildJob.schedule(); return null; }

Target:
ExecutionException is unnecessary but ok.
Source:
protected synchronized void setPinned(boolean pinned) { if (!pinned) { if (fSavedRangeSyncSignal != null) { windowRangeUpdated(fSavedRangeSyncSignal); fSavedRangeSyncSignal = null; } if (fSavedTimeSyncSignal != null) { selectionRangeUpdated(fSavedTimeSyncSignal); fSavedTimeSyncSignal = null; } } }

Target:
I would propose to have a common pin implementation to the base class AbstractTimeGraphView. Also note, the existing implementation in this class only inhibits changes coming in from external, but doesn't prevent the pinned Call Stack view from broadcasting a new window range.
Source:
private boolean requiresIncomingDecoration(AbstractAttributeEditor editor, TaskDataModel model, TaskAttribute attribute) { return editor.isDecorationEnabled() && model.hasBeenRead() && model.hasIncomingChanges(attribute) && isCompatibleKind(attribute.getMetaData().getKind()) ? true : false; }

Target:
Remove "? true : false"
Source:
protected int getMaximumTotalSize() { // Define max size in properties file. int maxSize = Integer.parseInt(DiagramUIPlugin.INSTANCE.getString("_Pref_DiagramExportSizeMax")); //$NON-NLS-1$ return maxSize; }

Target:
return Integer.parseInt(DiagramUIPlugin.INSTANCE.getString("_Pref_DiagramExportSizeMax")); //$NON-NLS-1$
Source:
public org.eclipse.swt.graphics.Rectangle calculateImageRectangle(List editparts) { org.eclipse.swt.graphics.Rectangle sourceRect = super.calculateImageRectangle(editparts); return new org.eclipse.swt.graphics.Rectangle(sourceRect.x, sourceRect.y, scaleAsInt(sourceRect.width), scaleAsInt(sourceRect.height)); }

Target:
No sure but in getDiagramPartInfo the x and y coordinates are scaled but not here. Is it expected?
Source:
public String toString() { final ToStringBuilder builder = new ToStringBuilder(this); builder .attr("name", m_name) .attr("type", m_type) .attr("resolveMethod", m_resolveMethod) .attr("properties", m_properties); return builder.toString(); }

Target:
Change to: return new ToStringBuilder(this) .attr("name", m_name) .attr("type", m_type) .attr("resolveMethod", m_resolveMethod) .attr("properties", m_properties) .toString();
Source:
public void test_addKeyListenerKeyPressedAdapterLorg_eclipse_swt_events_KeyListener() { KeyListener listener = KeyListener.keyPressedAdapter(event -> { eventOccurred = true; }); control.addKeyListener(listener); eventOccurred = false; control.notifyListeners(SWT.KeyDown, new Event()); assertTrue(eventOccurred); control.removeKeyListener(listener); eventOccurred = false; control.notifyListeners(SWT.KeyDown, new Event()); assertFalse(eventOccurred); }

Target:
Why not the shorter version? KeyListener listener = KeyListener.keyPressedAdapter(event -> eventOccurred = true);
Source:
public boolean isMirroringEnabled() { return fMirroringEnabled; }

Target:
final
Source:
public void setMirroringEnabled(boolean value) { fMirroringEnabled = value; }

Target:
final
Source:
protected void fireStoppedEvent(final MIOutput output, final IExecutionDMContext ctx) { final DsfSession session = DsfSession.getSession(ctx.getSessionId()); session.getExecutor().execute(new DsfRunnable() { @Override public void run() { int token = output.getMIResultRecord().getToken(); session.dispatchEvent(MIErrorEvent.parse(ctx, token, output.getMIResultRecord().getMIResults(), output.getMIOOBRecords()), null); } }); }

Target:
No need to call session.dispatchEvent() on the executor since it is @ThreadSafe. It will make its own call to the executor.
Source:
public UniquenessEnforcerNode(ReteContainer reteContainer, int tupleWidth) { super(reteContainer); this.parents = new ArrayList<Supplier>(); this.memory = new TupleMemory(); this.rederivableMemory = new TupleMemory(); this.tupleWidth = tupleWidth; reteContainer.registerClearable(this.memory); this.nullMask = TupleMask.linear(0, tupleWidth); this.identityMask = TupleMask.identity(tupleWidth); this.deleteRederive = true; }

Target:
rederivableMemory should be registered as clearable as well!
Source:
protected IDialogSettings getDialogBoundsSettings() { IDialogSettings settings = DebugUIPlugin.getDefault().getDialogSettings(); IDialogSettings section = settings.getSection(SETTINGS_ID); if (section == null) { section = settings.addNewSection(SETTINGS_ID); } return section; }

Target:
Do we really want this protected?
Source:
void messageConsumptionSingleThreaded() { while (!activeMailboxes.isEmpty() || getFirstRederivable() != null) { RederivableNode node = getFirstRederivable(); while (node != null) { node.rederiveOne(); node = getFirstRederivable(); } if (!activeMailboxes.isEmpty()) { Mailbox mailbox = activeMailboxes.iterator().next(); activeMailboxes.remove(mailbox); mailbox.deliverMessages(); } } }

Target:
why are the two steps reversed?
Source:
public RangeCondition<E> subCondition(E from, E to) { if (from.compareTo(to) > 0) { throw new IllegalArgumentException(from.toString() + " is greater than " + to.toString()); //$NON-NLS-1$ } return new ContinuousRangeCondition<>(max(fMin, from), min(fMax, to)); }

Target:
while I think it makes sense to check this if we are calling it E from, E to, wouldn't the constructor be a better place to enforce this? In the 2D query patch, Genevieve suggested not enforcing it in the constructor and using min/max instead.
Source:
public boolean close() { if (fetchResultImage != null) fetchResultImage.dispose(); return super.close(); }

Target:
Missing braces.
Source:
private void addViewerToSelectionProvider() { IWorkbenchPart part = getCompareConfiguration().getContainer().getWorkbenchPart(); ISelectionProvider provider = part.getSite().getSelectionProvider(); if (provider instanceof CompareEditorSelectionProvider) { // Replace existing selection provider with our own to track non-text selection EMFCompareEditorSelectionProviderWrapper compareProvider = new EMFCompareEditorSelectionProviderWrapper( (CompareEditorSelectionProvider)provider); part.getSite().setSelectionProvider(compareProvider); compareProvider.addViewers(Arrays.asList((Viewer)getViewer()), getViewer()); } }

Target:
Please declare method addViewers(List<? extends Viewer>...) and remove the cast to (Viewer) here.
Source:
public boolean provides(IDiagramElementEditPart editPart) { boolean provides = false; if (!(editPart instanceof IDiagramNameEditPart)) { provides = true; } return provides; }

Target:
This is not the same logic as org.eclipse.sirius.diagram.ui.tools.api.decoration.AbstractSiriusDecorationDescriptorProvider.shouldBeDecorated(EditPart). Is it expected?
Source:
public void setBranchName(String branchName) { this.branchName = branchName; if (nameText != null) nameText.setText(branchName); }

Target:
Missing braces.
Source:
public void setNewBranchName(String newBranchName) { this.newBranchName = newBranchName; if (myPage != null) myPage.setBranchName(newBranchName); }

Target:
Missing braces.
Source:
public static boolean isConnectedInside(Port port) { UMLRTPort rt = (port == null) ? null : UMLRTPort.getInstance(port); return (rt != null) && rt.isConnectedInside(); }

Target:
Could we consider here that a null Port is a non valid RTPort? This would avoid null tests (that are already performed in the getFacade() operation).
Source:
public String toString() { return new String(this.workspacePath) + "|" + new String(this.fieldDescriptor); //$NON-NLS-1$ }

Target:
This is an anti-pattern. Use a StringBuilder instead. Why not comma instead of |?
Source:
public final String toStringWithId() { return String.format("[%s][%s]", getId(), getName()); }

Target:
other methods like this put name first, then id. switch for consistency
Source:
public static String normalizeBranchName(String name, boolean trim) { if (trim) { name = name.trim(); } return name.replaceAll("\\s+([_:-])\\s+", "$1") //$NON-NLS-1$//$NON-NLS-2$ .replaceAll(":", "-") //$NON-NLS-1$//$NON-NLS-2$ .replaceAll("\\s+", "_") //$NON-NLS-1$//$NON-NLS-2$ .replaceAll("_{2,}", "_") //$NON-NLS-1$//$NON-NLS-2$ .replaceAll("^_", "") //$NON-NLS-1$//$NON-NLS-2$ .replaceAll("[^\\w-]", ""); //$NON-NLS-1$ //$NON-NLS-2$ }

Target:
I know it's done in plenty of other places in the code base, but I would prefer not to use parameter assignment.
Source:
public void removePage(int pageIndex) { if (0 > pageIndex || pageIndex >= getChildren().size()) { getChildren().remove(pageIndex); } }

Target:
Recheck the condition, it should be 0 <= pageIndex && pageIndex < getChildren().size()
Source:
protected void processDescriptionPropertiesRecursively(SIRIUS processedDescription, SIRIUS originalDescription, TransformationCache cache) { SIRIUS currentDescription = originalDescription; while (currentDescription != null) { for (EStructuralFeature feature : currentDescription.eClass().getEAllStructuralFeatures()) { this.processDescriptionFeature(feature, processedDescription, currentDescription, cache); } currentDescription = getParentOf(currentDescription); } }

Target:
java8-isation [forEach]
Source:
protected void updateProtocols() { protocols = new UniqueEList<>(); if (trigger != null) { for (Port port : trigger.getPorts()) { UMLRTPort facade = UMLRTPort.getInstance(port); UMLRTProtocol protocol = facade.getType(); if (protocol != null) { protocols.add(protocol); } } } }

Target:
This can return null if the port is not a valid UML-RT port (in particular, if it is missing its RTPort stereotype application for some reason).
Source:
public void run(IAction action) { try { PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView( RepositoryUi.ID_VIEW_REPOSITORIES); } catch (PartInitException e) { StatusHandler .log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Can not show Team Repository View", e)); //$NON-NLS-1$ e.printStackTrace(); } }

Target:
We should never printStackTrace. The log will have the stack trace.
Source:
static int getRefreshIndexInterval() { return 1000 * getDefault().getPreferenceStore() .getInt(UIPreferences.REFESH_INDEX_INTERVAL); }

Target:
private
Source:
private static IStatistics<@NonNull BasicSegment> getDescriptiveStatistics(ISeries series) { double[] ySeries = series.getYSeries(); assertNotNull(ySeries); IStatistics<@NonNull BasicSegment> stats = new Statistics<>(s -> s.getLength()); for (double item : ySeries) { stats.update(new BasicSegment(0, (long) (item - 1.0))); } return stats; }

Target:
Why not IStatistics<Long> ?
Source:
public Collection<EObject> getInverseReferences(final String featureName) { Preconditions.checkNotNull(featureName); return getInverseReferences(new Predicate<EStructuralFeature.Setting>() { @Override public boolean apply(Setting input) { return input != null && input.getEStructuralFeature() != null ? featureName.equals(input.getEStructuralFeature().getName()) : false; } }); }

Target:
&& input.getESF() != null && featureName.equals(input.getEFS().geName()
Source:
static void rotateProc(long /*int*/ gesture, double angle, double angle_delta, long/*int*/ user_data) { if (OS.gtk_gesture_is_recognized(gesture)) { // returning delta is off by two decimal points double delta = OS.gtk_gesture_rotate_get_angle_delta(gesture)*100; Control control = getControl(user_data); /* TODO: X and Y positions are not retrieved yet */ control.sendGestureEvent(0,SWT.GESTURE_ROTATE,0,0,delta); } }

Target:
space between long/*int*/ is critical for the replace task.
Source:
public Object getParent(Object element) { if (element instanceof IWorkingSet && element != workingSetRoot) return workingSetRoot; Object res = parents.get(element); if (res != null) { return res; } if (unassignedProjects.contains(res)) { return OTHERS_WORKING_SET; } return null; }

Target:
res is null here. Do we really expect that unassignedProjects contains null?
Source:
private void assertIsLegalIndex(final int index) { int totalCount = itemCount(); Assert.isTrue(index < totalCount && index > 0, java.text.MessageFormat.format( "The index ({0}) is more than the number of items ({1}) in the list.", index, totalCount)); //$NON-NLS-1$ }

Target:
This makes it illegal to select index 0... should be >= 0
Source:
protected void notifySelect() { notify(SWT.MouseEnter); notify(SWT.Activate); notify(SWT.FocusIn); notify(SWT.MouseMove); notify(SWT.MouseDown); notify(SWT.Selection); notify(SWT.MouseUp); notify(SWT.MouseHover); notify(SWT.MouseMove); notify(SWT.MouseExit); notify(SWT.Deactivate); notify(SWT.FocusOut); }

Target:
I think we should remove the following events
Source:
private IRegisterGroupDescriptor createGroupDescriptor(final String groupName, final IRegisterDescriptor[] iSelectedRegisters) { IRegisterGroupDescriptor groupDescriptor = new IRegisterGroupDescriptor() { @Override public boolean isEnabled() { return true; } @Override public String getName() { return groupName; } @Override public String getContainerId() { return null; // Not used } @Override public IRegisterDescriptor[] getChildren() throws CoreException { return iSelectedRegisters; } }; return groupDescriptor; }

Target:
we can move this one as a default method in the actual interface, thanks to Java 8.
Source:
public void doAfterTest() throws Exception { super.doAfterTest(); if (fServicesTracker != null) fServicesTracker.dispose(); }

Target:
It's a recommended practice to enclose the statement after the condition in curly brackets
Source:
private boolean isOrphan(File file) { String fileName = file.getName(); return fileName.startsWith("pack") && //$NON-NLS-1$ (fileName.endsWith(PackExt.BITMAP_INDEX.getExtension()) || fileName.endsWith(PackExt.INDEX.getExtension())) && !new File(file.getParentFile(), fileName.substring(0, fileName.lastIndexOf(".") + 1) //$NON-NLS-1$ + PackExt.PACK.getExtension()).exists(); }

Target:
What happens when we have a file named "pack-1234idx" in that directory. No '.' but ending in a well known extension. Such files would be deleted, or?
Source:
public boolean canStart(String line, int lineOffset) { if (lineOffset == 0) { Matcher m = pattern.matcher(line); if (m.matches()) { matcher = m; return true; } } matcher = null; return false; }

Target:
consider saving the value of group 1 and group 2 here rather than the whole matcher
Source:
protected boolean isLocationAllowed(Rectangle newBounds, Rectangle parentBounds, GraphicalEditPart containerEditpart) { boolean allowed = false; if (null != containerEditpart) { Rectangle absoluteBounds = newBounds.getTranslated(parentBounds.getLocation()); if (null != containerEditpart && containerEditpart.getFigure().getBounds().contains(absoluteBounds)) { allowed = true; } } return allowed; }

Target:
"null != containerEditpart" is already checked in the outer if
Source:
public ObjectId insert(int type, byte[] data, int off, int len, boolean createDuplicate) throws IOException { ObjectId id = idFor(type, data, off, len); if (!createDuplicate && db.has(id)) { return id; } else { File tmp = toTemp(type, data, off, len); return insertOneObject(tmp, id, createDuplicate); } }

Target:
Does this need to be public? I think the only caller is in the same package.
Source:
protected String getJavaCallDeclaration() { return "if (!window.callJava) {\n" + " window.callJava = function callJava(index, token, args) {\n" + " return external.callJava(index,token,args);\n" + " }\n" + "};\n"; }

Target:
You can not expose such thing as an API. There is now way one can open at that level and prevent crashes/deadlocks.
Source:
public void focusLost(FocusEvent e) { if (this.handleFocusChanges) { if (!e.widget.isDisposed() && !commit(MoveDirectionEnum.NONE, true)) { if (e.widget instanceof Control && !e.widget.isDisposed()) { ((Control) e.widget).forceFocus(); } } else { if (!AbstractCellEditor.this.parent.isDisposed()) AbstractCellEditor.this.parent.forceFocus(); } } }

Target:
minor thing ... the second check is not necessary anymore
Source:
public void focusLost(FocusEvent e) { if (this.handleFocusChanges && !e.widget.isDisposed()) { if (!commit(MoveDirectionEnum.NONE, true)) { if (e.widget instanceof Control && !e.widget.isDisposed()) { ((Control) e.widget).forceFocus(); } } else { if (!AbstractCellEditor.this.parent.isDisposed()) AbstractCellEditor.this.parent.forceFocus(); } } }

Target:
would it not make more sense to move this check one line down? the commit() call could produce such an error, so that one should be guarded. The else condition could be matched. Of course it needs to be the first check
Source:
public boolean supportsRefreshing() { for (AbstractTaskEditorPart part : subParts) { if (!part.supportsRefreshing()) { return false; } } return true; }

Target:
Should return false if !super.supportsRefreshing()
Source:
public boolean hasIncomingChanges() { for (AbstractTaskEditorPart part : subParts) { if (part.hasIncomingChanges()) { return true; } } return false; }

Target:
Should return true if super.hasIncomingChanges (the parent section may contain attribute editors directly, e.g. the bugzilla attribute section has attribute editors and also a subsection called Flags).
Source:
public Object[] getElements(Object inputElement) { if (inputElement instanceof IBuild) { return getChildren(inputElement); } if (inputElement instanceof String) { return new Object[] { inputElement }; } return NO_ELEMENTS; }

Target:
remore this case
Source:
public Object getParent(Object element) { if (element instanceof IBuild) { return ((IBuild) element).getParent(); } return NO_ELEMENTS; }

Target:
return null
Source:
public void testCall() { GetDiffCommand diff = new GetDiffCommand(fGerrit.getRepository(), change_id, commit_id, "/COMMIT_MSG"); try { DiffInfo di = diff.call(); System.out.println(di); } catch (EGerritException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

Target:
Just a system.out, no validation here
Source:
public void setUp() throws IOException { DfsRepositoryDescription desc = new DfsRepositoryDescription("test"); git = new TestRepository<>(new InMemoryRepository(desc)); repo = git.getRepository(); odb = repo.getObjectDatabase(); ticks = 0; mockSystemReader = new MockSystemReader() { @Override public long getCurrentTime() { // move forward time with every call return super.getCurrentTime() + ticks++; } }; SystemReader.setInstance(mockSystemReader); }

Target:
You can use tick() for this: tick(1); return super.getCurrentTime(); Most TestRepository operations call tick on its mockSystemReader, which is a little more resilient (since it makes behavior change less based on the number of times getCurrentTime gets called). Can the TestRepository use this as their MockSystemReader? Repository db = new InMemoryRepository(desc); git = new TestRepository<>(db, new RevWalk(db), mockSystemReader);
Source:
public boolean containsAll(Collection<?> c) { for (Object name : c) if (!wrappedSet.contains(IdentityWrapper.wrap(name))) return false; return true; }

Target:
rename 'element'
Source:
public boolean removeAll(Collection<?> c) { boolean changed = false; for (Object name : c) changed |= remove(name); return changed; }

Target:
rename 'element'
Source:
private void sleepGroup(GroupInfo group, JobInfo info) { Object[] listenersArray = listeners.getListeners(); for (Object element : listenersArray) { IJobProgressManagerListener listener = (IJobProgressManagerListener) element; if (isNeverDisplaying(info.getJob(), listener.showsDebug())) continue; if (listener.showsDebug() || group.isActive()) listener.refreshGroup(group); else listener.removeGroup(group); } }

Target:
inline listeners.getListeners()
Source:
public void refreshGroup(GroupInfo info) { Object[] listenersArray = listeners.getListeners(); for (Object element : listenersArray) { ((IJobProgressManagerListener)element).refreshGroup(info); } }

Target:
inline listeners.getListeners()
Source:
public void refreshAll() { pruneStaleJobs(); Object[] listenersArray = listeners.getListeners(); for (Object element : listenersArray) { ((IJobProgressManagerListener)element).refreshAll(); } }

Target:
inline listeners.getListeners()
Source:
public void removeJobInfo(JobInfo info) { Job job = info.getJob(); jobs.remove(job); runnableMonitors.remove(job); Object[] listenersArray = listeners.getListeners(); for (Object element : listenersArray) { IJobProgressManagerListener listener = (IJobProgressManagerListener) element; if (!isCurrentDisplaying(info.getJob(), listener.showsDebug())) { listener.removeJob(info); } } }

Target:
inline listeners.getListeners()
Source:
public void removeGroup(GroupInfo group) { Object[] listenersArray = listeners.getListeners(); for (Object element : listenersArray) { ((IJobProgressManagerListener)element).removeGroup(group); } }

Target:
inline listeners.getListeners()
Source:
protected void checkNewDefaultBrowser(Object browser) { TableItem[] children = tableViewer.getTable().getItems(); for (TableItem element : children) { TableItem item = element; if (!(item.getData().equals(browser))) item.setChecked(false); } }

Target:
unnecessary
Source:
protected void inputChanged(Object input, Object oldInput) { elements.clear(); Object[] children = getSortedChildren(getRoot()); list.removeAll(); for (Object element : children) { elements.add(element); mapElement(element, list); } list.setElements(children); }

Target:
rename 'child'
Source:
public final void setChildren(IEditorPart[] children) { innerEditors = children; activeEditorIndex = 0; for (IEditorPart element : children) { element.addPropertyListener( (source, propId) -> handlePropertyChange(propId)); } innerEditorsCreated(); }

Target:
rename 'child'
Source:
public void setEnabled(boolean enabled, Composite parent) { super.setEnabled(enabled, parent); group.setEnabled(enabled); for (Control element : group.getChildren()) { element.setEnabled(enabled); } }

Target:
rename 'child'
Source:
public AboutInfo[] getFeatureInfos() { // cannot be cached since bundle groups come and go List infos = new ArrayList(); // add an entry for each bundle group IBundleGroupProvider[] providers = Platform.getBundleGroupProviders(); if (providers != null) { for (IBundleGroupProvider provider : providers) { IBundleGroup[] bundleGroups = provider.getBundleGroups(); for (IBundleGroup bundleGroup : bundleGroups) { infos.add(new AboutInfo(bundleGroup)); } } } return (AboutInfo[]) infos.toArray(new AboutInfo[infos.size()]); }

Target:
inline
Source:
public void test_ConstructorLorg_eclipse_swt_widgets_CompositeI() { Browser browser = new Browser(shell, SWT.NONE); browser.dispose(); browser = new Browser(shell, SWT.BORDER); // System.out.println("Test_org_eclipse_swt_browser_Browser#test_Constructor*#getBrowserType(): " + browser.getBrowserType()); browser.dispose(); browser = new Browser(null, SWT.NONE); // Should throw. fail("No exception thrown for parent == null"); }

Target:
No need for the fail. Junit will auto fail the test if the expected exception is not thrown.
Source:
protected Spec[] getSelectedSpecs() { List list = fileAssociationViewer.getStructuredSelection().toList(); return (Spec[]) list.toArray(new Spec[list.size()]); }

Target:
add generic
Source:
private static <T> List<T> getReversed(Collection<T> collection) { ArrayList<T> result = new ArrayList<>(); result.addAll(collection); Collections.reverse(result); return result; }

Target:
Simpler: ArrayList<T> result = new ArrayList<>(collection);
Source:
private Figure getGroupFigure(List<Figure> dDiagramElementDecorationFigures, Position position, Rectangle expectedGroupBounds) { Figure groupFigure = null; for (Figure currentGroupFigure : dDiagramElementDecorationFigures) { System.out.println("figure bounds " + currentGroupFigure.getBounds()); if (currentGroupFigure.getBounds().equals(expectedGroupBounds)) { groupFigure = currentGroupFigure; break; } } assertNotNull("Bad group decoration position at " + position.getName(), groupFigure); return groupFigure; }

Target:
to remove
Source:
protected void updateEnablement(IAction action) { boolean enabled = isEnabled(); action.setEnabled(enabled); }

Target:
the superclass implementation seems to expect action may be null, also the super implementation also has some logic about whether the context is active. I don't know that we need this since our plugin XML is checking that property.
Source:
public ISearchResultPage getCurrentPage() { IViewPart view = super.getPartForAction(); return ((SearchView) view).getActivePage(); }

Target:
this should be private
Source:
public boolean isEnabled() { List<StructuredViewer> viewers = getViewers(); ISearchResultPage page = getCurrentPage(); return viewers.size() > 0 && page != null && WHITELISTED_IDS.contains(page.getID()); }

Target:
viewers > 0 implies page is non-null
Source:
public Object resolveArtifact(EObject artifact) { ArtifactWrapper wrapper = (ArtifactWrapper) artifact; String uri = wrapper.getUri(); CapraOfficeObject object = new CapraOfficeObject(); object.setUri(uri); return object; }

Target:
I am pretty sure that gives you an unchecked cast warning. I think it would be pertinent to add a check here, just to make the code more robust.
Source:
protected static MarkupParser createParserWithConfiguration(MarkupLanguageConfiguration configuration) { MarkupLanguage markupLanguage = new AsciiDocLanguage(); if (configuration != null) { markupLanguage.configure(configuration); } MarkupParser parser = new MarkupParser(markupLanguage); return parser; }

Target:
inline return statement here
Source:
protected boolean shouldBeDecorated(final EditPart editPart) { boolean shouldBeDecorated = super.shouldBeDecorated(editPart); return shouldBeDecorated && editPart instanceof IDiagramElementEditPart; }

Target:
Doing the "instanceof" test first would avoid calling the more costly "super": return editPart instanceof IDiagramElementEditPart && super.shouldBeDecorated(editPart);
Source:
private List<ApplicabilityToken> getStoredApplicabilities() { List<ApplicabilityToken> appls = new LinkedList<>(); appls.addAll(AtsClientService.getApplicabilityEndpoint( AtsClientService.get().getAtsBranch()).getApplicabilityReferenceTokens(workItem.getStoreObject())); return appls; }

Target:
Looks like getApplicabilityReferenceTokens already returns a list? Don't need to add to another list?
Source:
public boolean canHandleArtifact(T artifact) { try { @SuppressWarnings("rawtypes") Class<?> genericType = ((Class) ((ParameterizedType) this.getClass().getGenericSuperclass()) .getActualTypeArguments()[0]); return genericType.isAssignableFrom(artifact.getClass()); } catch (NoClassDefFoundError e) { return false; } }

Target:
This is not necessary if the cast is to Class<?>.
Source:
public synchronized void dispose() { /* Clean up the index if applicable */ if (getIndexer() != null) { getIndexer().dispose(); } /* Clean up the analysis modules */ @NonNull Iterable<IAnalysisModule> analysisModules = getAnalysisModules(); for (IAnalysisModule module : analysisModules) { module.dispose(); } fAnalysisModules.clear(); super.dispose(); }

Target:
Remove or put on same line?
Source:
protected T doGetValue() { // The value is not kept up to date when we are not listening. if (isListening) { return value; } return calculate(); }

Target:
final
Source:
protected void doSetValue(T value) { if (this.value != value) { fireValueChange(Diffs.createValueDiff(this.value, this.value = value)); } }

Target:
final This should probably contain this.value = value at some point... and it should only do so if isListening = true.
Source:
protected void firstListenerAdded() { if (getRealm().isCurrent()) { startListeningInternal(); } else { getRealm().asyncExec(() -> { if (hasListeners && !isListening) { startListeningInternal(); } }); } hasListeners = true; super.firstListenerAdded(); }

Target:
final
Source:
private void startListeningInternal() { startListening(); isListening = true; value = calculate(); }

Target:
startListening is overridable and calls into other code that this class has no control over. It should be the last thing in this method to prevent any possibility of other code calling back into this object while it's in an invalid intermediate state.
Source:
public void testMenuNoMarkerSet() { SWTBotRootMenu viewMenu = fViewBot.viewMenu(); List<String> menuItems = viewMenu.menu("Marker Set").menuItems(); assertEquals("number of items", 3, menuItems.size()); assertArrayEquals("menu items, no marker set", MENU_ITEMS_NO_MARKERS_SET, menuItems.toArray()); }

Target:
assertArrayEquals will check length
Source:
private boolean hasIndirectDependent(Set<StructDef<?>> visited, StructDef<?> structDef) { for (StructDef<?> next : this.dependents) { if (visited.contains(next)) { continue; } visited.add(next); if (next.equals(structDef)) { return true; } if (next.hasIndirectDependent(visited, structDef)) { return true; } } return false; }

Target:
Simpler: if (!visited.add(next))
Source:
public Map<String, String> createImageServerContent(String scheme) throws IOException { HashMap<String, String> map = new HashMap<>(); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml", createServerEntry("WikiToDocTaskIntegrationTest1.xml")); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml&gimcontinue=49671%7Cpict1.gif", createServerEntry("WikiToDocTaskIntegrationTest2.xml")); return map; }

Target:
Map here, makes code more readable, e.g. Map<String,String> map = new HashMap<>()
Source:
protected Reader createInputReader(URL apiUrl) throws UnsupportedEncodingException, IOException { if (serverContent == null) { throw new IllegalStateException( "Please specify some server content for images used during the tests. See: TestMediaWikiApiImageFetchingStrategy#serverContent"); } String key = apiUrl.toString(); if (!serverContent.containsKey(key)) { throw new IllegalStateException("Please define a server content used during the tests for the key: " + key); } String pageContent = serverContent.get(key); return new StringReader(pageContent); }

Target:
use checkNotNull in the constructor instead
Source:
public HashMap<String, String> createImageServerContent(String scheme) throws IOException { HashMap<String, String> map = new HashMap<String, String>(); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml", createServerEntry("WikiToDocTaskIntegrationTest1.xml")); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml&gimcontinue=49671%7Cpict1.gif", createServerEntry("WikiToDocTaskIntegrationTest2.xml")); return map; }

Target:
return Map instead of HashMap
Source:
private void findByName() throws IOException { RepositoryUtil repoUtil = getRepositoryUtil(); RepositoryCache repoCache = getRepositoryCache(); for (String dirs : repoUtil.getConfiguredRepositories()) { match = repoCache.lookupRepository(new File(dirs)); if (!ResourcePropertyTester.hasGerritConfiguration(match)) { break; } RemoteConfig remote = findRemoteByName(); if (remote != null) { return; } } match = null; }

Target:
I have a question : Why testing if the configuration has a Gerrit config, If we don't, then break. It should be the opposite and we should keep the match value not re-init at the end of the method to null. In all cases, the match will be null,
Source:
protected ICommand getBeforeMoveCommand(final MoveRequest request) { ICommand gmfCommand = super.getBeforeMoveCommand(request); if (request.getTargetContainer().eIsProxy()) { return UnexecutableCommand.INSTANCE; } return gmfCommand; }

Target:
why call super here if the first return is call, gmfCommand will be never used. More the gmfCommand will be always null. It's not necessary to call super. Just return the unexecutable command in case of proxy or null: return request.getTargetContainer().eIsProxy()?UnexecutableCommand.INSTANCE:null should be enough.
Source:
public boolean isExpandable(Object elementOrTreePath) { Object element; TreePath path; if (elementOrTreePath instanceof TreePath) { path = (TreePath) elementOrTreePath; element = path.getLastSegment(); } else { element = elementOrTreePath; path = null; } IContentProvider cp = getContentProvider(); if (cp instanceof ITreeContentProvider) { ITreeContentProvider tcp = (ITreeContentProvider) cp; return tcp.hasChildren(element); } return false; }

Target:
what is the point of setting path to null here. It looks like it is only needed in the if statement above
Source:
public void createPartControl(@Nullable Composite parent) { super.createPartControl(parent); String name = getViewSite().getSecondaryId(); if (name != null) { fViewInfo.setName(name); } setViewTitle(); }

Target:
Would the order need to be reversed here too? I don't have as many XY charts to test with...
Source:
public static synchronized IndexedUserContainer getInstance() { return container; }

Target:
obsolete now, accessing a class attribute is thread-safe
Source:
protected void appendName(ActivityPartition activitypartition, Collection<String> displayValue, StringBuilder sb) { Element represents = activitypartition.getRepresents(); String activitypartitionName = UMLLabelInternationalization.getInstance().getLabel(activitypartition); if (represents != null) { if (represents instanceof NamedElement) { activitypartitionName = ((NamedElement) represents).getName() ; } } appendString(sb, activitypartitionName, UNNAMED); return; }

Target:
instanceof already check the not null See https://gist.github.com/bmaggi/66a5803f79fefb6f57db887a9d9cec4f
Source:
protected void appendName(ActivityPartition activitypartition, Collection<String> displayValue, StringBuilder sb) { Element represents = activitypartition.getRepresents(); String activitypartitionName = UMLLabelInternationalization.getInstance().getLabel(activitypartition); if (represents != null) { try { activitypartitionName = ((NamedElement) represents).getName() ; } catch (ClassCastException e) { } } appendString(sb, activitypartitionName, UNAMED); return; }

Target:
Seems like a strange way of handling the cast. Why not make an explicit check the represents instanceof NamedElement? Why cause an exception to be thrown and then catch it?
Source:
public long getPacketSizeBits() { return 0; }

Target:
Should this be 1 if content size is 1?
Source:
public void addChild(LaunchObjectModel model) { for (LaunchObjectModel e : children) { model.compareTo(e); } children.add(model); }

Target:
This looks superfluous, since compareTo() must not have any side effects.
Source:
protected Map<String, TraceTypeHelper> getTraceTypeMap(String selected) { Map<String, TraceTypeHelper> traceTypeMap = new TreeMap<>(); for (TraceTypeHelper helper : TmfTraceType.getTraceTypeHelpers()) { if (!helper.isExperimentType() && (helper.isEnabled() || (selected != null && helper.getTraceTypeId().equals(selected)))) { traceTypeMap.put(helper.getLabel(), helper); } } return traceTypeMap; }

Target:
Can remove, if it's null it won't be equal, and helper's id can't be null.
Source:
private RevCommit parseCommit(AnyObjectId id) throws IncorrectObjectTypeException, IOException, MissingObjectException { if (id instanceof RevCommit) { return (RevCommit) id; } try (RevWalk walk = new RevWalk(this)) { return walk.parseCommit(id); } }

Target:
Shouldn't it be public?
Source:
private void writeCatchHandler(ICPPASTCatchHandler catchStatement) { writeAttributes(catchStatement, EnumSet.of(SpaceLocation.AFTER)); scribe.print(CATCH); if (catchStatement.isCatchAll()) { scribe.print(VAR_ARGS); } else { scribe.noSemicolon(); scribe.noNewLines(); catchStatement.getDeclaration().accept(visitor); scribe.newLines(); } scribe.print(')'); writeBodyStatement(catchStatement.getCatchBody(), true); }

Target:
Are you sure that we can have attributes on an ICPPASTCatchHandler? Even though it is a CPPASTAttributeOwner, it seems to me that the standard does not allow for attributes here. [gram.stmt] allows for attribute-specifier-seq on try-block but [gram.except] does not further allow for attribute-specifier-seq on neither handler-seq nor handler. Maybe its a "bug" that ICPPASTCatchHandler is a CPPASTAttributeOwner in the first place?
Source:
private static MergeAlgorithm getMergeAlgorithm(Config config) { SupportedAlgorithm diffAlg = config.getEnum( ConfigConstants.CONFIG_DIFF_SECTION, null, ConfigConstants.CONFIG_KEY_ALGORITHM, SupportedAlgorithm.HISTOGRAM); return new MergeAlgorithm(DiffAlgorithm.getAlgorithm(diffAlg)); }

Target:
optional: Can these be imported statically? I think that would make it easier to read.
Source:
public synchronized IObjectDescriptor[] getDependentObjects() { if (objectDescriptors == null) { objectDescriptors = descriptorCache.computeIfAbsent(location, l -> { IObjectDescriptor[] descriptors = calcDependentObjects(); return descriptors.length > 0 ? descriptors : EMPTY_DESCRIPTORS; }); } return objectDescriptors; }

Target:
This is an internal abstract class that I assume other parts of the code in this bundle implement for the calcDependentObjects() method. Wouldn't it be better for these implementations to all return the same EMPTY array constant instead of catching it here? I'm also concerned about impls that may return null resulting in an NPE here where one was not before.
Source:
protected Color createColor(IPreferenceStore store, String key, Display display) { RGB rgb= null; if (store.contains(key)) { if (store.isDefault(key)) rgb= PreferenceConverter.getDefaultColor(store, key); else rgb= PreferenceConverter.getColor(store, key); if (rgb != null) return new Color(display, rgb); } return null; }

Target:
this is a breaking change. NO GO.
Source:
public void notifyChanged(Notification notification) { // Handle when a port is defined as conjugated if ((notification.getFeatureID(Property.class) == UMLPackage.PORT__IS_CONJUGATED)) { refreshDisplay(); } else { super.notifyChanged(notification); Object object = notification.getNotifier(); Property property = getUMLElement(); if ((object != null) && (property != null)) { // Handle also the case of opaque expression bodies changing if (notification.getFeature() == UMLPackage.Literals.OPAQUE_EXPRESSION__BODY) { refreshDisplay(); } } } }

Target:
This API is only reliable when the notifier is known a priori to be of the 'expectedClass' type. Usually we just check whether notification.getFeature() == UMLPackage.Literals.PORT__IS_CONJUGATED The getFeatureID API is usually only employed for notifiers that aren't Objects, such as Resources and ResourceSets.
Source:
private PackWriter newPackWriter() { PackConfig pc = packConfig; if (pc == null) { pc = db != null ? new PackConfig(db) : new PackConfig(); } if (reader != null) { return new PackWriter(pc, reader); } final ObjectReader or = db.newObjectReader(); return new PackWriter(pc, or) { @Override public void close() { super.close(); or.close(); } }; }

Target:
super.close() already closes 'or' (as does writePack). Is the idea that PackWriter would gain a boolean to disable that behavior?
Source:
public synchronized void clear() { for (int i = 0; i < this.fPageTable.length; i++) { final Chunk chunk = this.fPageTable[i]; if (chunk == null) { continue; } chunk.fCacheIndex = -1; chunk.fDatabase.checkIfChunkReleased(chunk); this.fPageTable[i] = null; } this.fTableIsFull = false; this.fPointer = 0; }

Target:
What's the reasoning for making this final?
Source:
private StatusAdapter getSingleSelection() { IStructuredSelection selection = statusListViewer.getStructuredSelection(); if (selection.size() == 1) { return (StatusAdapter) selection.getFirstElement(); } return null; }

Target:
This is not same! *single* selection will return null if there are more then one element!
Source:
public static Color getSystemForegroundColor() { ColorRegistry colorRegistry = JFaceResources.getColorRegistry(); Color foreground = colorRegistry.get(JFacePreferences.INFORMATION_FOREGROUND_COLOR); if (foreground == null) { return JFaceColors.getInformationViewerForegroundColor(Display.getDefault()); } return foreground; }

Target:
No need to make this public.
Source:
private void initialize() { project = (IProject) getElement().getAdapter(IResource.class); if (project == null) { throw new RuntimeException( TasksUiPlugin.ID_PLUGIN + ": Can not get the project of " + getElement().toString()); //$NON-NLS-1$ } noDefaultAndApplyButton(); setDescription( Messages.ProjectTaskRepositoryPage_Select_a_task_repository_to_associate_with_this_project_below); }

Target:
explicit toString() is unnecessary. Simply "+ getElement()" will accomplish the same, and will work even if getElement() happens to return null
Source:
public void dispose() { super.dispose(); fCriticalPathModule.dispose(); }

Target:
should this be on top?
Source:
public void shutdown() { fShutdown = true; Job.getJobManager().cancel(AbstractDispatchJob.class); }

Target:
This is wrong, because this will try to cancel *all possible* dispatcher jobs, not the jobs of the current dispatcher.
Source:
public void setDisableHyperLink() { if (!selectHyperLinkLabel.isDisposed()) { selectHyperLinkLabel.setEnabled(false); } if (!clearHyperLinkLabel.isDisposed()) { clearHyperLinkLabel.setEnabled(false); } }

Target:
Can selectHyperLinkLabel be null?
Source:
public void testReadPipePosixCommandStartFailure() throws CommandFailedException { FS fs = FS.DETECTED.newInstance(); assumeTrue(fs instanceof FS_POSIX); FS.readPipe(fs.userHome(), new String[] { "this-command-does-not-exist" }, Charset.defaultCharset().name()); }

Target:
Why do you assume here that fs should be posix? This test should also fail on a windows machine, or?
Source:
protected IEclipseContext createContext(final Event trigger) { final IEclipseContext staticContext = EclipseContextFactory.create("keys-staticContext"); //$NON-NLS-1$ staticContext.set(Event.class, trigger); return staticContext; }

Target:
This method should be private or default as otherwise it is API addition.
Source:
public void stop(BundleContext context_p) throws Exception { __plugin = null; if(_adapterFactory != null) _adapterFactory.dispose(); super.stop(context_p); }

Target:
You should also set _adaterFactory to null after dispose.