auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Expression getExpressionWithoutParenthezis(Expression expression) { Expression currExpression= expression; while (currExpression instanceof ParenthesizedExpression) { currExpression= ((ParenthesizedExpression) currExpression).getExpression(); } return currExpression; }

Target:
'static' could be added, since it doesn't rely on any particular instance of the class.
Source:
public boolean handleSelection() { try { if (FoundInVersionColumnUI.promptFoundInVersion((TeamWorkFlowArtifact) getArtifact(), VersionReleaseType.UnReleased, VersionLockedType.UnLocked, getRelation())) { notifyXModifiedListeners(); refresh(); return true; } return false; } catch (Exception ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, ex); } return false; }

Target:
Don't think we want to specify UnLocked and UnReleased. We want to be able to select any version.
Source:
public Map<String, Ref> getRefs(String prefix) throws IOException { List<Ref> refs = reftableDatabase.getRefsByPrefix(prefix); RefList.Builder builder = new RefList.Builder(refs.size()); for (Ref r : refs) { builder.add(r); } return new RefMap(prefix, builder.toRefList(), RefList.emptyList(), RefList.emptyList()); }

Target:
missing type parameter causing warnings: RefList.Builder<Ref> builder = new RefList.Builder<>(refs.size());
Source:
private void updateSslVerifyUser(boolean value) { StoredConfig userConfig = null; try { userConfig = SystemReader.getInstance().getUserConfig(); updateSslVerify(userConfig, value); } catch (IOException | ConfigInvalidException e) { // Log it, but otherwise ignore here. LOG.error(MessageFormat.format(JGitText.get().userConfigInvalid, userConfig, e)); } }

Target:
Hm. We need to think a bit more about exception handling and how to report which config was invalid. Here in any case userConfig is always null. I think the ConfigInvalidException's message would include the file name.
Source:
public HttpConfig(URIish uri) { StoredConfig userConfig = GlobalConfigCache.getInstance() .getUserConfig(); try { userConfig.load(); } catch (IOException | ConfigInvalidException e) { // Log it and then work with default values. LOG.error(MessageFormat.format(JGitText.get().userConfigFileInvalid, userConfig, e)); init(new Config(), uri); return; } init(userConfig, uri); }

Target:
load() not needed anymore, and need to catch RuntimeException.
Source:
public static GlobalConfigCache getInstance() { return INSTANCE.get(); }

Target:
I think the SystemReader should server this cache instance. With two static instances, there is a brief interval in which this cache instance will be the old one while the SystemReader instance will already be the new one. Might be simpler if the two methods getSystemConfig() and getUserConfig() were on SystemReader, without this separate class.
Source:
public StoredConfig getSystemConfig() { if (systemConfig.isOutdated()) { try { LOG.debug("loading system config {}", //$NON-NLS-1$ systemConfig); systemConfig.load(); } catch (IOException e) { throw new RuntimeException(e); } catch (ConfigInvalidException e) { throw new RuntimeException( MessageFormat.format( JGitText.get().systemConfigFileInvalid, systemConfig.getFile().getAbsolutePath(), e), e); } } return systemConfig; }

Target:
Propagate IOE and ConfigInvalidException instead of translating to RuntimeException? I'm not happy about this translation -- unclear what the effects will be. If you propagate checked exceptions, the caller has to think about what to do with it. Most callers already catch IOE and ConfigInvalidException from load().
Source:
private void add(String... searchStrings) { if (searchStrings != null) { for (String searchString : searchStrings) { if (searchString == null || searchString.isEmpty()) { return; } Node node= root; for (char c : searchString.toCharArray()) { node= node.add(c); } node.match= searchString; } } }

Target:
True, was to thoughtless while inlining...
Source:
protected ConfigurableObject getInputType(Object input) { if (input instanceof EditPart) { input = ((EditPart) input).getModel(); } if (input instanceof ConfigurableObject) { return (ConfigurableObject) input; } return null; }

Target:
why not put this all in one if condition? if (input instanceof EditPart && ((EditPart) input).getModel() instanceof ConfigurableObject)
Source:
public PropertyParameter[] getParameters() { return m_parameters.values().toArray(new PropertyParameter[m_parameters.values().size()]); }

Target:
could we change to List<PropertyParameter> or is this API fixed?
Source:
public StateItem(Map<String, Object> style) { Map<String, Object> styleMap = new HashMap<>(); styleMap.putAll(style); fStyleMap = StylePropertiesUtils.updateEventStyleProperties(styleMap); fOriginalStyleMap = ImmutableMap.copyOf(StylePropertiesUtils.updateEventStyleProperties(styleMap)); }

Target:
can use fStyleMap here
Source:
private void commit(boolean pushUpstream) { boolean reEnable = false; // Don't allow to do anything as long as commit is in progress enableAllWidgets(false); try { boolean jobScheduled = !internalCommit(pushUpstream, () -> enableAllWidgets(true)); // If a job was scheduled, our Runnable will re-enable the widgets // once the commit and push is done; even if it fails. Otherwise, we // must re-enable the widgets here and now ourselves. reEnable = !jobScheduled; } catch (RuntimeException e) { // See bugs 550336, 550513 // If internalCommit() should fail after having scheduled the job, // we may re-enable a little too early. But better that than never. reEnable = true; Activator.handleError(e.getLocalizedMessage(), e, true); } finally { if (reEnable) { enableAllWidgets(true); } } }

Target:
why that ? I think internalCommit() returns true if a job was scheduled
Source:
private String getObjectText(IProductModel obj) { IProduct product = obj.getProduct(); String name = preventNull(product.getId()); if (VersionUtil.isEmptyVersion(product.getVersion())) { return name; } return name + ' ' + formatVersion(product.getVersion()); }

Target:
We have products without an ID in the workspace, we could fallback to the name instead of an empty string.
Source:
public void processQueue() { if (Thread.currentThread() == thread) { throw new IllegalStateException( "Cannot execute this method in the realm's own thread"); } try { synchronized (queue) { doProcess = true; queue.notifyAll(); while (!queue.isEmpty()) { if (!block) throw new IllegalStateException( "Cannot process queue, ThreadRealm is not blocking on its thread"); queue.wait(); } doProcess = false; } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }

Target:
What is this call for? If the queue is not empty then the `block` method should be running already? And if an element is added to the queue then notifyAll is called from that method? Do I miss some case?
Source:
protected boolean handles(EObject owner, EReference reference) { return !(owner instanceof Template) && EcoreUtil.getRootContainer(owner) instanceof TemplateCollection && !reference.isContainment(); }

Target:
A pedant would check the ereference-is-containment before the root container check that navigates the model. :-)
Source:
public boolean isThereAnInternalTraceBetween(EObject first, EObject second) { if (first.equals(second)) { return false; } else if (first instanceof INamed && second instanceof INamed) { if (!first.eCrossReferences().isEmpty() && !second.eCrossReferences().isEmpty()) { if (first.eCrossReferences().contains(second) || second.eCrossReferences().contains(first)) { return true; } } } return false; }

Target:
Can eCrossReferences() ever return null? In that case, we would get an uncaught exception here.
Source:
public boolean isThereAnInternalTraceBetween(EObject first, EObject second) { if (first.equals(second)) { return false; } else if (first instanceof INamed && second instanceof INamed) { if (first.eCrossReferences().contains(second) || second.eCrossReferences().contains(first)) { return true; } } return false; }

Target:
Are these lists always initialised? Might be worthwhile to put in a null check here.
Source:
public void dispose() { historyPage.removePropertyChangeListener(this); if (dialog != null) dialog.close(); }

Target:
missing braces
Source:
public boolean isOnlyHEADSelected(Set<RefFilter> filters) { for (RefFilter filter : filters) { if (filter.isSelected()) { if (!filtersForHEAD.contains(filter)) return false; } else { if (filtersForHEAD.contains(filter)) return false; } } return true; }

Target:
missing braces
Source:
public void dispose() { writeSettings(); LogReaderService[] services = this.logReaderServiceTracker.getServices(new LogReaderService[0]); for (LogReaderService logReaderService : services) { logReaderService.removeLogListener(this); } this.logReaderServiceTracker.close(); fClipboard.dispose(); if (fTextShell != null) fTextShell.dispose(); fLabelProvider.disconnect(this); fFilteredTree.dispose(); super.dispose(); }

Target:
I think ist is enough to close the tracker heres, this will triger "removedService in line 198 and then remove the listeners
Source:
private File getRunDirectory(Repository repository, @NonNull String hookName) { if (repository.isBare()) { return repository.getDirectory(); } else { switch (hookName) { case "pre-receive": //$NON-NLS-1$ case "update": //$NON-NLS-1$ case "post-receive": //$NON-NLS-1$ case "post-update": //$NON-NLS-1$ case "push-to-checkout": //$NON-NLS-1$ return repository.getDirectory(); default: return repository.getWorkTree(); } } }

Target:
remove unnecessary else clause ?
Source:
private static void testPidSorting(final SWTBotTree tree, final SWTBotTimeGraph timeGraph) { SWTBotTreeColumn column = tree.header(PID_COLUMN); String[] expected = { LTTNG_CONSUMER_PROCESS_NAME, KTHREAD_PROCESS_NAME, SYSTEMD_PROCESS_NAME }; /* Sort direction Up */ SWTBotTestCondition condition = getSortCondition(PID_COLUMN, PROCESS_COLUMN_ID, expected, timeGraph, false); clickColumn(tree, column, condition); /* Sort direction Down */ String[] expected2 = { SYSTEMD_PROCESS_NAME, KTHREAD_PROCESS_NAME, LTTNG_CONSUMER_PROCESS_NAME }; condition = getSortCondition(PID_COLUMN, PROCESS_COLUMN_ID, expected2, timeGraph, false); clickColumn(tree, column, condition); }

Target:
If you use here the order of expected2 and below this order, then it's successful.
Source:
public void log(IStatus status) { log(0, status); if (status.isMultiStatus()) { IStatus[] children = status.getChildren(); for (IStatus children1 : children) { log(1, children1); } } }

Target:
child
Source:
public void log(IStatus status) { int severity = status.getSeverity(); // Log the status message log(status.getMessage(), severity); // Log the exception if applicable if (status.getException() != null) log(status.getException().getMessage(), severity); // Log any children of this status IStatus[] nestedStatus = status.getChildren(); if (nestedStatus != null) for (IStatus nestedStatu : nestedStatus) { log(nestedStatu); } }

Target:
better name needed
Source:
protected void writeChildren(URI[] children) { if (children == null || children.length == 0) return; start(CHILDREN_ELEMENT); attribute(COLLECTION_SIZE_ATTRIBUTE, children.length); for (URI children1 : children) { writeChild(children1); } end(CHILDREN_ELEMENT); }

Target:
child
Source:
private boolean fullyDelete(File file) { if (file.isDirectory()) { File[] children = file.listFiles(); if (children != null) { for (File children1 : children) { // we will not stop even if some deletion failed fullyDelete(new File(file, children1.getName())); } } } // will attempt to delete before exists check to get rid of dead links if (file.delete()) { return true; } // will return true if files does not actually exist even delete fails return !file.exists(); }

Target:
child
Source:
public static void deleteDir(File file) throws IOException { if (file.isFile()) { if (!file.delete()) throw new IOException("Fail to delete File(" + file.getAbsolutePath() + ")"); return; } File[] children = file.listFiles(); for (File children1 : children) { deleteDir(children1); } if (!file.delete()) throw new IOException("Fail to delete Dir(" + file.getAbsolutePath() + ")"); return; }

Target:
child
Source:
public boolean applicabilityExistsOnBranchView(BranchId branch, ArtifactId viewId, String applicability) { boolean exists = false; List<GammaId> tuples = new ArrayList<>(); queryFactory.tupleQuery().getTuple2GammaFromE1E2(CoreTupleTypes.ViewApplicability, branch, viewId, applicability, tuples::add); if (!tuples.isEmpty()) { exists = true; } return exists; }

Target:
remove exists variable and just return !tuples.isEmpty();
Source:
protected boolean synchronizeModel(IDocument doc) { if (doc == null) { return false; } IFeatureModel model = (IFeatureModel) getModel(); String text = doc.get(); try (InputStream stream = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8))) { model.reload(stream, false); } catch (CoreException e) { return false; } catch (IOException e) { } return true; }

Target:
should return false also in this case use multi-catch catch (CoreException | IOException e) { return false; }
Source:
public void delete(Collection<RepositoryGroup> groupsToDelete) { for (RepositoryGroup group : groupsToDelete) { preferences .remove(PREFS_GROUP_PREFIX + group.getGroupId().toString()); groupMap.remove(group.getGroupId()); } savePreferences(); }

Target:
No necessary. + operator with a string operand (the prefix) performs auto-stringification of the other operand.
Source:
protected void initialize() { if (fields != null) { Iterator<FieldEditor> e = fields.iterator(); IPreferenceStore pagePreferenceStore = getPreferenceStore(); while (e.hasNext()) { FieldEditor pe = e.next(); pe.setPage(this); pe.setPropertyChangeListener(this); if (pe.getPreferenceStore() == null) { pe.setPreferenceStore(pagePreferenceStore); } pe.load(); } } }

Target:
I think the intention is clearer when you avoid pagePreferenceStore variable and write here: pe.setPreferenceStore(this.getPreferenceStore());
Source:
public ExecuteCliParsersJob(CliCommandLine commandLine) { super("Executing CLI parser"); //$NON-NLS-1$ setSystem(true); fCommandLine = commandLine; }

Target:
System jobs cannot be cancelled by the users. I wonder if we should have as user job so that it could be cancelled using the progress view?
Source:
public static Job getWorkspaceLoadingJob(CliCommandLine commandLine) { ExecuteCliParsersJob job = new ExecuteCliParsersJob(commandLine); return job; }

Target:
return new ExecuteCliParsersJob(commandLine);
Source:
private static P2ResolutionResult singleEnv(Map<TargetEnvironment, P2ResolutionResult> map) { assertEquals(1, map.size()); for (P2ResolutionResult result : map.values()) { return result; } throw new AssertionError("should never happen"); }

Target:
map.entrySet().iterator().next() seems a bit more idiomatic than using a loop with an unconditional return.
Source:
protected boolean hasTextTransform(CSSValue value) { if (value.getCssValueType() == CSSValue.CSS_PRIMITIVE_VALUE) { CSSPrimitiveValue primitiveValue = (CSSPrimitiveValue) value; String textTransform = primitiveValue.getStringValue(); if ("capitalize".equals(textTransform)) { return true; } if ("uppercase".equals(textTransform)) { return true; } if ("lowercase".equals(textTransform)) { return true; } } return false; }

Target:
use switch
Source:
public void disconnect() { Object lock = partitions != null ? partitions : new Object(); synchronized (lock) { document = null; partitions.clear(); try { inputStream.close(); } catch (IOException e) { } } }

Target:
The code is still wrong. One shoulkd never lock on objects that can be null, the check above is not reliable (it can be wrong just after the null check), and locking on a new Object() makes no sense at all - it does not lock *anything*, only the current thread knows the local object instance.
Source:
public boolean shouldRun() { final boolean shouldRun = pendingPartitions != null && pendingPartitions.size() > 0; return shouldRun; }

Target:
that can be null? This means all the locks above can throw NPE? Also accessing this object here without synchronized lock? I don't get what is the strategy is here. Again: object that can be set to null CAN'T BE USED FOR SYNCHRONIZATION. Please either make sure they are never null or use different objects for synchronization.
Source:
public void disconnect() { synchronized (partitions) { synchronized (pendingPartitions) { pendingPartitions.notifyAll(); } trimJob.cancel(); queueJob.cancel(); lld = null; document = null; inputPartitions = null; pendingPartitions.clear(); pendingSize = 0; partitions.clear(); } }

Target:
I'm worrying to see two locks acquired here. Can we first acquire pending partitions, notify and acquire partitions?
Source:
public void clearBuffer() { if (trimJob != null) { trimJob.setOffset(-1); trimJob.schedule(); } }

Target:
I don't see any place that would set trimJob to null. We also access that in other places without null check. So either we null the job somewhere and introduce checks, or remove check here.
Source:
protected void dispose() { super.dispose(); // Get lock on ourself before closing. Closing streams check for console finish. // Finish check need lock on (this) console. Since closing also lock on stream // this can deadlock with other threads (double) closing streams at same time // but already own a lock on console. (bug 551902) // Long story short. Before closing IOConsole...Stream get lock from associated // console to prevent deadlocks. synchronized (this) { // make a copy of the open streams and close them all // a copy is needed as close the streams results in a callback that // removes the streams from the openStreams collection (bug 152794) List<Closeable> list = new ArrayList<>(openStreams); for (Closeable closable : list) { try { closable.close(); } catch (IOException e) { // e.printStackTrace(); } } inputStream = null; } final IDocument document = partitioner.getDocument(); document.setDocumentPartitioner(null); partitioner.disconnect(); }

Target:
Not sure I've mentioned already : it is highly unusual that suoer.dispose() is called *before* the child dispose. Surely not your change, but I wonder if it makes sense to cleanup this too.
Source:
public void connect(IDocument doc) { if (doc == document) { return; } synchronized (partitions) { disconnect(); if (doc != null) { inputPartitions = new ArrayList<>(); document = doc; legalLineDelimiterMatcher = MultiStringMatcher.create(document.getLegalLineDelimiters()); } } }

Target:
does the disconnect() need to be inside the sync block? We are going to acquire another lock while holding partitions lock. Danger!
Source:
protected IShowInTargetList getShowInTargetList() { final String[] targetList= createShowInTargetList(); if (targetList != null && targetList.length > 0) { return () -> targetList; } return null; }

Target:
@since 3.13 missing
Source:
public boolean hasChildren(Object element) { Predicate<Object> predicate = Stream.of(fViewer.getFilters()) .map(filter -> predicateFor(filter, element)) .reduce(t -> true, Predicate::and); return Stream.of(getChildren(element)) .filter(predicate) .findAny() .isPresent(); }

Target:
This is not necessary, you can simply call setExpandPreCheckFilters(true) on the viewer.
Source:
private void finishInternal() { // Ensure task not currently running. if (m_leasedThread.get() != null) { return; } // Ensure task to be in done state, because method also called for periodic tasks which did not complete yet. if (!isDone()) { return; } // Ensure to be called only once (thread safety). if (!m_finished.compareAndSet(false, true)) { return; } finished(); }

Target:
At this point, too, an AtomicReference does not bring any added value compared to a volatile variable.
Source:
public boolean applicabilityExistsOnBranchView(BranchId branch, ArtifactId viewId, String applicability) { List<GammaId> tuples = new ArrayList<>(); queryFactory.tupleQuery().getTuple2GammaFromE1E2(CoreTupleTypes.ViewApplicability, branch, viewId, applicability, tuples::add); return (!tuples.isEmpty()); }

Target:
don't need parens
Source:
private static ILaunchConfigurationWorkingCopy getWorkingCopy(ILaunchConfiguration configuration) throws CoreException { ILaunchConfigurationWorkingCopy wc = null; if (configuration.isWorkingCopy()) { wc = (ILaunchConfigurationWorkingCopy) configuration; } else { wc = configuration.getWorkingCopy(); } return wc; }

Target:
should return directly
Source:
public static boolean isResurrected(ChangeItem changeItem) { // There's a change corresponding to a Deleted Item, item MUST have been resurrected return (changeItem.getBaselineVersion().isValid() && isDeleted( changeItem.getBaselineVersion())) || (changeItem.getChangeType().equals( ChangeType.TUPLE_CHANGE) && changeItem.getDestinationVersion().isValid() && isDeleted( changeItem.getDestinationVersion()) && changeItem.getCurrentVersion().getModType().equals( ModificationType.INTRODUCED)); }

Target:
I don't think this logic should require special support for tuples
Source:
private CloseableHttpResponse get(final HttpGet httpGet) { try { return this.httpclient.execute(httpGet, this.context); } catch (IOException e) { throw new IllegalArgumentException(); } }

Target:
Missing stacktrace
Source:
private CloseableHttpResponse put(final HttpPut httpPut) { try { return this.httpclient.execute(httpPut, this.context); } catch (IOException e) { throw new IllegalArgumentException(); } }

Target:
Missing stacktrace
Source:
private static Image getFBTypeImage(IFile element) { Image image; FBType type = getFBTypeFromFile(element); if (type instanceof BasicFBType) { image = FordiacImage.ICON_BASIC_FB.getImage(); } else if (type instanceof CompositeFBType) { image = FordiacImage.ICON_COMPOSITE_FB.getImage(); } else if (type instanceof ServiceInterfaceFBType) { image = FordiacImage.ICON_SIFB.getImage(); } else { // partly load file to determine type image = checkUnloadedFBType(element); } return image; }

Target:
instead of the pure declaration of image on top, returns for each if body would be nicer imho
Source:
public void handleSchemes(Collection<IScheme> toAdd, Collection<IScheme> toRemove) throws Exception { List<ISchemeInformation> schemesInformation = getSchemesInformation(toAdd); for (ISchemeInformation schemeInformation : schemesInformation) { String handlerInstanceLocation = schemeInformation.getHandlerInstanceLocation(); processExecutor.execute(LSREGISTER, UNREGISTER, handlerInstanceLocation); } String pathToEclipseApp = getPathToEclipseApp(); changePlistFile(toAdd, toRemove, pathToEclipseApp); registerAppWithLsregister(pathToEclipseApp); }

Target:
we by intention did not attempt to modify the info.plist of another app. One has to remove the registration in the other app manually. The platform pref page also provides a hint for the user.
Source:
public void start(BundleContext context) throws Exception { super.start(context); fPlugin = this; try { fCommandLine = CliParserManager.getInstance().parse(Platform.getCommandLineArgs()); } catch (CliParserException e) { logError("Error parsing command line arguments", e); //$NON-NLS-1$ throw e; } }

Target:
Don't throw the exception. It causes a lot of exception stack traces printed on the screen and stored in the .log file. It would be easy for the user to miss the usage message that is printed as well. I suggest, to find a different way to exit the application. Can't you just call CliParserManager.getInstance().parse(Platform.getCommandLineArgs()); in Application.java and exit if needed? I don't see the reason why it's done in the activator class.
Source:
public static void run(Repository repository, Work work) throws IOException { try (ConfigScope scope = new ConfigScope(repository)) { work.execute(); } }

Target:
Maybe it's just confused me, but did you eventually mean to have this and the next static method named exactly the other way around? Right now static run() calls instance execute, and static execute() calls instance run. And to avoid that confusion, would it eventually be possible to name the 2 methods identically? Or does that confuse the compiler? BTW: The class looks even better than I had thought when describing the lambda idea.
Source:
public static String getLineIndentation(IDocument document, int offset) throws BadLocationException { // find start of line int adjustedOffset= (offset == document.getLength() ? offset - 1 : offset); IRegion line= document.getLineInformationOfOffset(adjustedOffset); int start= line.getOffset(); // find white spaces int end= findEndOfWhiteSpace(document, start, offset + line.getLength()); return document.get(start, end - start); }

Target:
Not used outside the class. Can still be private.
Source:
public OwApplicability getOrCreateApplicability(OwArtifact artifact) { OwApplicability app = null; app = artifact.getAppId(); if (app == null) { app = new OwApplicability(); artifact.setAppId(app); } return app; }

Target:
combine these two lines -> OwApplicability app = artifact.getAppId();
Source:
public @Nullable Range getFixedYRange() { return this.fFixedYRange; }

Target:
remove the this here also
Source:
public void setFixedYRange(@Nullable Range fixedYRange) { this.fFixedYRange = fixedYRange; this.updateContent(); }

Target:
how about calling this "fixRange(boolean fixed)" and then override the getWindowRange()? Just a thought.
Source:
public List<@Nullable Object> getOngoingStateValues() { fRWLock.readLock().lock(); try { return Collections.unmodifiableList(fOngoingStateInfo); } finally { fRWLock.readLock().unlock(); } }

Target:
This returns a view of the transient state that is also transient, e.g. changes to transient state will be visible by the user of this method. I don't know if that's OK? Come to think of it, should all the queryOngoing*() methods have been in ITmfStateSystemBuilder instead of ITmfStateSystem?
Source:
public BreakpointContainer[] getRoots(IBreakpoint breakpoint) { if (isShowingGroups()) { List<BreakpointContainer> list = new ArrayList<>(); for (Object fElement : fElements) { BreakpointContainer container = (BreakpointContainer) fElement; if (container.contains(breakpoint)) { list.add(container); } } return list.toArray(new BreakpointContainer[list.size()]); } return null; }

Target:
rename to element
Source:
private void setSearchFilter(String string) { if (patternFilter == null) { patternFilter = new TypeListPatternFilter(); commonViewer.addFilter(patternFilter); } patternFilter.setPattern(string); commonViewer.refresh(false); handleTreeExpansion(string); }

Target:
this should be: null == patternFilter
Source:
public void run() { if (fBreakpoints != null) { for (BreakpointSetElement fBreakpoint : fBreakpoints) { fBreakpoint.container.getOrganizer().removeBreakpoint(fBreakpoint.breakpoint, fBreakpoint.container.getCategory()); } } }

Target:
rename to breakpoint
Source:
public boolean isItemVisible(VirtualItem item) { // visible items. For now only mark the selected items as visible. for (VirtualItem element : fSelection) { VirtualItem selectionItem = element; while (selectionItem != null) { if (item.equals(selectionItem)) { return true; } selectionItem = selectionItem.getParent(); } } return false; }

Target:
use as loopvar?
Source:
public void setup() { Link link = new Link(new Shell(), SWT.NONE); event = new HyperlinkEvent(link, "uri://test", "link", 0); linkEventConsumer = new HyperlinkEventConsumer(); }

Target:
shell should be disposed in teardown
Source:
public synchronized IPath[] getPaths() { List<IPath> result = new ArrayList<>(); for (Object element : objects.keySet()) { IPath path = (IPath) element; Node node = getNode(path); if (node.getPayload() != null) result.add(path); } return result.toArray(new IPath[result.size()]); }

Target:
to loop var; objects is typed
Source:
public synchronized Collection<Object> values() { List<Object> result = new ArrayList<>(); for (Object element : objects.keySet()) { IPath path = (IPath) element; Node node = getNode(path); if (node.getPayload() != null) result.add(node.getPayload()); } return result; }

Target:
to loop var
Source:
public boolean ruleContains(IResource resource) { for (Object element : rules) { ISchedulingRule rule = (ISchedulingRule) element; if (rule != NULL_SCHEDULING_RULE && rule.contains(resource)) { return true; } } return false; }

Target:
to loop var
Source:
private boolean isDescendantOfAddedRoot(IResource resource) { for (Object element : addedSubtrees) { IResource root = (IResource) element; if (isParent(root, resource)) { // There is a higher added root already in the list return true; } } return false; }

Target:
to loop var
Source:
private void applyDiff(MapDiff<? extends K, ? extends V> diff, Map<K, V> map) { for (K name : diff.getRemovedKeys()) map.remove(name); for (K key : diff.getChangedKeys()) { map.put(key, diff.getNewValue(key)); } for (K key : diff.getAddedKeys()) { map.put(key, diff.getNewValue(key)); } }

Target:
rename to key
Source:
public void setGlobalEntries(IAntClasspathEntry[] entries) { if (fUserGlobalEntry == null) { String name = AntPreferencesMessages.ClasspathModel_3; fUserGlobalEntry = createGlobalEntry(entries, name, true, true, GLOBAL_USER); } else { fUserGlobalEntry.removeAll(); for (IAntClasspathEntry entrie : entries) { fUserGlobalEntry.addEntry(new ClasspathEntry(entrie, fUserGlobalEntry)); } } }

Target:
rename to entry
Source:
public void isGitRepository() { assertTrue(new File(db.getDirectory(), "HEAD").delete()); assertTrue(RepositoryCache.FileKey.isGitRepository(db.getDirectory(), db.getFS())); }

Target:
Why does a repository converted to reftable contain .git/HEAD ? Shouldn't that be deleted by convertToReftable() ?
Source:
public void isGitRepository() throws IOException { assertTrue(new File(db.getDirectory(), "HEAD").delete()); assertTrue(RepositoryCache.FileKey.isGitRepository(db.getDirectory(), db.getFS())); }

Target:
This exception is not thrown, which causes the compilation failure: org.eclipse.jgit.test/tst/org/eclipse/jgit/internal/storage/file/FileReftableTest.java:[507,17333] The declared exception IOException is not actually thrown by the method isGitRepository() from type FileReftableTest
Source:
public long getNotificationCount() { return adapter.map(ad -> ad.getNotificationCount()).orElse(0l); }

Target:
why 0l? that could even be taken as a legitimate notification count. Or, with many fonts, misread as 01 (zero one) Instead, we could return a public static final long NOT_ATTACHED = -1l;
Source:
private static void clearPrefixedSystemProperties(String prefix, Map<String, String> targetPropertyMap) { for (Object element : System.getProperties().keySet()) { String propertyName = (String) element; if (propertyName.startsWith(prefix) && !targetPropertyMap.containsKey(propertyName)) { targetPropertyMap.put(propertyName, null); } } }

Target:
rename to key
Source:
public void start(@Nullable BundleContext context) throws Exception { super.start(context); plugin = this; // Register CLI parser only if the class exists try { Class.forName("org.eclipse.tracecompass.tracing.rcp.ui.cli.CliParserExtension"); //$NON-NLS-1$ } catch (ClassNotFoundException e) { // RCP not loaded return; } }

Target:
class doesn't exist
Source:
public NewSubAppCommand(FBNetwork fbNetwork, List<?> selection, int x, int y) { super(fbNetwork, LibraryElementFactory.eINSTANCE.createSubApp(), x, y); getSubApp().setSubAppNetwork(LibraryElementFactory.eINSTANCE.createFBNetwork()); PositioningUtilities.removeXYOffsetForFBNetwork(selection); addElements = new AddElementsToSubAppCommand(getSubApp(), selection); checkMapping(selection); }

Target:
wouldn't this break undo?
Source:
protected URI[] getSelectedLocations(Object[] selectionArray) { List<URI> urls = new ArrayList<>(); for (Object element : selectionArray) { if (element instanceof MetadataRepositoryElement) urls.add(((MetadataRepositoryElement) element).getLocation()); } return urls.toArray(new URI[urls.size()]); }

Target:
when you are on it: add braces
Source:
protected List<Object> getModelChildren() { ArrayList<Object> elements = new ArrayList<>(); elements.add(new InstanceName(getModel())); elements.addAll(getModel().getInterface().getAllInterfaceElements()); return elements; }

Target:
List<Object>
Source:
private DirectEditManager getManager() { if (manager == null) { manager = createDirectEditManager(); } return manager; }

Target:
null == manager
Source:
public static boolean isSupported(AST ast, int nodeType) { switch (nodeType) { case ASTNode.SWITCH_EXPRESSION: case ASTNode.YIELD_STATEMENT: if (ast.apiLevel() < AST.JLS14_INTERNAL) { return false; } break; case ASTNode.TEXT_BLOCK: return ast.isPreviewEnabled(); } return true; }

Target:
Another nitpick :) this can be replaced by return ast.apiLevel() >= AST.JLS14_INTERNAL
Source:
public static boolean isSupported(AST ast, int nodeType) { switch (nodeType) { case ASTNode.SWITCH_EXPRESSION: case ASTNode.YIELD_STATEMENT: if (ast.apiLevel() < AST.JLS14_INTERNAL) { return false; } break; case ASTNode.TEXT_BLOCK: if (!ast.isPreviewEnabled()) { return false; } } return true; }

Target:
you can as well return ast.isPreviewEnabled() ; However, is there a reason for skipping ast.apiLevel() == AST.JLS14_INTERNAL? [Consider the case where this is called from <14 levels]
Source:
public boolean isPreviewEnabled() { if (this.apiLevel == AST.JLS_Latest && this.previewEnabled) { return true; } return false; }

Target:
nitpick: just return <cond> sufficient
Source:
public boolean getFlag(String flag) { String[] flags = getFlags(); for (String flag2 : flags) { if (flag2.equals(flag)) return true; } return false; }

Target:
rename to f
Source:
void loadFiles () { // BAD - holds on to a lot of memory if (sourcePath == null) return; files = new HashMap<> (); for (String element : sourcePath) { File file = new File(element); if (file.exists()) { if (!file.isDirectory()) { if (file.getAbsolutePath().endsWith(".java")) { files.put(file, loadFile(file)); } } else { loadDirectory(file); } } } }

Target:
rename to path
Source:
protected void fillContentProvider(AbstractContentProvider contentProvider, ItemsFilter itemsFilter, IProgressMonitor progressMonitor) throws CoreException { if(fTypes != null && fTypes.length > 0) { for (IType fType : fTypes) { if (itemsFilter.isConsistentItem(fType)) { contentProvider.add(fType, itemsFilter); } } } }

Target:
rename to type
Source:
private CompletableFuture<List<? extends ICodeMining>> provideCodeMinings(@NonNull IDocument document) { URI docURI = LSPEclipseUtils.toUri(document); if (docURI != null) { CodeLensParams param = new CodeLensParams(new TextDocumentIdentifier(docURI.toString())); return LanguageServiceAccessor .getLanguageServers(document, capabilities -> capabilities.getCodeLensProvider() != null) .thenComposeAsync(languageServers -> getCodeMiningsFromServers(languageServers, document, param)); } else { return null; } }

Target:
This "else" can be removed.
Source:
public TmfGraphBuildRequest(ITmfGraphProvider provider, IProgressMonitor monitor) { super(TmfEvent.class, TmfTimeRange.ETERNITY, 0, ITmfEventRequest.ALL_DATA, ITmfEventRequest.ExecutionType.BACKGROUND); fProvider = provider; long nbEvents = provider.getTrace().getNbEvents(); fEventFactor = nbEvents / DEFAULT_FACTOR; fMonitor = SubMonitor.convert(monitor, DEFAULT_FACTOR + 2); }

Target:
Not sure I get it... For 10,000 events we would call worked(1) exactly 100 times?
Source:
public TmfGraphBuildRequest(ITmfGraphProvider provider, IProgressMonitor monitor) { super(TmfEvent.class, TmfTimeRange.ETERNITY, 0, ITmfEventRequest.ALL_DATA, ITmfEventRequest.ExecutionType.BACKGROUND); fProvider = provider; long nbEvents = provider.getTrace().getNbEvents(); fEventFactor = Math.max(DEFAULT_FACTOR, nbEvents / DEFAULT_FACTOR); fMonitor = SubMonitor.convert(monitor, DEFAULT_FACTOR + 2); }

Target:
This is not correct. I would suggest to have a index i starting at 1, and report 1 unit of work when nbRead > nbEvents*i/factor, incrementing i at the same time. The value of 'factor' should be nbEvents clampled to [1,DEFAULT_FACTOR], in case nbEvents is < DEFAULT_FACTOR or 0. This factor should be the SubMonitor's number of ticks.
Source:
protected GridData newGridData(int span) { GridData data = new GridData(GridData.GRAB_VERTICAL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL); data.horizontalSpan = span; return data; }

Target:
This could be private?
Source:
public Stream<Node> stream() { return Arrays.stream(getComposite().getChildren()).map(control -> getElement(control)); }

Target:
use method reference here?
Source:
public @Nullable Long getTimeForPoint(int x) { return UIThreadRunnable.syncExec((Result<@Nullable Long>) () -> { Rectangle bounds = widget.getBounds(); Point p = new Point(x, bounds.y + bounds.height / 2); if (!bounds.contains(p)) { return null; } return widget.getTimeAtX(x); }); }

Target:
@Nullable forces the test to do a null check, but in a unit test it would be acceptable to fail with a NullPointerException if something is not as expected.
Source:
public RoughToRealVerificationOperation(OrcsApi orcsApi, BranchId branchId, XResultData results, ArtifactReadable destinationArtifact, RoughArtifactCollector rawData, IArtifactImportResolver artifactResolver, boolean deleteUnmatchedArtifacts, IArtifactExtractor extractor) { this.results = results; this.orcsApi = orcsApi; this.branchId = branchId; this.rawData = rawData; this.artifactResolver = artifactResolver; this.destinationArtifact = destinationArtifact; this.roughToRealArtifacts = new HashMap<>(); roughToRealArtifacts.put(rawData.getParentRoughArtifact(), this.destinationArtifact); }

Target:
remove "this"
Source:
int memSize() { // treat Operator as free return BASE_NODE_SIZE + 2 * 4; }

Target:
One more - this will be 3
Source:
protected void addCNature(IProject project, IProgressMonitor monitor, boolean addMakeBuilder) throws CoreException { if (getWizard() instanceof ConversionWizard) { ConversionWizard cw = (ConversionWizard) getWizard(); if (cw.getBuildSystemId() != null) { CCorePlugin.getDefault().convertProjectToNewC(project, cw.getBuildSystemId(), monitor); } else { CCorePlugin.getDefault().convertProjectToC(project, monitor, cw.getProjectID()); } } }

Target:
Sort of the same thing here - this is an unrelated change.
Source:
public void doRun(IProgressMonitor monitor, String projectID) throws CoreException { Object[] selection = getCheckedElements(); int totalSelected = selection.length; if (totalSelected > 0) { if (monitor == null) { monitor = new NullProgressMonitor(); } SubMonitor submonitor = SubMonitor.convert(monitor, 1); submonitor.subTask(CUIPlugin.getResourceString(KEY_TITLE)); convertProjects(selection, submonitor.split(1), projectID); } }

Target:
subtask != task therefore these two lines should be: SubMonitor.convert(monitor, /title/, 1); (other cases of same marked with ditto2)
Source:
public ObjectId getItem(int index) { checkWidget(); if (0 > index || index >= commits.size()) { SWT.error(SWT.ERROR_INVALID_RANGE); } return commits.get(index).objectId; }

Target:
Personally I find index < 0 simpler to parse.
Source:
public static <T> T run(ISafeRunnableWithResult<T> code) { Assert.isNotNull(code); try { return code.runWithResult(); } catch (Exception | LinkageError | AssertionError e) { handleException(code, e); } return null; }

Target:
maybe even move the return null; inside the catch-block. Makes things a bit clearer IMHO.
Source:
protected StringBuilder customizeAfterNewLineForDeclaration(IDocument doc, IASTDeclaration dec, ITypedRegion region) { return customizeAfterNewLineForDeclaration(doc, dec, region, null); }

Target:
deprecate this
Source:
public DoxygenSingleAutoEditStrategy() { super(); }

Target:
personal style on my part - have only one constructor do super() - so have this one do this(true or false).
Source:
public Optional<String> getCommitTemplatePath() { return Optional.ofNullable(commitTemplatePath); }

Target:
What's the benefit of using Optional instead of returning null? In what way would it make a caller's life easier? I suspect instead of simply checking for null a caller will end up doing Optional.isPresent checks (maybe hidden in an ifPresent with a lambda thrown in for additional complexity).
Source:
private void copyJarInJarLoader(File targetFile) throws IOException { try (InputStream is= JavaPlugin.getDefault().getBundle().getEntry(FatJarRsrcUrlBuilder.JAR_RSRC_LOADER_ZIP).openStream()) { OutputStream os= new FileOutputStream(targetFile); byte[] buf= new byte[1024]; while (true) { int cnt= is.read(buf); if (cnt <= 0) break; os.write(buf, 0, cnt); } os.close(); } }

Target:
The OutputStream should also go into the try-with clause
Source:
private void initialize() { initializeFields(); initializeDefaultColors(); for (String[] element : fAppearanceColorListModel) { fAppearanceColorList.add(element[0]); } fAppearanceColorList.getDisplay().asyncExec(() -> { fAppearanceColorList.select(0); handleAppearanceColorListSelection(); }); fDocCommentOwnerComposite.loadValues(null); }

Target:
Invoking with null argument is an evil, please provide another method without arguments if it makes sense
Source:
public boolean performOk() { DocCommentOwnerManager.getInstance() .setWorkspaceCommentOwner(fDocCommentOwnerComposite.getSelectedDocCommentOwner()); fDocCommentOwnerComposite.performOk(null); return super.performOk(); }

Target:
Invoking with null argument is an evil, please provide another method without arguments if it makes sense.
Source:
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { if (property==null) return false; switch (property) { case "simple": //$NON-NLS-1$ return "simple".equals(expectedValue); //$NON-NLS-1$ case "overridden": //$NON-NLS-1$ return "A".equals(expectedValue); //$NON-NLS-1$ case "ordering": //$NON-NLS-1$ return "A".equals(expectedValue); //$NON-NLS-1$ case "chainOrdering": //$NON-NLS-1$ return "A".equals(expectedValue); //$NON-NLS-1$ default: break; } Assert.isTrue(false); return false; }

Target:
Brackets
Source:
private String getPushErrors() { StringBuilder messages = new StringBuilder(); for (URIish uri : result.getURIs()) { String errorMessage = result.getErrorMessage(uri); if (errorMessage != null && errorMessage.length() > 0) { if (messages.length() > 0) messages.append(System.lineSeparator()); messages.append(errorMessage); } } return messages.toString(); }

Target:
nit: add braces around the modified one line block to follow formatting rules
Source:
public CreateAlgorithmCommand(final BasicFBType fbType) { this.fbType = fbType; this.index = fbType.getAlgorithm().size() - 1; this.name = DEFAULT_ALGORITHM_NAME; }

Target:
wouldn't a this call to the new constructor with name = null be nicer here? this(fbType, fType.getAlgorithm().size() - 1, null);
Source:
public CreateInternalVariableCommand(final BasicFBType fbType) { this.dataType = DataTypeLibrary.getInstance().getType("BOOL"); //$NON-NLS-1$ this.fbType = fbType; this.name = DEFAULT_VAR_NAME; this.index = fbType.getInternalVars().size() - 1; }

Target:
as with the algorithm command I think calling the new constructor with appropriate values would be nice here. This would value all the cool new logic of the new constructor.
Source:
protected void consumeRecordHeaderNameWithTypeParameters() { // RecordHeaderName ::= RecordHeaderName1 TypeParameters consumeTypeHeaderNameWithTypeParameters(); TypeDeclaration typeDecl = (TypeDeclaration)this.astStack[this.astPtr]; typeDecl.modifiers |= ExtraCompilerModifiers.AccRecord; }

Target:
These two changes in the two consumeRec...() methods are in fact a property of RecordDecl - public RecordDeclaration(TypeDeclaration t) { this.modifiers =.. -> add here this.modifier |=
Source:
public boolean canBeInstantiated() { return (this.modifiers & (ClassFileConstants.AccAbstract | ClassFileConstants.AccInterface | ClassFileConstants.AccEnum | ClassFileConstants.AccAnnotation | ExtraCompilerModifiers.AccRecord)) == 0; }

Target:
This looks incorrect - Record can be instantiated.
Source:
public TmfTimeViewAlignmentInfo getTimeViewAlignmentInfo() { if (fLanes.size() == 0) { return null; } return new TmfTimeViewAlignmentInfo(fLanes.get(0).getChartViewer().getControl().getShell(), fSashForm.toDisplay(0, 0), getTimeAxisOffset()); }

Target:
fLanes.isEmpty()
Source:
public static ProxyData[] getProxyData(String provider) { ProxyManager manager = (ProxyManager) ProxyManager.getProxyManager(); switch (provider) { case DIRECT_PROVIDER: return new ProxyData[0]; case ECLIPSE_PROVIDER: return castArray(manager.getProxyData()); case NATIVE_PROVIDER: return castArray(manager.getNativeProxyData()); default: break; } throw new IllegalArgumentException("Provider not supported"); //$NON-NLS-1$ }

Target:
Can we decide on one or the other? I'd just move the throw into the default case.
Source:
private int getFlag(String propertyName) { if (propertyName==null) return 0; switch (propertyName) { case BUSY_PROPERTY: return BUSY_FLAG; case PROPAGATED_CONFLICT_PROPERTY: return PROPAGATED_CONFLICT_FLAG; case PROPAGATED_ERROR_MARKER_PROPERTY: return PROPAGATED_ERROR_FLAG; case PROPAGATED_WARNING_MARKER_PROPERTY: return PROPAGATED_WARNING_FLAG; default: break; } return 0; }

Target:
Missing whitespace around ==, missing {}, trailing whitespace.
Source:
public List<ArtifactId> getBranchViewsForApplicability(BranchId branch, ApplicabilityId applId) { List<ArtifactId> arts = new ArrayList<>(); for (Iterator<Long> iterator = queryFactory.tupleQuery().getTuple2E1ListRaw(CoreTupleTypes.ViewApplicability, branch, applId.getId()).iterator(); iterator.hasNext();) { Long long1 = iterator.next(); arts.add(ArtifactId.valueOf(long1)); } return arts; }

Target:
Don't need to access iterator, just: for (Long long1: queryFactory.tupleQuery().getTuple2E1ListRaw(CoreTupleTypes.ViewApplicability, branch, applId.getId()) { ... }
Source:
public synchronized void cancel() { super.cancel(); while (fEventsQueue.size() >= 1) { fEventIterator.next(); } fEventsQueue.put(END_EVENT); fEventsQueue.flushInputBuffer(); }

Target:
!fEventsQueue.isEmpty() would be clearer
Source:
public void saveWidgetValues() { IDialogSettings settings = getDialogSettings(); if (settings != null) { settings.put(STORE_OPEN_TYPE_ID, openType); settings.put(STORE_REPLACE_SOURCE_ID, replaceSource); } }

Target:
null != settings
Source:
private void restoreWidgetValues() { IDialogSettings settings = getDialogSettings(); if (settings != null) { openType = settings.getBoolean(STORE_OPEN_TYPE_ID); replaceSource = settings.getBoolean(STORE_REPLACE_SOURCE_ID); } }

Target:
null != settings
Source:
public static void error (int code, Throwable throwable) { error (code, throwable, " [Application is out of heap memory]"); }

Target:
We can't change the message here. It'll apply to all calls to error(int, Throwable). Instead, use error() with the String arg.
Source:
private void createTextMenu() { final MenuManager popupManager = new MenuManager(); // FIXME missing commands for EDIT_COPY and EDIT_SELECT_ALL // as context menu textWidget.setMenu(popupManager.createContextMenu(textWidget)); textWidget.addDisposeListener(e -> { popupManager.dispose(); }); }

Target:
`{}` may be ommited for single statement
Source:
public AboutItem(String text, List<HyperlinkRange> linkRanges, List<String> links) { this.text = text; this.linkRanges = linkRanges; this.hrefs = links; }

Target:
it is safer to use linkRanges.addAll, otherwise the class content can be externally modified
Source:
public IId<?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { return m_idExternalFormatter.get().fromExternalForm(p.readValueAs(String.class)); }

Target:
JsonProcessingExceptio is sublass of IOException -> remove
Source:
private void dispose() { fContextService.removeDebugContextListener(this); fgServices.remove(fWindow); fCommandUpdates.clear(); fWindow = null; }

Target:
this one misses synchronized block. Not your problem, but seeing your change we should fix that too.
Source:
private static boolean hasMultipleWindowServices() { synchronized (fgServices) { return fgServices.size() >= 2; } }

Target:
"> 1" is more natural
Source:
protected void configureParameters(InterfaceList interfaceList, String parentNodeName) throws TypeImportException, XMLStreamException { processChildren(parentNodeName, name -> { if (name.equals(LibraryElementTags.PARAMETER_ELEMENT)) { VarDeclaration paramter = parseParameter(); VarDeclaration vInput = getVarNamed(interfaceList, paramter.getName(), true); if (null != vInput) { vInput.setValue(paramter.getValue()); } return true; } return false; }); }

Target:
call equals on constant not on name