auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void use(String iconSetName) { try { IconSet iconSet = iconSetManager.getIconSet(iconSetName); if (iconSet == null) { START iconSet = iconSetManager.getDefaultIconSet(); END } iconRenderer.use(iconSet); } catch (IconException e) { setLastError(e); } } I don't think we should do a fallback here.

Target:
public void use(String iconSetName) { try { IconSet iconSet = iconSetManager.getIconSet(iconSetName); iconRenderer.use(iconSet); } catch (IconException e) { setLastError(e); } }
Source:
START public DocumentMovedEvent(DocumentReference documentReference) END { this(documentReference, null); } It's really not clear if this is the source or the target.

Target:
public DocumentMovedEvent(DocumentReference documentReference) { super(documentReference); }
Source:
public XWikiAttachment setAttachment(XWikiAttachment attachment) { START attachment.setDoc(this); END return this.attachmentList.set(attachment); } Actually you do have this feature in XWikiAttachmentList#set arleady but you do it after adding the attachment instead of before :)

Target:
public XWikiAttachment setAttachment(XWikiAttachment attachment) { return this.attachmentList.set(attachment); }
Source:
public boolean add(XWikiAttachment attachment) { START map.put(attachment.getFilename(), attachment); END this.list = new ArrayList<XWikiAttachment>(map.values()); onUpdate(); added(attachment); return true; } Most of the method is a duplicate of #set() so you should reuse it instead.

Target:
public boolean add(XWikiAttachment attachment) { XWikiAttachment set = set(attachment); return set != attachment; }
Source:
public boolean addAll(Collection<? extends XWikiAttachment> c) { boolean changed = false; for (XWikiAttachment x : c) { START if (map.put(x.getFilename(), x) == null) { END changed = true; added(x); } } if (changed) { updatedMap(); } return changed; } You should compare with x, not null since there could already be a different attachment in the map.

Target:
public boolean addAll(Collection<? extends XWikiAttachment> c) { boolean changed = false; for (XWikiAttachment x : c) { XWikiAttachment put = map.put(x.getFilename(), x); if (put != x) { changed = true; added(x); } } if (changed) { updatedMap(); } return changed; }
Source:
public boolean add(XWikiAttachment attachment) { XWikiAttachment set = set(attachment); START return !set.equals(attachment); END } Don't use equals for attachment instances.

Target:
public boolean add(XWikiAttachment attachment) { XWikiAttachment set = set(attachment); return set != attachment; }
Source:
public boolean addAll(Collection<? extends XWikiAttachment> c) { boolean changed = false; for (XWikiAttachment x : c) { XWikiAttachment put = map.put(x.getFilename(), x); START if (!x.equals(put)) { END changed = true; added(x); } } if (changed) { updatedMap(); } return changed; } Don't use equals for attachment instances.

Target:
public boolean addAll(Collection<? extends XWikiAttachment> c) { boolean changed = false; for (XWikiAttachment x : c) { XWikiAttachment put = map.put(x.getFilename(), x); if (put != x) { changed = true; added(x); } } if (changed) { updatedMap(); } return changed; }
Source:
private void updatedMap() { document.setMetaDataDirty(true); START this.setCollection(map.values()); END } This is not right. You need to pass a new new ArrayList to setCollection() since values() is not a List and any call to decorated() will crash.

Target:
private void updatedMap() { document.setMetaDataDirty(true); this.setCollection(new ArrayList<>(map.values())); }
Source:
public boolean retainAll(Collection<?> c) { boolean changed = false; Collection<XWikiAttachment> values = map.values(); for (XWikiAttachment x : values) { if (!c.contains(x)) { START map.remove(x.getFilename(), x); END changed = true; } } if (changed) { updatedMap(); } return changed; } Too quick, I doubt this builds :) Also a better way to do that in term of performance is to use an Iterator in the for and call Iterator#remove() instead of making it search the entry in the Map again.

Target:
public boolean retainAll(Collection<?> c) { boolean changed = false; Collection<XWikiAttachment> values = map.values(); for (XWikiAttachment x : values) { if (!c.contains(x)) { map.remove(x.getFilename()); changed = true; } } if (changed) { updatedMap(); } return changed; }
Source:
public void listClear() throws XWikiException{ attachmentList.clear(); START assertEquals(attachmentList,new ArrayList<XWikiAttachment>()); END } I would assertTrue attachmentList.isEmpty() instead since that's what you want to know (not that it's equals to some list).

Target:
public void listClear() throws XWikiException { attachmentList.clear(); assertTrue(attachmentList.isEmpty()); }
Source:
public byte[] getResourceContentAsBytes(String name) throws IOException { byte output[] = new byte[0]; START if (getEngineContext() != null) { END try (InputStream is = getResourceAsStream(name)) { if (is == null) { output = FileUtils.readFileToByteArray(new File(name)); } else output = IOUtils.toByteArray(is); } } return output; } Actually I mixed with the other pull request, there was indeed a catch before so you should put it back, sorry.

Target:
public byte[] getResourceContentAsBytes(String name) throws IOException { if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is != null) { return IOUtils.toByteArray(is); } } catch (Exception e) { } } return FileUtils.readFileToByteArray(new File(name)); }
Source:
public byte[] getResourceContentAsBytes(String name) throws IOException { if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is != null) { return IOUtils.toByteArray(is); } } catch(Exception e){ } START return FileUtils.readFileToByteArray(new File(name)); END } return new byte[0]; } Was not part of the `if (getEngineContext() != null) {` before.

Target:
public byte[] getResourceContentAsBytes(String name) throws IOException { if (getEngineContext() != null) { try (InputStream is = getResourceAsStream(name)) { if (is != null) { return IOUtils.toByteArray(is); } } catch (Exception e) { } } return FileUtils.readFileToByteArray(new File(name)); }
Source:
START public BodyPart addPart(BodyPart bodyPart) END { return addPart(null, bodyPart); } missing a `@since` and an `@Unstable` annotations.

