auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void addFile(String fileName, File file) throws Exception { Git gitProject = getGitProject(); CommonTestUtil.copy(file, new File(getFolder(), fileName)); START gitProject.add().addFilepattern(".").call(); END } consider using the file name rather than adding all files ("."). The result should be the same, though.

Target:
public void addFile(String fileName, File file) throws Exception { Git gitProject = getGitProject(); CommonTestUtil.copy(file, new File(getFolder(), fileName)); gitProject.add().addFilepattern(fileName).call(); }
Source:
START private Matcher<byte[]> empty() { END return nullValue(byte[].class); } static?

Target:
private static Matcher<byte[]> empty() { return nullValue(byte[].class); }
Source:
public void dispose() { if (fTreeViewer != null) { fTreeViewer.dispose(); } if (fXYViewer != null) { fXYViewer.dispose(); START } END } You should probably call super.dispose() here too

Target:
public void dispose() { super.dispose(); if (fTreeViewer != null) { fTreeViewer.dispose(); } if (fXYViewer != null) { fXYViewer.dispose(); } }
Source:
public AbstractCommandSelectionDialog(Shell parentShell, IModelResource resource, Messages Messages) { super(parentShell); this.resource = resource; this.Messages = Messages; START ToolsEmfUiPlugin.getDefault().registerForLocationAndSizePersistence(this); END } 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()

Target:
public AbstractCommandSelectionDialog(Shell parentShell, IModelResource resource, Messages Messages) { super(parentShell); this.resource = resource; this.Messages = Messages; }
Source:
public void TestExist() { START BtfTrace fixture = (BtfTrace) BtfTestTrace.BTF_TEST.getTrace(); END assertNotNull(fixture); } EVERY one of the tests do this. How about a @Before instead? I assume those traces should get closed/disposed too?

Target:
public void TestExist() { fixture = BtfTestTrace.BTF_TEST.getTrace(); assertNotNull(fixture); }
Source:
public void initTrace(IResource resource, String path, Class<? extends ITmfEvent> type) throws TmfTraceException { super.initTrace(resource, path, type); fFile = new File(path); try { START fFileInput = new RandomAccessFile(fFile, "r"); //$NON-NLS-1$ END parseHeader(); } catch (IOException e) { // won't happen } } 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.

Target:
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(fFileInput); } catch (IOException e) { // won't happen } }
Source:
public Object getAdapter(Object element, Class key) { START BtfEvent tmfEvent = (BtfEvent) element; END if (IPropertySource.class.equals(key)) { return new BtfEventPropertySource(tmfEvent); } return null; } Type should be checked before casting

Target:
public Object getAdapter(Object element, Class key) { if (element instanceof BtfEvent && IPropertySource.class.equals(key)) { BtfEvent tmfEvent = (BtfEvent) element; return new BtfEventPropertySource(tmfEvent); } return null; }
Source:
public void tearDown() { START if (fModule != null) { END fModule.close(); } if (fTrace != null) { fTrace.dispose(); File suppDir = new File(TmfTraceManager.getSupplementaryFileDir(fTrace)); deleteDirectory(suppDir); } } Why a null check here, but not in previous test classes? Can this one be null more than others?

Target:
public void tearDown() { fModule.close(); if (fTrace != null) { fTrace.dispose(); File suppDir = new File(TmfTraceManager.getSupplementaryFileDir(fTrace)); deleteDirectory(suppDir); } }
Source:
START public List<IEventDeclaration> getEventDeclarations() { END ArrayList<IEventDeclaration> retVal = new ArrayList<>(fEvents); retVal.removeAll(Collections.singletonList(null)); return retVal; } 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).

Target:
public Collection<IEventDeclaration> getEventDeclarations() { ArrayList<IEventDeclaration> retVal = new ArrayList<>(fEvents); retVal.removeAll(Collections.singletonList(null)); return retVal; }
Source:
public WorkState getState(String string) { START for (WorkState state : new CopyOnWriteArrayList<WorkState>(states)) { END if (state.getName().equals(string)) { return state; } } return null; } 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.

Target:
public WorkState getState(String string) { for (WorkState state : states) { if (state.getName().equals(string)) { return state; } } return null; }
Source:
public ExecutationType solutionFound(ThreadContext context, Solution solution) { START if (solution == null) { END return ExecutationType.CONTINUE; } return ExecutationType.STOP_ALL; } is solution allowed to be null?

Target:
public ExecutationType solutionFound(ThreadContext context, Solution solution) { return ExecutationType.STOP_ALL; }
Source:
public void calculateHash(int mDepth) { int maxDepth = coders.size() + 1; if (!isRoot()) { throw new InvalidParameterException("Can only be called on the root VertexCoder!"); } START String lastHash = "XXX"; END calculateCodes(maxDepth, false); int expansionDepth = 1; while (!lastHash.equals(labellessCode) && expansionDepth <= mDepth) { lastHash = labellessCode; expand(expansionDepth++); calculateCodes(maxDepth, false); } calculateCodes(maxDepth, true); } use more descriptive string, and maybe put it into a constant

Target:
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 = null; calculateCodes(maxDepth, false); int expansionDepth = 1; while (!lastHash.equals(labellessCode) && expansionDepth <= mDepth) { lastHash = labellessCode; expand(expansionDepth++); calculateCodes(maxDepth, false); } calculateCodes(maxDepth, true); }
Source:
private MyModel[] createModel() { START MyModel[] elements = new MyModel[10]; END for (int i = 0; i < elements.length; i++) { elements[i] = new MyModel(i); } return elements; } Lists

