auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public OutputStream write(String item, IProgressMonitor monitor) throws IOException { File file = getFile(item); return new BufferedOutputStream(new FileOutputStream(file)); }

Target:
let's not modify this. looks like the classes that use this method implement buffered writing
Source:
public void display(IStructuredSelection selection) { if (selection != null && selection.getFirstElement() instanceof IJavaVariable) { IJavaVariable variable = (IJavaVariable) (selection.getFirstElement()); if (fVariable == null || !fVariable.equals(variable)) { fVariable = variable; fExpressionHistory.setEnabled(true); initializeExpressionHistoryDropDown(); } } super.display(selection); }

Target:
I see NPE's here...
Source:
public DynamicSourcesWorkingSetUpdater() { fUpdateJob= new Job(WorkingSetMessages.JavaSourcesWorkingSets_updating) { @Override protected IStatus run(IProgressMonitor monitor) { return updateElements(monitor); } }; fUpdateUIJob = new UpdateUIJob(); fUpdateJob.setSystem(true); fResourceChangeListener= new ResourceChangeListener(); ResourcesPlugin.getWorkspace().addResourceChangeListener(fResourceChangeListener, IResourceChangeEvent.POST_CHANGE); fJavaElementChangeListener= new JavaElementChangeListener(); JavaCore.addElementChangedListener(fJavaElementChangeListener, ElementChangedEvent.POST_CHANGE); }

Target:
shouldn't we also do: fUpdateUIJob.setSystem(true);
Source:
public int getMaxSeverityIncludingNestedProjects(IResource resource) { return cache.getOrDefault(resource, 0).intValue(); }

Target:
Would be nice to add @return about what kind of values are expected here
Source:
public String getText(final Object element) { if (element == null) { return ""; //$NON-NLS-1$ } return ((FileDiff) element).getLabel(element); }

Target:
The super() returns "" on null. Why should we differ?
Source:
public PictogramElement[] getSelections(PictogramElement selection) { if (selection instanceof Connection && !isConnectionSelectionEnabled()) { return null; } PictogramElement[] selections = { selection }; return selections; }

Target:
I agree. However, this is done inside the TBP to preserve backward compatibility. If backward compatibility is not desired, this should, indeed, move to caller.
Source:
long /*int*/ getsurePressReleaseProc (long /*int*/ gesture, int n_press, double x, double y, long /*int*/ user_data) { long /*int*/ event = GTK.gtk_get_current_event(); long /*int*/ result = 0; switch ((int)/*64*/user_data) { case GESTURE_PRESSED: result = gtk_gesture_press_event(gesture, n_press, x, y); break; case GESTURE_RELEASED: result = gtk_gesture_release_event(gesture, n_press, x, y); break; } gdk_event_free(event); return result; }

Target:
If we aren't feeding the GdkEvent to the callback methods then just remove this line -- otherwise we are fetching the event and freeing it for no reason. :)
Source:
public LanguageFilterServer() { this.filterBoxService = new FilterBoxService(this); this.filterWorkspaceService = new FilterWorkspaceService(); }

Target:
Remove the this.
Source:
public void createArtifacts() { ArtifactId parentArtifact = CoreArtifactTokens.OseeTypesFolder; List<String> names = new ArrayList<>(); names.add("TestArtifact1"); names.add("TestArtifact2"); names.add("TestArtifact3"); List<ArtifactToken> newArtifacts = artifactEndpoint.createArtifacts(COMMON, CoreArtifactTypes.PlainText, parentArtifact, names); Assert.assertFalse(newArtifacts.isEmpty()); }

Target:
Consider Arrays.asList("xxx","yyy", "zzz");
Source:
private Topic getOrCreateTopic(MessageID messageId) throws JMSException { Topic topic = topicCache.get(messageId.getId()); if (topic == null) { topic = session.createTopic(messageId.getId()); Topic catchReturn = topicCache.putIfAbsent(messageId.getId(), topic); } return topic; }

Target:
This variable is not being used. No reason to include it since calling a non-void method doesn't require catching its return object typically. To satisfy Findbugs, you could do something like this: if (topic == null) { topic = session.createTopic(messageId.getId()); return topicCache.putIfAbsent(messageId.getId(), topic); } return topic;
Source:
private void createButton(Composite parent) { artifactSelectButton = new Button(parent, SWT.PUSH); artifactSelectButton.setText(String.format("Select " + itemName)); artifactSelectButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { handleSelectedArtifact(event); notifyListener(event); } }); artifactSelectButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); }