Target:
public void addPart(BodyPart bodyPart) { addPart(null, bodyPart); }
Source:
public DocumentMovedEvent(DocumentReference documentReference) { START String move; END super(documentReference); this.move = move; } This does not build.

Target:
public DocumentMovedEvent(DocumentReference documentReference) { this(documentReference, null); }
Source:
public CompositeEvent(CompositeEvent compositeEvent) { START this.events = compositeEvent.events; END this.similarityBetweenEvents = compositeEvent.similarityBetweenEvents; } It means you will the same list. So if you change `this.events`, it will impact `compositeEvent.events` too.

Target:
public CompositeEvent(CompositeEvent compositeEvent) { this.events = new ArrayList<>(compositeEvent.events); this.similarityBetweenEvents = compositeEvent.similarityBetweenEvents; }
Source:
public boolean matches(Object o) { START return (this.getClass().isInstance(o) && ((AbstractEventStreamEvent) o).getEvent().equals(this.event)); END } It means you cannot create a listener actually, because the listener will never match: ``` ((AbstractEventStreamEvent) o).getEvent().equals(this.event)) ``` You see what I mean?

Target:
public boolean matches(Object o) { return (this.getClass().isInstance(o)); }
Source:
START private boolean isAllGroupImplicit(XWikiContext context) END { return context.getWiki().isAllGroupImplicit(); } You should not change the visibility. Since XWikiGroupServiceImpl is a public class what you do here is the same as removing a method from an API. If you build with -Pquality you should get an error.

Target:
protected boolean isAllGroupImplicit(XWikiContext context) { return context.getWiki().isAllGroupImplicit(); }
Source:
private String getPropertyType(String className, String propertyName, XWikiContext context) throws Exception { PropertyClass pc = null; try { pc = (PropertyClass) context.getWiki().getDocument(className, context).getXClass().get(propertyName); } catch (XWikiException e) { LOGGER.error("Failed to get property for document [{}]", propertyName, className, e); } START return pc.newProperty().getClass().getName(); END } This will throw a `NullPointerException` if an `XWikiException` is caught above. You need to choose between - falling back on a default property type in case of an `XWikiException` or - let the `XWikiException` propagate In general, there are two main reasons for which you would catch an exception: - provide a fall back or - throw a more domain-specific exception that wraps the caught exception.

Target:
private String getPropertyType(String className, String propertyName, XWikiContext context) throws Exception { PropertyClass pc = null; try { pc = (PropertyClass) context.getWiki().getDocument(className, context).getXClass().get(propertyName); } catch (XWikiException e) { LOGGER.error("Failed to get property for document [{}]", propertyName, className, e); } return pc == null ? null : pc.newProperty().getClass().getName(); }
Source:
public void maxSimultaneousCompilations() throws Exception { when(xwikiPropertiesSource.getProperty("lesscss.maximumSimultaneousCompilations",4)).thenReturn(4); int i = mocker.getComponentUnderTest().getMaximumSimultaneousCompilations(); START assertTrue(i == 4); END } Just for the information, you could use: ``` assertEquals(4, i) ```

Target:
public void maxSimultaneousCompilations() throws Exception { when(xwikiPropertiesSource.getProperty("lesscss.maximumSimultaneousCompilations",4)).thenReturn(4); int i = mocker.getComponentUnderTest().getMaximumSimultaneousCompilations(); assertEquals(4,i); }
Source:
public String getHint() { START return getBasePropertyClass().getTranslatedHint(context); END } API methods are supposed to be simple wrappers for the protected classes. As such, it's not quite right that an API method calls a different method (`getHint` doesn't call the equivalent `getHint`, but `getTranslatedHint`).

Target:
public String getHint() { return getBasePropertyClass().getHint(); }
Source:
START List<GermplasmList> retrieveAndValidateIfHasGermplasmList(Integer studyId) throws MiddlewareQueryException, END CrossingTemplateExportException { List<GermplasmList> crossesList = this.fieldbookMiddlewareService.getGermplasmListsByProjectId(studyId, GermplasmListType.NURSERY); if (crossesList.isEmpty()) { throw new CrossingTemplateExportException("study.export.crosses.no.germplasm.list.available"); } return crossesList; } Remove MiddlewareQueryException