Target:
private List<MyModel> createModel() { List<MyModel> elements = new ArrayList<MyModel>(); for (int i = 0; i < 10; i++) { elements.add(new MyModel(i)); } return elements; }
Source:
private MyModel[] createModel() { START MyModel[] elements = new MyModel[11]; END for (int i = 0; i < elements.length - 1; i++) { elements[i] = new MyModel(i); } elements[elements.length - 1] = new MyModel(42); return elements; } Use list

Target:
private List<MyModel> createModel() { List<MyModel> elements = new ArrayList<MyModel>(); for (int i = 0; i < 10; i++) { elements.add(new MyModel(i)); } return elements; }
Source:
public ArrayDefinition lookupArray(String name) { Definition def = lookupDefinition(name); START return (ArrayDefinition) ((def.getDeclaration() instanceof ArrayDeclaration) ? def : null); END } why not do (def instanceof ArrayDefinition) ?

Target:
public ArrayDefinition lookupArray(String name) { Definition def = lookupDefinition(name); return (ArrayDefinition) ((def instanceof ArrayDefinition) ? def : null); }
Source:
public TmfStatisticsTreeNode getTop() { if (fTopNode == null) { fTopNode = this; while (fTopNode.getParent() != null && fTopNode.getParent().getParent() != null) { fTopNode = fTopNode.getParent(); START } END } return fTopNode; } Can't you do this in the constructor, and make the field fTopNode final?

Target:
public TmfStatisticsTreeNode getTop() { return fTopNode; }
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(); START assertNotNull(stashed); END validateStashedCommit(stashed); assertTrue("untracked file should be left untouched.", untrackedFile.exists()); assertEquals("content", read(untrackedFile)); } this is already included in validateCoreStashedCommit()

Target:
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(); validateStashedCommit(stashed); assertTrue("untracked file should be left untouched.", untrackedFile.exists()); assertEquals("content", read(untrackedFile)); }
Source:
private static boolean anyFile(IResource[] memebers) { for (IResource member : memebers) { if (member.getType() == IResource.FILE) return true; else if (member.getType() == IResource.FOLDER) START return hasContainerAnyFiles(member); END } return false; } This returns too early. Maybe use something like this: if (member.getType() == IResource.FOLDER && hasContainerAnyFiles(member)) return true;

Target:
private static boolean anyFile(IResource[] memebers) { for (IResource member : memebers) { if (member.getType() == IResource.FILE) return true; else if (member.getType() == IResource.FOLDER) if (hasContainerAnyFiles(member)) return true; } return false; }
Source:
public void setVirtSpecifier(ICPPASTClassVirtSpecifier virtSpecifier) { assertNotFrozen(); if (virtSpecifier != null) { START this.virtSpecifier = virtSpecifier; END virtSpecifier.setParent(this); virtSpecifier.setPropertyInParent(CLASS_VIRT_SPECIFIER); } } Should this line be outside of the 'if' statement.

