auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void reserveTicketWhenExists(TicketsInteractor mockedTicketsInteractor) throws RecordNotFoundException, MaximumExceededException, UpdateTicketStateUnauthorizedException { long ticketId = 1; ObjectNode json = Json.newObject(); ArrayNode node = json.putArray(ConstantsManager.TICKET_IDS_FIELD_NAME); node.add(ticketId); when(mockedBody.asJson()).thenReturn(json); Result result = ticketsController.reserve(); assertEquals(Helpers.OK, Helpers.status(result)); START verify(mockedTicketsInteractor, times(1)).reserveATicket(ticketId); END } same here, times(1)

Target:
public void reserveTicketWhenExists(TicketsInteractor mockedTicketsInteractor) throws RecordNotFoundException, MaximumExceededException, UpdateTicketStateUnauthorizedException { long ticketId = 1; ObjectNode json = Json.newObject(); ArrayNode node = json.putArray(ConstantsManager.TICKET_IDS_FIELD_NAME); node.add(ticketId); when(mockedBody.asJson()).thenReturn(json); Result result = ticketsController.reserve(); assertEquals(Helpers.OK, Helpers.status(result)); verify(mockedTicketsInteractor).reserveATicket(ticketId); }
Source:
public TicketSearchCriteria() { states = new ArrayList<>(); START quantity = ConstantsManager.TICKET_SEARCH_CRITERIA_INVALID_QUANTITY; END } pourquoi utiliser une valeur invalid plutot que null

Target:
public TicketSearchCriteria() { states = new ArrayList<>(); quantity = null; }
Source:
public Transaction startNewTransaction(User user) { Transaction transaction = new Transaction(user); START this.transactionDao.create(transaction); END return transaction; } il me semble qu'au début de la session on s'était dit que les usages de this on essayait de les limiter au assignations dans le constructeur