Target:
List<GermplasmList> retrieveAndValidateIfHasGermplasmList(Integer studyId) throws CrossingTemplateExportException { List<GermplasmList> crossesList = this.fieldbookMiddlewareService.getGermplasmListsByProjectId(studyId, GermplasmListType.NURSERY); if (crossesList.isEmpty()) { throw new CrossingTemplateExportException("study.export.crosses.no.germplasm.list.available"); } return crossesList; }
Source:
public Expression lookup(final String pattern) { if (expressionMap.containsKey(pattern)) { return expressionMap.get(pattern); } START for (String key : expressionMap.keySet()) { END if (key != null && pattern.matches(key)) { Expression expression = expressionMap.get(key); expressionMap.put(pattern, expression); // memoize return expression; } } return null; } add final

Target:
public Expression lookup(final String pattern) { if (expressionMap.containsKey(pattern)) { return expressionMap.get(pattern); } for (final String key : expressionMap.keySet()) { if (key != null && pattern.matches(key)) { final Expression expression = expressionMap.get(key); expressionMap.put(pattern, expression); // memoize return expression; } } return null; }
Source:
public void testGetStartingSequenceNumberWhereCrossSettingStartNumberIsNull() { this.crossSetting.getCrossNameSetting().setStartNumber(null); final CrossNameSetting setting = new CrossNameSetting(); START setting.setStartNumber(0); END setting.setPrefix("A"); final int startingSequenceNumber = this.crossingService.getStartingSequenceNumber(setting); Assert.assertEquals("The starting sequence number should be " + startingSequenceNumber, CrossingServiceImplTest.NEXT_NUMBER.intValue(), startingSequenceNumber); } In this test, the start number is not null but zero. Please create a test also when it is actually null.

Target:
public void testGetStartingSequenceNumberWhereCrossSettingStartNumberIsNull() { final CrossNameSetting setting = new CrossNameSetting(); setting.setStartNumber(null); setting.setPrefix("A"); final int startingSequenceNumber = this.crossingService.getStartingSequenceNumber(setting); Assert.assertEquals("The starting sequence number should be " + startingSequenceNumber, CrossingServiceImplTest.NEXT_NUMBER.intValue(), startingSequenceNumber); }
Source:
private void validateAndSetNewDesignation(final int desigColumn, final Row xlsRow, final MeasurementRow measurementRow) throws WorkbookParserException { final String newDesig = this.getDesignation(xlsRow, desigColumn); START setNewDesignation(measurementRow, newDesig); END } Please add this.

Target:
private void validateAndSetNewDesignation(final int desigColumn, final Row xlsRow, final MeasurementRow measurementRow) throws WorkbookParserException { final String newDesig = this.getDesignation(xlsRow, desigColumn); this.setNewDesignation(measurementRow, newDesig); }
Source:
public List<Object> configurations() { START return Collections.singletonList(new TooManyLinesInFileCheck.Config(maximum)); END } You can probably remove `TooManyLinesInFileCheck`

Target:
public List<Object> configurations() { return Collections.singletonList(new Config(maximum)); }
Source:
public List<Object> configurations() { START return Collections.singletonList(new TooManyLinesInFunctionCheck.Config(max)); END } same here, remove `TooManyLinesInFunctionCheck`

Target:
public List<Object> configurations() { return Collections.singletonList(new Config(max)); }
Source:
private static void saveHighlights(InputFile file, SensorContext context, AnalysisResponseHighlight[] highlights) { NewHighlighting highlighting = context.newHighlighting().onFile(file); for (AnalysisResponseHighlight highlight : highlights) { highlighting.highlight(highlight.startLine, highlight.startCol, highlight.endLine, highlight.endCol, START TypeOfText.valueOf(highlight.textType.toUpperCase(Locale.ENGLISH))); END } highlighting.save(); } we should avoid this conversion by sending uppercase constants in the response directly

Target:
private static void saveHighlights(InputFile file, SensorContext context, AnalysisResponseHighlight[] highlights) { NewHighlighting highlighting = context.newHighlighting().onFile(file); for (AnalysisResponseHighlight highlight : highlights) { highlighting.highlight(highlight.startLine, highlight.startCol, highlight.endLine, highlight.endCol, TypeOfText.valueOf(highlight.textType)); } highlighting.save(); }
Source:
START public String[] getFileSuffixes() { END String[] suffixes = configuration.getStringArray(FILE_SUFFIXES_KEY); if (suffixes == null || suffixes.length == 0) { suffixes = StringUtils.split(FILE_SUFFIXES_DEFVALUE, ","); } return suffixes; } should we simplify this implementation the same way it's done for TS?

Target:
public String[] getFileSuffixes() { return configuration.getStringArray(FILE_SUFFIXES_KEY); }
Source:
public void execute(SensorContext context) { if (rules.length == 0) { START LOG.info("Skipping execution of eslint-based rules because none of them are activated"); END return; } startEslintBridgeServerProcess(); if (process == null) { return; } try { for (InputFile inputFile : getInputFiles(context)) { analyze(inputFile, context); } } finally { clean(); } } I think this should be `DEBUG`

Target:
public void execute(SensorContext context) { if (rules.length == 0) { LOG.debug("Skipping execution of eslint-based rules because none of them are activated"); return; } startEslintBridgeServerProcess(); if (process == null) { return; } try { for (InputFile inputFile : getInputFiles(context)) { analyze(inputFile, context); } } finally { clean(); } }
Source:
public static int findOpenPort() { try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); } catch (IOException e) { START return 3000; END } } I don't think it makes sense to try to recover from this exception, we should just log and fail in the sensor (i.e. skip analysis)

Target:
public static int findOpenPort() throws IOException { try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); } }
Source:
START private List<String> buildCommand(String nodeExecutable, List<String> nodeJsArgs, @Nullable String scriptFilename, List<String> args) { END List<String> result = new ArrayList<>(); result.add(nodeExecutable); result.addAll(nodeJsArgs); if (scriptFilename != null) { result.add(scriptFilename); } result.addAll(args); return Collections.unmodifiableList(result); } ![Code Smell](https://sonarsource.github.io/sonar-github/code_smell.png 'Code Smell') Code Smell: Make "buildCommand" a "static" method. ([squid:S2325](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS2325)) [See it in SonarQube](https://next.sonarqube.com/sonarqube/project/issues?id=org.sonarsource.javascript%3Ajavascript&pullRequest=1065&issues=AWYLrx4p0ts69roINji_&open=AWYLrx4p0ts69roINji_) [ISSUE_KEY]: AWYLrx4p0ts69roINji_

Target:
private static List<String> buildCommand(String nodeExecutable, List<String> nodeJsArgs, @Nullable String scriptFilename, List<String> args) { List<String> result = new ArrayList<>(); result.add(nodeExecutable); result.addAll(nodeJsArgs); if (scriptFilename != null) { result.add(scriptFilename); } result.addAll(args); return Collections.unmodifiableList(result); }
Source:
START public static WsClient newWsClient() { END return WsClientFactories.getDefault().newClient(HttpConnector.newBuilder() .url(orchestrator.getServer().getUrl()) .build()); } Also here access can be private

Target:
private static WsClient newWsClient() { return WsClientFactories.getDefault().newClient(HttpConnector.newBuilder() .url(orchestrator.getServer().getUrl()) .build()); }
Source:
public boolean isExcluded(InputFile file) { boolean isMinified = new MinificationAssessor().isMinified(file); if (isMinified) { START LOG.debug("File [" + file.toString() + "] looks like a minified file and will not be analyzed"); END } return isMinified; } @vilchik-elena same

Target:
public boolean isExcluded(InputFile file) { boolean isMinified = new MinificationAssessor().isMinified(file); if (isMinified) { LOG.debug("File [" + file.uri() + "] looks like a minified file and will not be analyzed"); } return isMinified; }
Source:
public void should_add_error_to_context_but_not_fail_analysis_with_technical_error() { JavaScriptCheck check = new ExceptionRaisingCheck(new NullPointerException("NPE forcibly raised by check class")); InputFile file = inputFile("file.js"); createSensor().analyseFiles(context, ImmutableList.of((TreeVisitor) check), ImmutableList.of(file), executor, progressReport); assertThat(context.allAnalysisErrors()).hasSize(1); START assertThat(logTester.logs()).contains("Unable to analyse file: " + file.toString()); END } @vilchik-elena if you follow my suggestion on `file.uri()` you'll have to update here as well

Target:
public void should_add_error_to_context_but_not_fail_analysis_with_technical_error() { JavaScriptCheck check = new ExceptionRaisingCheck(new NullPointerException("NPE forcibly raised by check class")); InputFile file = inputFile("file.js"); createSensor().analyseFiles(context, ImmutableList.of((TreeVisitor) check), ImmutableList.of(file), executor, progressReport); assertThat(context.allAnalysisErrors()).hasSize(1); assertThat(logTester.logs()).contains("Unable to analyse file: " + file.uri()); }
Source:
public void test() throws Exception { assertThat(g.rule(Tree.Kind.FLOW_FUNCTION_TYPE)) .matches("(str: string) => void") .matches("(str: string, number) => void") .matches("() => void") .matches("(string, string,) => void") .matches("(name: string, ...numbers:SomeArrayType) => void") .matches("(name: string, middle?: string) => void") .matches("(string, SomeArrayType) => SomeType") .matches("(await: number) => void") .matches("string => number") START .matches("number | string => number") END ; } @inverno we need more tests, let's have model test for parameter clause at least

Target:
public void test() throws Exception { assertThat(g.rule(Tree.Kind.FLOW_FUNCTION_TYPE)) .matches("(str: string) => void") .matches("(str: string, number) => void") .matches("() => void") .matches("(string, string,) => void") .matches("(name: string, ...numbers:SomeArrayType) => void") .matches("(name: string, middle?: string) => void") .matches("(string, SomeArrayType) => SomeType") .matches("(await: number) => void") .matches("string => number") ; }
Source:
public Iterator<Tree> childrenIterator() { START if (parameters != null) { END return Iterators.concat(Iterators.singletonIterator(lParenthesis), parameters.elementsAndSeparators(Functions.identity()), Iterators.forArray(restParameter, comma, rParenthesis)); } else { return Iterators.forArray(lParenthesis, restParameter, comma, rParenthesis); } } @inverno when you will make `parameters` not nullable, you can simplify this method

Target:
public Iterator<Tree> childrenIterator() { return Iterators.concat(Iterators.singletonIterator(lParenthesis), parameters.elementsAndSeparators(Functions.identity()), Iterators.singletonIterator(rParenthesis)); }
Source:
private static boolean insideCondition(SyntaxToken token) { Tree treeWithCondition = CheckUtils.getFirstAncestor(token, Kind.IF_STATEMENT, Kind.WHILE_STATEMENT, Kind.DO_WHILE_STATEMENT, Kind.FOR_STATEMENT, Kind.CONDITIONAL_EXPRESSION); START END Tree condition = condition(treeWithCondition); return condition != null && ((JavaScriptTree) condition).isAncestorOf((JavaScriptTree) token); } I would rather check for a null treeWithCondition here and return false rather than passing it into the `condition` method as a nullable.

Target:
private static boolean insideCondition(SyntaxToken token) { Tree treeWithCondition = CheckUtils.getFirstAncestor(token, Kind.IF_STATEMENT, Kind.WHILE_STATEMENT, Kind.DO_WHILE_STATEMENT, Kind.FOR_STATEMENT, Kind.CONDITIONAL_EXPRESSION); if (treeWithCondition == null) { return false; } Tree condition = condition(treeWithCondition); return condition != null && ((JavaScriptTree) condition).isAncestorOf((JavaScriptTree) token); }
Source:
private void checkSuperOnlyInvokedInDerivedClassConstructor(SuperTreeImpl superTree) { START if (!isInConstructor(superTree) || isInBaseClass(getEnclosingConstructor(superTree))) { END addIssue(superTree, MESSAGE_SUPER_ONLY_IN_DERIVED_CLASS_CONSTRUCTOR); } } @ivandalbosco Minor: another possibility would have been to move these tests up to `visitSuper`.

Target:
private void checkSuperOnlyInvokedInDerivedClassConstructor(SuperTreeImpl superTree) { addIssue(superTree, MESSAGE_SUPER_ONLY_IN_DERIVED_CLASS_CONSTRUCTOR); }
Source:
private static boolean isConstructor(FunctionTree tree) { if (tree.is(Kind.METHOD)) { MethodDeclarationTree constructor = (MethodDeclarationTree) tree; Tree nameTree = constructor.name(); if (nameTree.is(Kind.IDENTIFIER_NAME)) { String name = ((IdentifierTree) nameTree).name(); START if ("constructor".equals(name)) { END return true; } } } return false; } @ivandalbosco Why not `return "constructor".equals(name)`?

Target:
private static boolean isConstructor(FunctionTree tree) { if (tree.is(Kind.METHOD)) { MethodDeclarationTree constructor = (MethodDeclarationTree) tree; Tree nameTree = constructor.name(); if (nameTree.is(Kind.IDENTIFIER_NAME)) { String name = ((IdentifierTree) nameTree).name(); return "constructor".equals(name); } } return false; }
Source:
START public String contents() throws IOException { END return wrapped.contents(); } @janos-ss We usually don't want to deal with an `IOException` in our analyzers. Why not simply wrapping it in a subclass of `RuntimeException`? That would simplify a bit this pull request.

Target:
public String contents() { try { return wrapped.contents(); } catch (IOException e) { throw new IllegalStateException(e); } }
Source:
public void technical_error_should_add_error_to_context() { thrown.expect(AnalysisException.class); JavaScriptCheck check = new ExceptionRaisingCheck(new NullPointerException("NPE forcibly raised by check class")); START createSensor().analyseFiles(context, ImmutableList.of((TreeVisitor)check), ImmutableList.of(new CompatibleInputFile(inputFile("file.js"))), progressReport); END assertThat(context.allAnalysisErrors()).hasSize(1); } @janos-ss We could probably change the `inputFile`method defined in this class to return a `CompatibleInputFile `.

Target:
public void technical_error_should_add_error_to_context() { thrown.expect(AnalysisException.class); JavaScriptCheck check = new ExceptionRaisingCheck(new NullPointerException("NPE forcibly raised by check class")); createSensor().analyseFiles(context, ImmutableList.of((TreeVisitor)check), ImmutableList.of(inputFile("file.js")), progressReport); assertThat(context.allAnalysisErrors()).hasSize(1); }
Source:
public synchronized void writeIssues(Iterator<Issue> issues, File file) { while (issues.hasNext()) { Issue issue = issues.next(); IssueEntry entry = IssueEntry.from(issue, file); if (expectedIssues.expects(entry)) { START continue; END } output.accept(entry.createExcerpt()); } } @inverno I don't like this style: I would not use a `continue` here.

Target:
public synchronized void writeIssues(Iterator<Issue> issues, File file) { while (issues.hasNext()) { Issue issue = issues.next(); IssueEntry entry = IssueEntry.from(issue, file); if (!expectedIssues.expects(entry)) { output.accept(entry.createExcerpt()); } } }
Source:
public boolean isAncestorOf(JavaScriptTree tree) { Tree parentTree = tree.getParent(); if (this.equals(parentTree)) { return true; } START if (parentTree instanceof JavaScriptTree) { END return this.isAncestorOf((JavaScriptTree) parentTree); } return false; } @inverno remove this check and make `getParent` return JSTree

Target:
public boolean isAncestorOf(JavaScriptTree tree) { Tree parentTree = tree.getParent(); if (this.equals(parentTree)) { return true; } if (parentTree == null) { return false; } return this.isAncestorOf((JavaScriptTree) parentTree); }
Source:
private boolean isInfiniteLoop(IterationStatementTree tree, @Nullable JavaScriptTree condition) { if (isNeverExecutedLoop(condition)) { return false; } ControlFlowGraph flowGraph = CheckUtils.buildControlFlowGraph(tree); Map<Tree, CfgBlock> treesOfFlowGraph = treesToBlocks(flowGraph); if (isBrokenLoop(tree, flowGraph)) { return false; } START if (condition != null && conditionIsUpdated(condition, (JavaScriptTree) tree, treesOfFlowGraph)) { END return false; } else { return true; } } ![MINOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-minor.png) Replace this if-then-else statement by a single return statement. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS1126)

Target:
private static boolean isInfiniteLoop(IterationStatementTree tree, @Nullable JavaScriptTree condition) { if (isNeverExecutedLoop(condition)) { return false; } ControlFlowGraph flowGraph = CheckUtils.buildControlFlowGraph(tree); Map<Tree, CfgBlock> treesOfFlowGraph = treesToBlocks(flowGraph); if (isBrokenLoop(tree, flowGraph)) { return false; } return condition == null || conditionIsUpdated(condition, (JavaScriptTree) tree, treesOfFlowGraph); }
Source:
private void issueIfLineMismatch(SyntaxToken curlyBrace, SyntaxToken target) { CodeLine curlyBraceLine = new CodeLine(curlyBrace.line()); if (curlyBraceLine.isJustBelow(target.line())) { addIssue(new PreciseIssue(this, new IssueLocation(curlyBrace, "Move this open curly brace to the end of the previous line."))); } START if (curlyBraceLine.isFarBelow(target.line())) { END addIssue(new PreciseIssue(this, new IssueLocation(curlyBrace, "Move this open curly brace to the end of line " + target.line() + "."))); } } @inverno Why don't you use an "else" here? With an "else", without reading the implementation of methods isJust/FarBelow, we know that all cases are covered, that is, that we will always hit one of the 2 cases. Further advantage: either of the two methods isJust/FarBelow can be removed.

Target:
private void issueIfLineMismatch(SyntaxToken curlyBrace, SyntaxToken target) { CodeLine curlyBraceLine = new CodeLine(curlyBrace.line()); if (curlyBraceLine.isJustBelow(target.line())) { addIssue(new PreciseIssue(this, new IssueLocation(curlyBrace, "Move this open curly brace to the end of the previous line."))); } else if (curlyBraceLine.isFarBelow(target.line())) { addIssue(new PreciseIssue(this, new IssueLocation(curlyBrace, "Move this open curly brace to the end of line " + target.line() + "."))); } }
Source:
public void beforeBlockElement(ProgramState currentState, Tree element) { if (element.is(Kind.DOT_MEMBER_EXPRESSION)) { DotMemberExpressionTree memberExpression = (DotMemberExpressionTree) element; if (isArrayPropertyExecuted(currentState) && METHODS_WITH_CALLBACK.contains(memberExpression.property().name())) { checkArgumentToBeFunctionWithReturn(memberExpression, 0); } START if (isArrayFromMethod(memberExpression, currentState)) { END checkArgumentToBeFunctionWithReturn(memberExpression, 1); } } } @vilchik-elena "else if" rather than "if" would be clearer (and a picosecond faster).

Target:
public void beforeBlockElement(ProgramState currentState, Tree element) { if (element.is(Kind.DOT_MEMBER_EXPRESSION)) { DotMemberExpressionTree memberExpression = (DotMemberExpressionTree) element; if (isArrayPropertyExecuted(currentState) && METHODS_WITH_CALLBACK.contains(memberExpression.property().name())) { checkArgumentToBeFunctionWithReturn(memberExpression, 0); } else if (isArrayFromMethod(memberExpression, currentState)) { checkArgumentToBeFunctionWithReturn(memberExpression, 1); } } }
Source:
START public BuiltInFunctionSymbolicValue(Constraint returnedValueConstraint, IntFunction<Constraint> signature) { END this.returnedValueConstraint = returnedValueConstraint; this.signature = signature; this.argumentsConstrainer = null; } @vilchik-elena Why not make this constructor call the third one?

Target:
public BuiltInFunctionSymbolicValue(Constraint returnedValueConstraint, IntFunction<Constraint> signature) { this(returnedValueConstraint, null, signature); }
Source:
public void startOfExecution(Scope functionScope) { operandsWithIssues.clear(); START super.startOfExecution(functionScope); END } @ivandalbosco we better remove call to `super`, it does nothing

Target:
public void startOfExecution(Scope functionScope) { operandsWithIssues.clear(); }
Source:
private void checkPlus(ExpressionTree leftOperand, ExpressionTree rightOperand, Type leftType, Type rightType, Tree operator) { if (leftType != Type.STRING && rightType != Type.STRING) { if (leftType == Type.NUMBER && BOOLEAN_DATE.contains(rightType)) { raiseIssue(rightOperand, leftOperand, operator); } if (rightType == Type.NUMBER && BOOLEAN_DATE.contains(leftType)) { START raiseIssue(leftOperand, leftOperand, operator); END } } } @vilchik-elena copy-paste issue

Target:
private void checkPlus(ExpressionTree leftOperand, ExpressionTree rightOperand, Type leftType, Type rightType, Tree operator) { if (leftType != Type.STRING && rightType != Type.STRING) { if (leftType == Type.NUMBER && BOOLEAN_DATE.contains(rightType)) { raiseIssue(rightOperand, leftOperand, operator); } if (rightType == Type.NUMBER && BOOLEAN_DATE.contains(leftType)) { raiseIssue(leftOperand, rightOperand, operator); } } }
Source:
public List<ProgramState> constrain(ProgramState state, Constraint constraint) { ProgramState newState = state.constrainOwnSV(this, constraint); if (newState == null) { return ImmutableList.of(); } if (constraint.isStricterOrEqualTo(Constraint.TRUTHY)) { return checkRelationsAndConstrain(newState, relationWhenTrue); } else if (constraint.isStricterOrEqualTo(Constraint.FALSY)) { return checkRelationsAndConstrain(newState, relationWhenTrue.not()); } START return ImmutableList.of(state); END } Should be `newState`

Target:
public List<ProgramState> constrain(ProgramState state, Constraint constraint) { ProgramState newState = state.constrainOwnSV(this, constraint); if (newState == null) { return ImmutableList.of(); } if (constraint.isStricterOrEqualTo(Constraint.TRUTHY)) { return checkRelationsAndConstrain(newState, relationWhenTrue); } else if (constraint.isStricterOrEqualTo(Constraint.FALSY)) { return checkRelationsAndConstrain(newState, relationWhenTrue.not()); } return ImmutableList.of(newState); }
Source:
public List<ProgramState> constrain(ProgramState state, Constraint constraint) { if (constraint.isStricterOrEqualTo(Constraint.TRUTHY)) { return firstOperandValue.constrain(state, secondOperandConstraint); } else if (constraint.isStricterOrEqualTo(Constraint.FALSY)) { return firstOperandValue.constrain(state, secondOperandConstraint.not()); } START return ImmutableList.of(state); END } @vilchik-elena Good question: what happens here? Can we reach that code?

Target:
public List<ProgramState> constrain(ProgramState state, Constraint constraint) { if (constraint.equals(Constraint.TRUTHY)) { return firstOperandValue.constrain(state, secondOperandConstraint); } else if (constraint.equals(Constraint.FALSY)) { return firstOperandValue.constrain(state, secondOperandConstraint.not()); } return ImmutableList.of(); }
Source:
START private boolean isNullyComparison(Tree lastElement) { END if (lastElement.is(Kind.NOT_EQUAL_TO, Kind.EQUAL_TO)) { BinaryExpressionTree comparison = (BinaryExpressionTree) lastElement; return SymbolicValue.get(comparison.leftOperand()).nullability().isNullOrUndefined().equals(State.YES) || SymbolicValue.get(comparison.rightOperand()).nullability().isNullOrUndefined().equals(State.YES); } return false; } ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Make "isNullyComparison" a "static" method. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://dory.sonarsource.com/sonarqube/coding_rules#rule_key=squid%3AS2325)

Target:
private boolean isNullyComparison(Tree lastElement) { if (lastElement.is(Kind.NOT_EQUAL_TO, Kind.EQUAL_TO)) { BinaryExpressionTree comparison = (BinaryExpressionTree) lastElement; return SymbolicValue.get(comparison.leftOperand()).nullability().isNullOrUndefined() || SymbolicValue.get(comparison.rightOperand()).nullability().isNullOrUndefined(); } return false; }
Source:
public Truthiness not() { START if (this == TRUTHY) { END return FALSY; } else if (this == FALSY) { return TRUTHY; } else { return UNKNOWN; } } @pynicolas why not switch?

Target:
public Truthiness not() { switch (this) { case TRUTHY: return FALSY; case FALSY: return TRUTHY; default: return UNKNOWN; } }
Source:
public void visitScript(ScriptTree tree) { START storageTypes = new HashedMap(); END super.visitScript(tree); checkForIssues(); } @ganncamp minor: could be instantiate at the field declaration level and here it could be cleared by calling `storage.clear()` WDYT ?

Target:
public void visitScript(ScriptTree tree) { storageTypes.clear(); super.visitScript(tree); checkForIssues(); }
Source:
private static String getObjectName(MemberExpressionTree dme) { START if (dme.object() != null) { END if (dme.object().is(Tree.Kind.DOT_MEMBER_EXPRESSION)) { DotMemberExpressionTree d2 = (DotMemberExpressionTree) dme.object(); return d2.property().name(); } else { return CheckUtils.asString(dme.object()); } } return ""; } @ganncamp actually this null check should not be required be [MemberExpression#object()](https://github.com/SonarCommunity/sonar-javascript/blob/master/javascript-frontend/src/main/java/org/sonar/plugins/javascript/api/tree/expression/MemberExpressionTree.java#L35) is not nullable and should never be null.

Target:
private static String getObjectName(MemberExpressionTree dme) { if (dme.object().is(Tree.Kind.DOT_MEMBER_EXPRESSION)) { DotMemberExpressionTree d2 = (DotMemberExpressionTree) dme.object(); return d2.property().name(); } else { return CheckUtils.asString(dme.object()); } }
Source:
public void scanFile(AstTreeVisitorContext context) { super.scanFile(context); RandomAccessFile randomAccessFile = null; START try { END randomAccessFile = new RandomAccessFile(getContext().getFile(), "r"); if (!endsWithNewline(randomAccessFile)) { getContext().addFileIssue(this, "Add a new line at the end of this file."); } } catch (IOException e) { LOG.error("Unable to execute rule \"MissingNewlineAtEndOfFile\" for file because of error: {}", getContext().getFile().getName(), e); } finally { Closeables.closeQuietly(randomAccessFile); } } We are now compatible with java 7 so you should probably use a try with resource.

Target:
public void scanFile(AstTreeVisitorContext context) { super.scanFile(context); try (RandomAccessFile randomAccessFile = new RandomAccessFile(getContext().getFile(), "r")) { if (!endsWithNewline(randomAccessFile)) { getContext().addFileIssue(this, "Add a new line at the end of this file."); } } catch (IOException e) { LOG.error("Unable to execute rule \"MissingNewlineAtEndOfFile\" for file because of error: {}", getContext().getFile().getName(), e); } }
Source:
public int hashCode() { int result = super.hashCode(); result = 31 * result + center.hashCode(); START result = 31 * result + new Double(scale.getResolution()).hashCode(); END return result; } You could implement hashCode in Scale

Target:
public int hashCode() { int result = super.hashCode(); result = 31 * result + (this.center != null ? this.center.hashCode() : 0); result = 31 * result + (this.scale != null ? this.scale.hashCode() : 0); return result; }
Source:
public int hashCode() { int result; long temp; START temp = Double.doubleToLongBits(resolution); END result = (int) (temp ^ (temp >>> 32)); return result; } You should use static Double.hasCode

Target:
public int hashCode() { return new Double(resolution).hashCode(); }
Source:
public final void cacheResources(final HttpRequestCache httpRequestCache, final MfClientHttpRequestFactory clientHttpRequestFactory, final MapfishMapContext transformer) { final MapfishMapContext layerTransformer = getLayerTransformer(transformer); final double dpi = transformer.getDPI(); final TilePreparationTask task = new TilePreparationTask( clientHttpRequestFactory, dpi, layerTransformer, this.tileCacheInformation, httpRequestCache); START this.tilePreparationInfo = this.forkJoinPool.invoke(task); END } Does it still make sense to use `forkJoinPool`? The tiles are no longer downloaded at this point, so it would add an overhead to run this in parallel.

Target:
public final void cacheResources(final HttpRequestCache httpRequestCache, final MfClientHttpRequestFactory clientHttpRequestFactory, final MapfishMapContext transformer) { final MapfishMapContext layerTransformer = getLayerTransformer(transformer); final double dpi = transformer.getDPI(); final TilePreparationTask task = new TilePreparationTask( clientHttpRequestFactory, dpi, layerTransformer, this.tileCacheInformation, httpRequestCache); this.tilePreparationInfo = task.call(); }
Source:
public void setFeatureAttributeName(String featureAttributeName) { START if (null == featureAttributeName) END log.debug("WPS request process error: Feature Attribute Name was null. Can not process without the output column name."); this.featureAttributeName = featureAttributeName; } I know Sonar will flag this for not having the around the block. This can be tricky to read the logic coming back at a later date.

Target:
public void setFeatureAttributeName(String featureAttributeName) { if (null == featureAttributeName) { log.debug("WPS request process error: Feature Attribute Name was null. Can not process without the output column name."); } this.featureAttributeName = featureAttributeName; }
Source:
private void initializeBaseDirectory(PropertyUtil propertyUtil) throws IOException { String baseDirectoryPath = propertyUtil.extractString(KEY_DATABASE_PATH, DEFAULT_BASE_DIRECTORY); BASE_DIRECTORY = Paths.get(baseDirectoryPath); LOGGER.info("Using \"{}\" as base directory for results database", baseDirectoryPath); START if (!Files.isDirectory(BASE_DIRECTORY)) { END Files.createDirectories(BASE_DIRECTORY); } } Does there need to be an if check here? From JavaDoc: Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists. So if it doesn't already exist, it will create it, otherwise, it will move on.

Target:
private void initializeBaseDirectory(PropertyUtil propertyUtil) throws IOException { String baseDirectoryPath = propertyUtil.extractString(KEY_DATABASE_PATH, DEFAULT_BASE_DIRECTORY); BASE_DIRECTORY = Paths.get(baseDirectoryPath); LOGGER.info("Using \"{}\" as base directory for results database", baseDirectoryPath); Files.createDirectories(BASE_DIRECTORY); }
Source:
public void contextDestroyed(ServletContextEvent sce) { START LOGGER.info("(\"*****************************************************WPSJobListener - context destroyed, cancelling request tasks"); END for (Runnable runnable : RequestHandler.pool.getQueue()) { ((FutureTask) runnable).cancel(true); LOGGER.info("cancelling task"); } } Personally I'd prefer just a couple asterisks if you want this to stick out, this is quite jarring to see in code.

Target:
public void contextDestroyed(ServletContextEvent sce) { for (Runnable runnable : RequestHandler.pool.getQueue()) { ((FutureTask) runnable).cancel(true); LOGGER.info("cancelling task"); } }
Source:
public boolean offer(Message msg) { if (capacity == 0) { try { // for synchronous queue, this will block until the sink takes the message from the queue queue.put(msg); } catch (InterruptedException e) { return false; } return true; } START return queue.offer(msg); END } I thought you were just changing this offer to put. but that will be a big change. you current change doesn't break any existing behavior. looks good/safe to me. nitpicking: a if-else might be more straightforward.

Target:
public boolean offer(Message msg) { if (capacity == 0) { try { // for synchronous queue, this will block until the sink takes the message from the queue queue.put(msg); } catch (InterruptedException e) { return false; } return true; } else { return queue.offer(msg); } }
Source:
public void onViewStateRestored(Bundle savedInstanceState) { if (savedInstanceState != null) { layoutManagerSavedState = savedInstanceState.getParcelable(LAYOUT_MANAGER_STATE); START prevLeftAction = savedInstanceState.getString("prevLeftAction", ""); END prevRightAction = savedInstanceState.getString("prevRightAction", ""); } super.onViewStateRestored(savedInstanceState); } Do we need this here? I think `onResume()` is called when the activity is restored. Therefore the settings will be reloaded. So I think we can remove the logic from both the `onViewStateRestored()` and `onSaveInstanceState()` right? Or am I missing something here?

Target:
public void onViewStateRestored(Bundle savedInstanceState) { if (savedInstanceState != null) layoutManagerSavedState = savedInstanceState.getParcelable(LAYOUT_MANAGER_STATE); super.onViewStateRestored(savedInstanceState); }
Source:
public SSDate resetTime() { this.setHours(0); this.setMinutes(0); this.setSeconds(0); START return this; END } dont think a setter type function should return the "this"

Target:
public void resetTime() { this.setHours(0); this.setMinutes(0); this.setSeconds(0); }
Source:
public FilterDropdownListBox(FilterDropdownResources resources) { super(true); this.setStyleName(""); this.resources = resources; this.resources.filterDropdownStyle().ensureInjected(); mainPanel.setStyleName(this.resources.filterDropdownStyle().dropDown()); this.add(mainPanel); addInfoMessages(); START mainPanel.getElement().getStyle().setProperty("maxHeight", "250px"); END mainPanel.getElement().getStyle().setProperty("overflow", "auto"); } create a setter for this so that the height can be changed from outside

Target:
public FilterDropdownListBox(FilterDropdownResources resources) { super(true); this.setStyleName(""); this.resources = resources; this.resources.filterDropdownStyle().ensureInjected(); mainPanel.setStyleName(this.resources.filterDropdownStyle().dropDown()); this.add(mainPanel); addInfoMessages(); mainPanel.getElement().getStyle().setProperty("overflow", "auto"); }
Source:
public Field(InputField inputField, String label, boolean embeded, int layout) { START this(inputField, label, embeded, DynamicForm.LAYOUT_VERTICAL, ""); END } this is wrong

Target:
public Field(InputField inputField, String label, boolean embeded, int layout) { this(inputField, label, embeded, layout, ""); }
Source:
public void displayHelpWidget() { //display helpWidget //will be implemented at a later stage START Window.alert( "Coming soon!" ); END } spaces inside brackets should be removed

Target:
public void displayHelpWidget() { //display helpWidget //will be implemented at a later stage }
Source:
public float getLeftMargin(Actor actor) { for (Constraints c : constraints) { if (c.actor == actor) { return marginLeft(c); } } START return -1; END } Hmm. This a weird value for the default, which should likely be positive. Maybe this should be 0?

Target:
public float getLeftMargin(Actor actor) { for (Constraints c : constraints) { if (c.actor == actor) { return marginLeft(c); } } return 0; }
Source:
public Array<Actor> getExtras() { START final Array<Actor> actors = new Array<Actor>(false, 2); END actors.add(this.paint); actors.add(this.eraser); return actors; } Unnecessary final.

Target:
public Array<Actor> getExtras() { Array<Actor> actors = new Array<Actor>(false, 2); actors.add(this.paint); actors.add(this.eraser); return actors; }
Source:
public void render() { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); stage.act(); stage.draw(); START Table.drawDebug(stage); END } How do you control drawing the debug lines? It should be conditioned by a global variable that sets the editor in debug (pass as command line argument).

Target:
public void render() { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); stage.act(); stage.draw(); }
Source:
private TimedRenderer getCurrentFrame() { // In case the current frame is null, just return an empty timed // renderer as a frame START if (frames.get(currentFrame) != null) END return frames.get(currentFrame); else { return new TimedRenderer() { @Override public void draw(Batch batch) { } @Override public float getHeight() { return 0; } @Override public float getWidth() { return 0; } @Override public void initialize(Object schemaObject) { } public float surplusTime() { return 0; } }; } } Frames shouldn't contain null frames.

Target:
private TimedRenderer getCurrentFrame() { return frames.get(currentFrame); }
Source:
public void initialize(AddAction schemaObject) { Action action = schemaObject.getAction(); for (String tag : schemaObject.getTags()) { SceneActor scene = gameLoop.getSceneView().getCurrentScene(); Array<SceneElementActor> sceneElements = scene.findByTag(tag); START if (sceneElements != null) { END for (SceneElementActor sceneElement : sceneElements) { sceneElement.addAction(action); } } } } We don't check if schemaObject.getTags() or gameLoop.getSceneView().getCurrentScene() are null. I assume this is because those methods will never return null. To be consistent, scene.findByTag(tag) should never return null.

Target:
public void initialize(AddAction schemaObject) { Action action = schemaObject.getAction(); for (String tag : schemaObject.getTags()) { SceneActor scene = gameLoop.getSceneView().getCurrentScene(); Array<SceneElementActor> sceneElements = scene.findByTag(tag); for (SceneElementActor sceneElement : sceneElements) { sceneElement.addAction(action); } } }
Source:
public void initialize(Scene schemaObject) { for (SceneElement se : schemaObject.getChildren()) { addActor(se); } START sceneElementTags.clear(); END addChildrenTagsTo(this); } why is this needed?

Target:
public void initialize(Scene schemaObject) { for (SceneElement se : schemaObject.getChildren()) { addActor(se); } }