Target:
public void setVirtSpecifier(ICPPASTClassVirtSpecifier virtSpecifier) { assertNotFrozen(); this.virtSpecifier = virtSpecifier; if (virtSpecifier != null) { virtSpecifier.setParent(this); virtSpecifier.setPropertyInParent(CLASS_VIRT_SPECIFIER); } }
Source:
protected void handleDemandLoadException(Resource resource, IOException exception) throws RuntimeException { try { super.handleDemandLoadException(resource, exception); START } catch (Exception e) { END // do nothing, continue with loading, the exception has been added to the diagnostics of the // resource } } I'd rather we catch only the "org.eclipse.emf.common.util.WrappedException" instead of "any and all Exceptions". Wouldn't this be sufficient?

Target:
protected void handleDemandLoadException(Resource resource, IOException exception) throws RuntimeException { try { super.handleDemandLoadException(resource, exception); } catch (RuntimeException e) { // do nothing, continue with loading, the exception has been added to the diagnostics of the // resource } }
Source:
public void addCompareInputChangeListener(ICompareInputChangeListener listener) { START if (!containsListener(listener)) { END listeners.add(listener); } } The ListenerList implementation already takes care of this. Remove the "contains" test.

Target:
public void addCompareInputChangeListener(ICompareInputChangeListener listener) { listeners.add(listener); }
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); } START succeeded = true; END } finally { if (!succeeded) { // Cleanly end the content assist session before propagating an exception (see bug 434901). hide(); } } return proposals; } My suggestion about Throwable was incorrect, but the version in patch set #2 was simpler than this one.

Target:
private ICompletionProposal[] computeProposals(int offset) { if (fContentAssistSubjectControl != null) return fContentAssistant.computeCompletionProposals(fContentAssistSubjectControl, offset); return fContentAssistant.computeCompletionProposals(fViewer, offset); }
Source:
public void uncaughtException(Thread t, Throwable e) { if (e instanceof OperationCanceledException) { // handle cancellation } else { START if (diagnostic != null) { END diagnostic.add(BasicDiagnostic.toDiagnostic(e)); } else { EMFCompareIDEUIPlugin.getDefault().log(e); } } } Un-nest this if

Target:
public void uncaughtException(Thread t, Throwable e) { if (e instanceof OperationCanceledException) { // TODO: handle cancellation } else if (diagnostic != null) { diagnostic.add(BasicDiagnostic.toDiagnostic(e)); } else { EMFCompareIDEUIPlugin.getDefault().log(e); } }
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", START "Commnets"}; END return toReturn; } this should be a constants static final array since it never changes. No need to keep re-creating the array every time ?

Target:
private static 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; }
Source:
public Collection<Ref> call() throws GitAPIException, InvalidRemoteException, org.eclipse.jgit.api.errors.TransportException { START return callAsMap().values(); END } API breakage. The returned collection used to be modifiable, but is no more. I'm not sure if anyone will be affected.

Target:
public Collection<Ref> call() throws GitAPIException, InvalidRemoteException, org.eclipse.jgit.api.errors.TransportException { return execute().values(); }
Source:
START private void ensureLoaded() { END 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; } } this method should probably be synchronized

Target:
protected synchronized 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; } }
Source:
public void registerConnectorUis() { registerFromExtensionPoint(); START registerConnetorToConnectorUi(); END registerFromAdaptable(); } Can we move this down 1 line and remove the call to setConnectorForConnectorUi from registerFromAdaptable?

Target:
public void registerConnectorUis() { registerFromExtensionPoint(); registerFromAdaptable(); registerConnetorToConnectorUi(); }
Source:
START protected void setConnector(AbstractRepositoryConnector connector) { END this.connector = connector; } Should we make this private and remove the @since tag?

Target:
private void setConnector(AbstractRepositoryConnector connector) { this.connector = connector; }
Source:
START private void setConnector(AbstractRepositoryConnector connector) { END this.connector = connector; } 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.

Target:
public void setConnector(AbstractRepositoryConnector connector) { this.connector = connector; }
Source:
public BugzillaRestRepositorySettingsPage(TaskRepository taskRepository, AbstractRepositoryConnector connector, AbstractRepositoryConnectorUi connectorUi) { START super("Bugzilla REST Repository Settings", DESCRIPTION, taskRepository, connector == null END ? (BugzillaRestConnector.getDefault() == null ? new BugzillaRestConnector() : BugzillaRestConnector.getDefault()) : connector, connectorUi == null ? new BugzillaRestRepositoryConnectorUi() : connectorUi); setNeedsAnonymousLogin(true); setNeedsValidateOnFinish(true); } Should pass parameters along instead of doing null checks.

Target:
public BugzillaRestRepositorySettingsPage(TaskRepository taskRepository, AbstractRepositoryConnector connector, AbstractRepositoryConnectorUi connectorUi) { super("Bugzilla REST Repository Settings", DESCRIPTION, taskRepository, connector, connectorUi); setNeedsAnonymousLogin(true); setNeedsValidateOnFinish(true); }
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) START treeWalk.addTree(new RevWalk(repo).parseTree(rev)); END treeWalk.addTree(new DirCacheIterator(repo.readDirCache())); treeWalk.setFilter(TreeFilter.ANY_DIFF); return treeWalk.next(); } If rev is null, what will happen. Shouldn't it bail at that point? Also, brackets are needed.

Target:
private boolean anyDiffInIndex() throws IOException { final Repository repo = getRepository(); final TreeWalk treeWalk = new TreeWalk(repo); treeWalk.setRecursive(true); //recursive is required because a hash for a (sub)tree might not be available final ObjectId rev = repo.resolve("HEAD"); //$NON-NLS-1$ if (rev != null) { //HEAD doesn't exist for a new repo, then we want to compare against empty tree treeWalk.addTree(new RevWalk(repo).parseTree(rev)); } treeWalk.addTree(new DirCacheIterator(repo.readDirCache())); treeWalk.setFilter(TreeFilter.ANY_DIFF); return treeWalk.next(); }
Source:
public void dispose() { super.dispose(); START for (Resource disposable : this.disposables) { END disposable.dispose(); } } style nit: we don't use braces around single line blocks

Target:
public void dispose() { super.dispose(); for (Resource disposable : this.disposables) disposable.dispose(); }
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); START commands.add(new ApplyProfileCommand(umlSource, profile, (TransactionalEditingDomain)domain)); END return wrappedList.add(o); } Again, we're applying the same profile twice to the same package. Only this time it?s exactly the same command.