Target:
Not sure what is going on here, as String.format always takes at least two arguments? "Select" is being picked up as an actual class and not treated as a string for some reason.
Source:
private void recreateEmptyArea() { if (emptyArea != null) { // throw away already existing empty area emptyArea.dispose(); emptyArea = null; } if (images != null) { disposeImages(); images = new ArrayList<>(); } // re-read the project wizards and re-create the empty area createEmptyArea(displayArea); switchTopControlRunnable.run(); }

Target:
images is never null so just call disposeImages()
Source:
public String getLine(int lineIndex) { try { final IRegion lineRegion = getLineInformation(lineIndex); return document.get(lineRegion.getOffset(), lineRegion.getLength()); } catch (BadLocationException e) { ConsolePlugin.log(e); return null; } }

Target:
Before we always had non-null returns
Source:
static long /*int*/ gdk_pixbuf_new_from_file(String filename) { int length = filename.length (); char chars = new char [length]; filename.getChars (0, length, chars, 0); byte buffer = Converter.wcsToMbcs(chars, true); long /*int*/ pixbuf = GDK.gdk_pixbuf_new_from_file(buffer, null); return pixbuf; }

Target:
This can be combined into one line.
Source:
public void tesIsModifiedBySameLastModifiedAndDifferentSize() throws Exception { File f1 = createFile("foo", "lorem".getBytes()); File f2 = createFile("bar", "lorem ipsum".getBytes()); long now = System.currentTimeMillis(); f1.setLastModified(f2.lastModified()); // Make sure f1 and f2 have the same lastModified FileSnapshot save = FileSnapshot.save(f1); Thread.sleep(3000L); assertEquals(save.lastModified(), f2.lastModified()); assertTrue(save.isModified(f2)); }

Target:
now is unused
Source:
public void createArtifact(@Nullable ArtifactToken parent, ArtifactToken artifact) { ArtifactToken art = createArtifact(artifact); addChild(parent, art); }

Target:
If parent can be null, we need to check before setting parent. Or switch to NonNullable
Source:
public void setEmptyExceptionSpecification() { assertNotFrozen(); typeIds = IASTTypeId.EMPTY_TYPEID_ARRAY; setNoexceptExpression(new CPPASTLiteralExpression(IASTLiteralExpression.lk_true, "true".toCharArray())); //$NON-NLS-1$ // TODO this is probably not the correct way to do it... }

Target:
I don't think we need to invent an AST node, we can just do it at the evaluation level. We can add ICPPASTFunctionDeclarator.getNoexceptEvaluation(), whose implementation does: if (getNoexceptionExpression() != null) { return getNoexceptionExpression().getEvaluation(); } if (getExceptionSpecification() == IASTTypeId.EMPTY_TYPEID_ARRAY) { return /* EvalFixed for "true" */; } return null; and then use getNoexceptionEvaluation() instead of getNoexceptExpression().getEvaluation() when creating function types.
Source:
public boolean isNoexcept(boolean inCalledContext) { ICPPFunction overload = getOverload(); if (overload != null) { return EvalUtil.evaluateNoexceptSpecifier(overload.getType().getNoexceptSpecifier()); } return fArg1.isNoexcept(inCalledContext) && fArg2.isNoexcept(inCalledContext); }

Target:
If there's an overload the result should be (overload is noexcept) && (arg1 is noexcept) && (arg2 is noexcept).
Source:
public boolean isNoexcept(boolean inCalledContext) { if (fOperator == op_throw) return false; ICPPFunction overload = getOverload(); if (overload != null) { return EvalUtil.evaluateNoexceptSpecifier(overload.getType().getNoexceptSpecifier()); } return fArgument.isNoexcept(inCalledContext); }

Target:
(overload is noexcept) && (argument is noexcept)
Source:
public static boolean evaluateNoexceptSpecifier(ICPPEvaluation noexceptSpecifier) { if (noexceptSpecifier == null) return false; else { IntegralValue v = (IntegralValue) noexceptSpecifier.getValue(); return v.numberValue().longValue() == 1; } }

Target:
numberValue() needs a null check
Source:
public static boolean evaluateNoexceptSpecifier(ICPPEvaluation noexceptSpecifier) { if (noexceptSpecifier != null) { IntegralValue v = (IntegralValue) noexceptSpecifier.getValue(); if (v.numberValue() != null) return v.numberValue().longValue() == 1; } return false; }

Target:
Do we know it will be an IntegralValue? (Could we get here if it's dependent, in which case it could be a DependentValue?)
Source:
private AccountInfo adaptAccountInfo(CommitInfo commitInfo, IProgressMonitor monitor) throws GerritException { String accountId = commitInfo.getAuthor().getEmail(); for (int retries = 0;; retries++) { try { return retrieveAccountInfo(accountId, monitor); } catch (GerritException e) { if (retries < 3) { accountId = commitInfo.getAuthor().getName(); continue; } } } }

Target:
else throw e?
Source:
private void addMethodToClass(ICPPClassType classType, Method method) { if (!isDuplicate(method)) { List<Method> methods = fData.get(classType); if (methods == null) { methods = new ArrayList<>(); methods.add(method); fData.put(classType, methods); } else { methods.add(method); } } }

Target:
Can we do instead: if (methods == null) { methods = new ArrayList<>(); fData.put(classType, methods); } methods.add(method); ?
Source:
public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { if (adapterType == IToggleBreakpointsTarget.class && adaptableObject instanceof ExtensionBasedTextEditor || adaptableObject instanceof TextEditor) { return (T) new DSPBreakpointAdapter(); } return null; }

Target:
I'm often unsure of the operator priority here, and I guess most people are. Can you please wrap the 2nd term of && with parenthesis to remove any form of doubt?
Source:
public static void setUpBeforeClass() throws CoreException { project = TestUtils.createProject("EditorToOutlineAdapterFactoryTest" + System.currentTimeMillis()); testFile = TestUtils.createUniqueTestFile(project, "Hello World !!"); // look for content outline in current workbench, could be null IViewPart viewPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .findView("org.eclipse.ui.views.ContentOutline"); //$NON-NLS-1$ // implicitly checks for null if (viewPart instanceof ContentOutline) { outline = (ContentOutline) viewPart; } Assert.assertNotNull(outline); }

Target:
I think the AllCleanRule may delete the project and test file after this @BeforeClass. It may be better to put this directly in the test method.
Source:
public void testEquals_other() { setUp(); try (CtfIterator obj = (CtfIterator) trace.createIterator();) { assertNotNull(obj); CtfLocation ctfLocation1 = new CtfLocation(new CtfLocationInfo(1, 0)); obj.setLocation(ctfLocation1); obj.increaseRank(); boolean result = iterator.equals(obj); assertTrue(result); } }

Target:
Why are you calling setUp()? Is there a way to avoid this?
Source:
public boolean visit(ConstructorInvocation constructorInvocation) { List<?> arguments= constructorInvocation.arguments(); if (!arguments.isEmpty()) { IMethodBinding constructorBinding= constructorInvocation.resolveConstructorBinding(); IMethod method = resolveMethodBinding(constructorBinding); collectParameterNamesCodeMinings(method, arguments, constructorBinding.isVarargs()); } return super.visit(constructorInvocation); }

Target:
The same thing as mentioned below can also happen here.
Source:
public boolean visit(MethodInvocation methodInvocation) { List<?> arguments= methodInvocation.arguments(); if (!arguments.isEmpty()) { IMethodBinding methodBinding= methodInvocation.resolveMethodBinding(); IMethod method = resolveMethodBinding(methodBinding); collectParameterNamesCodeMinings(method, arguments, methodBinding.isVarargs()); } return super.visit(methodInvocation); }

Target:
methodBinding.isVarargs() will NPE if the line in question can't resolve its bindings. MethodInvocation.resolveMethodBinding() can return null, especially if there's plenty of errors. Your local resolveMethodBinding() checks that, so it's fine but methodBinding.isVarargs() would fail.
Source:
public static void beforeClass() { SWTBotUtils.initialize(); Thread.currentThread().setName("SWTBotTest"); /* set up for swtbot */ SWTBotPreferences.TIMEOUT = 60000; /* 60 second timeout */ SWTBotPreferences.KEYBOARD_LAYOUT = "EN_US"; SWTWorkbenchBot bot = new SWTWorkbenchBot(); SWTBotUtils.closeView("welcome", bot); /* Prepare the workspace */ prepareWorkspace(); /* Finish waiting for eclipse to load */ WaitUtils.waitForJobs(); /* Create project */ SWTBotUtils.createProject(PROJECT_NAME); }

Target:
Implementing classes should be able to override this method to do their own stuff to prepare the workspace. With static, it is not possible to do so.
Source:
public void tearDown() { fBot.closeAllEditors(); SWTBotUtils.deleteProject(PROJECT_NAME, fBot); }

Target:
This part should be move to cleanUp(). Right now the project is deleted after each test and never created again
Source:
public static void before() { SWTBotUtils.openTrace(TRACE_PROJECT_NAME, fTestFile.getAbsolutePath(), TRACE_TYPE); fEditorBot = SWTBotUtils.activateEditor(fBot, fTestFile.getName()); }

Target:
inline it instead of doing this.
Source:
private static int inversePremultipliedColor(int color, int alpha) { // Calculating inverse for premultiplied color gives a range of possible colors // due to rounding that occurs with integer calculations. However, alpha-blend // formula only has the multiplied component, so all of those inverses are equivalent. return (255*color + alpha-1) / alpha; }

Target:
Let's make this non-static and non-private. It seems like it's a function that might be useful down the line.
Source:
private boolean isVirtual(ContextInfo info) { if (info.isVirtual != null) return info.isVirtual; info.isVirtual = ClassTypeHelper.isVirtual(info.method); return info.isVirtual; }

Target:
Slightly shorter: if (info.isVirtual == null) { info.isVirtual = ClassTypeHelper.isVirtual(info.method); } return info.isVirtual;
Source:
protected Notifier getNotifierFromEditorInput(Object editorInput) { Object input = editorInput; if (input instanceof RootObject) { final EObject root = ((RootObject) input).getRoot(); if (root.eResource() != null) { input = root.eResource(); } else { input = root; } } if (!Notifier.class.isInstance(input)) { throw new IllegalStateException("The editor input is not a Notifier!"); //$NON-NLS-1$ } return (Notifier) input; }

Target:
In what case would there ever not be a resource? And we weren't previously setting the resource as input. Can this change break existing clients of the GenericEditor class, especially subclasses?
Source:
private org.eclipse.equinox.p2.repository.spi.RepositoryReference toSpiRepositoryReference(RepositoryReference rr) { return new org.eclipse.equinox.p2.repository.spi.RepositoryReference(URI.create(rr.getLocation()), rr.getName(), IRepository.TYPE_METADATA, rr.isEnable() ? IRepository.ENABLED : IRepository.NONE); }

Target:
could be static.
Source:
private Set<InferenceVariable> getInferenceVariables(ParameterizedTypeBinding parameterizedType) { final Set<InferenceVariable> inferenceVariables = new LinkedHashSet<>(); for(int i=0;i<parameterizedType.arguments.length;i++) { final TypeBinding argument = parameterizedType.arguments[i]; argument.collectInferenceVariables(inferenceVariables); } return inferenceVariables; }

Target:
For each loop?
Source:
private boolean reportInternalServerErrorOverSideband() throws IOException { @SuppressWarnings("resource" /* java 7 */) SideBandOutputStream err = new SideBandOutputStream( SideBandOutputStream.CH_ERROR, SideBandOutputStream.SMALL_BUF, rawOut); err.write(Constants.encode(JGitText.get().internalServerError)); err.flush(); return true; }

Target:
Does this method still need to return a boolean type, now that it always returns true?
Source:
public TmfExperiment(final Class<? extends ITmfEvent> type, final String path, final ITmfTrace[] traces, final int indexPageSize, final @Nullable IResource resource) { initExperiment(type, path, traces, indexPageSize, resource, null); }

Target:
shouldn't we pass TmfTraceType.DEFAULT_EXPERIMENT_TYPE instead?
Source:
public boolean contains(Object o) { return fInnerElements.containsValue(o); }

Target:
Should we make special code for null (maybe by comparing size of this vs. size of hash map).
Source:
protected void setResult(Collection<T> newUserSelection) { if (newUserSelection == null) { result = null; } else { result = newUserSelection; } }

Target:
The if and else blocks are unnecessary, you could just write "result = newUserSelection"
Source:
public T getFirstResult() { Collection<T> list = getResult(); if (list == null) { return null; } Iterator<T> iterator = list.iterator(); if (iterator.hasNext()) { return iterator.next(); } return null; }

Target:
For new API I'd prefer to return an java.util.Optional<T> instead of null to avoid potential NPEs.
Source:
protected void setResult(Collection<T> newUserSelection) { if (newUserSelection == null) { result = Collections.emptyList(); } else { result = newUserSelection; } }

Target:
simply do "result = newUserSelection" here because the changed getResult() mehtod, which will manage the null
Source:
protected void setResult(T... newUserSelection) { if (newUserSelection == null) { result = Collections.emptyList(); } else { result = Arrays.asList(newUserSelection); } }

Target:
Simply set the result to null here
Source:
public boolean supportsAtomicCreateNewFile() { if (supportsAtomicCreateNewFile == AtomicFileCreation.UNDEFINED) { determineAtomicFileCreationSupport(); if (supportsAtomicCreateNewFile == AtomicFileCreation.UNDEFINED) { supportsAtomicCreateNewFile = AtomicFileCreation.SUPPORTED; } } return supportsAtomicCreateNewFile == AtomicFileCreation.SUPPORTED; }

Target:
I wonder if it's better to move this into the determineAtomicFileCreationSupport method? At the moment the only caller is here (L360) but if in future it gets called from somewhere else, this patch won't be effective.
Source:
public void traceClosed(@Nullable TmfTraceClosedSignal signal) { if (signal == null || signal.getTrace() != fTrace) { return; } // Reset the internal data fTrace = null; Runnable r = this::reset; // Make sure that runnable is called from UI thread if (Display.getCurrent() == null) { Display d = Display.getDefault(); if (!d.isDisposed()) { d.asyncExec(r); } } else { r.run(); } }

Target:
Not necessary, the signal should be sent from UI thread.
Source:
private GitModelObject[] createChildren() { FileModelFactory fileModelFactory = new FileModelFactory() { @Override public GitModelBlob createFileModel(GitModelObjectContainer parent, Repository repository, Change change, IPath fullPath) { return new GitModelBlob(parent, repository, change, fullPath); } @Override public boolean isWorkingTree() { return false; } }; TreeModelFactory treeModelFactory = GitModelTree::new; return TreeBuilder.build(this, repo, commit.getChildren(), fileModelFactory, treeModelFactory); }

Target:
Use GitModelTree::new here directly and remove the local variable treeModelFactory altogether.
Source:
private Property toProperty(@NonNull String value) { switch (value) { case "hasStagedChanges": //$NON-NLS-1$ return Property.HAS_STAGED_CHANGES; case "hasUnstagedChanges": //$NON-NLS-1$ return Property.HAS_UNSTAGED_CHANGES; case "hasNotIgnoredResources": //$NON-NLS-1$ return Property.HAS_NOT_IGNORED_RESOURCES; case "hasTrackedResources": //$NON-NLS-1$ return Property.HAS_TRACKED_RESOURCES; default: break; } return null; }

Target:
Simply default: return null; and removing line 129 would be a bit shorter and more regular.
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof ConnectionEndpoint)) { return false; } ConnectionEndpoint other = (ConnectionEndpoint) obj; return Arrays.equals(fAddress, other.fAddress) && fPort == other.fPort; }

Target:
this is redundant with next instanceof check
Source:
public boolean isSameValue(ICPPTemplateArgument arg) { return arg.isTypeValue() && fType.isSameType(arg.getTypeValue()); }

Target:
To answer your question: I don't think so. I think there could be legitimate reasons to compare type and non-type template arguments. Thinking of an example is somewhat tricky, but perhaps something like this: template <typename T> void foo(); // Overload on template parameter kind. That's valid. template <int I> void foo(); template <typename T> auto bar() -> decltype(foo<T>()); // Declaration matching code will need to compare // template argument lists <T> and <T()> to determine // if this is a redeclaration or an overload. template <typename T> auto bar() -> decltype(foo<T()>());
Source:
public ImageDescriptor getImageDescriptorForProgram(String extension) { ImageDescriptor imageDescriptor = getImageRegistry().getDescriptor(extension); if (imageDescriptor == null && extension != null) { Program program = ProgramFinder.findProgram(extension.toLowerCase()); if (program == null || program.getImageData() == null) { // provide no image (i.e. leave null) } else { imageDescriptor = ImageDescriptor.createFromImageData(program.getImageData()); getImageRegistry().put(extension, imageDescriptor); } } return imageDescriptor; }

Target:
Perform this operation in the custom ProgramFinder.findProgram() method instead.
Source:
public ImageDescriptor createImageDescriptor() { Program program = ProgramFinder.findProgram(extension.toLowerCase()); if (program == null || program.getImageData() == null) { return null; } return ImageDescriptor.createFromImageData(program.getImageData()); }

Target:
Perform this operation in the custom ProgramFinder.findProgram() method instead.
Source:
public boolean hasTimeEvents() { return fModel instanceof ITimeGraphEntryModel ? ((TimeGraphEntryModel) fModel).hasRowModel() : true; }

Target:
I would have thought that if it's not a ITimeGraphEntryModel then it doesn't have a row model? If it does, then why is it not a ITimeGraphEntryModel? Cast should be to ITimeGraphEntryModel.
Source:
public long nanosToCycles(long nanos) { // CTFTrace subtracts the clock offset in cycles from the output CTFTrace trace = fTrace; if (trace != null) { return trace.timestampNanoToCycles(nanos - trace.getClock().getClockOffsetNs()) + trace.getOffset(); } return 0; }

Target:
This method is a simple converter that is only dependent on frequency and not dependent on clock offset. It should return nanos * clock.getAntiScale(), or nanos if clock is null.
Source:
private void setOptionalDependencies(TargetPlatformConfiguration result, Xpp3Dom resolverDom) { String value = getStringValue(resolverDom.getChild("optionalDependencies")); if (null == value) { return; } else switch (value) { case OPTIONAL_RESOLUTION_REQUIRE: result.setOptionalResolutionAction(OptionalResolutionAction.REQUIRE); break; case OPTIONAL_RESOLUTION_IGNORE: result.setOptionalResolutionAction(OptionalResolutionAction.IGNORE); break; default: throw new BuildFailureException("Illegal value of <optionalDependencies> dependency resolution parameter: " + value); } }

Target:
Same thing as in other class, it'd be better to invert the condition for readability.
Source:
public void testReWriteArtifactViaStreamFails() throws Exception { ProvisionException expectedException = null; try { try (OutputStream addSink = subject.getOutputStream(ARTIFACT_A_CANONICAL)) { addSink.write(new byte[1]); } } catch (ProvisionException e) { expectedException = e; } assertThat(expectedException, is(instanceOf(ProvisionException.class))); assertThat(expectedException.getStatus().getCode(), is(ProvisionException.ARTIFACT_EXISTS)); }

Target:
style nit: tabs vs spaces, inconsistent with surrounding code
Source:
public static synchronized void dispose() { ScriptingDataProviderManager manager = INSTANCE; if (manager != null) { TmfSignalManager.deregister(manager); manager.fInstances.clear(); } INSTANCE = null; }

Target:
Move inside if statement
Source:
private void disposeToolBarElement(ToolBarManager parentManager, MToolBarElement toolBarElement) { IContributionItem ici = getContribution(toolBarElement); if (ici == null) { return; } parentManager.remove(ici); ici.dispose(); clearModelToContribution(toolBarElement, ici); }

Target:
Shouldn't we dispose ici as last step?
Source:
public void testDynamicItem_AddOne() { contextRule.createAndRunWorkbench(window); ToolBarManager tbm = getManager(toolBar); assertTrue(tbm.getSize() == 0); MToolItem toolItem1 = ems.createModelElement(MDirectToolItem.class); toolBar.getChildren().add(toolItem1); assertTrue(tbm.getSize() == 1); }

Target:
It makes sense to use assertEquals here and below, to see the actual value in the failing case
Source:
public TagOperation(Repository repo, TagBuilder tag, boolean shouldMoveTag) { this.tag = tag; this.repo = repo; this.shouldMoveTag = shouldMoveTag; this.annotated = true; }

Target:
while that pattern can be found quite often in the egit sources, it's code duplication for me. I'm a big fan of just one implemented constructor and constructor chaining. Call the other constructor from this one please.
Source:
public void execute(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, 2); progress.setTaskName(NLS.bind(CoreText.TagOperation_performingTagging, tag.getTag())); ObjectId tagId = !annotated ? tag.getObjectId() : updateTagObject(); progress.worked(1); updateRepo(tagId); progress.worked(1); }

Target:
please invert the conditional operator to get rid of the negation
Source:
public int getInt(String key) throws NumberFormatException { String setting = items.get(key); if (setting == null) { // Integer.valueOf(null) will throw a NumberFormatException and // meet our spec, but this message is clearer. throw new NumberFormatException( "There is no setting associated with the key \"" + key + "\"");//$NON-NLS-1$ //$NON-NLS-2$ } return Integer.valueOf(setting).intValue(); }

Target:
Not an exception
Source:
private static void runInCurrentThread(IRunnableWithProgress runnable, IProgressMonitor progressMonitor) throws InterruptedException, InvocationTargetException { try { if (runnable != null) { runnable.run(progressMonitor); } } catch (InvocationTargetException | InterruptedException | ThreadDeath e) { // Make sure to propagate ThreadDeath, or threads will never fully // terminate. throw e; }catch (OperationCanceledException e) { throw new InterruptedException(); } catch (RuntimeException | Error e) { throw new InvocationTargetException(e); } }

Target:
space before catch
Source:
public static boolean isTarFile(String fileName) { if (fileName.length() == 0) { return false; } TarFile tarFile = null; try { tarFile = new TarFile(fileName); } catch (TarException | IOException tarException) { return false; } finally { if (tarFile != null) { try { tarFile.close(); } catch (IOException e) { // ignore } } } return true; }

Target:
rename exception
Source:
public Expression create(ExpressionConverter converter, IConfigurationElement element) { String name = element.getName(); if (name==null) return null; switch (name) { case HasFileExpression.TAG: return new HasFileExpression(element); case HasFileRecursivelyExpression.TAG: return new HasFileRecursivelyExpression(element); case HasFileWithSuffixRecursivelyExpression.TAG: return new HasFileWithSuffixRecursivelyExpression(element); case HasFolderExpression.TAG: return new HasFolderExpression(element); default: break; } return null; }

Target:
Use for blocks
Source:
private void copyFiles(File src, File dest) throws IOException { FileOutputStream fos; try (FileInputStream fis = new FileInputStream(src)) { fos = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { fos.write(buffer, 0, length); } } fos.close(); }

Target:
fos can be inside try ()
Source:
public static int positionToDragCursor(int swtPositionConstant) { switch (swtPositionConstant) { case SWT.LEFT: return LEFT; case SWT.RIGHT: return RIGHT; case SWT.TOP: return TOP; case SWT.BOTTOM: return BOTTOM; case SWT.CENTER: return CENTER; } return INVALID; }

Target:
and default ?
Source:
public void refresh() { fCategoryViewer.setInput(fModel); super.refresh(); }

Target:
Is this necessary? It causes the tree to collapse.
Source:
public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null) { return false; } if (obj instanceof ReferenceBindingSetWrapper) { ReferenceBindingSetWrapper other = (ReferenceBindingSetWrapper) obj; return identityEqual(this.referenceBinding, other.referenceBinding); } return false; }

Target:
I see that the only reason for this is the compiler error created: The uninterned types ReferenceBinding and ReferenceBinding should not be compared using ==/!= operators. See discussion here https://bugs.eclipse.org/bugs/show_bug.cgi?id=417803 Not sure if it is safe what we are doing here.
Source:
private boolean contains(CodeSource codeSource) { if (codeSource == null) return false; URL url = codeSource.getLocation(); if (url == null) return false; // Check to see if this URL is in our set of URLs to give AllPermissions to. for (URL url1 : urls) { // We do simple equals test here because we assume the URLs will be the same objects. if (url1 == url) { return true; } } return false; }

Target:
rename this url variable to location and then simply use the variable name url in the foreach loop below
Source:
private void writeList(DataOutputStream out, String[] list) throws IOException { if (list == null) { out.writeInt(0); } else { out.writeInt(list.length); for (String list1 : list) { writeStringOrNull(list1, out); } } }

Target:
rename to s or string
Source:
public String toString() { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < this.size; i++) { buffer.append(CharOperation.toString(this.elements[i])).append("\n"); //$NON-NLS-1$ } return buffer.toString(); }

Target:
If Lars would see it, he would cry. How could you even think about using StringBuffer in 21 century? (I know, copy/paste).
Source:
public Position cursorPosition() { return syncExec(new Result<Position>() { @Override public Position run() { widget.setFocus(); int offset = widget.getSelectionRange().x; int line = widget.getContent().getLineAtOffset(offset); int offsetAtLine = widget.getContent().getOffsetAtLine(line); int column = offset - offsetAtLine; return new Position(line, column); } }); }

Target:
I think that using the start of selection was just wrong. I would have no problem to use the caret position for this one too as part of the bug fix. Then the implementation could just be to call cursorPosition(false).
Source:
protected static ILaunchConfiguration findLaunchConfiguration(String name) throws CoreException { ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfiguration[] launchConfigurations = launchManager.getLaunchConfigurations(); for (ILaunchConfiguration lConf : launchConfigurations) { if (lConf.getName().equals(name)) { return lConf; } } return null; }

Target:
rename to conf/config
Source:
public Color getForeground(Object element, int columnIndex) { String legendItemText = (String) element; if (legendItemText.equals("Population > 1,000,000") | legendItemText.equals("Population > 50,000")) { return Display.getCurrent().getSystemColor(SWT.COLOR_WHITE); } return null; }

Target:
I guess || should be used here
Source:
public void register() { Chart chart = getChart(); chart.getPlotArea().addMouseTrackListener(this); chart.getPlotArea().addMouseMoveListener(this); chart.getPlotArea().addPaintListener(this); fTooltipHandler.activateHoverHelp(chart.getPlotArea()); }

Target:
remove
Source:
public void deregister() { Chart chart = getChart(); if ((chart != null) && !chart.isDisposed()) { chart.getPlotArea().removeMouseTrackListener(this); chart.getPlotArea().removeMouseMoveListener(this); chart.getPlotArea().removePaintListener(this); fTooltipHandler.deactivateHoverHelp(chart.getPlotArea()); } }

Target:
remove
Source:
public Saveable[] getSaveables() { if (!hasSaveablesProvider()) { IEditorPart saveablePart = getSite().getPage().getActiveEditor(); return saveablePart instanceof ISaveablesSource ? ((ISaveablesSource) saveablePart).getSaveables() : new Saveable[] { new DefaultSaveable(saveablePart) }; } return super.getSaveables(); }

Target:
Case of null should return an empty array.
Source:
private URI resolve(IResourceLocator locator) { String attributeDataPath = getAttributeDataPath(); StringBuilder builder = new StringBuilder(attributeDataPath); String rawPath = locator.getRawPath(); builder.append(rawPath); String pathname = builder.toString(); // Default db/attr to workspace if this is developer's runtime if (pathname.contains("workspace")) { pathname = pathname.replaceAll("\\\\", "/"); pathname = pathname.replaceFirst("file:", ""); } File file = new File(pathname); return file.toURI(); }

Target:
lines 82 to 86 collapse to: String pathname = attributeDataPath + locator.getRawPath();
Source:
public void setImage (Image image) { checkWidget (); if ((style & SWT.SEPARATOR) != 0) return; if (image != null && image.isDisposed()) error(SWT.ERROR_INVALID_ARGUMENT); this.image = image; updateStyleBits(false); OS.InvalidateRect (handle, null, true); }

Target:
With the proposed change: updateStyleBits(image == null)
Source:
public AttributeEntryModel(long id, long parentId, String name, long start, long end, int quark) { super(id, parentId, name, start, end, true); fQuark = quark; }

Target:
Since you use builders and you may not want to have external code create new entries, just use the content, you can make the constructor private or protected.
Source:
public void setVisible(final boolean visible) { super.setVisible(visible); fIsVisible = visible; if (visible) { getContainer().getShell().getDisplay().asyncExec(() -> updateViewer()); } else { getElementViewer().setInput(null); } }

Target:
can this be a method reference?
Source:
public void setUp() throws Exception { IEclipseContext context = E4Application.createDefaultContext(); modelService = context.get(EModelService.class); editor = modelService.createModelElement(MPart.class); editor.setElementId(DUMMY_EDITOR_ID); editor.getTags().add("Editor"); }

Target:
I think we don't need this, because the EModelService is injected via WorkbenchContextRule
Source:
private String getGitPath(IFileRevision revision) { if (revision instanceof CommitFileRevision) { return ((CommitFileRevision) revision).getGitPath(); } IResourceVariant variant = Adapters.adapt((revision), IResourceVariant.class); if (variant instanceof GitRemoteResource) { return ((GitRemoteResource) variant).getPath(); } return null; }

Target:
Extra parentheses could go away, too.
Source:
private boolean sameCommit(RevCommit a, RevCommit b) { // Reference comparison is intentional; BlameGenerator uses a single // RevWalk which caches the RevCommit objects, and if a given commit // is cached the RevWalk returns the same instance. return a == b; }

Target:
this method can be made static
Source:
private void setListForWhiteSelection(Object treeElement) { List listItemsChecked = new ArrayList(); java.util.Collections.addAll(listItemsChecked, listContentProvider.getElements(treeElement)); checkedStateStore.put(treeElement, listItemsChecked); }

Target:
Maybe directly add to contructor here? List listItemsChecked = new ArrayList(Arrays.asList(listContentProvider.getElements(treeElement)));
Source:
public IterateExpression(Element element) throws CoreException { String opValue= element.getAttribute(ATT_OPERATOR); initializeOperatorValue(opValue.isEmpty() ? opValue : null); String ifEmpty= element.getAttribute(ATT_IF_EMPTY); initializeEmptyResultValue(ifEmpty.isEmpty() ? null : ifEmpty); }

Target:
bug
Source:
public void initializeDefaultPreferences() { IEclipsePreferences node = DefaultScope.INSTANCE .getNode(CodanCorePlugin.getDefault().getBundle().getSymbolicName()); node.putBoolean(PreferenceConstants.P_RUN_ON_BUILD, true); node.putBoolean(PreferenceConstants.P_RUN_IN_EDITOR, true); node.putBoolean(PreferenceConstants.P_USE_PARENT, true); }

Target:
Setting this to true initially won't have any effect because the codan builder is added when the property changes, see BuildPropertyPage. I'm also not sure we should impose such a big change in behavior.
Source:
protected void setSelectionToWidget(ISelection selection, boolean reveal) { if (selection instanceof ITreeSelection) { ITreeSelection treeSelection = (ITreeSelection) selection; setSelectionToWidget(new ArrayList<Object>(Arrays.asList(treeSelection.getPaths())), reveal); } else { super.setSelectionToWidget(selection, reveal); } }

Target:
this change does not seem to be needed it would create 2 lists, where just an array-to-list conversion is needed
Source:
public void testBug548456_concurrentElementInfoAccess() throws Exception { int iterations = 20; int numberOfThreads = 2; for (int i = 0; i < iterations; ++i) { doTestBug548456_concurrentCallBinaryTypeExists(numberOfThreads); } }

Target:
with 10 threads I can almost always reproduce the bug.
Source:
private MethodInvocation createStandaloneJ7HashCall() { MethodInvocation j7Invoc= fAst.newMethodInvocation(); for (IVariableBinding fField : fFields) { j7Invoc.arguments().add(fAst.newSimpleName(fField.getName())); } j7Invoc.setExpression(getQualifiedName(JAVA_UTIL_OBJECTS)); j7Invoc.setName(fAst.newSimpleName(METHODNAME_HASH)); return j7Invoc; }

Target:
rename to field
Source:
private void delete(File file) { if (file.isDirectory()) { for (File listFile : file.listFiles()) { delete(listFile); } } file.delete(); }

Target:
rename to f
Source:
private RefactoringStatus checkAbstractMembersInDestinationClasses(IMember[] membersToPushDown, IType[] destinationClassesForAbstract) throws JavaModelException { RefactoringStatus result= new RefactoringStatus(); IMember[] abstractMembersToPushDown= getAbstractMembers(membersToPushDown); for (IType t : destinationClassesForAbstract) { result.merge(MemberCheckUtil.checkMembersInDestinationType(abstractMembersToPushDown, t)); } return result; }

Target:
rename to type
Source:
private static void findFiles(IResource resource, List<IResource> files) throws CoreException { if (resource instanceof IFile) { files.add(resource); return; } if (resource instanceof IContainer) { for (IResource resource1 : ((IContainer) resource).members()) { findFiles(resource1, files); } } }

Target:
rename to res
Source:
private static String getTracePath(String projectName, String traceName, Boolean isExperiment) { String separator = "/"; //$NON-NLS-1$ StringJoiner filePath = new StringJoiner(separator, separator, separator); filePath.add(projectName); String childrenName = isExperiment ? "Experiments" : "Traces"; //$NON-NLS-1$ //$NON-NLS-2$ filePath.add(childrenName); filePath.add(traceName); return filePath.toString(); }

Target:
String.valueOf(filePath) is equivalent and nonNull, it will remove a warning
Source:
public int getMarks(TreeWalk walk) throws MissingObjectException, IncorrectObjectTypeException, IOException { int marks = 0; for (int index = 0; index < filters.length; index++) { TreeFilter filter = filters[index]; if (filter != null) { try { boolean marked = filter.include(walk); if (marked) marks |= (int) (1L << index); } catch (StopWalkException e) { // Don't check tree filter anymore, it will no longer // match filters[index] = null; } } } return marks; }

Target:
Instead of casting can't we just omit the "L"?
Source:
public boolean isDecorationReady(Object element, IDecorationContext context) { // the decoration is only reported as ready, if we are in the UI thread and if // the update job is running. // Because the update job is running in the UI thread, it can be the only caller // of this method if the flag isUpdateJobRunning is TRUE if (isUpdateJobRunning.get()) { return internalGetResult(element, context) != null; } // in all other cases, some other logic than the update job is asking and that // should always be answered with false - see Bug 417255 return false; }

Target:
this is always called on the UI, so I would replace the threadlocal with a simple boolean
Source:
public void addStream(long id, File streamFile) throws CTFException { final File file = streamFile; if (file == null) { throw new CTFException("cannot create a stream with no file"); //$NON-NLS-1$ } ICTFStream stream = fStreams.computeIfAbsent(id, k -> new CTFStream(this)); if (stream instanceof CTFStream) { CTFStream ctfStream = (CTFStream) stream; ctfStream.addInput(new CTFStreamInput(stream, file)); } else { throw new CTFException("Stream does not support adding input"); //$NON-NLS-1$ } }

Target:
method ref?
Source:
public StringFieldEditor(String name, String labelText, int width, int strategy, Composite parent) { init(name, labelText); widthInChars = width; setValidateStrategy(strategy); isValid = false; errorMessage = JFaceResources .getString("StringFieldEditor.errorMessage");//$NON-NLS-1$ createControl(parent); }

Target:
I suggest you invoke `this(name, labelText, wight, 1, strategy, parent)` here.
Source:
public static void touch(Path f) throws IOException { try (FileChannel fc = FileChannel.open(f, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.SYNC)) { Files.setLastModifiedTime(f, FileTime.from(Instant.now())); } }

Target:
Now Andrey's question about clock sync between NFS and the machine this Java code runs on becomes relevant?
Source:
protected void doExecute() { if (representationDescriptor != null) { representationDescriptor.setName(newName); representationDescriptor.setName(newName); } }

Target:
to remove. Same line as above :)
Source:
private static List<IProject> getSelectedProjects(ISelection selection) { List<IProject> projectSelection = new ArrayList<>(); if (selection instanceof IStructuredSelection) { for (Object element : ((StructuredSelection) selection).toList()) { if (element instanceof AutomationSystem) { projectSelection.add(((AutomationSystem) element).getProject()); } } } return projectSelection; }

Target:
same question here: is this limitation to AutomationSystem wanted nad/or necessary? What if a user has also other types of projects open, e.g. as part of a research prototype?
Source:
public static boolean openRenameWizard(String newName, IStructuredSelection structuredSelection) { Map<String, Object> commandParameters = Collections.emptyMap(); commandParameters.put(LTK_RENAME_COMMAND_NEWNAME_PARAMETER_KEY, newName); return runCommand(LTK_RENAME_ID, structuredSelection, commandParameters); }

Target:
This is not legal: collections.emptyMap returns a non-modifiable empty map (and always the very same empty map). Invoking .put on it should fail. For maps with a single element, use Collections.singletonMap(...). It also return a non-modifiable map. Note that this is highlighting an trap in the Java language and API.
Source:
public int hashCode() { return Objects.hash(fEntry, fTime, fDuration, fValue); }

Target:
Active properties are ignored.
Source:
private boolean isFileKeyChanged(Object currFileKey) { boolean changed = currFileKey != MISSING_FILEKEY && !currFileKey.equals(fileKey); LOG.debug("file={}, FileKey changed from to {}", //$NON-NLS-1$ file, fileKey, currFileKey); return changed; }

Target:
Should this be enclosed in "if (changed)" like in the following method?
Source:
private void start() { if (!control.isDisposed()) { if (control instanceof Text) { ((Text) control).addVerifyListener(this); } else if (control instanceof Combo) { ((Combo) control).addVerifyListener(this); } } }

Target:
how can this happen? and should we check for null like in stop?
Source:
public void dispose() { if (fOverlayStore != null) { fOverlayStore.stop(); fOverlayStore= null; } for (Image image : colorPreviewImages) { image.dispose(); } super.dispose(); }

Target:
I suggest you reset colorPreviewImages to null after that.
Source:
private void updateAppearanceColorWidgets(String systemDefaultKey) { if (systemDefaultKey == null) { fAppearanceColorDefault.setSelection(false); fAppearanceColorDefault.setVisible(false); fAppearanceColorEditor.getButton().setEnabled(true); } else { boolean systemDefault= fOverlayStore.getBoolean(systemDefaultKey); fAppearanceColorDefault.setSelection(systemDefault); fAppearanceColorDefault.setVisible(true); fAppearanceColorEditor.getButton().setEnabled(!systemDefault); } fAppearanceColorTableViewer.refresh(); }

Target:
Why is this necessary here?
Source:
private void createShowFirstParentOnlyAction() { showFirstParentOnlyAction = new ShowFirstParentOnlyPrefAction(); showFirstParentOnlyAction .setImageDescriptor(UIIcons.FIRST_PARENT_ONLY); showFirstParentOnlyAction .setToolTipText(UIText.GitHistoryPage_showFirstParentOnly); actionsToDispose.add(showFirstParentOnlyAction); }

Target:
why not in the constructor of that action class?
Source:
public void dispose() { super.dispose(); for (IAction action : this.actions) { action.removePropertyChangeListener(listener); } }

Target:
is there any reason for calling super first? I thought calling super.dispose last were a common best practice (unless some of the other code in this dispose method requires some fields to be disposed by such a call before).
Source:
public static Set<String> getPreviousTypeParamNames(List<TypeParameter> typeParams, ASTNode missingNode) { Set<String> previousNames= new HashSet<>(); for (int i = 0; i < typeParams.size(); i++) { TypeParameter curr= typeParams.get(i); if (curr == missingNode) { return previousNames; } previousNames.add('<' + curr.getName().getIdentifier() + '>'); } return previousNames; }

Target:
Foreach?
Source:
public void testRenameSymref() throws IOException { ObjectId id = db.resolve("HEAD"); RefRename r = db.renameRef("HEAD", "KOPF"); assertEquals(IO_FAILURE, r.rename()); }

Target:
unused
Source:
private static MergedReftable merge(byte[]... table) throws IOException { List<ReftableReader> stack = new ArrayList<>(table.length); for (byte[] b : table) { stack.add(read(b)); } return new MergedReftable(stack); }

Target:
remove unthrown exception
Source:
protected void addUserInputPages() { RenameResourceProcessor processor= getRefactoring().getAdapter(RenameResourceProcessor.class); RenameResourceRefactoringConfigurationPage page= new RenameResourceRefactoringConfigurationPage(processor); addPage(page); }

Target:
Is this change necessary? Seems like you're just breaking it up but it's not any different in functionality from how it was before.
Source:
public RenameResourceWizard(IResource resource, String newName) { super(new RenameRefactoring(new RenameResourceProcessor(resource)), DIALOG_BASED_USER_INTERFACE); RenameResourceProcessor fRenameResourceProcessor= (RenameResourceProcessor) ((RenameRefactoring) super.getRefactoring()).getProcessor(); fRenameResourceProcessor.setNewResourceName(newName); setDefaultPageTitle(RefactoringUIMessages.RenameResourceWizard_page_title); setWindowTitle(RefactoringUIMessages.RenameResourceWizard_window_title); }

Target:
you can make it this(resource); fRenameResourceProcessor.setNewResourceName(newName); which would improve factorization
Source:
public RenameResourceWizard(IResource resource, String newName) { this(resource); RenameResourceProcessor fRenameResourceProcessor= (RenameResourceProcessor) ((RenameRefactoring) super.getRefactoring()).getProcessor(); fRenameResourceProcessor.setNewResourceName(newName); setDefaultPageTitle(RefactoringUIMessages.RenameResourceWizard_page_title); setWindowTitle(RefactoringUIMessages.RenameResourceWizard_window_title); }

Target:
You don't need to repeat lines 67, 69 and 70 as this will be invoked by this(resource) : this(...) invokes the other constructor first so no need to repeat it's content.
Source:
public void setNewName(String newName) { this.fRenameResourceProcessor.setNewResourceName(newName); super.setForcePreview(true); super.setForceFinish(true); }

Target:
Instead of calling those 2 setters, you could try invoking `validatePage` which should take care of fixing button enablement.
Source:
public void setNewName(String newName) { this.fRenameResourceProcessor.setNewResourceName(newName); super.setForcePreview(true); super.setForceFinish(true); System.out.println("new name set"); //$NON-NLS-1$ }

Target:
Please don't use System.out in production code ;)