auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected @NonNull ITmfStateProvider createStateProvider() { ITmfTrace trace = getTrace(); if (!(trace instanceof LttngKernelTrace)) { throw new IllegalStateException("LttngKernelStateSystemModule: trace should be of type LttngKernelTrace"); //$NON-NLS-1$ } return new LttngKernelStateProvider((LttngKernelTrace) trace); }

Target:
This check should be moved to setTrace() (overridden version which then calls super.setTrace()). Then getTrace() can be overridden in this class to always return a LttngKernelTrace.
Source:
public String getHelpText() { return new String(); }

Target:
You should instead use return ""; It would avoid creating new objects everytime the method is called, since all "" refer to the same object (string literals get internalized). Or you can have a private static final String EMTPY_STRING = ""; in your class and use that instead, if you use a lot of them in the same file.
Source:
public GdbMemoryBlockRetrievalManager(String modelId, ILaunchConfiguration config, DsfSession session) throws DebugException { fModelId = modelId; fSession = session; fLaunchConfig = config; }

Target:
Why throw an exception?
Source:
private PositionInfo findMovePositionInfo(MUIElement element) { if (element != null) { for (String tag : element.getTags()) { if (tag.startsWith(MOVE_TAG)) { return PositionInfo.parse(tag.substring(5)); } } } return null; }

Target:
The substring(#) should be calculated against the MOVE_TAG
Source:
void writeInfoFromNode(ITmfStateIntervalList stateInfo) { assert (this.isDone); // not sure this will always be the case... if (intervals.size() == 0) { return; } for (int i = 0; i < intervals.size(); i++) { stateInfo.add(intervals.get(i)); } return; }

Target:
This is common in the code base, and I dislike it. size() == 0 -> isEmpty() You cannot assume the way the List operator implements size() and may be a huge cost (linear and not constant time).
Source:
public EList<org.eclipse.sirius.diagram.description.filter.FilterDescription> getFilters() { if (filters == null) { filters = new EObjectContainmentEList.Resolving<org.eclipse.sirius.diagram.description.filter.FilterDescription>(org.eclipse.sirius.diagram.description.filter.FilterDescription.class, this, DescriptionPackage.DIAGRAM_DESCRIPTION__FILTERS); } return filters; }

Target:
There should be an import in the import section.
Source:
public int getLocationQuark(ITmfEvent event, int startQuark) { int quark = startQuark; for (TmfXmlStateAttribute attrib : fPath) { quark = attrib.getAttributeQuark(event, quark); } return quark; }

Target:
throw an error
Source:
protected void updateTreeNode(ITreeNode node) { if (getSwtTreeViewer() != null) { getSwtTreeViewer().update(node, null); } }

Target:
null check needed?
Source:
public String getGuid() { return String.valueOf(id); }

Target:
Why the valueof? Id is already a String
Source:
public void start(BundleContext context) throws Exception { super.start(context); setDefault(this); TmfAnalysisManager.initializeModuleSources(); }

Target:
we already have this in tmf.core.Activator now. Since this plugin depends on tmf.core, it will already be loaded. Is this necessary to call this again?
Source:
public Iterable<IAnalysisModuleHelper> getAnalysisModules() { if (fModules == null) { populateAnalysisModules(); } return fModules; }

Target:
Why is fModules static? The list of modules is really the same for all XML modules? In this case, the getAnalysisModules() method here should be a static method also (and not using the interface method). And the whole class ends up being a "static" class, so it could have an empty private constructor to prevent instantiation. Also this method should be synchronized, to avoid the risk of two threads calling it at the same time and both entering the if block.
Source:
public void invalidate(final boolean direct) { if (direct) { layoutState = LAYOUT_REDO; // if (getParent() instanceof AbstractBlockBox) { // // The parent box may contain text elements after the edited offset, that has to be updated // ((AbstractBlockBox) getParent()).invalidateChildrenAfterOffset(getStartOffset()); // } } else if (layoutState != LAYOUT_REDO) { layoutState = LAYOUT_PROPAGATE; } if (getParent() instanceof AbstractBlockBox) { ((AbstractBlockBox) getParent()).invalidate(false); } }

Target:
If it's not needed anymore, just delete it ;-)
Source:
private List<ProblemMarkerFilterDesc> findEnabledFilters(IProject project) { List<ProblemMarkerFilterDesc> result = filtersCache.get(project); if (result == null) { result = new ArrayList<ProblemMarkerFilterDesc>(); for (ProblemMarkerFilterDesc filterDesc: filters) { if ( filterDesc.matches(project) ) { result.add(filterDesc); } } filtersCache.put(project, result); } return result; }

Target:
I think that access to filtersCache should be synchronized, no?
Source:
protected int getNbPendingBackgroundRequests() { int nbBackgroundRequests = 0; synchronized (fLock) { for (ITmfEventRequest request : fPendingCoalescedRequests) { if (request.getExecType().equals(ExecutionType.BACKGROUND)) { nbBackgroundRequests++; } } } return nbBackgroundRequests; }

Target:
Does this need to be protected, couldn't it be private? The "number of background requests" is really something that is specific to the internal implementation (just as the notion of foreground and background, but that's another story ;) ).
Source:
private void setUp() throws CTFReaderException { assumeTrue(testTrace.exists()); fixture = new Metadata(testTrace.getTrace()); }

Target:
We should probably keep setUp for @Before and make another method "init". The assumeTrue should probably stay in the setUp
Source:
public void setFirstReference(PDOMLinkage linkage, PDOMName name) throws CoreException { if (linkage.equals(getLinkage())) setFirstReference(name); else new PDOMExternalReferencesList(getPDOM(), record + FIRST_EXTREF_OFFSET).setFirstReference(linkage, name); }

Target:
'If" statements with 'else' branches should have curly braces around both branches.
Source:
private boolean transitionToWithWorkingBranchRuleExists(IAtsStateDefinition toStateDef) { return (toStateDef.hasRule(RuleDefinitionOption.AllowTransitionWithWorkingBranch.name())); }

Target:
remove unnecessary surrounding parenthesis
Source:
public void set(V future) { this.resultObject = future; }

Target:
Should be protected.
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } return this.repository.equals(((RepositoryKey) obj).getRepository()); }

Target:
(Rather than a bunch of IF statements, you could do this all as one return statement w/ && for above.)
Source:
public void setUp() { manager = new TaskRepositoryManager(); manager.addRepository(actualFixture.repository()); connector = new BugzillaRestConnector(); }

Target:
Do we need this? It doesn't seem to be used.
Source:
public void testLoadCacheWrongRepository() throws Exception { BugzillaRestConnector connector = new BugzillaRestConnector(); assertNotNull(connector); assertEquals(connector, BugzillaRestConnector.getDefault()); TaskRepository taskRepository = new TaskRepository(BugzillaRestConnector.getDefault().getConnectorKind(), "http://mylyn.org/bugzilla-rest-trunk-wrong/"); AuthenticationCredentials credentials = new AuthenticationCredentials("username", "password"); taskRepository.setCredentials(AuthenticationType.REPOSITORY, credentials, false); BugzillaRestConfiguration configuration = BugzillaRestConnector.getDefault().getRepositoryConfiguration( taskRepository); assertNull(configuration); }

Target:
Instead of making it a singleton, why not create the connector in setUp?
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((repository == null) ? 0 : repository.hashCode()); return result; }

Target:
This can just return repository.hashCode()
Source:
public Collection<Field> getFields() { return fields.values(); }

Target:
This should return an immutable collection.
Source:
public Map<String, Product> getProducts(IOperationMonitor monitor) throws BugzillaRestException { return retrieveItems(monitor, "/product?type=accessible", new Function<ProductResponse, Product[]>() { public Product[] apply(ProductResponse input) { return input.getProducts(); } }, new TypeToken<ProductResponse>() { }); }

Target:
Should these methods be private?
Source:
public void init(String name, Class<? extends ITmfEvent> type) { super.init(name); fType = type; fDataQueue = (fQueueSize > 1) ? new LinkedBlockingQueue<ITmfEvent>(fQueueSize) : new SynchronousQueue<ITmfEvent>(); fExecutor.init(); fSignalDepth = 0; synchronized (fLock) { fTimer = new Timer(); } TmfProviderManager.register(fType, this); }

Target:
One of the constructors calls init() directly, so this could still create a thread at construction. Or are we sure that one is never called from "fake traces"? I think it'd be safer with the lazy-init that was done in the previous version. getTimer() and dispose() could both be synchronized (so it synchronizes on "this"), it doesn't really have anything to do with fLock.
Source:
public void assumeShallow(Collection<? extends ObjectId> ids) throws IOException { if (!shallowCommitsInitialized) initializeShallowCommits(); for (ObjectId id : ids) lookupCommit(id).parents = RevCommit.NO_PARENTS; }

Target:
I think handling fetches from a server that has its own shallow commits will take more work (see v1.9-rc0~3^2~17, "upload-pack: make sure deepening preserves shallow roots", 2013-12-05). Are the above two lines needed here?
Source:
protected RGB getBackground() { return fDisplay.getSystemColor(SWT.COLOR_LIST_BACKGROUND).getRGB(); }

Target:
this should be private
Source:
protected void preHookCreateControlAndViewer() { fAdapterFactory = new ComposedAdapterFactory(EMFCompareRCPPlugin.getDefault() .getAdapterFactoryRegistry()); fAdapterFactory.addAdapterFactory(new TreeItemProviderAdapterFactorySpec()); fAdapterFactory.addAdapterFactory(new ReflectiveItemProviderAdapterFactory()); fAdapterFactory.addAdapterFactory(new ResourceItemProviderAdapterFactory()); getCompareConfiguration().setAdapterFactory(fAdapterFactory); updateColors(); inputChangedTask = new CompareInputChangedJob("Computing Model Differences"); }

Target:
use ICompareColor instead, it will ease the maintenance
Source:
public DefaultDiffEngine() { this.diffProcessor = new DiffBuilder(); }

Target:
call the other constructor and giving the diff builder instance in parameter
Source:
public Binding[] getBindings() { Set<Binding> bindings = new HashSet<Binding>(); bindings.addAll(bindingService.getActiveBindings()); for (Binding binding : manager.getBindings()) { bindings.add(binding); } return bindings.toArray(new Binding[0]); }

Target:
This probably isn't the place for modifying the list of bindings that can be seen. I would think that progammatically created bindings would have to be added to the model to survive
Source:
public List<IItemDescriptor<T>> getItemDescriptors() { ArrayList<IItemDescriptor<T>> descriptors = Lists.newArrayList(registry.values()); if (descriptors.size() > 0) { Collections.sort(descriptors); } return descriptors; }

Target:
get this sort out of the getter
Source:
private void initPreferenceDefaults() { getPreferenceStore().setDefault(CHANGE_SET_MANAGE, true); getPreferenceStore().setDefault(COMMIT_TEMPLATE, DEFAULT_COMMIT_TEMPLATE); // 2.0M1 - 2.0M2 Default template migration if (getPreferenceStore().getString(COMMIT_TEMPLATE).equals(OLD_DEFAULT_COMMIT_TEMPLATE) || getPreferenceStore().getString(COMMIT_TEMPLATE).equals(OLD_DEFAULT_COMMIT_TEMPLATE2) || getPreferenceStore().getString(COMMIT_TEMPLATE).equals(OLD_DEFAULT_COMMIT_TEMPLATE3)) { getPreferenceStore().setValue(COMMIT_TEMPLATE, DEFAULT_COMMIT_TEMPLATE); } }

Target:
Since we already have a bunch of old templates I would keep them in a list/set and check if it contains the template from pref store.
Source:
public void init(IEditorSite site, IEditorInput input) throws PartInitException { setSite(site); setInput(input); if (!(input instanceof FileEditorInput)) { throw new PartInitException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Expected editor input to be of type FileEditorInput")); } FileEditorInput fileInput = ((FileEditorInput)input); if (fileInput != null) { source = fileInput.getFile(); } }

Target:
This should occur before setInput(input);
Source:
public NetRC(File netrc) { this.netrc = netrc; }

Target:
shouldn't we call parse() here as well ?
Source:
public static void install() { final NetRCCredentialsProvider c = new NetRCCredentialsProvider(); CredentialsProvider.setDefault(c); }

Target:
there is no need for this variable, instead inline this
Source:
private boolean isSelected(EditPart part) { boolean result; result = part != null && part.getSelected() == EditPart.SELECTED_PRIMARY || part.getSelected() == EditPart.SELECTED; return result; }

Target:
Introducing a local variable for this is not justified.
Source:
public static boolean isDynamicTabbar() { return isJuno4Platform() || isKeplerPlatform(); }

Target:
Isn't this condition inverted? Juno and Kepler are the only versions for which we can *not* support the dynamic tabbar.
Source:
public TaskRepository repository() { repository = new TaskRepository(getConnectorKind(), getRepositoryUrl()); return repository; }

Target:
The field should be removed as well.
Source:
public String getSelection() { if (fSelection == null) { return ""; } else { return fSelection; } }

Target:
I think it's ok to return null here, looking at how the GerritTableView is handling the result.
Source:
public BugzillaRestTaskEditorPage(TaskEditor editor, String connectorKind) { super(editor, connectorKind); setNeedsPrivateSection(false); setNeedsSubmitButton(false); }

Target:
Why do we set these false? It seems that we should set them true.
Source:
public void traceOpened(TmfTraceOpenedSignal signal) { assert (signal != null); fTrace = signal.getTrace(); ITmfTrace[] traces = TmfTraceManager.getTraceSet(fTrace); if (traces != null) { this.showTraceAction.setEnabled(traces.length < fFullTraceHistogram.getMaxNbTraces()); } loadTrace(); }

Target:
This needs to be done in traceSelected() below too. Maybe it's better to do it in initalizeHistogram() instead.
Source:
public CTFCallsite(String en, String func, long ip, String fn, long line) { fEventName = en; fFileName = fn; fFunctionName = func; this.fIp = ip; this.fLineNumber = line; }

Target:
Let's remove 'this.' also below.
Source:
protected T validateValueInternal(T rawValue) throws ProcessingException { T validValue; if (rawValue == null) { validValue = null; } else { T t = TypeCastUtility.castValue(rawValue, getHolderType()); IRadioButton b = getButtonFor(t); if (b != null) { validValue = t; } else { throw new ProcessingException("Illegal radio value: " + rawValue); } } return validValue; }

Target:
there is no need for casting here
Source:
public IRadioButton<T> getButtonFor(T value) { for (IRadioButton<T> b : getButtons()) { T radioValue = TypeCastUtility.castValue(b.getRadioValue(), getHolderType()); if (CompareUtility.equals(radioValue, value)) { return b; } } return null; }

Target:
no need for casting here
Source:
protected void execLoad() throws ProcessingException { getResultTableField().getTable().setDefaultIconId(getContentAssistField().getBrowseIconId()); getActiveStateRadioButtonGroup().setVisible(getContentAssistField().isActiveFilterEnabled()); getActiveStateRadioButtonGroup().setValue((TriState) getContentAssistField().getActiveFilter()); getNewButton().setEnabled(getContentAssistField().getBrowseNewText() != null); getNewButton().setLabel(getContentAssistField().getBrowseNewText()); }

Target:
remove unnecessary cast
Source:
public EventDefinition(IEventDeclaration declaration, StreamInputReader streamInputReader) { this.fDeclaration = declaration; this.fStreamInputReader = streamInputReader; }

Target:
Remove this. and the one below
Source:
public DeclarationScope(DeclarationScope parentScope) { this.fParentScope = parentScope; }

Target:
remove this.
Source:
public IOStructGen(CommonTree tree, CTFTrace trace) { this.fTrace = trace; this.fTree = tree; }

Target:
Remove this. and the one below
Source:
public ICPPASTAttributeSpecifier copy(CopyStyle style) { ICPPASTAttributeSpecifier copy = copy(new CPPASTAttributeSpecifier(), style); for (ICPPASTAttribute attribute : ArrayUtil.trim(attributes)){ copy.addAttribute(attribute.copy(style)); } return copy; }

Target:
Slightly more efficient: CPPASTAttributeSpecifier copy = copy(new CPPASTAttributeSpecifier(), style); copy.attributes = ArrayUtil.trim(attributes); for (int i = 0; i < copy.attributes.length; i++) { copy.attributes[i] = copy.attributes[i].copy(style); } return copy;
Source:
public void toggleStarred(String key, String value) { TaskAttribute taskAttribute = fTaskData.getRoot(); taskAttribute.getAttribute(key).setValue(value); // Update the Review Table setAttribute(key, value); }

Target:
Could the attribute be null here?
Source:
protected ArrayList<TaskAttribute> parseFromJson(InputStreamReader in) { TypeToken<ArrayList<TaskAttribute>> type = new TypeToken<ArrayList<TaskAttribute>>() { }; return new GsonBuilder().registerTypeAdapter(type.getType(), new JSonTaskDataDeserializer()) .setExclusionStrategies(exclustionStrategy) .create() .fromJson(in, type.getType()); }

Target:
Should use List
Source:
public InteractiveUIContent build() { if (isSimple) { // If simple only one element check at a time Preconditions.checkArgument(defaultCheck == null || defaultCheck.size() == 1); } boolean hasConfiguration = configurationUIRegistry != null; if (hasConfiguration) { // If has a configuration composite then the key to retreive te preference shall be set up. Preconditions.checkArgument(configurationNodeKey != null); } final InteractiveUIContent interactiveUI = new InteractiveUIContent(parent, hasDescription, hasConfiguration); CheckboxTableViewer descriptorViewer = createViewer(interactiveUI); if (hasConfiguration) { createConfigurationComposite(interactiveUI); } // Filter input with input with higher rank than default item descriptor setViewerInput(descriptorViewer); // Init and bind data bindAndInit(interactiveUI, descriptorViewer); return interactiveUI; }

Target:
Change this whole if to Preconditions.checkArgument(!isSimple || defaultCheck == null || defaultCheck.size() == 1)
Source:
public static void closeView(String title, SWTWorkbenchBot bot) { final List<SWTBotView> openViews = bot.views(); for (SWTBotView view : openViews) { if (view.getTitle().toLowerCase().equals(title.toLowerCase())) { view.close(); bot.waitUntil(ConditionHelpers.ViewIsClosed(view)); } } }

Target:
can bot.viewByTitle be used instead of looping?
Source:
public static String execWithFile(String filename) { try (BufferedReader br = new BufferedReader(new FileReader(filename))) { StringBuffer buffer = new StringBuffer(); String line; while ((line = br.readLine()) != null) { buffer.append(line.concat("\n")); //$NON-NLS-1$ } return exec(buffer.toString()); } catch (IOException e) { e.printStackTrace(); return ""; //$NON-NLS-1$ } }

Target:
Please don't print stack trace like that. Either log it properly or ignore if the information is useless.
Source:
public static void registerModuleSource(IAnalysisModuleSource source) { synchronized (fSources) { fSources.add(source); refreshModules(); } }

Target:
This needs to be synchronized because of fSources
Source:
public static Map<String, IAnalysisModuleHelper> getAnalysisModules() { synchronized (fAnalysisModules) { if (fAnalysisModules.isEmpty()) { for (IAnalysisModuleSource source : fSources) { for (IAnalysisModuleHelper helper : source.getAnalysisModules()) { fAnalysisModules.put(helper.getId(), helper); } } } } return Collections.unmodifiableMap(fAnalysisModules); }

Target:
This needs to be synchronized because of fSources / registerModuleSource / initialize
Source:
public void sortingShouldWorkForEasyStrings() { assertSortedLike("", ""); assertSortedLike("", "a"); assertSortedLike("a", "asdf"); assertSortedLike("aaa", "bbb"); assertSortedLike("1", "2"); assertEquals(0, cmp("", "")); assertEquals(0, cmp("a", "a")); assertTrue(cmp("", "a") < 0); assertTrue(cmp("a", "") > 0); }

Target:
Consider moving these assertions to separate method.
Source:
private boolean isDotGit(byte[] buf, int p) { if (ignoreCase || windows) return toLower(buf[p]) == 'g' && toLower(buf[p + 1]) == 'i' && toLower(buf[p + 2]) == 't'; return buf[p] == 'g' && buf[p + 1] == 'i' && buf[p + 2] == 't'; }

Target:
Not needed, since windows implies ignoreCase (unless someone has explicitly chosen to setIgnoreCase(false) after setSafeForWindows(true)).
Source:
void sendSelection (long /*int*/ id, long /*int*/ sel, long /*int*/ arg) { panel.validateVisibleColumns(); if (filterExtensions.length > 0){ setAllowedFileType(filterExtensions[(int)/*64*/popup.indexOfSelectedItem()]); } }

Target:
- add single space before '{'
Source:
public void dispose() { super.dispose(); if (control != null) { control.dispose(); } }

Target:
You'd probably dispose your stuff, and call super.dispose() at the end.
Source:
protected PatchLineComment execute(GerritClient client, IProgressMonitor monitor) throws GerritException { return client.saveDraft(getPatchKey(), getMessage(), getLine(), getSide(), getParentUuid(), monitor, getUuid()); }

Target:
By convention if there is a monitor being passed, it's always the last param.
Source:
private boolean isWindowPlatform() { if (Platform.getOS().equals(Platform.WS_WIN32)) { return true; } return false; }

Target:
return Platform.getOS().equals(Platform.WS_WIN32)
Source:
public static ReviewCompareAnnotationSupport getAnnotationSupport(Viewer contentViewer) { ReviewCompareAnnotationSupport support = (ReviewCompareAnnotationSupport) contentViewer.getData(KEY_ANNOTAION_SUPPORT); if (support == null) { if (support == null) { support = new ReviewCompareAnnotationSupport(contentViewer); contentViewer.setData(KEY_ANNOTAION_SUPPORT, support); } } return support; }

Target:
Making *really* sure it's null? ;)
Source:
public void addStream(long id, File streamFile) throws CTFReaderException { if (!fStreams.containsKey(id)) { fStreams.put(id, new Stream(this)); } Stream stream = fStreams.get(id); stream.addInput(new StreamInput(stream, streamFile)); }

Target:
minor thing, but in the case where you go inside the if, you could keep a reference to the "new Stream", so you do not need to do a map lookup in that case.
Source:
public void setSessionId(long sessionId) { this.fSessionId = sessionId; }

Target:
remote this
Source:
public void setSeek(SeekCommand seekCommand) { this.fSeek = seekCommand; }

Target:
remove this
Source:
public void handleData(final @Nullable ITmfEvent event) { super.handleData(event); if (event != null && event.getTrace() != trace) { System.out.println("alld"); //$NON-NLS-1$ } if (event != null && event.getTrace() == trace) { sci.processEvent(event); } }

Target:
I guess this is the WIP part...
Source:
int findItemIndex(ITimeGraphEntry entry) { Item item = fItemMap.get(entry); if (item == null) { return -1; } return item.fExpandedIndex; }

Target:
should have public modifier, for consistency.
Source:
public EditCommitOperation(Repository repository, RevCommit commit) { if (commit.getParentCount() != 1) { throw new UnsupportedOperationException( "commit is expected to have exactly one parent"); //$NON-NLS-1$ } this.repository = repository; this.commit = commit; }

Target:
no braces around single line block
Source:
public void contextDisposed() { super.contextDisposed(); eventBroker.unsubscribe(itemUpdater); eventBroker.unsubscribe(selectionUpdater); eventBroker.unsubscribe(enabledUpdater); eventBroker.unsubscribe(toBeRenderedUpdater); eventBroker.unsubscribe(childAdditionUpdater); }

Target:
Should probably be at the end of the method.
Source:
public void testAddNull() { registry.add(null); assertTrue(registry.getItemDescriptors().isEmpty()); }

Target:
remove this assertion, since it will never be reached.
Source:
public void removeCompareInputChangeListener(ICompareInputChangeListener listener) { if (containsListener(listener)) { listeners.remove(listener); } }

Target:
No use checking if the list contains() before remove(), let's avoid double iterations.
Source:
public String getNamespaceURI() { if (namespaceURI == null) { namespaceURI = ClassUtils.getPackageName(getNativeWidget() .getClass()); } System.err.println(namespaceURI); return namespaceURI; }

Target:
We should remove syserrs
Source:
public void addSubAttribute(Attribute newSubAttribute) { /* This should catch buggy state changing statements */ if (newSubAttribute == null || newSubAttribute.getName() == null || newSubAttribute.getName().equals(this.getName())) { throw new IllegalArgumentException(); } subAttributes.put(newSubAttribute.getName(), newSubAttribute); }

Target:
That 3rd one is a weird condition: I cannot add an attribute "0" (the tid) as a subattribute of "0" (the cpu) it throws this exception. Since the asserts did do nothing, I never noticed before.
Source:
public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { List<TmfAnalysisRequirement> requirements = new ArrayList<>(); AnalysisRequirementFactory factory = new AnalysisRequirementFactory(); switch (fModule) { case TEST: requirements.add(factory.getRequirement1()); requirements.add(factory.getRequirement3()); break; case TESTCTF: requirements.add(factory.getRequirement2()); requirements.add(factory.getRequirement3()); break; default: break; } return requirements; }

Target:
Here a Set could be used instead of ArrayList
Source:
public int getLength() { Widget widget = getWidget(); int childCount = 0; if (widget instanceof Composite) { childCount = ((Composite) widget).getChildren().length; if (widget instanceof CTabFolder) { // if it's a CTabFolder, include the child items in the count for (CTabItem tabItem : ((CTabFolder) widget).getItems()) { if (tabItem.isDisposed()) { // widget (CTabFolder) is internaly marked as inDispose // It has disposed the CTabItem, but has not taken it out of the items array. // Do not return disposed items to the css engine // TODO: When as to why CTabFolderElement is even getting called is solved, we can remove this guard. System.err.println("CTabItem was disposed"); break; } else { childCount++; } } } } return childCount; }

Target:
The syserr should come out.
Source:
Project(String name, String path, String groups) { this.name = name; this.path = path; this.groups = new HashSet<String>(); if (groups != null && groups.length() > 0) { this.groups.addAll(Arrays.asList(groups.split(","))); } }

Target:
we don't use braces around single line blocks
Source:
void copy() throws IOException { FileInputStream input = new FileInputStream(src); FileOutputStream output = new FileOutputStream(dest); try { FileChannel channel = input.getChannel(); output.getChannel().transferFrom(channel, 0, channel.size()); } finally { input.close(); output.close(); } }

Target:
Actually you need two levels of try/finally here as the input should be closed if the FileOutputStream fails to create.
Source:
void copy() throws IOException { FileInputStream input = new FileInputStream(src); FileOutputStream output = new FileOutputStream(dest); FileChannel channel = input.getChannel(); output.getChannel().transferFrom(channel, 0, channel.size()); input.close(); output.close(); }

Target:
Wrap with try/finally to ensure the streams are closed in case of failure.
Source:
private static Map<String, String> getMergedEnvironment(LaunchConfiguration configuration) throws IOException { Map<String, String> currentEnv = new HashMap<String, String>(EnvironmentUtils.getProcEnvironment()); currentEnv.putAll(configuration.getEnvironment()); return currentEnv; }

Target:
Does order matter here?
Source:
public Version getVersion() { return version; }

Target:
I think we should still return a string here.
Source:
public boolean isNewerJenkinsServer() { return Type.JENKINS.equals(type) && HudsonServerInfo.JENKINS_1_511.compareTo(version) < 0; }

Target:
No need to qualify the access to JENKINS_1_511 with the type name.
Source:
private static PrintStream printTime(long start, long end) { return System.out.format(", %.3f", 0.000000001 * (end - start)); }

Target:
You could add a text here to show what the output means. You probably know, but me running this benchmark, I'd need something more verbose ;-)
Source:
boolean add(RevFlag flag) { if (sourceCommit.has(flag)) return false; else { sourceCommit.add(flag); return true; } }

Target:
style nit: use the early return above to avoid the need for else here for the two statements in the else case.
Source:
public Response getDispoItemsByIdJson(@PathParam("itemId") String itemId) { Response response; DispoItem result = dispoApi.getDispoItemById(program, itemId); if (result == null) { response = Response.status(Response.Status.NOT_FOUND).entity(DispoMessages.Item_NotFound).build(); } else { response = Response.status(Response.Status.OK).entity(DispoUtil.itemArtToItemData(result)).build(); } return response; }

Target:
should this be part of a different commit?
Source:
public DefaultInterpretedExpressionTargetSwitch(EStructuralFeature feature, IInterpretedExpressionTargetSwitch globalSwitch) { IInterpretedExpressionTargetSwitch theGlobalSwitch = Objects.firstNonNull(globalSwitch, this); this.firstRelevantContainerFinder = new FirstRelevantContainerDefaultFunction(); this.descriptionSwitch = new DescriptionInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); this.styleSwitch = new StyleInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); this.toolSwitch = new ToolInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); this.validationSwitch = new ValidationInterpretedExpressionTargetSwitch(feature, theGlobalSwitch); }

Target:
We should remove the field and directly create the function in the getFirstRelevantContainer method.
Source:
public void logout(final IProgressMonitor monitor) throws XmlRpcException { try { (new BugzillaXmlRpcOperation<Integer>(this) { @Override public Integer execute() throws XmlRpcException { call(monitor, XML_USER_LOGOUT); return -1; } }).execute(); } catch (XmlRpcException e) { e.printStackTrace(); throw e; } finally { userID = -1; token = null; } return; }

Target:
I don't think we should have a catch block if we're just going to rethrow the exception.
Source:
public void logout(final IProgressMonitor monitor) throws XmlRpcException { userID = -1; token = null; (new BugzillaXmlRpcOperation<Integer>(this) { @SuppressWarnings("serial") @Override public Integer execute() throws XmlRpcException { try { bugzillaClient.authenticate(null); } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } Object response = call(monitor, XML_USER_LOGOUT, null); return -1; } }).execute(); return; }

Target:
It seems to call authenticate when logging out. Also, why not pass the monitor?
Source:
public static boolean isZippedContent(byte[] bin) { return bin.length > 4 && bin[0] == 'P' && bin[1] == 'K' && bin[2] == 3 && bin[3] == 4; }

Target:
Is null possible to be passed here?
Source:
public void addFile(String fileName, File file) throws Exception { Git gitProject = getGitProject(); CommonTestUtil.copy(file, new File(getFolder(), fileName)); gitProject.add().addFilepattern(".").call(); }

Target:
consider using the file name rather than adding all files ("."). The result should be the same, though.
Source:
private Matcher<byte[]> empty() { return nullValue(byte[].class); }

Target:
static?
Source:
public void dispose() { if (fTreeViewer != null) { fTreeViewer.dispose(); } if (fXYViewer != null) { fXYViewer.dispose(); } }

Target:
You should probably call super.dispose() here too
Source:
public AbstractCommandSelectionDialog(Shell parentShell, IModelResource resource, Messages Messages) { super(parentShell); this.resource = resource; this.Messages = Messages; ToolsEmfUiPlugin.getDefault().registerForLocationAndSizePersistence(this); }

Target:
No, not like this. See https://bugs.eclipse.org/bugs/attachment.cgi?id=224190&action=diff the object TitleAreaDialog already provides a method that allows to add information about dialog boundaries. -> getDialogBoundsSettings()
Source:
public void TestExist() { BtfTrace fixture = (BtfTrace) BtfTestTrace.BTF_TEST.getTrace(); assertNotNull(fixture); }

Target:
EVERY one of the tests do this. How about a @Before instead? I assume those traces should get closed/disposed too?
Source:
public void initTrace(IResource resource, String path, Class<? extends ITmfEvent> type) throws TmfTraceException { super.initTrace(resource, path, type); fFile = new File(path); try { fFileInput = new RandomAccessFile(fFile, "r"); //$NON-NLS-1$ parseHeader(); } catch (IOException e) { // won't happen } }

Target:
Do you want this to be the same RAF (no, that's not the Royal Air Force) that will be used to read events? It could be a separate, local one (which you pass as parameter to parseHeader), and then you close it before opening the "real" one that will be used for events.
Source:
public Object getAdapter(Object element, Class key) { BtfEvent tmfEvent = (BtfEvent) element; if (IPropertySource.class.equals(key)) { return new BtfEventPropertySource(tmfEvent); } return null; }

Target:
Type should be checked before casting
Source:
public void tearDown() { if (fModule != null) { fModule.close(); } if (fTrace != null) { fTrace.dispose(); File suppDir = new File(TmfTraceManager.getSupplementaryFileDir(fTrace)); deleteDirectory(suppDir); } }

Target:
Why a null check here, but not in previous test classes? Can this one be null more than others?
Source:
public List<IEventDeclaration> getEventDeclarations() { ArrayList<IEventDeclaration> retVal = new ArrayList<>(fEvents); retVal.removeAll(Collections.singletonList(null)); return retVal; }

Target:
Is this really needed? What can you do with this that you cannot do with get(int id) ? If your answer is: "Well you can iterate on them, dingus!", then I'll say you should return an Iterable here instead, and not expose the underlying data structure (this will allow you to change the underlying implementation to TreeMap etc. without breaking this API).
Source:
public WorkState getState(String string) { for (WorkState state : new CopyOnWriteArrayList<WorkState>(states)) { if (state.getName().equals(string)) { return state; } } return null; }

Target:
neither of these need to be a concurrent data structure. if you just make them a regular list like a linkedlist, the variable will be local, not subject to comodification.
Source:
public ExecutationType solutionFound(ThreadContext context, Solution solution) { if (solution == null) { return ExecutationType.CONTINUE; } return ExecutationType.STOP_ALL; }

Target:
is solution allowed to be null?
Source:
public void calculateHash(int mDepth) { int maxDepth = coders.size() + 1; if (!isRoot()) { throw new InvalidParameterException("Can only be called on the root VertexCoder!"); } String lastHash = "XXX"; calculateCodes(maxDepth, false); int expansionDepth = 1; while (!lastHash.equals(labellessCode) && expansionDepth <= mDepth) { lastHash = labellessCode; expand(expansionDepth++); calculateCodes(maxDepth, false); } calculateCodes(maxDepth, true); }

Target:
use more descriptive string, and maybe put it into a constant
Source:
private MyModel[] createModel() { MyModel[] elements = new MyModel[10]; for (int i = 0; i < elements.length; i++) { elements[i] = new MyModel(i); } return elements; }

Target:
Lists
Source:
private MyModel[] createModel() { MyModel[] elements = new MyModel[11]; for (int i = 0; i < elements.length - 1; i++) { elements[i] = new MyModel(i); } elements[elements.length - 1] = new MyModel(42); return elements; }

Target:
Use list
Source:
public ArrayDefinition lookupArray(String name) { Definition def = lookupDefinition(name); return (ArrayDefinition) ((def.getDeclaration() instanceof ArrayDeclaration) ? def : null); }

Target:
why not do (def instanceof ArrayDefinition) ?
Source:
public TmfStatisticsTreeNode getTop() { if (fTopNode == null) { fTopNode = this; while (fTopNode.getParent() != null && fTopNode.getParent().getParent() != null) { fTopNode = fTopNode.getParent(); } } return fTopNode; }

Target:
Can't you do this in the constructor, and make the field fTopNode final?
Source:
public void untrackedFileNotIncluded() throws Exception { String trackedPath = "tracked.txt"; // at least one modification needed writeTrashFile(trackedPath, "content2"); git.add().addFilepattern(trackedPath).call(); RevCommit stashed = git.stashCreate().call(); assertNotNull(stashed); validateStashedCommit(stashed); assertTrue("untracked file should be left untouched.", untrackedFile.exists()); assertEquals("content", read(untrackedFile)); }

Target:
this is already included in validateCoreStashedCommit()
Source:
private static boolean anyFile(IResource[] memebers) { for (IResource member : memebers) { if (member.getType() == IResource.FILE) return true; else if (member.getType() == IResource.FOLDER) return hasContainerAnyFiles(member); } return false; }

Target:
This returns too early. Maybe use something like this: if (member.getType() == IResource.FOLDER && hasContainerAnyFiles(member)) return true;
Source:
public void setVirtSpecifier(ICPPASTClassVirtSpecifier virtSpecifier) { assertNotFrozen(); if (virtSpecifier != null) { this.virtSpecifier = virtSpecifier; virtSpecifier.setParent(this); virtSpecifier.setPropertyInParent(CLASS_VIRT_SPECIFIER); } }

Target:
Should this line be outside of the 'if' statement.
Source:
protected void handleDemandLoadException(Resource resource, IOException exception) throws RuntimeException { try { super.handleDemandLoadException(resource, exception); } catch (Exception e) { // do nothing, continue with loading, the exception has been added to the diagnostics of the // resource } }

Target:
I'd rather we catch only the "org.eclipse.emf.common.util.WrappedException" instead of "any and all Exceptions". Wouldn't this be sufficient?
Source:
public void addCompareInputChangeListener(ICompareInputChangeListener listener) { if (!containsListener(listener)) { listeners.add(listener); } }

Target:
The ListenerList implementation already takes care of this. Remove the "contains" test.
Source:
private ICompletionProposal[] computeProposals(int offset) { ICompletionProposal[] proposals = null; boolean succeeded = false; try { if (fContentAssistSubjectControl != null) { proposals = fContentAssistant.computeCompletionProposals(fContentAssistSubjectControl, offset); } else { proposals = fContentAssistant.computeCompletionProposals(fViewer, offset); } succeeded = true; } finally { if (!succeeded) { // Cleanly end the content assist session before propagating an exception (see bug 434901). hide(); } } return proposals; }

Target:
My suggestion about Throwable was incorrect, but the version in patch set #2 was simpler than this one.
Source:
public void uncaughtException(Thread t, Throwable e) { if (e instanceof OperationCanceledException) { // handle cancellation } else { if (diagnostic != null) { diagnostic.add(BasicDiagnostic.toDiagnostic(e)); } else { EMFCompareIDEUIPlugin.getDefault().log(e); } } }

Target:
Un-nest this if
Source:
private String[] getHeaders() { String[] toReturn = { "Test Case", "Dry Run Results:Test Points", "Dry Run Results:Total Fails", "DemoResults:Total Test Points", "Demo: Code Problems", "Script Problems", "Requirements", "Under Investigation", "Other", "Total Fails", "Verification of RPCR", "Commnets"}; return toReturn; }

Target:
this should be a constants static final array since it never changes. No need to keep re-creating the array every time ?
Source:
public Collection<Ref> call() throws GitAPIException, InvalidRemoteException, org.eclipse.jgit.api.errors.TransportException { return callAsMap().values(); }

Target:
API breakage. The returned collection used to be modifiable, but is no more. I'm not sure if anyone will be affected.
Source:
private void ensureLoaded() { if (!loaded) { for (Artifact art : ArtifactQuery.getArtifactListFromType(CoreArtifactTypes.User, AtsUtilCore.getAtsBranch())) { User user = (User) art; AtsUser atsUser = new AtsUser(user); userIdToAtsUser.put(user.getUserId(), atsUser); nameToAtsUser.put(user.getName(), atsUser); } loaded = true; } }

Target:
this method should probably be synchronized
Source:
public void registerConnectorUis() { registerFromExtensionPoint(); registerConnetorToConnectorUi(); registerFromAdaptable(); }

Target:
Can we move this down 1 line and remove the call to setConnectorForConnectorUi from registerFromAdaptable?
Source:
protected void setConnector(AbstractRepositoryConnector connector) { this.connector = connector; }

Target:
Should we make this private and remove the @since tag?
Source:
private void setConnector(AbstractRepositoryConnector connector) { this.connector = connector; }

Target:
I would prefer to make this public since otherwise it's impossible for clients to correctly initialize the class. Mark it as @noreference to hide it from the API.
Source:
public BugzillaRestRepositorySettingsPage(TaskRepository taskRepository, AbstractRepositoryConnector connector, AbstractRepositoryConnectorUi connectorUi) { super("Bugzilla REST Repository Settings", DESCRIPTION, taskRepository, connector == null ? (BugzillaRestConnector.getDefault() == null ? new BugzillaRestConnector() : BugzillaRestConnector.getDefault()) : connector, connectorUi == null ? new BugzillaRestRepositoryConnectorUi() : connectorUi); setNeedsAnonymousLogin(true); setNeedsValidateOnFinish(true); }

Target:
Should pass parameters along instead of doing null checks.
Source:
private boolean anyDiffInIndex() throws IOException { Repository repo = getRepository(); TreeWalk treeWalk = new TreeWalk(repo); treeWalk.setRecursive(true); final ObjectId rev = repo.resolve("HEAD"); //$NON-NLS-1$ if (rev!=null) treeWalk.addTree(new RevWalk(repo).parseTree(rev)); treeWalk.addTree(new DirCacheIterator(repo.readDirCache())); treeWalk.setFilter(TreeFilter.ANY_DIFF); return treeWalk.next(); }

Target:
If rev is null, what will happen. Shouldn't it bail at that point? Also, brackets are needed.
Source:
public void dispose() { super.dispose(); for (Resource disposable : this.disposables) { disposable.dispose(); } }

Target:
style nit: we don't use braces around single line blocks
Source:
public boolean add(Object o) { if(!(o instanceof Profile)) { return false; } Profile profile = EMFHelper.reloadIntoContext((Profile)o, umlSource); Command command = new ApplyProfileCommand(umlSource, profile, (TransactionalEditingDomain)domain); commands.add(command); commands.add(new ApplyProfileCommand(umlSource, profile, (TransactionalEditingDomain)domain)); return wrappedList.add(o); }

Target:
Again, we're applying the same profile twice to the same package. Only this time it?s exactly the same command.
Source:
public GroupIntoToolGroupCommand(ResourceSet set, ToolSection parent, Collection<EObject> selection) { super(set); this.selection = selection; this.parent = parent; }

Target:
The two last instruction should be in the abstract class as the two fields belong to it. Here we must have super(set, parent, selection); only.
Source:
void hideToolTip () { checkWidget (); if (itemToolTip == null) return; itemToolTip.setVisible (false); }

Target:
For non-public methods checkWidget() is not required.
Source:
void showTooltip (int x, int y) { checkWidget (); if (itemToolTip == null) return; itemToolTip.setLocation (x, y); itemToolTip.setVisible (true); }

Target:
For non-public methods checkWidget() is not required.
Source:
int getClientWidth () { if ((state & ZERO_WIDTH) != 0) return 0; GtkAllocation allocation = new GtkAllocation(); if (handle != 0) { gtk_widget_get_allocation (handle, allocation); return allocation.width; } else { return 0; } }

Target:
This implementation could be restructured as below: int getClientWidth () { if (handle == 0 || (state & ZERO_WIDTH) != 0) return 0; GtkAllocation allocation = new GtkAllocation (); gtk_widget_get_allocation (handle, allocation); return allocation.width; }
Source:
public void testLookupVariant() { // we want to test null @SuppressWarnings("null") VariantDefinition result = fixture.lookupVariant(ENUM_8); assertNull(result); }

Target:
There is no point testing this if the method is marked @NonNull. It becomes a compiler check instead of a "unit test check". This means we can remove this test altogether.
Source:
private void setSubtreeChecked(Object element, boolean checked) { fCheckboxTreeViewer.setChecked(element, checked); if (checked) { fCheckboxTreeViewer.setGrayed(element, false); } fCheckboxTreeViewer.setChecked(element, checked); Object[] children = fContentProvider.getChildren(element); if (children != null) { for (Object child : children) { setSubtreeChecked(child, checked); } } }

Target:
Redundant with the one below the if?
Source:
public void dispose() { if (diagram.eResource() != null) { diagram.eAdapters().remove(this); } diagram = null; session = null; }

Target:
diagram != null && diagram.eResource != null if dispose is called twice for example, your proposition leads to a NPE we did not have before.
Source:
public void close() { fBitBuffer = BitBuffer.EMPTY_BITBUFFER; }

Target:
I'm not convinced this is really needed to free file descriptors... you don't close ByteBuffers, they're only something in memory. Anyway, to be safe, we could keep it as it is. However, it's be more simple/representative to make the fBitBuffer null here.
Source:
private @NonNull static List<Definition> createIntDefs(int size, int bits) { List<Definition> defs = new ArrayList<>(size); for (int i = 0; i < size; i++) { String content = "test" + i; defs.add(new IntegerDefinition(IntegerDeclaration.createDeclaration(bits, false, 16, ByteOrder.LITTLE_ENDIAN, Encoding.UTF8, content, 24), null, content, i)); } return defs; }

Target:
@NonNull on its own on line above
Source:
@NonNull ByteBuffer getByteBufferAt(long position, long size) throws CTFReaderException, IOException { MappedByteBuffer map = fFileChannel.map(MapMode.READ_ONLY, position, size); if( map == null){ throw new CTFReaderException("Failed to allocate mapped byte buffer"); //$NON-NLS-1$ } return map; }

Target:
annotation on a separate line
Source:
public Color getBackground(Object aElement, int aColumnIndex) { // GerritUi.Ftracer.traceInfo("getBackground column : " + // aColumnIndex + // " ]: "+ aElement ); if (aElement instanceof GerritTask) { GerritTask item = (GerritTask) aElement; // // To modify when we can verify the review state String state = item.getAttribute(GerritTask.IS_STARRED); if (state != null) { if (state.equals("true")) { //$NON-NLS-1$ return INCOMING_COLOR; } else if (state.equals("false")) { //$NON-NLS-1$ return CLOSED_COLOR; } } } return DEFAULT_COLOR; }

Target:
Should use Boolean.toString(true)
Source:
public void setVisible(boolean visible) { super.setVisible(visible); if (!visible) { setInput(null); } }

Target:
style nit: we don't use braces around single line blocks
Source:
public int handlesSelection(ISelection selection) { // By default, we don't support anything. int result = 0; Object sel = SelectionUtils.getSelectedObject(selection); if (sel instanceof GdbLaunch || sel instanceof GDBProcess || sel instanceof IDMVMContext) { result = 2; } // While we're here, see if we need to attach debug view listener updateDebugViewListener(); return result; }

Target:
Probably should not only increase to two. We should give ourselves some space for other visualizer to come in between, so maybe go to 10?
Source:
private DocumentBuilder newDocumentBuilder(StringWriter writer, boolean xhtmlStrict) { HtmlLanguage language = builder.add(BlockType.PARAGRAPH) .setXhtmlStrict(xhtmlStrict) .document("", "") .name("Test") .create(); return language.createDocumentBuilder(writer); }

Target:
inline return (no need for language variable here)
Source:
private static IConfiguration helper_getActiveConfiguration(IProject project) { IManagedBuildInfo buildInfo = ManagedBuildManager.getBuildInfo(project); IConfiguration ActiveConf = buildInfo.getDefaultConfiguration(); return ActiveConf; }

Target:
Please stick to java convention for naming variables - first letter should be lower case. Also this is another case where local variable is not needed just return it directly.