Target:
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); return wrappedList.add(o); }
Source:
public GroupIntoToolGroupCommand(ResourceSet set, ToolSection parent, Collection<EObject> selection) { super(set); this.selection = selection; START this.parent = parent; END } 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.

Target:
public GroupIntoToolGroupCommand(ResourceSet set, ToolSection parent, Collection<EObject> selection) { super(set, parent, selection); }
Source:
void hideToolTip () { START checkWidget (); END if (itemToolTip == null) return; itemToolTip.setVisible (false); } For non-public methods checkWidget() is not required.

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

Target:
void showTooltip (int x, int y) { if (itemToolTip == null) return; itemToolTip.setLocation (x, y); itemToolTip.setVisible (true); }
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; START } END } 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; }

Target:
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 START @SuppressWarnings("null") END VariantDefinition result = fixture.lookupVariant(ENUM_8); assertNull(result); } 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.

Target:
public void testLookupVariant() { VariantDefinition result = fixture.lookupVariant(ENUM_8); assertNull(result); }
Source:
private void setSubtreeChecked(Object element, boolean checked) { START fCheckboxTreeViewer.setChecked(element, checked); END 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); } } } Redundant with the one below the if?

Target:
private void setSubtreeChecked(Object element, boolean checked) { fCheckboxTreeViewer.setChecked(element, checked); if (checked) { fCheckboxTreeViewer.setGrayed(element, false); } Object[] children = fContentProvider.getChildren(element); if (children != null) { for (Object child : children) { setSubtreeChecked(child, checked); } } }
Source:
public void dispose() { START if (diagram.eResource() != null) { END diagram.eAdapters().remove(this); } diagram = null; session = null; } diagram != null && diagram.eResource != null if dispose is called twice for example, your proposition leads to a NPE we did not have before.

Target:
public void dispose() { if (diagram != null && diagram.eResource() != null) { diagram.eAdapters().remove(this); } diagram = null; session = null; }
Source:
public void close() { START fBitBuffer = BitBuffer.EMPTY_BITBUFFER; END } 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.

Target:
public void close() { fBitBuffer = null; }
Source:
START private @NonNull static List<Definition> createIntDefs(int size, int bits) { END 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; } @NonNull on its own on line above

Target:
private 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; }
Source:
START @NonNull ByteBuffer getByteBufferAt(long position, long size) throws CTFReaderException, IOException { END 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; } annotation on a separate line

Target:
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; }
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) { START if (state.equals("true")) { //$NON-NLS-1$ END return INCOMING_COLOR; } else if (state.equals("false")) { //$NON-NLS-1$ return CLOSED_COLOR; } } } return DEFAULT_COLOR; } Should use Boolean.toString(true)

Target:
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(Boolean.toString(true))) { return INCOMING_COLOR; } else if (state.equals(Boolean.toString(false))) { return CLOSED_COLOR; } } } return DEFAULT_COLOR; }
Source:
public void setVisible(boolean visible) { super.setVisible(visible); START if (!visible) { END setInput(null); } } style nit: we don't use braces around single line blocks

Target:
public void setVisible(boolean visible) { super.setVisible(visible); if (!visible) setInput(null); }
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) { START result = 2; END } // While we're here, see if we need to attach debug view listener updateDebugViewListener(); return result; } 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?

Target:
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 = 10; } // While we're here, see if we need to attach debug view listener updateDebugViewListener(); return result; }
Source:
private DocumentBuilder newDocumentBuilder(StringWriter writer, boolean xhtmlStrict) { HtmlLanguage language = builder.add(BlockType.PARAGRAPH) .setXhtmlStrict(xhtmlStrict) .document("", "") .name("Test") .create(); START return language.createDocumentBuilder(writer); END } inline return (no need for language variable here)

Target:
private DocumentBuilder newDocumentBuilder(StringWriter writer, boolean xhtmlStrict) { return builder.add(BlockType.PARAGRAPH) .setXhtmlStrict(xhtmlStrict) .document("", "") .name("Test") .create().createDocumentBuilder(writer); }
Source:
private static IConfiguration helper_getActiveConfiguration(IProject project) { IManagedBuildInfo buildInfo = ManagedBuildManager.getBuildInfo(project); START IConfiguration ActiveConf = buildInfo.getDefaultConfiguration(); END return ActiveConf; } 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.

Target:
private static IConfiguration helper_getActiveConfiguration(IProject project) { IManagedBuildInfo buildInfo = ManagedBuildManager.getBuildInfo(project); return buildInfo.getDefaultConfiguration(); }
Source:
public void registerModule(IAnalysisModule module) { if (module == null) { throw new IllegalArgumentException(); } ITmfTrace selectedTrace = TmfTraceManager.getInstance().getActiveTrace(); /* If no trace is active, just register the module */ if (selectedTrace == null) { fModule = module; return; } START @SuppressWarnings("resource") END IAnalysisModule selectedModule = selectedTrace.getAnalysisModule(module.getId()); /* register only if the module is for the currently selected trace */ if (selectedModule == module) { fModule = module; } } Don't put this, it's a "real" warning atm, until we get rid of it ;)