Target:
public Transaction startNewTransaction(User user) { Transaction transaction = new Transaction(user); transactionDao.create(transaction); return transaction; }
Source:
public void persistsOnAdd() { // Arrange DaoPersistenceService persistenceSvc = mock(InMemoryDaoPersistenceService.class); dao = new PersistedDao<TestRecord>(persistenceSvc) {}; // Act dao.create(new TestRecord()); // Assert try { verify(persistenceSvc, times(1)).persist(dao); } catch(Exception ex) { START fail("Expected no error in persistence."); END } } C'est quoi l'avantage d'utiliser `fail` versus ajouter l'exception à la signature. Le test va échouer anyway.

Target:
public void persistsOnAdd() throws IOException { // Arrange DaoPersistenceService persistenceSvc = mock(InMemoryDaoPersistenceService.class); dao = new PersistedDao<TestRecord>(persistenceSvc) {}; // Act dao.create(new TestRecord()); // Assert verify(persistenceSvc, times(1)).persist(dao); }
Source:
public void decrementNumberOfTickets(int decrementNumber) throws MaximumExceededException { if(numberOfTickets < decrementNumber) throw new MaximumExceededException(); START numberOfTickets -= decrementNumber; END } La meilleure façon de savoir si on est dans le champ est le jour ou on aura besoin d'injecter des services dans les modèles ahah

Target:
public synchronized void decrementNumberOfTickets(int decrementNumber) throws MaximumExceededException { if (numberOfTickets < decrementNumber) throw new MaximumExceededException(); numberOfTickets -= decrementNumber; }
Source:
public void addDynamicTemplateData(String key, Object value) { if (dynamicTemplateData == null) { dynamicTemplateData = new HashMap<String,Object>(); dynamicTemplateData.put(key, value); } else { dynamicTemplateData.put(key, value); START } END } Thanks for taking the time to review @dgranahan!

Target:
public void addDynamicTemplateData(String key, Object value) { if (dynamicTemplateData == null) { dynamicTemplateData = new HashMap<String,Object>(); } dynamicTemplateData.put(key, value); }
Source:
public void nearbyStationsAddress() throws Exception { nearbyStationsAddress(-34618072, -58436443); START System.out.println("\n"); END } Can you remove this line? No printing to sysout please.

Target:
public void nearbyStationsAddress() throws Exception { nearbyStationsAddress(-34618072, -58436443); }
Source:
public HslProvider(String user, String pass) { super(NetworkId.HSL); START apiBase = String.format("http://api.reittiopas.fi/hsl/%s/?user=%s&pass=%s", END SERVER_VERSION, user, pass); try { parserFactory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); } catch (final XmlPullParserException x) { throw new RuntimeException(x); } } Why are username and password part of the API base? My understanding is that they are constant (http://api.reittiopas.fi/hsl/1_2_0/ in this case) and the parameters are appended dynamically. Username and password could be appended in the apiUri() method.

Target:
public HslProvider(String user, String pass) { super(NetworkId.HSL); this.user = user; this.pass = pass; try { parserFactory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); } catch (final XmlPullParserException x) { throw new RuntimeException(x); } }
Source:
private static int determineContentStart(String s) { int start = TEXTBLOCK_DELIMITER.length(); // this is the opening delimiter boolean lineTerminator = false; // the content begins after at the first character after the line terminator // of the opening delimiter while (start < s.length() && Character.isWhitespace(s.charAt(start))) { if (s.charAt(start) == '\r' || s.charAt(start) == '\n') { START lineTerminator = true; END } else if (lineTerminator) { // first character after the line terminator break; } start++; } return start; } Does this work with CRLF delimited strings? It looks like it's not going past the LF. Maybe you just need to call this method on the normalized string, and stop caring about CR. Also maybe it would be clearer to just `return start + 1;` here instead of breaking on the next iteration.

Target:
private static int determineContentStart(String s) { int start = TEXTBLOCK_DELIMITER.length(); // this is the opening delimiter // the content begins after at the first character after the line terminator // of the opening delimiter while (start < s.length() && Character.isWhitespace(s.charAt(start))) { if (s.charAt(start) == '\n') { return start + 1; } start++; } return start; }
Source:
START public static void reset() { END FACADE.reset(); } Maybe, a better solution wrt to visibility would be to move the LanguageMetricsProvider out of ApexHandler, and into this package. ApexMetrics will probably not change for 7.0 (apart from this method), while LanguageMetricsProvider is still experimental and we can remove the new API freely in 7.0

Target:
static void reset() { FACADE.reset(); }
Source:
public TokenEntry(String image, String tokenSrcID, int beginLine) { setImage(image); this.tokenSrcID = tokenSrcID; this.beginLine = beginLine; START this.beginColumn = -1; END this.endColumn = -1; this.index = TOKEN_COUNT.get().getAndIncrement(); } Please call here the other constructor via `this(image, tokenSrcID, beginLine, -1, -1)`. That way, we don't need to duplicate the logic...

Target:
public TokenEntry(String image, String tokenSrcID, int beginLine) { this(image, tokenSrcID, beginLine, -1, -1); }
Source:
START public CppCharStream(JavaccTokenDocument document) { END super(document); } We probably should internalize our *CharStream impls on master, they should anyway not be used directly

Target:
CppCharStream(JavaccTokenDocument document) { super(document); }
Source:
private void parseSingleRuleNode(RuleSetReferenceId ruleSetReferenceId, RuleSetBuilder ruleSetBuilder, Node ruleNode) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Element ruleElement = (Element) ruleNode; // Stop if we're looking for a particular Rule, and this element is not // it. if (StringUtils.isNotBlank(ruleSetReferenceId.getRuleName()) && !isRuleName(ruleElement, ruleSetReferenceId.getRuleName())) { return; } START Rule rule = new RuleFactory().buildRule(ruleElement, resourceLoader); END rule.setRuleSetName(ruleSetBuilder.getName()); ruleSetBuilder.addRule(rule); } Can you add two constructors in RuleFactory? * RuleFactory() - default constructor for backwards compatibility * RuleFactory(ResourceLoader) - the new one to be used here I think, the resource loader should be a property of the rule factory rather than a method argument for parsing the rule element. In theory, we could reuse the RuleFactory instance for parsing all rules within one ruleset (which we don't do currently).

Target:
private void parseSingleRuleNode(RuleSetReferenceId ruleSetReferenceId, RuleSetBuilder ruleSetBuilder, Node ruleNode) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Element ruleElement = (Element) ruleNode; // Stop if we're looking for a particular Rule, and this element is not // it. if (StringUtils.isNotBlank(ruleSetReferenceId.getRuleName()) && !isRuleName(ruleElement, ruleSetReferenceId.getRuleName())) { return; } Rule rule = new RuleFactory(resourceLoader).buildRule(ruleElement); rule.setRuleSetName(ruleSetBuilder.getName()); ruleSetBuilder.addRule(rule); }
Source:
public RuleBuilder(String name, String clazz, String language) { START this.name = name; END this.resourceLoader = new ResourceLoader(); language(language); className(clazz); } Please call here just the other constructor: ``` this(name, new ResourceLoader(), clazz, language); ``` No need to duplicated the code here.

Target:
public RuleBuilder(String name, String clazz, String language) { this(name, new ResourceLoader(), clazz, language); }
Source:
public static Set<Language> getLanguages() { START return new LinkedHashSet<>(getInstance().languages.values()); END } maybe better use `Collections.unmodifiableSet` instead of a new `LinkedHashSet `?

Target:
public static Set<Language> getLanguages() { return getInstance().languages; }
Source:
private static long computeFileChecksum(final File sourceFile) { try ( CheckedInputStream stream = new CheckedInputStream( new BufferedInputStream(Files.newInputStream(sourceFile.toPath())), new Adler32()); ) { // Just read it, the CheckedInputStream will update the checksum on it's own IOUtils.skipFully(stream, sourceFile.length()); return stream.getChecksum().getValue(); } catch (final IOException ignored) { // We don't really care, if it's unreadable // the analysis will fail and report the error on it's own since the checksum won't match } // we couldn't read the file, maybe the file doesn't exist // in any case, we can't use the cache. Returning here the timestamp should make // sure, we see that the file changed every time we analyze it. START return System.currentTimeMillis(); END } this seems unrelated to the rest of the PR, although related to the original report

Target:
private static long computeFileChecksum(final File sourceFile) { try ( CheckedInputStream stream = new CheckedInputStream( new BufferedInputStream(Files.newInputStream(sourceFile.toPath())), new Adler32()); ) { // Just read it, the CheckedInputStream will update the checksum on it's own IOUtils.skipFully(stream, sourceFile.length()); return stream.getChecksum().getValue(); } catch (final IOException ignored) { // We don't really care, if it's unreadable // the analysis will fail and report the error on it's own since the checksum won't match } return 0; }
Source:
public ASTAnnotation getAnnotation(String annotQualifiedName) { List<ASTAnnotation> annotations = getDeclaredAnnotations(); for (ASTAnnotation annotation : annotations) { START if (annotation.getType() != null) { END // since annotQulifiedName is fully qualified, we can directly compare now if (annotQualifiedName.equals(annotation.getType().getName())) { return annotation; } } else { // note: this alternative might fall back to comparing simple class names. If auxclasspath is not // correct, this might lead to false-positives/false-negatives. ASTName name = annotation.getFirstDescendantOfType(ASTName.class); if (name != null && TypeHelper.isA(name, annotQualifiedName)) { return annotation; } } } return null; } why not build this behavior right into `TypeHelper.isA`?

Target:
public ASTAnnotation getAnnotation(String annotQualifiedName) { List<ASTAnnotation> annotations = getDeclaredAnnotations(); for (ASTAnnotation annotation : annotations) { ASTName name = annotation.getFirstDescendantOfType(ASTName.class); if (name != null && TypeHelper.isA(name, annotQualifiedName)) { return annotation; } } return null; }
Source:
START private Boolean hasUnavailableModifier(final List<SwiftParser.AttributeContext> attributes) { END return attributes.stream().anyMatch(atr -> AVAILABLE_UNAVAILABLE.equals(atr.getText())); } do we need a boxed primitive here?

Target:
private boolean hasUnavailableModifier(final List<SwiftParser.AttributeContext> attributes) { return attributes.stream().anyMatch(atr -> AVAILABLE_UNAVAILABLE.equals(atr.getText())); }
Source:
START private Boolean shouldIncludeUnavailableModifier(final SwiftParser.CodeBlockContext ctx) { END if (ctx == null || ctx.statements() == null) { return false; } final List<SwiftParser.StatementContext> statements = ctx.statements().statement(); return statements.size() == 1 && FATAL_ERROR.equals(statements.get(0).getStart().getText()); } do we need a boxed primitive here?

Target:
private boolean shouldIncludeUnavailableModifier(final SwiftParser.CodeBlockContext ctx) { if (ctx == null || ctx.statements() == null) { return false; } final List<SwiftParser.StatementContext> statements = ctx.statements().statement(); return statements.size() == 1 && FATAL_ERROR.equals(statements.get(0).getStart().getText()); }
Source:
START public String getImage() { END return getText(); } The image attribute is not supposed to be the text of the node. I'd rather keep it separate (the previous `@Text` attribute was fine). A practical reason for that is in the future, other languages may have a way to get the text of their node, in which case that wouldn't be fetched with `getImage`, for compatibility, but probably with a `getText` method, or `getSourceCode` like in #1728. Also we *may* deprecate or otherwise put `getImage` out of use as soon as 7.0, given its contract is super loose.

Target:
public String getImage() { return null; }
Source:
public void testRawStringLiterals() throws IOException { final String code = IOUtils.toString(CPPTokenizerTest.class.getResourceAsStream("cpp/issue-1784.cpp"), StandardCharsets.UTF_8); Tokens tokens = parse(code); START System.out.println(tokens.getTokens()); END assertTrue(TokenEntry.getEOF() != tokens.getTokens().get(0)); assertEquals(16, tokens.size()); } Please remove the System.out here...

Target:
public void testRawStringLiterals() throws IOException { final String code = IOUtils.toString(CPPTokenizerTest.class.getResourceAsStream("cpp/issue-1784.cpp"), StandardCharsets.UTF_8); Tokens tokens = parse(code); assertTrue(TokenEntry.getEOF() != tokens.getTokens().get(0)); assertEquals(16, tokens.size()); }
Source:
START public List<AstProcessingStage<?>> testOnlyGetDependencies(RuleSets ruleSets, LanguageVersion languageVersion) { END return getDependencies(ruleSets, languageVersion); } rather than have a public test method, consider turning `getDependencies` to package-private, and therefore accessible to the test (same package) but invisible to the outside world

Target:
List<AstProcessingStage<?>> testOnlyGetDependencies(RuleSets ruleSets, LanguageVersion languageVersion) { return getDependencies(ruleSets, languageVersion); }
Source:
public static Optional<PrimitiveType> fromToken(String token) { START return Optional.ofNullable(LOOKUP.get(token)); END } I'm not sure about this optional… I believe you should just throw here (equivalent to `Enum.valueOf`)… actually the only use you have in this PR simply calls `.get()` on the optional and have it throw if called illegally…

Target:
public static PrimitiveType fromToken(String token) { return LOOKUP.get(token); }
Source:
START ASTExpression getLengthExpression() { END return (ASTExpression) jjtGetChild(jjtGetNumChildren() - 1); } getLengthExpression, why package private? Should it be public?

Target:
public ASTExpression getLengthExpression() { return (ASTExpression) jjtGetChild(jjtGetNumChildren() - 1); }
Source:
START public ASTLambdaParameter(int id) { END super(id); } The constructors should be package private

Target:
ASTLambdaParameter(int id) { super(id); }
Source:
default <T> List<T> findDescendantsOfType(Class<T> targetType) { final List<T> list = new ArrayList<>(); TraversalUtils.findDescendantsOfType(this, targetType, list, false); START return list; END } this implementation seems bogus, you can simply call `return findDescendantsOfType(targetType, false);`

Target:
default <T> List<T> findDescendantsOfType(Class<T> targetType) { return findDescendantsOfType(targetType, false); }
Source:
private void checkSetters(ASTMethodDeclaration node, Object data, String nameOfMethod) { START if (!hasIgnoredAnnotation(node)) { END ASTResultType resultType = node.getResultType(); if (hasPrefix(nameOfMethod, "set") && !resultType.isVoid()) { addViolationWithMessage(data, node, "Linguistics Antipattern - The setter ''{0}'' should not return any type except void linguistically", new Object[] { nameOfMethod }); } } } I'd move this to line 83 (within `visit(ASTMethodDeclaration node, Object data)`), so we ignore all overridden methods and not just setters

Target:
private void checkSetters(ASTMethodDeclaration node, Object data, String nameOfMethod) { ASTResultType resultType = node.getResultType(); if (hasPrefix(nameOfMethod, "set") && !resultType.isVoid()) { addViolationWithMessage(data, node, "Linguistics Antipattern - The setter ''{0}'' should not return any type except void linguistically", new Object[] { nameOfMethod }); } }
Source:
public List<File> findFilesFrom(File dir, FilenameFilter filter, boolean recurse) { this.filter = filter; List<File> files = new ArrayList<>(); scanDirectory(dir, files, recurse); Collections.sort(files, new Comparator<File>() { @Override public int compare(File o1, File o2) { START return o1.getPath().compareToIgnoreCase(o2.getPath()); END } }); return files; } While digging further into this sorting, I found out that `java.io.File` implements Comparable and would sort Files correctly depending on the operating system. So, we could even just say `Collections.sort(files);`. However, we can also change the method `scanDirectory` below instead to do the sorting already: ```java File[] candidates = dir.listFiles(filter); if (candidates == null) { return; } Arrays.sort(candidates); ... ``` Using File instead of String here has the advantage, that we don't need to create new File instances on our own.

Target:
public List<File> findFilesFrom(File dir, FilenameFilter filter, boolean recurse) { this.filter = filter; List<File> files = new ArrayList<>(); scanDirectory(dir, files, recurse); return files; }
Source:
UnsynchronizedStaticFormatterRule(Class<?> formatterClassToCheck) { START this.formatterClassToCheck = formatterClassToCheck; END } using this constructor doesn't use the rule chain... a call to `this();` is probably missing

Target:
UnsynchronizedStaticFormatterRule(Class<?> formatterClassToCheck) { this(); this.formatterClassToCheck = formatterClassToCheck; }
Source:
protected void setUp() { String[] packages = getClass().getPackage().getName().split("\\."); START String categoryName = packages[packages.length - 1]; END String language = packages[packages.length - 3]; String rulesetXml = "category/" + language + "/" + categoryName + ".xml"; addRule(rulesetXml, getClass().getSimpleName().replaceFirst("Test$", "")); } This is PMD specific, I guess it would probably fail most of the time outside of PMD. Wouldn't it be better to use our own subclass of SimpleAggregatorTst (or RuleTst, since we test a single rule)?

Target:
protected void setUp() { // empty, to be overridden. }
Source:
private List<String> createList(Class[] classArray) { return Arrays.asList(classArray).stream() .filter(files -> files.getSimpleName().startsWith("AST")) START .map(m -> m.getSimpleName().substring(("AST").length())) END .collect(Collectors.toList()); } useless parenthesis around "AST"

Target:
private List<String> createList(Class[] classArray) { return Arrays.asList(classArray).stream() .filter(files -> files.getSimpleName().startsWith("AST")) .map(m -> m.getSimpleName().substring("AST".length())) .collect(Collectors.toList()); }
Source:
public String getAuxclasspathFiles() { String files = auxclasspathFiles.getValue().stream().map(p -> File.pathSeparator + p.getAbsolutePath()) START .collect(Collectors.joining("")); END return files; } You could use Collectors.joining(File.pathSeparator)

Target:
public String getAuxclasspathFiles() { return auxclasspathFiles.getValue().stream().map(p -> p.getAbsolutePath()).collect(Collectors.joining(File.pathSeparator)); }
Source:
private static URL[] fileToURL(List<File> files) throws IOException { List<URL> urlList = new ArrayList<>(); for (File f : files) { START addFileURLs(urlList, f.toURI().toURL()); END } return urlList.toArray(new URL[urlList.size()]); } Don't use addFileUrls, just add to your urlList

Target:
private static URL[] fileToURL(List<File> files) throws IOException { List<URL> urlList = new ArrayList<>(); for (File f : files) { urlList.add(f.toURI().toURL()); } return urlList.toArray(new URL[0]); }
Source:
START public static TimedOperation initThread() { END if (!trackTime) { return NOOP_TIMED_OPERATION; } return startOperation(TimedOperationCategory.UNACCOUNTED); } None of the callers seem to use the return from this method. Is that okay? Is it needed?

Target:
public static void initThread() { if (!trackTime) { return; } startOperation(TimedOperationCategory.UNACCOUNTED); }
Source:
public String getTypeImage() { if (isTypeInferred()) { START return getImage(); END } ASTClassOrInterfaceType refType = getFirstDescendantOfType(ASTClassOrInterfaceType.class); if (refType != null) { return refType.getImage(); } return getFirstDescendantOfType(ASTPrimitiveType.class).getImage(); } is this ok? Shouldn't we return null / empty string here?

Target:
public String getTypeImage() { ASTClassOrInterfaceType refType = getFirstDescendantOfType(ASTClassOrInterfaceType.class); if (refType != null) { return refType.getImage(); } return getFirstDescendantOfType(ASTPrimitiveType.class).getImage(); }
Source:
public void testScopesAreCreated() { parseCode(TEST1); START ASTBlock n = acu.findDescendantsOfType(ASTIfStatement.class).get(0) END .getFirstDescendantOfType(ASTBlock.class); assertTrue(n.getScope() instanceof LocalScope); } This could be a `getFirstDescendantOfType`

Target:
public void testScopesAreCreated() { parseCode(TEST1); ASTBlock n = acu.getFirstDescendantOfType(ASTIfStatement.class) .getFirstDescendantOfType(ASTBlock.class); assertTrue(n.getScope() instanceof LocalScope); }
Source:
protected Collection<String> defaultSuppressionAnnotations() { Collection<String> defaultValues = new HashSet<>(); defaultValues.add("javax.inject.Inject"); START return defaultValues; END } You may just return `Arrays.asList("javax.inject.Inject")`

Target:
protected Collection<String> defaultSuppressionAnnotations() { return Arrays.asList("javax.inject.Inject"); }
Source:
protected Collection<String> defaultSuppressionAnnotations() { START Collection defaultValues = new ArrayList<String>(); END defaultValues.add("java.lang.Deprecated"); return defaultValues; } This is a raw type, please use a parameterized type (`Collection<String>`)

Target:
protected Collection<String> defaultSuppressionAnnotations() { Collection<String> defaultValues = new ArrayList<>(); defaultValues.add("java.lang.Deprecated"); return defaultValues; }
Source:
public void setAnalysisCache(final AnalysisCache cache) { START if (cache == null && isAnalysisCacheFunctional()) { END analysisCache = new NoopAnalysisCache(); } else { analysisCache = cache; } // the doc says it's a noop if incremental analysis was disabled, // but it's actually the getter that enforces that } do we really care?

Target:
public void setAnalysisCache(final AnalysisCache cache) { // the doc says it's a noop if incremental analysis was disabled, // but it's actually the getter that enforces that this.analysisCache = cache == null ? new NoopAnalysisCache() : cache; }
Source:
static boolean isSystemLevelClass(ASTUserClass node) { List<TypeRef> interfaces = node.getNode().getDefiningType().getCodeUnitDetails().getInterfaceTypeRefs(); boolean hasWhitelistedInterfaces = false; for (TypeRef intObject : interfaces) { if (isWhitelisted(intObject.getNames())) { START hasWhitelistedInterfaces = true; END break; } } return hasWhitelistedInterfaces; } `return true` would be cleaner... or am I missing the point of the rule ?

Target:
static boolean isSystemLevelClass(ASTUserClass node) { List<TypeRef> interfaces = node.getNode().getDefiningType().getCodeUnitDetails().getInterfaceTypeRefs(); for (TypeRef intObject : interfaces) { if (isWhitelisted(intObject.getNames())) { return true; } } return false; }
Source:
private void initXPathRuleQuery() { START if (xPathRuleQueryNeedsInitialization()) { END final String xpath = getProperty(XPATH_DESCRIPTOR); final String version = getProperty(VERSION_DESCRIPTOR); initRuleQueryBasedOnVersion(version); xpathRuleQuery.setXPath(xpath); xpathRuleQuery.setVersion(version); xpathRuleQuery.setProperties(getPropertiesByPropertyDescriptor()); } } This check should be moved out to call-sites (l. 100), which is btw already the case l. 145

Target:
private void initXPathRuleQuery() { String xpath = getProperty(XPATH_DESCRIPTOR); String version = getProperty(VERSION_DESCRIPTOR); initRuleQueryBasedOnVersion(version); xpathRuleQuery.setXPath(xpath); xpathRuleQuery.setVersion(version); xpathRuleQuery.setProperties(getPropertiesByPropertyDescriptor()); }
Source:
private void initRuleQueryBasedOnVersion(final String version) { START if (XPATH_1_0.equals(version)) { END xpathRuleQuery = new JaxenXPathRuleQuery(); } else { xpathRuleQuery = new SaxonXPathRuleQuery(); } } Maybe use a ternary expression? Up to you

Target:
private void initRuleQueryBasedOnVersion(final String version) { xpathRuleQuery = XPATH_1_0.equals(version) ? new JaxenXPathRuleQuery() : new SaxonXPathRuleQuery(); }
Source:
public Value atomize() throws XPathException { if (value == null) { START final Object v = attribute.getValue(); END value = SaxonXPathRuleQuery.getAtomicRepresentation(v); } return value; } Maybe inline that variable

Target:
public Value atomize() { if (value == null) { value = SaxonXPathRuleQuery.getAtomicRepresentation(attribute.getValue()); } return value; }
Source:
private boolean isStringConcat(Node childNode, Node baseNode) { Node currentNode = childNode; // limit to 10 levels START for (int i = 0; i < 10 && currentNode != null && currentNode != baseNode; i++) { END currentNode = currentNode.jjtGetParent(); if (currentNode instanceof ASTAdditiveExpression) { return true; } } return false; } this is rather arbitrary... why the limit? we are always going to be able to get up to the basenode given that the childNode is guaranteed to be a descendant

Target:
private boolean isStringConcat(Node childNode, Node baseNode) { Node currentNode = childNode; while (currentNode != baseNode) { currentNode = currentNode.jjtGetParent(); if (currentNode instanceof ASTAdditiveExpression) { return true; } } return false; }
Source:
public DocumentOperationsApplierForNonOverlappingRegions(final Document document) { this.document = Objects.requireNonNull(document); START comparator = new DocumentOperationNonOverlappingRegionsComparator(); END operations = new ArrayList<>(); applied = false; } there is no reason for this to be an instance field, could be a static final

Target:
public DocumentOperationsApplierForNonOverlappingRegions(final Document document) { this.document = Objects.requireNonNull(document); operations = new ArrayList<>(); applied = false; }
Source:
START XPathEvaluationException(Throwable cause) { END super(cause); } is package-private the intended visibility? or you just missed the access modifier?

Target:
public XPathEvaluationException(Throwable cause) { super(cause); }
Source:
START StyleLayer getLayer(String id) { END return layersById.get(id); } package-private?

Target:
public StyleLayer getLayer(String id) { return layersById.get(id); }
Source:
START void dropLayer(String id) { END layersById.remove(id); } package-private?

Target:
public void dropLayer(String id) { layersById.remove(id); }
Source:
public void initialize(URL location, ResourceBundle resources) { START metricResultsListView.setCellFactory(param -> new MetricResultListCell()); END scopeHierarchyTreeView.setCellFactory(param -> new ScopeHierarchyTreeCell()); scopeHierarchyTreeView.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal) -> { if (newVal != null && newVal.getValue() instanceof NameDeclaration) { parent.onNameDeclarationSelected((NameDeclaration) newVal.getValue()); } }); } In theory, these cell factories can be set directly in fxml: ``` <?import net.sourceforge.pmd.util.fxdesigner.util.controls.MetricResultListCell?> <?import net.sourceforge.pmd.util.fxdesigner.util.controls.ScopeHierarchyTreeCell?> <ListView fx:id="metricResultsListView" styleClass="secondary-panel" BorderPane.alignment="CENTER"> <cellFactory> <MetricResultListCell /> </cellFactory> </ListView> <TreeView fx:id="scopeHierarchyTreeView" styleClass="secondary-panel" BorderPane.alignment="CENTER"> <cellFactory> <ScopeHierarchyTreeCell /> </cellFactory> </TreeView> ```

Target:
public void initialize(URL location, ResourceBundle resources) { scopeHierarchyTreeView.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal) -> { if (newVal != null && newVal.getValue() instanceof NameDeclaration) { parent.onNameDeclarationSelected((NameDeclaration) newVal.getValue()); } }); }
Source:
public void removeChildAtIndex(final int childIndex) { if (0 <= childIndex && childIndex < jjtGetNumChildren()) { // Remove the child at the given index children = ArrayUtils.remove(children, childIndex); // Update the remaining children indexes START for (int i = 0; i < jjtGetNumChildren(); i++) { END jjtGetChild(i).jjtSetChildIndex(i); } } } This loop can safely start at `childIndex`, since previous indexes should not be affected

Target:
public void removeChildAtIndex(final int childIndex) { if (0 <= childIndex && childIndex < jjtGetNumChildren()) { // Remove the child at the given index children = ArrayUtils.remove(children, childIndex); // Update the remaining & left-shifted children indexes for (int i = childIndex; i < jjtGetNumChildren(); i++) { jjtGetChild(i).jjtSetChildIndex(i); } } }
Source:
protected Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException { // First, check if the class has already been loaded Class<?> c = findLoadedClass(name); if (c == null) { START if (c == null) { END try { // checking local c = findClass(name); } catch (final ClassNotFoundException e) { // checking parent // This call to loadClass may eventually call findClass again, in case the parent doesn't find anything. c = super.loadClass(name, resolve); } } } if (resolve) { resolveClass(c); } return c; } Nothing harmful, but the null check is done twice.

Target:
protected Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException { // First, check if the class has already been loaded Class<?> c = findLoadedClass(name); if (c == null) { try { // checking local c = findClass(name); } catch (final ClassNotFoundException e) { // checking parent // This call to loadClass may eventually call findClass again, in case the parent doesn't find anything. c = super.loadClass(name, resolve); } } if (resolve) { resolveClass(c); } return c; }
Source:
public boolean isIntersectionType() { START return typeList.size() == 1; END } I believe this should be `typeList.size() != 1`, isn't it?

Target:
public boolean isIntersectionType() { return typeList.size() != 1; }
Source:
public <T> List<T> getParentsOfType(Class<T> parentType) { List<T> parents = new ArrayList<>(); Node parentNode = jjtGetParent(); while (parentNode != null) { START if (parentType.isInstance(parentNode.getClass())) { END parents.add((T) parentNode); } parentNode = parentNode.jjtGetParent(); } return parents; } This is the cause for the unit test failures (wouldn't have seen it otherwise): It must be `parentType.isInstance(parentNode)` (without the getClass()) - now all the parent nodes have been matched (since every class is a class...).

Target:
public <T> List<T> getParentsOfType(Class<T> parentType) { List<T> parents = new ArrayList<>(); Node parentNode = jjtGetParent(); while (parentNode != null) { if (parentType.isInstance(parentNode)) { parents.add((T) parentNode); } parentNode = parentNode.jjtGetParent(); } return parents; }
Source:
public EnumeratedProperty(String theName, String theDescription, Map<String, E> labelsToChoices, E defaultValue, Class<E> valueType, float theUIOrder) { super(theName, theDescription, defaultValue, theUIOrder); START this.valueType = valueType; END choicesByLabel = Collections.unmodifiableMap(labelsToChoices); labelsByChoice = Collections.unmodifiableMap(CollectionUtil.invertedMapFrom(choicesByLabel)); } Can we derive `Class<E>` by looking at one of the label choices, if at least one is always provided? Given these are immutable, a real-world case for an empty enumerations eludes me.

Target:
public EnumeratedProperty(String theName, String theDescription, Map<String, E> labelsToChoices, E defaultValue, Class<E> valueType, float theUIOrder) { this(theName, theDescription, labelsToChoices, defaultValue, valueType, theUIOrder, false); }
Source:
START public Object createNonNullArray() { END return new Object @NonNull[0]; } `public Object[] createNonNullArray() {` maybe?

Target:
public Object[] createNonNullArray() { return new Object @NonNull[0]; }
Source:
public DataPointGroup aggregate(DataPointGroup dataPointGroup) { START if (m_sampling == null) // TODO is this clean? END m_sampling = new Sampling(1, TimeUnit.MILLISECONDS); checkNotNull(dataPointGroup); if (m_alignSampling) { m_startTime = alignRangeBoundary(m_startTime); } return (new RangeDataPointAggregator(dataPointGroup, getSubAggregator())); } This is unnecessary as the annotation won't let this value be null. We catch this as an api syntax error and return that to the caller.

Target:
public DataPointGroup aggregate(DataPointGroup dataPointGroup) { checkNotNull(dataPointGroup); if (m_alignSampling) m_startTime = alignRangeBoundary(m_startTime); return (new RangeDataPointAggregator(dataPointGroup, getSubAggregator())); }
Source:
public OutputStreamFlushableCommandline( String[] excludedEnvironmentVariables ) { this.excludedEnvironmentVariables = new ConcurrentLinkedDeque<>(); START this.addedEnvironmentVariables = new HashSet<>( ); END Collections.addAll( this.excludedEnvironmentVariables, excludedEnvironmentVariables ); } try to rewrite to `addedEnvironmentVariables = new HashSet<>();` without `this` and space in constructor.

Target:
public OutputStreamFlushableCommandline( String[] excludedEnvironmentVariables ) { this.excludedEnvironmentVariables = new ConcurrentLinkedDeque<>(); addedEnvironmentVariables = new HashSet<>(); Collections.addAll( this.excludedEnvironmentVariables, excludedEnvironmentVariables ); }
Source:
START public synchronized void putAll(Map<?, ?> t) { END for (Map.Entry<?, ?> entry : t.entrySet()) { this.put(entry.getKey(), entry.getValue()); } } We have different conventions. Please see the spaces around brackets and method parameters, and brackets on new lines. The checkstyle plugin would crash the build. Did you try to run "mvn install -P run-its"? It would take quite long time to complete the build, cca one hour.

Target:
public synchronized void putAll( Map<?, ?> t ) { for ( Map.Entry<?, ?> entry : t.entrySet() ) { put( entry.getKey(), entry.getValue() ); } }
Source:
public NullStatisticsReporter() { START super( FileUtils.getFile( FileUtils.getTempDirectory(), RandomStringUtils.randomAlphabetic( 24 ) ) ); END } It would be nice to have protected no-arg constructor of `StatisticsReporter` for these purposes and null variables of `File` and `RunEntryStatisticsMap`, etc. Not necessary to create new objects if unused.

Target:
private NullStatisticsReporter() { super( null, null, null ); }
Source:
public void testAssumptionFailure( Failure failure ) { START this.reporter.testAssumptionFailure( SimpleReportEntry.ignored( getClassName( failure.getDescription() ) , END failure.getDescription().getDisplayName() , failure.getMessage() ) ); failureFlag.set( Boolean.TRUE ); } @jimma Can you please introduce a new constructor `public SimpleReportEntry( String source, String name, String message )` and call it instead of `SimpleReportEntry.ignored`? Can you call that constructor in `SimpleReportEntry.ignored` as well? Thx.

Target:
public void testAssumptionFailure( Failure failure ) { reporter.testAssumptionFailure( new SimpleReportEntry( getClassName( failure.getDescription() ) , failure.getDescription().getDisplayName() , failure.getMessage() ) ); failureFlag.set( true ); }
Source:
public MockSCMSource build() { MockSCMSource source = controller == null ? new MockSCMSource(controllerId, repository, traits()) : new MockSCMSource(controller, repository, traits()); START source.setId(id); END return source; } Perhaps make `id` optional for `MockSCMSourceBuilder` too.

Target:
public MockSCMSource build() { MockSCMSource source = controller == null ? new MockSCMSource(controllerId, repository, traits()) : new MockSCMSource(controller, repository, traits()); source.setId(id()); return source; }
Source:
public MockSCMSource build() { MockSCMSource source = controller == null ? new MockSCMSource(controllerId, repository, traits()) : new MockSCMSource(controller, repository, traits()); START if (id != null) { END source.setId(id()); } return source; } harmless to call even if null, so could use `withId` IIUC

Target:
public MockSCMSource build() { MockSCMSource source = controller == null ? new MockSCMSource(controllerId, repository, traits()) : new MockSCMSource(controller, repository, traits()); source.setId(id()); return source; }
Source:
START @Override protected void after() { END tmp.delete(); } Scm api has rules on the placement of annotations for methods

Target:
protected void after() { tmp.delete(); }
Source:
START @Override public final String toString() { END return sampleRepo.getAbsolutePath(); } Annotations on wrong line

Target:
public final String toString() { return sampleRepo.getAbsolutePath(); }
Source:
public static SCMHead readResolveSCMHead(@NonNull SCMSource source, @NonNull SCMHead head) { for (SCMHeadMigration m : ExtensionList.lookup(SCMHeadMigration.class)) { START if (m.sourceClass.equals(source.getClass()) END && m.headClass.equals(head.getClass())) { SCMHead migrated = m.migrate(source, head); if (migrated != null) { return migrated; } } } return head; } Can use `==` for `Class`es.

Target:
public static SCMHead readResolveSCMHead(@NonNull SCMSource source, @NonNull SCMHead head) { for (SCMHeadMigration m : ExtensionList.lookup(SCMHeadMigration.class)) { if (m.sourceClass == source.getClass() && m.headClass == head.getClass()) { SCMHead migrated = m.migrate(source, head); if (migrated != null) { return migrated; } } } return head; }
Source:
START public ChangeRequestSCMHeadCategory() { END super("change-requests", Messages._ChangeRequestSCMHeadCategory_DisplayName()); } Why is this in the `impl` package? Would not an SCM implementation wish to return this among others?

Target:
private ChangeRequestSCMHeadCategory() { super("change-requests", Messages._ChangeRequestSCMHeadCategory_DisplayName()); }
Source:
public <T extends Action> T getAction(@NonNull Class<T> type) { // TODO should be deleted but old versions of blue ocean api rely on this START return ChangeRequestAction.class.equals(type) ? (T)new ChangeRequestAction(){} : null; END } No, I meant to actually implement the methods!

Target:
public <T extends Action> T getAction(@NonNull Class<T> type) { // TODO should be deleted but old versions of blue ocean api call this method return null; }
Source:
START public List<Action> retrieveActions(@NonNull SCMNavigatorOwner owner, END @CheckForNull SCMNavigatorEvent event, @NonNull TaskListener listener) throws IOException, InterruptedException { return Collections.emptyList(); } I don't really see the difference between this and `fetchActions`? Maybe my speed reading isn't up to snuff?

Target:
protected List<Action> retrieveActions(@NonNull SCMNavigatorOwner owner, @CheckForNull SCMNavigatorEvent event, @NonNull TaskListener listener) throws IOException, InterruptedException { return Collections.emptyList(); }
Source:
START @Override public SCMNavigator newInstance(String name) { END return null; } style guide

Target:
public SCMNavigator newInstance(String name) { return null; }
Source:
public void put(String URL, String key, String value) { if (parseMap.containsKey(URL)) { parseMap.get(URL).getMetadata().addValue(key, value); } else { START ParseData parse = ParseData.empty; END parse.put(key, value); parseMap.put(URL, parse); } } isn't 'ParseData.empty' immutable?

Target:
public void put(String URL, String key, String value) { if (parseMap.containsKey(URL)) { parseMap.get(URL).getMetadata().addValue(key, value); } else { ParseData parse = new ParseData(); parse.put(key, value); parseMap.put(URL, parse); } }
Source:
public void setValues(String key, String[] values) { START md.put(key, values); END } SHould we check that values is neither null nor empty?

Target:
public void setValues(String key, String[] values) { if (values == null || values.length == 0) return; md.put(key, values); }
Source:
public static NotificationCompat.Builder setSecretVisibility(NotificationCompat.Builder builder) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { START return builder.setVisibility(Notification.VISIBILITY_SECRET).setPriority(Notification.PRIORITY_MIN); END } return builder; } Extract the Priority into a constant so we don't have to change it in 2 places

Target:
public static NotificationCompat.Builder setSecretVisibility(NotificationCompat.Builder builder) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return builder.setVisibility(Notification.VISIBILITY_SECRET); } return builder; }
Source:
public void setUp() throws Exception { super.setUp(); START localPhone = new ClippingDto().setContent("+919876543210") END .setType(ClippingDto.ClippingType.PHONE_NUMBER) .setClippingProvider(ClippingDto.ClippingProvider.LOCAL).setCreateAt(new Date()) .setDeviceId("uniqueId"); remoteAddress = new ClippingDto(localPhone).setContent("H.No. 22/7, India") .setType(ClippingDto.ClippingType.ADDRESS) .setClippingProvider(ClippingDto.ClippingProvider.CLOUD); context = DroidOmniApplication_.getAppContext(); } the name is poorly chose, the object created is not a Phone is a clipping the name should be `localClipping`, the content of the clipping is not relevant for the test.

Target:
public void setUp() throws Exception { super.setUp(); context = DroidOmniApplication_.getAppContext(); }
Source:
protected void onPostExecute(String result) { a.setProgressBarIndeterminateVisibility(false); if(result != null && result.length() > 0) { Toast.makeText(a, result, Toast.LENGTH_LONG).show(); } if (operation == RESTORE_OPERATION || operation == BACKUP_OPERATION || operation == CLEAR_TILES_OPERATION) { a.reloadLocalIndexes(); } else { a.newDownloadIndexes(); } START getMyApplication().getPoiHelper().readPoiTypesFromMapAsync(); END } UI ?

Target:
protected void onPostExecute(String result) { a.setProgressBarIndeterminateVisibility(false); if(result != null && result.length() > 0) { Toast.makeText(a, result, Toast.LENGTH_LONG).show(); } if (operation == RESTORE_OPERATION || operation == BACKUP_OPERATION || operation == CLEAR_TILES_OPERATION) { a.reloadLocalIndexes(); } else { a.newDownloadIndexes(); } }
Source:
public void addItem(ContextMenuItem item) { try { String id = item.getId(); if (id != null) { item.setHidden(isItemHidden(id)); item.setOrder(getItemOrder(id, item.getOrder())); } items.add(item.getPos(), item); START } catch (IndexOutOfBoundsException ex) { END items.add(item); } sortItemsByOrder(); } Bad code. Remove try - catch.

Target:
public void addItem(ContextMenuItem item) { String id = item.getId(); if (id != null) { item.setHidden(isItemHidden(id)); item.setOrder(getItemOrder(id, item.getOrder())); } items.add(item); sortItemsByOrder(); }
Source:
public List<ContextMenuItem> getDefaultItems() { String idScheme = getIdScheme(); List<ContextMenuItem> items = new ArrayList<>(); for (ContextMenuItem item : this.items) { String id = item.getId(); START if (id != null && (id.startsWith(idScheme) && !APP_PROFILES_ID.equals(id) || id.startsWith(AIDL_LAYERS_PREFIX))) { END items.add(item); } } return items; } Wrong code. Should be "if (id != null && (id.startsWith(idScheme))" only.

Target:
public List<ContextMenuItem> getDefaultItems() { String idScheme = getIdScheme(); List<ContextMenuItem> items = new ArrayList<>(); for (ContextMenuItem item : this.items) { String id = item.getId(); if (id != null && (id.startsWith(idScheme))) { items.add(item); } } return items; }
Source:
private List<String> readIdsList(JSONArray jsonArray, @NonNull String idScheme) { List<String> list = new ArrayList<>(); if (jsonArray != null) { for (int i = 0; i < jsonArray.length(); i++) { String id = jsonArray.optString(i); START if (id.startsWith(AIDL_LAYERS_PREFIX)) { END list.add(id); } else { list.add(idScheme + id); } } } return list; } Not clear why AIDL_LAYERS_PREFIX here

Target:
protected List<String> readIdsList(JSONArray jsonArray, @NonNull String idScheme) { List<String> list = new ArrayList<>(); if (jsonArray != null) { for (int i = 0; i < jsonArray.length(); i++) { String id = jsonArray.optString(i); list.add(idScheme + id); } } return list; }
Source:
public ContextMenuItem createItem() { return new ContextMenuItem(mTitleId, mTitle, mIcon, mColorRes, mSecondaryIcon, mSelected, mProgress, mLayout, mLoading, mIsCategory, mIsClickable, mSkipPaintingWithoutColor, START mPosition, mOrder, mDescription, mItemClickListener, mIntegerListener, mProgressListener, mItemDeleteAction, END mHideDivider, mHideCompoundButton, mMinHeight, mTag, mId); } mPosition?

Target:
public ContextMenuItem createItem() { return new ContextMenuItem(mTitleId, mTitle, mIcon, mColorRes, mSecondaryIcon, mSelected, mProgress, mLayout, mLoading, mIsCategory, mIsClickable, mSkipPaintingWithoutColor, mOrder, mDescription, mItemClickListener, mIntegerListener, mProgressListener, mItemDeleteAction, mHideDivider, mHideCompoundButton, mMinHeight, mTag, mId); }
Source:
protected List<QuickActionType> getQuickActionTypes() { START ArrayList<QuickActionType> quickActionTypes = new ArrayList<>(); END quickActionTypes.add(AddPOIAction.TYPE); quickActionTypes.add(AddOSMBugAction.TYPE); quickActionTypes.add(ShowHideOSMBugAction.TYPE); return quickActionTypes; } ArrayList -> List

Target:
protected List<QuickActionType> getQuickActionTypes() { List<QuickActionType> quickActionTypes = new ArrayList<>(); quickActionTypes.add(AddPOIAction.TYPE); quickActionTypes.add(AddOSMBugAction.TYPE); quickActionTypes.add(ShowHideOSMBugAction.TYPE); return quickActionTypes; }
Source:
public boolean isLoaded() { START return gpxFile.modifiedTime != 0; END } better to use -1 if it is going to be used. Sometimes 0 is system time

Target:
public boolean isLoaded() { return gpxFile.modifiedTime != -1; }
Source:
private FavouritePoint getPersonalPoint(PersonalFavouritePoint.PointType pointType) { FavouritePoint personalPoint = null; for (FavouritePoint fp : cachedPersonalFavoritePoints) { if (fp instanceof PersonalFavouritePoint) { if (((PersonalFavouritePoint) fp).getType() == pointType) { START personalPoint = fp; END } } } return personalPoint; } return fp;

Target:
private FavouritePoint getPersonalPoint(PersonalFavouritePoint.PointType pointType) { for (FavouritePoint fp : cachedPersonalFavoritePoints) { if (((PersonalFavouritePoint) fp).getType() == pointType) { return fp; } } return null; }