Target:
public void registerModule(IAnalysisModule module) { if (module == null) { throw new IllegalArgumentException(); } ITmfTrace selectedTrace = TmfTraceManager.getInstance().getActiveTrace(); /* If no trace is active, just register the module */ if (selectedTrace == null) { fModule = module; return; } IAnalysisModule selectedModule = selectedTrace.getAnalysisModule(module.getId()); /* register only if the module is for the currently selected trace */ if (selectedModule == module) { fModule = module; } }
Source:
START public RankedAdapterFactoryDescriptor.Registry getAdapterFactoryRegistry() { END RankedAdapterFactoryDescriptorRegistryImpl rankedAdapterFactoryRegistry = new RankedAdapterFactoryDescriptorRegistryImpl( ComposedAdapterFactory.Descriptor.Registry.INSTANCE, Multimaps .unmodifiableMultimap(adapterFactoryRegistry)); return rankedAdapterFactoryRegistry; } this method should return the same instance each time (meaning of "get"), store this value in a field named 'adapterFactoryRegistry'

Target:
public RankedAdapterFactoryDescriptor.Registry getAdapterFactoryRegistry() { return rankedAdapterFactoryRegistry; }
Source:
public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { START try (IAnalysisModule module = createModule();) { END if (module != null) { return module.getAnalysisRequirements(); } return Collections.EMPTY_SET; } } Not sure if it's worth changing this, once we remove AutoCloseable from IAnalysisModule, this will become an _error_! *gasp*

Target:
public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { IAnalysisModule module = createModule(); if (module != null) { return module.getAnalysisRequirements(); } return Collections.EMPTY_SET; }
Source:
START protected int getReplaceOffset() { END int start; if (fContext instanceof DocumentTemplateContext) { DocumentTemplateContext docContext = (DocumentTemplateContext)fContext; start= docContext.getStart(); } else { start= fRegion.getOffset(); } return start; } Why do you need this? Can't you pass the offset via context or region?

Target:
protected final int getReplaceOffset() { int start; if (fContext instanceof DocumentTemplateContext) { DocumentTemplateContext docContext = (DocumentTemplateContext)fContext; start= docContext.getStart(); } else { start= fRegion.getOffset(); } return start; }
Source:
public void setLockStatePrefetchEnabled(boolean enabled) { checkActive(); IEvent event = null; synchronized (CDOViewImpl.this) { if (enabled != lockStatePrefetchEnabled) { lockStatePrefetchEnabled = enabled; if (enabled) { cdoLockStatePrefetcher = new CDOLockStatePrefetcher(CDOViewImpl.this); } START else if (cdoLockStatePrefetcher != null) END { cdoLockStatePrefetcher.dispose(); cdoLockStatePrefetcher = null; } event = new LockStatePrefetchEventImpl(enabled); } } fireEvent(event); } Why not just an "else"?

Target:
public void setLockStatePrefetchEnabled(boolean enabled) { checkActive(); IEvent event = null; synchronized (CDOViewImpl.this) { if (enabled != lockStatePrefetchEnabled) { lockStatePrefetchEnabled = enabled; if (enabled) { cdoLockStatePrefetcher = new CDOLockStatePrefetcher(); } else { cdoLockStatePrefetcher.dispose(); cdoLockStatePrefetcher = null; } event = new LockStatePrefetchEventImpl(enabled); } } fireEvent(event); }
Source:
START public Collection<LockState<OBJECT, CONTEXT>> getLockStates() END { return new ArrayList<RWOLockManager.LockState<OBJECT, CONTEXT>>(objectToLockStateMap.values()); } It seems safer to synchronize this method! And all other methods return a List<...>.

Target:
public synchronized List<LockState<OBJECT, CONTEXT>> getLockStates() { return new ArrayList<RWOLockManager.LockState<OBJECT, CONTEXT>>(objectToLockStateMap.values()); }
Source:
public static void checkConfiguration() { // Schedule a job // This avoids that the check is executed too early // because in startup phase the JobManager is suspended // and scheduled Jobs are executed later Job job = new Job(UIText.ConfigurationChecker_checkConfiguration) { @Override protected IStatus run(IProgressMonitor monitor) { if (PlatformUI.isWorkbenchRunning()) PlatformUI.getWorkbench().getDisplay() .asyncExec(new Runnable() { public void run() { check(); } }); else START schedule(1000L); END return Status.OK_STATUS; } }; job.schedule(); } Could you add braces for if and else? We only omit the braces in simple statements.

Target:
public static void checkConfiguration() { // Schedule a job // This avoids that the check is executed too early // because in startup phase the JobManager is suspended // and scheduled Jobs are executed later Job job = new Job(UIText.ConfigurationChecker_checkConfiguration) { @Override protected IStatus run(IProgressMonitor monitor) { if (PlatformUI.isWorkbenchRunning()) { PlatformUI.getWorkbench().getDisplay() .asyncExec(new Runnable() { public void run() { check(); } }); } else { schedule(1000L); } return Status.OK_STATUS; } }; job.schedule(); }
Source:
public String getLabel(long time){ try { int quark = fValuechange.handleEntry(fBaseQuark, time); ITmfStateInterval value = fSs.querySingleState(time, quark); if (value != null && !value.getStateValue().isNull()) { ITmfStateValue state = value.getStateValue(); return state.toString(); } } catch (StateValueTypeException | TimeRangeException | AttributeNotFoundException | StateSystemDisposedException e) { } return null; START END } extra blank line

Target:
public String getLabel(long time){ if (fValuechange == null) { return null; } try { int quark = fValuechange.handleEntry(fBaseQuark, time); ITmfStateInterval value = fSs.querySingleState(time, quark); if (value != null && !value.getStateValue().isNull()) { ITmfStateValue state = value.getStateValue(); return state.toString(); } } catch (StateValueTypeException | TimeRangeException | AttributeNotFoundException | StateSystemDisposedException e) { } return null; }
Source:
private static Collection<CustomEventTableColumn> generateColumns(CustomTraceDefinition definition) { START List<CustomEventTableColumn> columns = new LinkedList<>(); END List<OutputColumn> outputs = definition.outputs; for (int i = 0; i < outputs.size(); i++) { String name = outputs.get(i).name; if (name != null) { columns.add(new CustomEventTableColumn(name, i)); } } return columns; } LinkedList :(

Target:
private static Collection<CustomEventTableColumn> generateColumns(CustomTraceDefinition definition) { ImmutableList.Builder<CustomEventTableColumn> builder = new ImmutableList.Builder<>(); List<OutputColumn> outputs = definition.outputs; for (int i = 0; i < outputs.size(); i++) { String name = outputs.get(i).name; if (name != null) { builder.add(new CustomEventTableColumn(name, i)); } } return builder.build(); }
Source:
START public TmfConstantTransform(ITmfTimestamp offset) { END fOffset = new TmfNanoTimestamp(offset); } If (?!) the offset is larger than Long.MAX_VALUE nanoseconds (using a different scale), this will overflow...

Target:
public TmfConstantTransform(ITmfTimestamp offset) { fOffset = offset; }
Source:
private String buildConflictingMessage(MergeResult mergeResult) { START final StringBuilder messageBuildder = new StringBuilder(); END final Integer returnCode; for (String conflictingFile : mergeResult.getConflicts().keySet()) { messageBuildder.append("Auto-merging failed in ").append(conflictingFile).append(EOL); messageBuildder.append("Automatic merge failed; fix conflicts and then commit the result.") .append(conflictingFile).append(EOL); } return messageBuildder.toString(); } Unused variable

Target:
private String buildConflictingMessage(MergeResult mergeResult) { final StringBuilder messageBuildder = new StringBuilder(); for (String conflictingFile : mergeResult.getConflicts().keySet()) { messageBuildder.append("Auto-merging failed in ").append(conflictingFile).append(EOL); messageBuildder.append("Automatic merge failed; fix conflicts and then commit the result.") .append(conflictingFile).append(EOL); } return messageBuildder.toString(); }
Source:
private boolean isAdd(ReferenceChange diff, boolean rightToLeft) { START return rightToLeft ? isLeftDeleteOrRightAdd(diff) : isLeftAddOrRightDelete(diff); END } Please install checkstyle in your environment (https://wiki.eclipse.org/EMF_Compare/Contributor_Guide#Checkstyle), we forbid the use of the ternary operator in EMF Compare. This should be if (rightToLeft) { return isLeftDeleteOrRightAdd(diff); } else { return isLeftAddOrRightDelete(diff); }

Target:
private boolean isAdd(ReferenceChange diff, boolean rightToLeft) { if (rightToLeft) { return isLeftDeleteOrRightAdd(diff); } else { return isLeftAddOrRightDelete(diff); } }
Source:
private boolean isLeftAddOrRightDelete(ReferenceChange diff) { START return (diff.getKind() == DifferenceKind.ADD && diff.getSource() == DifferenceSource.LEFT) END || (diff.getKind() == DifferenceKind.DELETE && diff.getSource() == DifferenceSource.RIGHT); } Checkstyle would allow this one, but I think the following would be easier to read : if (diff.getSource() == DifferenceSource.LEFT) { return diff.getKind() == DifferenceKind.ADD; } else { return diff.getKind() == DiferenceKind.DELETE; }

Target:
private boolean isLeftAddOrRightDelete(ReferenceChange diff) { if (diff.getSource() == DifferenceSource.LEFT) { return diff.getKind() == DifferenceKind.ADD; } else { return diff.getKind() == DifferenceKind.DELETE; } }
Source:
public void characters(String text) { assertOpenBlock(); START try { END for (int x = 0; x < text.length(); ++x) { char c = text.charAt(x); currentBlock.write(c); } } catch (IOException e) { throw new RuntimeException(e); } } why not just use currentBlock.write(text) here?

Target:
public void characters(String text) { assertOpenBlock(); try { currentBlock.write(text); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
public void entityReference(String entity) { START throw new UnsupportedOperationException("Builder does not currently support entity references."); //$NON-NLS-1$ END } no need for messages on these exceptions (detail will be available from the stack trace, and these throw statements will have to be removed as part of this review chain anyways)

Target:
public void entityReference(String entity) { throw new UnsupportedOperationException(); }
Source:
protected void finalize() throws Throwable { START ((ClassDiagramPattern) comboSelection).setPatternConfiguration(false, false); END super.finalize(); } Do not configure the selected pattern from here. If the user clic on finish, the skeleton will be created with the default value. Another remark : you make again a dangerous cast: the combo selection is a IPatternPovider, You will not have enough time but ClassDiagramPattern is expected to have friends.

Target:
protected void finalize() throws Throwable { if (comboSelection instanceof ClassDiagramPattern) ((ClassDiagramPattern) comboSelection).setPatternConfiguration(false, false); super.finalize(); }
Source:
public Collection<IPatternProvider> getPatternsList() { Collection<IPatternProvider> newPatternList = new ArrayList<IPatternProvider>(); //creating a class Diagram pattern //and create his own command // the command can be changed by configuration page. ClassDiagramPattern pattern = new ClassDiagramPattern(); START pattern.setPatternCommand(new InitializerCommand(resourceSet, selection)); END newPatternList.add(pattern); return newPatternList; } You must not init here the command. You configuration page should configure the pattern provider and it will instantiate the command on demand.

Target:
public Collection<IPatternProvider> getPatternsList() { Collection<IPatternProvider> newPatternList = new ArrayList<IPatternProvider>(); // creating a class Diagram pattern ClassDiagramPattern pattern = new ClassDiagramPattern(this.resourceSet, this.selection); newPatternList.add(pattern); return newPatternList; }
Source:
public void run() { InitializerWizard wizard = new InitializerWizard(this.editingDomain.getResourceSet(), selection); WizardDialog dialog = new WizardDialog(null, wizard); dialog.create(); if (dialog.open() == Window.OK) START this.result = wizard.getCommand(); END } Please, add { and } to the if statement. if (dialog.open() == Window.OK) { ICommand cmd = wizard.getCommand(); //command execution ? } Modifiy the inheritance of the action and add the command execution

Target:
public void run() { InitializerWizard wizard = new InitializerWizard(this.editingDomain.getResourceSet(), selection); WizardDialog dialog = new WizardDialog(null, wizard); dialog.create(); if (dialog.open() == Window.OK) { this.result = wizard.getCommand(); result.execute(); } }
Source:
public int compareTo(Filter other) { START if (!this.methodName.equals(other.methodName)) { END return this.methodName.compareTo(other.methodName); } else if (!this.className.equals(other.className)) { return this.className.compareTo(other.className); } return 0; } Rewrite as: int c = methodName.compareTo(other.methodName); if (c != 0) return c; return className.compareTo(other.className);

Target:
public int compareTo(Filter other) { int c = methodName.compareTo(other.methodName); if (c != 0) { return c; } return className.compareTo(other.className); }
Source:
public void addFilter(ITmfFilterTreeNode filter) { ITmfFilterTreeNode root = fViewer.getInput(); for (int i = 0; i < root.getChildrenCount(); i++) { START if (root.getChild(0).equals(filter)) { END return; } } root.addChild(filter); fViewer.setInput(root); } did you mean getChild(i)?

Target:
public void addFilter(ITmfFilterTreeNode filter) { ITmfFilterTreeNode root = fViewer.getInput(); for (int i = 0; i < root.getChildrenCount(); i++) { if (root.getChild(i).equals(filter)) { return; } } root.addChild(filter); fViewer.setInput(root); }
Source:
public TmfConstantTransform(long offset) { START fOffset = Long.valueOf(offset); END } fOffset = offset?

Target:
public TmfConstantTransform(long offset) { fOffset = offset; }
Source:
public InputStream prefetchStream(URI uri, Map<?, ?> options) throws IOException { InputStream stream = createInputStream(uri, options); if (stream != null) { synchronized(prefetchedStreams) { START prefetchedStreams.put(uri, stream); END } } return stream; } put(uri, stream) on a concurrentHashMap avoids the "synchronized"

Target:
public boolean prefetchStream(URI uri, Map<?, ?> options) throws IOException { InputStream stream = createInputStream(uri, options); if (stream != null) { prefetchedStreams.put(uri, stream); } return stream != null; }
Source:
public String getTargetTypeName(ILaunchTarget target) { START return getContribution(target) == null ? null : getContribution(target).name; END } Instead of all these null check why don't you make getContribution always return non-null? I.e. return default provider if there is no mapping

Target:
public String getTargetTypeName(ILaunchTarget target) { return getContribution(target).name; }
Source:
public Set<ApprovalCategoryValue.Id> getApprovals() { START return Collections.unmodifiableSet(approvals); END } Why are you using "Collections.unmodifiableSet(approvals);" and not just "approvals" since the variable is already defined as "Collections.unmodifiableSet"

Target:
public Set<ApprovalCategoryValue.Id> getApprovals() { return approvals; }
Source:
START public void testRetrieveCollecton() throws ItemNotFoundException, IllegalOperationException, IOException, END AccessDeniedException, NoSuchResourceStoreException { final String collectionPath = "/dir"; final StorageItem item = unzipRepo.doRetrieveItem(new ResourceStoreRequest(collectionPath)); Assert.assertTrue(item instanceof ZipAwareStorageCollectionItem); final StorageCollectionItem collectionItem = (StorageCollectionItem) item; Assert.assertEquals(collectionPath, collectionItem.getPath()); TestUtil.assertMembers(new String[] { "/dir/subdir" }, new String[0], collectionItem.list()); } (minor) simply declare "throws Exception" to remove clutter. This is perfectly OK for test methods. Same for other test methods in this class I guess.

Target:
public void testRetrieveCollecton() throws Exception { final String collectionPath = "/dir"; final StorageItem item = unzipRepo.doRetrieveItem(new ResourceStoreRequest(collectionPath)); Assert.assertTrue(item instanceof ZipAwareStorageCollectionItem); final StorageCollectionItem collectionItem = (StorageCollectionItem) item; Assert.assertEquals(collectionPath, collectionItem.getPath()); TestUtil.assertMembers(new String[] { "/dir/subdir" }, new String[0], collectionItem.list()); }
Source:
public static TraceLogLevel valueOfString(String name) { if (name == null) { START throw new InvalidParameterException(); END } for (TraceLogLevel tllevel : TraceLogLevel.values()) { if (tllevel.getInName().equalsIgnoreCase(name)) { return tllevel; } } // No match return LEVEL_UNKNOWN; } Use InvalidArgumentException instead

Target:
public static TraceLogLevel valueOfString(String name) { if (name == null) { throw new IllegalArgumentException(); } for (TraceLogLevel tllevel : TraceLogLevel.values()) { if (tllevel.getInName().equalsIgnoreCase(name)) { return tllevel; } } // No match return LEVEL_UNKNOWN; }
Source:
START public ILocation getLocation() { END LineRange selectedRange = getSelectedRange(); ILineLocation location = ReviewsFactory.eINSTANCE.createLineLocation(); ILineRange range = ReviewsFactory.eINSTANCE.createLineRange(); range.setStart(selectedRange.getStartLine()); range.setEnd(selectedRange.getStartLine() + selectedRange.getNumberOfLines()); location.getRanges().add(range); return location; } Fine to move the command, but since you try to refactor the code, this method should be private

Target:
private ILocation getLocation() { LineRange selectedRange = getSelectedRange(); ILineLocation location = ReviewsFactory.eINSTANCE.createLineLocation(); ILineRange range = ReviewsFactory.eINSTANCE.createLineRange(); range.setStart(selectedRange.getStartLine()); range.setEnd(selectedRange.getStartLine() + selectedRange.getNumberOfLines()); location.getRanges().add(range); return location; }
Source:
START public long getId() { END return fId; } should remain int too

Target:
public int getId() { return fId; }
Source:
public void widgetSelected(SelectionEvent e) { IStructuredSelection selection = viewer.getStructuredSelection(); START if (selection != null) { END viewer.editElement(selection.getFirstElement(), 0); } } Okay then I will apply a patch for your proposed bug report.

Target:
public void widgetSelected(SelectionEvent e) { IStructuredSelection selection = viewer.getStructuredSelection(); if (!selection.isEmpty()) { viewer.editElement(selection.getFirstElement(), 0); } }
Source:
START public int compareQualifier(RepositoryVersion other) { END if (this.qualifier != null && other.qualifier == null) { return -1; } else { if (this.qualifier == null && other.qualifier != null) { return 1; } else { if (this.qualifier == null && other.qualifier == null) { return 0; } else { return this.qualifier.compareTo(other.qualifier); } } } } protected?

Target:
protected int compareQualifier(RepositoryVersion other) { if (this.qualifier != null && other.qualifier == null) { return -1; } else { if (this.qualifier == null && other.qualifier != null) { return 1; } else { if (this.qualifier == null && other.qualifier == null) { return 0; } else { return this.qualifier.compareTo(other.qualifier); } } } }
Source:
START public int compareMajor(RepositoryVersion other) { END if (this.major != null && other.major == null) { return 1; } else { if (this.major == null && other.major != null) { return -1; } else { if (this.major == null && other.major == null) { return 0; } else { return this.major - other.major; } } } } Should these be protected?

Target:
protected int compareMajor(RepositoryVersion other) { if (this.major != null && other.major == null) { return 1; } else { if (this.major == null && other.major != null) { return -1; } else { if (this.major == null && other.major == null) { return 0; } else { return this.major - other.major; } } } }