auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected AuditMessageType.ActiveParticipant getActiveParticipant(UserType oUserInfo) { // Create Active Participant Section // create a method to call the AuditDataTransformHelper - one expectation AuditMessageType.ActiveParticipant participant = createActiveParticipantFromUser( START oUserInfo, Boolean.TRUE); END if (oUserInfo.getRoleCoded() != null) { participant.getRoleIDCode().add(AuditDataTransformHelper.createCodeValueType(oUserInfo.getRoleCoded().getCode(), "", oUserInfo.getRoleCoded().getCodeSystemName(), oUserInfo.getRoleCoded().getDisplayName())); } return participant; } You line wrap MUCH later a couple lines down; should this wrap later on this line, or wrapped earlier down below?

Target:
protected AuditMessageType.ActiveParticipant getActiveParticipant(UserType oUserInfo) { // Create Active Participant Section // create a method to call the AuditDataTransformHelper - one expectation AuditMessageType.ActiveParticipant participant = createActiveParticipantFromUser(oUserInfo); if (oUserInfo.getRoleCoded() != null) { participant.getRoleIDCode().add(AuditDataTransformHelper.createCodeValueType(oUserInfo.getRoleCoded(). getCode(), "", oUserInfo.getRoleCoded().getCodeSystemName(), oUserInfo.getRoleCoded().getDisplayName())); } return participant; }
Source:
START public String getToken() throws NoSuchAlgorithmException { END createToken(); return token; } hmm. Don't think this should just throw the exception but don't know a better way of handling this. since this should be a fatal error.

Target:
public String getToken() { createToken(); return token; }
Source:
public String getToken() { createToken(); START if (token != null) { END return token; } return null; } This function should be simplified to: createToken(); return token;

Target:
public String getToken() { createToken(); return token; }
Source:
private String getSenderEmailId(MimeMessage message) throws MessagingException { InternetAddress sender = (InternetAddress) message.getSender(); if (sender == null) { InternetAddress[] fromAddresses = (InternetAddress[]) message.getFrom(); START sender = fromAddresses[0]; END } return (sender.getAddress()); } Has "message" been null checked before this point? Also, is there a guarantee that the fromAddresses length will be greater than 0?

Target:
private String getSenderEmailId(MimeMessage message) throws MessagingException { InternetAddress sender = null; sender = (InternetAddress) message.getSender(); if (sender == null) { InternetAddress[] fromAddresses = (InternetAddress[]) message.getFrom(); if (fromAddresses.length > 0) { sender = fromAddresses[0]; } } return ((sender == null) ? null : sender.getAddress()); }
Source:
private boolean getDirectTestFlag(String fileName, String property) { boolean directTestFlag = false; String directTestingFlag = getDirectTestingParam(fileName, property); START if (directTestingFlag.equals("true")) { END directTestFlag = true; } return directTestFlag; } Need to check if the directTestingFlag is null.

Target:
private boolean getDirectTestFlag(String fileName, String property) { boolean directTestFlag = false; String directTestingFlag = getDirectTestingParam(fileName, property); if (directTestingFlag != null && !directTestingFlag.isEmpty() && directTestingFlag.equals("true")) { directTestFlag = true; } return directTestFlag; }
Source:
public String getDocumentId() { START return (documentId == null) ? URI : documentId; END } "URI" should be lowercase

Target:
public String getDocumentId() { //workaround for now, once the CONNECT FHIR adapter supports //documentId, we will remove this logic return (documentId == null) ? uri : documentId; }
Source:
public void auditNhinCoreX12RealtimeRequest(COREEnvelopeRealTimeRequest message, AssertionType assertion, NhinTargetSystemType target, String direction) { START LOG.debug("---Begin COREX12AuditLogger.auditCoreX12RealtimeRequest()---"); END // Set up the audit logging request message AuditRepositoryLogger auditLogger = new AuditRepositoryLogger(); LogEventRequestType auditLogMsg = auditLogger.logNhinCoreX12RealtimeRequest(message, assertion, target, direction); if (auditLogMsg != null && auditLogMsg.getAuditMessage() != null) { audit(auditLogMsg, assertion); } else { LOG.error("Core X12 Realtime Request auditLogMsg is null"); } LOG.debug("---End COREX12AuditLogger.auditCoreX12RealtimeRequest()---"); } Any logging that is just "begin" and "end" statements should really just be trace. Apply to all subsequent uses in pr.

Target:
public void auditNhinCoreX12RealtimeRequest(COREEnvelopeRealTimeRequest message, AssertionType assertion, NhinTargetSystemType target, String direction) { LOG.trace("---Begin COREX12AuditLogger.auditCoreX12RealtimeRequest()---"); // Set up the audit logging request message LogEventRequestType auditLogMsg = auditLogger.logNhinCoreX12RealtimeRequest(message, assertion, target, direction); if (auditLogMsg != null && auditLogMsg.getAuditMessage() != null) { audit(auditLogMsg, assertion); } else { LOG.error("Core X12 Realtime Request auditLogMsg is null"); } LOG.trace("---End COREX12AuditLogger.auditCoreX12RealtimeRequest()---"); }
Source:
protected List<PRPAIN201306UV02MFMIMT700711UV01Subject1> getSubjects(PRPAIN201306UV02 response) { START List<PRPAIN201306UV02MFMIMT700711UV01Subject1> subjects = null; END if (response != null && response.getControlActProcess() != null) { subjects = response.getControlActProcess().getSubject(); } return subjects; } Only a suggestion, but anytime you have a function that will return a Collection, consider initializing as empty instead of null unless there's a compelling reason otherwise -- this allows callers to run the result through an enhanced for loop (or similar) without requiring a null check.

Target:
protected List<PRPAIN201306UV02MFMIMT700711UV01Subject1> getSubjects(PRPAIN201306UV02 response) { List<PRPAIN201306UV02MFMIMT700711UV01Subject1> subjects = new ArrayList<PRPAIN201306UV02MFMIMT700711UV01Subject1>(); if (response != null && response.getControlActProcess() != null) { subjects = response.getControlActProcess().getSubject(); } return subjects; }
Source:
public void registerHandlers() { //initialize the HibernateUtil when the Direct Servlet is initialized.. DO NOT Remove this. SessionFactory session = gov.hhs.fha.nhinc.event.persistence.HibernateUtil.getSessionFactory(); session = gov.hhs.fha.nhinc.direct.messagemonitoring.persistence.HibernateUtil.getSessionFactory(); LOG.debug("Registering event Loggers"); EventLoggerFactory.getInstance().registerLoggers(); START LOG.debug("Registering handlers..."); END getDirectReceiver(); } These debug statements should either be changed to trace or removed.

Target:
public void registerHandlers() { //initialize the HibernateUtil when the Direct Servlet is initialized.. DO NOT Remove this. SessionFactory session = gov.hhs.fha.nhinc.event.persistence.HibernateUtil.getSessionFactory(); session = gov.hhs.fha.nhinc.direct.messagemonitoring.persistence.HibernateUtil.getSessionFactory(); LOG.trace("Registering event Loggers"); EventLoggerFactory.getInstance().registerLoggers(); LOG.trace("Registering handlers..."); getDirectReceiver(); }
Source:
public COREEnvelopeRealTimeResponse realTimeRequest(COREEnvelopeRealTimeRequest coreEnvelopeRealTimeRequest, AssertionType assertion) { COREEnvelopeRealTimeResponse oResponse = null; if (coreEnvelopeRealTimeRequest != null) { LOG.trace("Begin AdapterCORE_X12DSRealTimeOrchImpl.realTimeRequest()"); //Call to a method which builds response metadata and returns response oResponse = buildAdapterCORE_X12DSRealTimeResponseMetadata(); //Call for logging inbound logAdapterCORE_X12DSRealTimeRequest(coreEnvelopeRealTimeRequest); LOG.trace("End AdapterCORE_X12DSRealTimeOrchImpl.realTimeRequest()"); } else { oResponse = new COREEnvelopeRealTimeResponse(); START return oResponse; END //TODO: Need to add error handling } return oResponse; } remove this return statement, it's redundant.

Target:
public COREEnvelopeRealTimeResponse realTimeRequest(COREEnvelopeRealTimeRequest coreEnvelopeRealTimeRequest, AssertionType assertion) { COREEnvelopeRealTimeResponse oResponse = null; if (coreEnvelopeRealTimeRequest != null) { LOG.trace("Begin AdapterCORE_X12DSRealTimeOrchImpl.realTimeRequest()"); //Call to a method which builds response metadata and returns response oResponse = buildAdapterCORE_X12DSRealTimeResponseMetadata(); //Call for logging inbound logAdapterCORE_X12DSRealTimeRequest(coreEnvelopeRealTimeRequest); LOG.trace("End AdapterCORE_X12DSRealTimeOrchImpl.realTimeRequest()"); } else { oResponse = new COREEnvelopeRealTimeResponse(); //TODO: Need to add error handling } return oResponse; }
Source:
public void deleteAddress() { List<Address> addresses = selectedDomain.getAddress(); for (int i = 0; i < addresses.size(); i++) { if (addresses.get(i).getEmailAddress().equals(getEmailAddress())) { START addresses.remove(i); END } } UpdateDomain updateDomain = new UpdateDomain(); updateDomain.setDomain(selectedDomain); directService.updateDomain(updateDomain); } You should break out of the for loop once the address is found.

Target:
public void deleteAddress() { List<Address> addresses = selectedDomain.getAddress(); for (int i = 0; i < addresses.size(); i++) { if (addresses.get(i).getEmailAddress().equals(getEmailAddress())) { addresses.remove(i); break; } } UpdateDomain updateDomain = new UpdateDomain(); updateDomain.setDomain(selectedDomain); directService.updateDomain(updateDomain); }
Source:
public SimpleDateFormatThreadSafe(final String pattern, final DateFormatSymbols formatSymbols) { super(pattern, formatSymbols); localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() { START protected SimpleDateFormat initialValue() { END return new SimpleDateFormat(pattern, formatSymbols); } }; } where's your @override?

Target:
public SimpleDateFormatThreadSafe(final String pattern, final DateFormatSymbols formatSymbols) { super(pattern, formatSymbols); localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat(pattern, formatSymbols); } }; }
Source:
private void display(String message, int lengthMillis) { if (contextIsStillAlive()) { Toast toast = Toast.makeText(context, message, lengthMillis); toast.show(); START toasts.add(toast); END } else { Log.e("Couldn't toast, context has become null. Attempted message: " + message); } } I would add then show, means later you could add , then something else could show

Target:
private void display(String message, int lengthMillis) { Toast toast = Toast.makeText(context, message, lengthMillis); display(toast); }
Source:
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException { String name = rs.getString(names[0]); START return rs.wasNull() ? null : new CEP(name); END } `name` não é um bom nome de variável. Acho que oc erto aqui seria value ou cep mesmo, que acha?

Target:
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException { String value = rs.getString(names[0]); return rs.wasNull() ? null : new CEP(value); }
Source:
public void boletoNaoDeveAceitarDescricaoNula() { Boleto b = Boleto.novoBoleto(); START b.comDescricao(""); END } Não deveria ser null aqui?

Target:
public void boletoNaoDeveAceitarDescricaoNula() { Boleto b = Boleto.novoBoleto(); b.comDescricao(null); }
Source:
public void getParts() { Iterator<DoubleSegment> edges = RECTANGLE.getParts().iterator(); START assertEquals(TOP_EDGE, edges.next()); END assertEquals(LEFT_EDGE, edges.next()); assertEquals(RIGHT_EDGE, edges.next()); assertEquals(BOTTOM_EDGE, edges.next()); assertFalse(edges.hasNext()); } I would use something like assertEquals(Arrays.asList(...), edges)

Target:
public void getParts() { assertEquals( asList(TOP_EDGE, LEFT_EDGE, RIGHT_EDGE, BOTTOM_EDGE), RECTANGLE.getParts() ); }
Source:
public void internalMapFailure() { Async<Integer> failure = Asyncs.failure(new Throwable()); Async<Integer> mapped = Asyncs.map(failure, new Function<Integer, Integer>() { @Override public Integer apply(Integer input) { return input + 1; } }, new SimpleAsync<Integer>()); START assertThat(mapped, AsyncMatchers.<Integer>failed()); END } As far as I understand, we can get rid of explicit type parameters is such calls

Target:
public void internalMapFailure() { Async<Integer> failure = Asyncs.failure(new Throwable()); Async<Integer> mapped = Asyncs.map(failure, new Function<Integer, Integer>() { @Override public Integer apply(Integer input) { return input + 1; } }, new SimpleAsync<Integer>()); assertThat(mapped, failed()); }
Source:
List<CompositeT> allBetween(CompositeT from, CompositeT to) { List<CompositeT> res = new ArrayList<>(); START res.add(from); END if (to != from) { includeClosed(from, to, res); } return res; } I think it is better to exclude "from" and "to" objects from resulting list

Target:
List<CompositeT> allBetween(CompositeT from, CompositeT to) { List<CompositeT> res = new ArrayList<>(); if (to != from) { includeClosed(from, to, res); } return res; }
Source:
boolean includeClosed(CompositeT left, CompositeT to, List<CompositeT> res) { for (CompositeT next = left.nextSibling(); next != null; next = next.nextSibling()) { if (includeOpen(next, to, res)) { return true; } } START if (left.getParent() == null) { END throw new IllegalArgumentException("Right bound not found in left's bound hierarchy. to=" + to); } return includeClosed(left.getParent(), to, res); } First, it is better to assert something in the beginning on the method. Second, left may be root in the first call of this method , I think.

Target:
void includeClosed(CompositeT left, CompositeT to, List<CompositeT> res) { for (CompositeT next = left.nextSibling(); next != null; next = next.nextSibling()) { if (includeOpen(next, to, res)) { return; } } if (left.getParent() == null) { throw new IllegalArgumentException("Right bound not found in left's bound hierarchy. to=" + to); } includeClosed(left.getParent(), to, res); }
Source:
public String decapitalize(String word) { // do nothing if null or empty if ((word == null) || (word.length() < 1)) { return word; } // or if already decapitalized char first = word.charAt(0); if (Character.isLowerCase(first)) { return word; } // otherwise turn the first character to lower case and attach the rest START return String.valueOf(Character.toLowerCase(first)) + word.substring(1); END } I agree with the other changes, but not sure in this case. Is this really more optimal than the previous version?

Target:
public String decapitalize(String word) { // do nothing if null or empty if ((word == null) || (word.length() < 1)) { return word; } // or if already decapitalized char first = word.charAt(0); if (Character.isLowerCase(first)) { return word; } // otherwise turn the first character to lower case and attach the rest StringBuilder sb = new StringBuilder(word.length()); sb.append(Character.toLowerCase(first)); sb.append(word.substring(1)); return sb.toString(); }
Source:
public void visitCtYieldStatement(CtYieldStatement statement) { START String foo = ""; END } to be removed

Target:
public void visitCtYieldStatement(CtYieldStatement statement) { }
Source:
public static void setup() { testMethods = testMethods.stream() .filter(v -> v.hasAnnotation(Test.class) && v.hasAnnotation(Ignore.class) START && v.getAnnotation(Ignore.class).value().equals("UnresolvedBug")) END .collect(Collectors.toList()); } how about https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equalsIgnoreCase(java.lang.String) instead of `equals`?

Target:
public static void setup() { testMethods = testMethods.stream() .filter(v -> v.hasAnnotation(Test.class) && v.hasAnnotation(Ignore.class) && v.getAnnotation(Ignore.class).value().equalsIgnoreCase("UnresolvedBug")) .collect(Collectors.toList()); }
Source:
private void defineCommentContent(String tagContent, CtJavaDocTag.TagType tagType) { if (tagType != null) { CtJavaDocTag docTag = this.getFactory().Code().createJavaDocTag(tagContent, tagType); this.addTag(docTag); } else if (!tagContent.isEmpty()) { START this.setContent(tagContent.trim()); END } } Is it recursive call to setContent which calls defineCommentContent, which calls setContent ... ? I have not checked it deeper I just do not understand it on first sight.

Target:
private void defineCommentContent(String tagContent, CtJavaDocTag.TagType tagType) { if (tagType != null) { CtJavaDocTag docTag = this.getFactory().Code().createJavaDocTag(tagContent, tagType); this.addTag(docTag); } }
Source:
private static ContainerKind containerKindOf(Class<?> valueClass) { if (List.class.isAssignableFrom(valueClass)) { return ContainerKind.LIST; } if (Map.class.isAssignableFrom(valueClass)) { return ContainerKind.MAP; } START if (Set.class.isAssignableFrom(valueClass) || Collection.class.isAssignableFrom(valueClass)) { END return ContainerKind.SET; } return ContainerKind.SINGLE; } Set is a subtype of Collection so only the second part is necessary ```suggestion if (Collection.class.isAssignableFrom(valueClass)) { ```

Target:
private static ContainerKind containerKindOf(Class<?> valueClass) { if (List.class.isAssignableFrom(valueClass)) { return ContainerKind.LIST; } if (Map.class.isAssignableFrom(valueClass)) { return ContainerKind.MAP; } if (Collection.class.isAssignableFrom(valueClass)) { return ContainerKind.SET; } return ContainerKind.SINGLE; }
Source:
public ScanningMode enter(CtElement element) { if (ignoredParent != null && element != null) { START if (element.hasParent(ignoredParent)) { END return ScanningMode.SKIP_ALL; } } if (element instanceof CtType) { nrOfNestedLocalClasses++; } return ScanningMode.NORMAL; } Thank you, it is really better now. Would not it be even easier, if there would be only one `if` and longer condition?

Target:
public ScanningMode enter(CtElement element) { if (ignoredParent != null && element != null && element.hasParent(ignoredParent)) { return ScanningMode.SKIP_ALL; } if (element instanceof CtType) { nrOfNestedLocalClasses++; } return ScanningMode.NORMAL; }
Source:
public <E extends CtElement> E setAllMetadata(Map<String, Object> metadata) { START if (metadata != null) { END if (this.metadata == null) { this.metadata = new HashMap<>(); } else { this.metadata.clear(); } this.metadata.putAll(metadata); } else { this.metadata = null; } return (E) this; } `if (metadata != null && metadata.size() > 0) ...` WDYT?

Target:
public <E extends CtElement> E setAllMetadata(Map<String, Object> metadata) { if (metadata == null || metadata.isEmpty()) { this.metadata = null; return (E) this; } if (this.metadata == null) { this.metadata = new HashMap<>(); } else { this.metadata.clear(); } this.metadata.putAll(metadata); return (E) this; }
Source:
private String getCommentContent(int start, int end) { try { START return IOUtils.toString(new CharArrayReader(contents, start, end - start)); END } catch (IOException e) { throw new SpoonException(e); } } `return new String(contents, start, end-start);`

Target:
private String getCommentContent(int start, int end) { return new String(contents, start, end - start); }
Source:
public boolean getNoClasspath() { if (this.noclasspath == null) { START logger.warn("Spoon is currently use with the default noClasspath option set as true. Read the documentation for more information: http://spoon.gforge.inria.fr/launcher.html#about-the-classpath"); END return true; } return noclasspath; } Do we want to print this warning A) only once B) for each call ... to fill the log by these warnings? I vote for A) ... then add `this.noclasspath = true`

Target:
public boolean getNoClasspath() { if (this.noclasspath == null) { logger.warn("Spoon is currently use with the default noClasspath option set as true. Read the documentation for more information: http://spoon.gforge.inria.fr/launcher.html#about-the-classpath"); this.noclasspath = true; } return noclasspath; }
Source:
public <T extends CtStatementList> T setStatements(List<CtStatement> statements) { if (statements == null || statements.isEmpty()) { START this.statements.clear(); END return (T) this; } this.statements.clear(); this.statements.addAll(statements); return (T) this; } We already call `clear` below in the method: this could now be simlified by just adding a if not null around the final `addAll`

Target:
public <T extends CtStatementList> T setStatements(List<CtStatement> statements) { this.statements.set(statements); return (T) this; }
Source:
static void linkToParent(CtElement owner, CtElement element) { if (owner.getFactory().getEnvironment().checksAreSkipped() == false && element.isParentInitialized() && element.getParent() != owner) { //the `e` already has an different parent. Check if it is still linked to that parent START if (element.getRoleInParent() != null) { END throw new SpoonException("The element " + element + " is already used by another part of SpoonModel. Remove it from previous model or clone it before."); } } element.setParent(owner); } This change: - is good for explicit behavior - is bad for concise API (must always delete in parent before intercession) - will break a lot of client code (it already breaks the test code, see the changes in `src/test`) I would prefer to revert it, so that it remains fully backward compatible, and that while keeping the other awesome advantages of the rest of this PR. WDYT?

Target:
static void linkToParent(CtElement owner, CtElement element) { element.setParent(owner); }
Source:
protected boolean biScan(CtRole role, Collection<? extends CtElement> elements, Collection<? extends CtElement> others) { START for (Iterator<? extends CtElement> firstIt = elements.iterator(), secondIt = others.iterator(); (firstIt.hasNext()) && (secondIt.hasNext());) { END biScan(role, firstIt.next(), secondIt.next()); } return true; } I guess this code does not work for `Set` since beginning, because you cannot assure that elements in 2 Sets are iterated in consistent pairs. I wonder why it works ... WDYT?

Target:
protected void biScan(CtRole role, Collection<? extends CtElement> elements, Collection<? extends CtElement> others) { for (Iterator<? extends CtElement> firstIt = elements.iterator(), secondIt = others.iterator(); (firstIt.hasNext()) && (secondIt.hasNext());) { biScan(role, firstIt.next(), secondIt.next()); } }
Source:
public boolean addModule(CtModule module) { if (allModules.containsKey(module.getSimpleName())) { return false; } START allModules.put(module.getSimpleName(), module); END return true; } I see one more problem. Later call of CtModule.setSimpleName(...) will cause inconsistency in modules, because the module is registered under old name. May be we should store modules as List<CtModule> and `getModule` should always search that list by name. Then you can add the module into that list sooner directly in `factory.Core().createModule()` call - at time when it has no name. WDYT?

Target:
public boolean addModule(CtModule module) { return this.allModules.add(module); }
Source:
public <T extends CtElement> T setParent(T parent) { if (!this.getSimpleName().equals(CtModule.TOP_LEVEL_MODULE_NAME) && parent != getFactory().Module().getUnnamedModule()) { throw new SpoonException("The parent of a module should necessarily be the unnamed module."); } START return (T) super.setParent(parent); END } May be we can mark setParent here as Derived property and ignore call of setParent here? I guess there is no case when somebody should be able to set different parent then `unnamedModule`...

Target:
public <T extends CtElement> T setParent(T parent) { return (T) this; }
Source:
public boolean isOverriding(CtMethod<?> thisMethod, CtMethod<?> thatMethod) { if (thisMethod == thatMethod) { //method overrides itself in spoon model return true; } CtType<?> thatDeclType = thatMethod.getDeclaringType(); CtType<?> thisDeclType = getAdaptationScope(); if (thatDeclType != thisDeclType) { if (isSubtypeOf(thatDeclType.getReference()) == false) { //the declaringType of that method must be superType of this scope type return false; } } //TODO check method visibility following https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.8.1 START return isSubSignature(thisMethod, thatMethod) || isSubSignature(thatMethod, thisMethod); END } Not that, because in our case we can be sure that thisMethod belongs to sub class and thatMethod belongs to super class. So origin code is OK

Target:
public boolean isOverriding(CtMethod<?> thisMethod, CtMethod<?> thatMethod) { if (thisMethod == thatMethod) { //method overrides itself in spoon model return true; } CtType<?> thatDeclType = thatMethod.getDeclaringType(); CtType<?> thisDeclType = getAdaptationScope(); if (thatDeclType != thisDeclType) { if (isSubtypeOf(thatDeclType.getReference()) == false) { //the declaringType of that method must be superType of this scope type return false; } } //TODO check method visibility following https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.8.1 return isSubSignature(thisMethod, thatMethod); }
Source:
public CtStatement apply(CtType<?> targetType) { CtClass<?> c = Substitution.getTemplateCtClass(targetType, this); // we substitute the first statement of method statement CtStatement result = c.getMethod("statement").getBody().getStatements().get(0).clone(); START return (CtStatement) new SubstitutionVisitor(c.getFactory(), targetType, this).substitute(result); END } It seems that the class Substitute also use the `SubstitutionVisitor.scan()` usage you let it as it is on purpose or is it a miss?

Target:
public CtStatement apply(CtType<?> targetType) { CtClass<?> c = Substitution.getTemplateCtClass(targetType, this); // we substitute the first statement of method statement CtStatement result = c.getMethod("statement").getBody().getStatements().get(0).clone(); return new SubstitutionVisitor(c.getFactory(), targetType, this).substitute(result); }
Source:
public <C extends CtTypedElement> C setType(CtTypeReference<T> type) { if (getExecutable() != null && type != null) { getExecutable().setType(type); START type.setParent(this); END } return (C) this; } null check after

Target:
public <C extends CtTypedElement> C setType(CtTypeReference<T> type) { if (type != null) { type.setParent(this); } if (getExecutable() != null) { getExecutable().setType(type); } return (C) this; }
Source:
public List<SpoonFile> getAllFiles() { List<SpoonFile> result = new ArrayList<>(); Set<SpoonFile> distinctSet = new HashSet<>(); for (SpoonFile f : getFiles()) { // we take care not to add a file that was already found in a folder START if (distinctSet.add(f)) { END result.add(f); } } return result; } are your sure hashCode/equals of SpoonFile are correct? I'm not sure they are well tested.

Target:
public List<SpoonFile> getAllFiles() { List<SpoonFile> result = new ArrayList<>(); for (SpoonFile f : getFiles()) { // we take care not to add a file that was already found in a folder if (!result.contains(f)) { result.add(f); } } return result; }
Source:
public void setBinaryOutputDirectory(File outputDirectory) { modelBuilder.setBinaryOutputDirectory(outputDirectory); START getFactory().getEnvironment().setBinaryOutputDirectory(outputDirectory.getAbsolutePath()); END } Do not duplicate the information. You can use the environment in the in the model builder.

Target:
public void setBinaryOutputDirectory(File outputDirectory) { setBinaryOutputDirectory(outputDirectory.getPath()); }
Source:
public void testWildcard() throws Exception { START assertEquals(3, buildClass(Paella.class).getElements(new TypeFilter<CtWildcardReference>(CtWildcardReference.class) { END @Override public boolean matches(CtWildcardReference element) { return element.getParent(CtTypeParameter.class) != null; } }).size()); } remove change cf scan problem

Target:
public void testWildcard() throws Exception { assertEquals(3, buildClass(Paella.class).getElements(new TypeFilter<CtWildcardReference>(CtWildcardReference.class)).size()); }
Source:
public void reflectionAPI() throws Exception { // Spoon can be used as reflection API CtType s = new TypeFactory().get(String.class); assertEquals("String", s.getSimpleName()); assertEquals("java.lang.String", s.getQualifiedName()); START assertEquals(3, s.getSuperInterfaces().size()); END assertEquals(2,s.getMethodsByName("toLowerCase").size()); System.out.println(s); } This can be false if the String API changes in the next version of Java.

Target:
public void reflectionAPI() throws Exception { // Spoon can be used as reflection API CtType s = new TypeFactory().get(String.class); assertEquals("String", s.getSimpleName()); assertEquals("java.lang.String", s.getQualifiedName()); assertEquals(3, s.getSuperInterfaces().size()); assertEquals(2,s.getMethodsByName("toLowerCase").size()); }
Source:
public void testSourceClasspath() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { START final SpoonModelBuilder.ClasspathOptions options = new SpoonModelBuilder.ClasspathOptions().classpath(systemClasspath); END Assert.assertEquals("-cp " + TEST_CLASSPATH, String.join(" ", options.build())); } then update doc and command line?

Target:
public void testSourceClasspath() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { final ClasspathOptions options = new ClasspathOptions().classpath(systemClasspath); Assert.assertEquals("-cp " + TEST_CLASSPATH, String.join(" ", options.build())); }
Source:
public void setParams(Collection<?> set) { if (set != null) { this.set = set; elements = set.toArray(); this.hasS = true; prob = set.isEmpty() ? 1 : 1.0 / set.size(); logprob = set.isEmpty() ? 0 : (-Math.log(set.size())); START finiteSupport = elements.clone(); END } } why clone?

Target:
public void setParams(Collection<?> set) { if (set != null) { this.set = set; elements = set.toArray(); this.hasS = true; prob = set.isEmpty() ? 1 : 1.0 / set.size(); logprob = set.isEmpty() ? 0 : (-Math.log(set.size())); } }
Source:
public Object[] getFiniteSupport() { START checkHasParams(); END return null; } remove?

Target:
public Object[] getFiniteSupport() { return null; }
Source:
public String toString() { START StringBuffer buffer = new StringBuffer(); END buffer.append("UniformChoice("); for (Object item : s) { buffer.append(item.toString() + ", "); } buffer.replace(buffer.length() - 2, buffer.length(), ""); buffer.append(")"); return buffer.toString(); } @chrisgioia64 Pls use `StringBuilder`, which is faster!

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("UniformChoice("); for (Object item : s) { builder.append(item.toString() + ", "); } builder.replace(builder.length() - 2, builder.length(), ""); builder.append(")"); return builder.toString(); }
Source:
public static double beta(double a, double b) { START return ((Gamma.gamma(a) * Gamma.gamma(b)) / Gamma.gamma(a + b)); END } this should be private static function.

Target:
private static double beta(double a, double b) { return ((Gamma.gamma(a) * Gamma.gamma(b)) / Gamma.gamma(a + b)); }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FunctionSignature other = (FunctionSignature) obj; START return Arrays.equals(argTypes, other.argTypes) && name.equals(other.name); END } I think you can swap the order of the conjuncts because `name.equals(other.name)` is less expensive.

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof FunctionSignature)) return false; FunctionSignature other = (FunctionSignature) obj; return (name == other.name) && Arrays.equals(argTypes, other.argTypes); }
Source:
START public void addPackages(List<String> pkgs) { END for (String pkg: pkgs) { packages.add(pkg); } } could use ``` java packages.addAll(pkgs); ```

Target:
public void addPackages(List<String> pkgs) { packages.addAll(pkgs); }
Source:
public static int parseInt(String s, Dimension dimension) throws NumberFormatException { switch (dimension) { case NOT: case SIZE: return parseInt(s); case DURATION: try { long durationInMillis = TimeUtil.toMillis(s); if ((int) durationInMillis == durationInMillis) { return (int) durationInMillis; } throw new ArithmeticException("integer overflow"); } catch (NumberFormatException e) { START return parseInt(s); END } } throw new AssertionError("Unknown dimension " + dimension); } shouldn’t the NumberFormatException be caught where the method is used — and for example lead to ignoring he new value?

Target:
public static int parseInt(String s, Dimension dimension) throws NumberFormatException { switch (dimension) { case NOT: case SIZE: return parseInt(s); case DURATION: long durationInMillis = TimeUtil.toMillis(s); if ((int) durationInMillis == durationInMillis) { return (int) durationInMillis; } throw new ArithmeticException("integer overflow"); } throw new AssertionError("Unknown dimension " + dimension); }
Source:
private int checkHeaderField(String headerName, String fieldName, BitInputStream input, int sizeInBits, Predicate<Integer> validator) throws IOException { int value = input.readInt(sizeInBits); START if (validator.test(value)) { END throw new UnknownContentTypeException(headerName + "Header " + fieldName + ": " + value); } return value; } A validator should return `true`if the given value is valid, something needs to be the other way around here. :)

Target:
private int checkHeaderField(String headerName, String fieldName, BitInputStream input, int sizeInBits, Predicate<Integer> validator) throws IOException { int value = input.readInt(sizeInBits); if (!validator.test(value)) { throw new UnknownContentTypeException(headerName + "Header " + fieldName + ": " + value); } return value; }
Source:
public synchronized int getFirst() { START if (data.isEmpty()) { END return -1; } return data.get(0); } `return data.isEmpty() ? -1 : data.get(0);`?

Target:
public synchronized int getFirst() { return data.isEmpty() ? -1 : data.get(0); }
Source:
public synchronized int getLast() { START if (data.isEmpty()) { END return -1; } return data.get(data.size() - 1); } Here I would also prefer a one-liner with a ternary operator.

Target:
public synchronized int getLast() { return data.isEmpty() ? -1 : data.get(data.size() - 1); }
Source:
private void assertSorted(int[] input) { START if (input.length < 2) { END return; } for (int i = 1; i < input.length; i++) { if (input[i-1] > input[i]) { throw new IllegalStateException("Input must be sorted"); } } } `<= 1` seems to be clearer than `< 2`…

Target:
private void assertSorted(int[] input) { if (input.length <= 1) { return; } for (int i = 1; i < input.length; i++) { if (input[i-1] > input[i]) { throw new IllegalStateException("Input must be sorted"); } } }
Source:
public void writeFilter(InputStream input, OutputStream output, String charset, HashMap<String, String> otherParams, FilterCallback cb) throws DataFilterException, IOException { output.write(input.read()); START return; END } What exact purpose does this `return` have here?

Target:
public void writeFilter(InputStream input, OutputStream output, String charset, HashMap<String, String> otherParams, FilterCallback cb) throws DataFilterException, IOException { output.write(input.read()); }
Source:
START public int queuedJobsUniqueTimes() { END synchronized(timedJobsByTime) { return timedJobsByTime.size(); } } I don't think this should be part of the public API. Do we need this outside of unit tests? If not, please make it package-private.

Target:
int queuedJobsUniqueTimes() { synchronized(timedJobsByTime) { return timedJobsByTime.size(); } }
Source:
public boolean showSearchBox() { // Only show it if Library is loaded. START if (node.pluginManager != null && END node.pluginManager.isPluginLoaded("plugins.Library.Main")) { return true; } else { return false; } } if (a) then return true else return false? Are you kidding me? :)

Target:
public boolean showSearchBox() { // Only show it if Library is loaded. return (node.pluginManager != null && node.pluginManager.isPluginLoaded("plugins.Library.Main")); }
Source:
public boolean hasIV(){ if(ivSize != null){ return true; } START return false; END } Is there a reason not to replace this method body with ``` return ivSize != null; ```

Target:
public boolean hasIV(){ return ivSize != null; }
Source:
private CryptByteBufferType(int bitmask, KeyType keyType, int blockSize){ this.bitmask = bitmask; START this.ivSize = -1; END this.keyType = keyType; this.cipherName = keyType.alg; this.blockSize = blockSize; algName = name(); } Should this be set to `null` now?

Target:
private CryptByteBufferType(int bitmask, KeyType keyType, int blockSize){ this.bitmask = bitmask; this.ivSize = null; this.keyType = keyType; this.cipherName = keyType.alg; this.blockSize = blockSize; algName = name(); }
Source:
public static PublicKey getPublicKey(KeyPairType type, byte[] pub) throws UnsupportedTypeException{ if(type.equals(KeyPairType.DSA)){ throw new UnsupportedTypeException(type); } try { KeyFactory kf = KeyFactory.getInstance(type.alg); X509EncodedKeySpec xks = new X509EncodedKeySpec(pub); START return kf.generatePublic(xks); END } catch (GeneralSecurityException e) { Logger.error(KeyGenUtils.class, "Internal error; please report:", e); } return null; } Mind the whitespace, please.

Target:
public static PublicKey getPublicKey(KeyPairType type, byte[] pub){ if(type.equals(KeyPairType.DSA)){ throw new UnsupportedTypeException(type); } try { KeyFactory kf = KeyFactory.getInstance(type.alg); X509EncodedKeySpec xks = new X509EncodedKeySpec(pub); return kf.generatePublic(xks); } catch (GeneralSecurityException e) { Logger.error(KeyGenUtils.class, "Internal error; please report:", e); } return null; }
Source:
public static KeyPair genKeyPair(KeyPairType type) throws UnsupportedTypeException{ if(type.equals(KeyPairType.DSA)){ START throw new UnsupportedTypeException(type); END } try { KeyPairGenerator kg = KeyPairGenerator.getInstance(type.alg); kg.initialize(type.spec); return kg.generateKeyPair(); } catch (GeneralSecurityException e) { Logger.error(KeyGenUtils.class, "Internal error; please report:", e); } return null; } Any reason for not using the plain old `IllegalArgumentException`? I think the types in `KeyPairType` (except for DSA) should always be present on a Freenet installation, so forcing the user to wrap his code with `try(…) catch(…)` would unnecessarily increase the number of lines in the consuming code.

Target:
public static KeyPair genKeyPair(KeyPairType type) { if(type.equals(KeyPairType.DSA)){ throw new UnsupportedTypeException(type); } try { KeyPairGenerator kg = KeyPairGenerator.getInstance(type.alg); kg.initialize(type.spec); return kg.generateKeyPair(); } catch (GeneralSecurityException e) { Logger.error(KeyGenUtils.class, "Internal error; please report:", e); } return null; }
Source:
public final static boolean verify(HashResult hash1, HashResult hash2){ START if(hash1.compareTo(hash2) == 0){ END return true; } return false; } `HashResult.compareTo(…)` only compares `HashResult.type`, not `HashResult.result` (yes, **that** is wrong, but has not been fixed AFAIK). Also, please compare hashes in a way that is insensitive to timing attacks, `Comparable.compareTo(…)` does not guarantee any such property.

Target:
public final static boolean verify(HashResult hash1, HashResult hash2){ return hash1.equals(hash2); }
Source:
public int hashCode(){ int hash = 1; hash = hash * 31 + type.hashCode(); START hash = hash * 31 + result.hashCode(); END return hash; } Where did 31 come from? Why not use `*=`?

Target:
public int hashCode(){ int hash = 1; hash *= 31 + type.hashCode(); hash *= 31 + result.hashCode(); return hash; }
Source:
public void testVerifyByteArrayByteArray() { for(int i = 0; i < types.length; i++){ Hash hash = new Hash(types[i]); START boolean verified = hash.verify(Hex.decode(trueHashes[i]), helloWorld); END assertTrue("HashType: "+types[i].name(), verified); } } Some places have this separate boolean to assert on and others put the entire condition in the assert statement. It seems preferable to use one consistently. Which one?

Target:
public void testVerifyByteArrayByteArray() { for(int i = 0; i < types.length; i++){ Hash hash = new Hash(types[i]); assertTrue("HashType: "+types[i].name(), hash.verify(Hex.decode(trueHashes[i]), helloWorld)); } }
Source:
private void closeRAF() { START if(!(closed || lockLevel == 0)) throw new IllegalStateException(); END if(raf == null) return; try { raf.close(); } catch (IOException e) { Logger.error(this, "Error closing "+this+" : "+e, e); } raf = null; OPEN_FDS--; } Writing this as `if(!closed && lockLevel != 0)` instead of the negated disjunction allows for easier recognition of exactly when this condition actually holds.

Target:
private void closeRAF() { if(!closed && lockLevel != 0) throw new IllegalStateException(); if(raf == null) return; try { raf.close(); } catch (IOException e) { Logger.error(this, "Error closing "+this+" : "+e, e); } raf = null; OPEN_FDS--; }
Source:
public boolean isDefaultValue() { if(this.equals(FRIEND_TRUST.NORMAL)) return true; else return false; START } END Can this be reduced to `return equals(FRIEND_TRUST.NORMAL)`?

Target:
public boolean isDefaultValue() { return this.equals(FRIEND_TRUST.NORMAL); }
Source:
public int hashCode() { // see #equals START return element.hashCode(); END } What I'm missing here is the check if the element is null. I know that the probability is very low, but still...

Target:
public int hashCode() { if (element == null) { // shouldn't ever happen return super.hashCode(); } // see #equals for explanation return element.hashCode(); }
Source:
public Tool getExecutable() { for (Tool t : Tool.EMULATORS) { START if (t.getExecutable(true).equals(executable)) { END return t; } } return Tool.EMULATOR; } I imagine this should be `!Functions.isWindows()`, rather than being hardcoded to `true`.

Target:
public Tool getExecutable() { for (Tool t : Tool.EMULATORS) { if (t.executable.equals(executable)) { return t; } } return Tool.EMULATOR; }
Source:
protected int getPriorityFromTaintFrame(TaintFrame fact, int offset) throws DataflowAnalysisException { Taint mvcResultTaint = fact.getStackValue(offset); // The MVC Result object was tainted - This could still be safe if the content-type is a safe one if (!mvcResultTaint.isSafe()) { // Get the value of the content-type parameter Taint parameterTaint = fact.getStackValue(0); START if ( !parameterTaint.isSafe() END || (parameterTaint.getConstantValue() != null && parameterTaint.getConstantValue().toLowerCase().equals(VULNERABLE_CONTENT_TYPE)) ) { return getPriority(mvcResultTaint); } } return Priorities.IGNORE_PRIORITY; } of simply : `if(!parameterTaint.isSafe() || VULNERABLE_CONTENT_TYPE.equalsIgnoreCase(parameterTaint.getConstantValue())) {`

Target:
protected int getPriorityFromTaintFrame(TaintFrame fact, int offset) throws DataflowAnalysisException { Taint mvcResultTaint = fact.getStackValue(offset); // The MVC Result object was tainted - This could still be safe if the content-type is a safe one if (!mvcResultTaint.isSafe()) { // Get the value of the content-type parameter Taint parameterTaint = fact.getStackValue(0); if ( !parameterTaint.isSafe() || VULNERABLE_CONTENT_TYPE.equalsIgnoreCase(parameterTaint.getConstantValue())) { return getPriority(mvcResultTaint); } } return Priorities.IGNORE_PRIORITY; }
Source:
public Long getCount() { START return countResults; END } Field and constructor parameters may be renamed as well.

Target:
public Long getCount() { return count; }
Source:
START public final void loginThrowSInvalidPasswordException() throws SPlatformLoginException, SInvalidUserException, SInvalidPasswordException, SInvalidPlatformCredentialsException { END final String userName = "userName"; final String password = "pwd"; doThrow(new SInvalidPasswordException("")).when(authenticationService).checkUserCredentials(userName, password); platformLoginServiceImpl.login(userName, password); } tests method could only throws Exception, since you already expect which one will bo throwned

Target:
public final void loginThrowSInvalidPasswordException() throws Exception { final String userName = "userName"; final String password = "pwd"; doThrow(new SInvalidPasswordException("")).when(authenticationService).checkUserCredentials(userName, password); platformLoginServiceImpl.login(userName, password); }
Source:
public Actor() { users = new HashSet<String>(); groups = new HashSet<String>(); roles = new HashSet<String>(); START memberships = new HashSet<BEntry<String, String>>(); END } This should be done with field declaration example: ``` java private Set<String> users = new HashSet<>() ```

Target:
public Actor() { memberships = new HashSet<>(); }
Source:
public APISession login(final String userName, final String password) throws LoginException { try { return loginInternal(userName, password, null); START } catch (final UnknownUserException e) { END throw e; } catch (final LoginException e) { throw e; } catch (final Exception e) { throw new LoginException(e); } } you shouldn't need it as UnknownUserException extends LoginException

Target:
public APISession login(final String userName, final String password) throws LoginException { try { return loginInternal(userName, password, null); } catch (final LoginException e) { throw e; } catch (final Exception e) { throw new LoginException(e); } }
Source:
long flush(final long now) { try { final FlushResult flushResult = this.timeTracker.flush(); START return flushResult.getFlushTime(); END } catch (Exception e) { if (this.logger.isLoggable(getClass(), TechnicalLogSeverity.WARNING)) { this.logger.log(getClass(), TechnicalLogSeverity.WARNING, "Exception caught while flushing: " + e.getMessage(), e); } } return now; } it's strange to delegate to the flush result what is the last flush timestamp, should the flush result return the time to flush and let the thread determine when was it's last flush timestamp

Target:
long flush(final long now) { try { final FlushResult flushResult = this.timeTracker.flush(); return flushResult.getFlushTime(); } catch (Exception e) { log(TechnicalLogSeverity.WARNING, "Exception caught while flushing: " + e.getMessage(), e); } return now; }
Source:
START public DesignProcessDefinition getDesignProcessDefinition(long processDefinitionId) throws SProcessDefinitionNotFoundException { END try { return processDefinitionBARContribution.convertXmlToProcess(getProcessDeploymentInfo(processDefinitionId).getDesignContent().getContent()); } catch (SProcessDefinitionReadException | IOException | XMLParseException e) { throw new SProcessDefinitionNotFoundException(e, processDefinitionId); } } Leave **SProcessDefinitionReadException** pass, add them in method signature. Convert IOException and XMLParseException into **SProcessDefinitionReadException**

Target:
public DesignProcessDefinition getDesignProcessDefinition(long processDefinitionId) throws SProcessDefinitionNotFoundException, SProcessDefinitionReadException { try { return processDefinitionBARContribution.convertXmlToProcess(getProcessDeploymentInfo(processDefinitionId).getDesignContent().getContent()); } catch (IOException | XMLParseException e) { throw new SProcessDefinitionReadException(e); } }
Source:
protected Expression getExpressionFromOperationList(List<Operation> operations, long expressionDefinitionId) { for (Operation operation : operations) { final Expression expression = getExpressionFromContainer(operation, expressionDefinitionId); START if (expression == null) { END return expression; } } return null; } != null

Target:
protected Expression getExpressionFromOperationList(List<Operation> operations, long expressionDefinitionId) { for (Operation operation : operations) { final Expression expression = getExpressionFromContainer(operation, expressionDefinitionId); if (expression != null) { return expression; } } return null; }
Source:
protected Expression getExpressionFromContainer(Container container, long expressionDefinitionId) { if (container != null) { final Expression expression = container.accept(this, expressionDefinitionId); if (expression != null) { return expression; } } return null; START } END same thing ``` java return container != null ? container.accept(this, expressionDefinitionId) : null; ```

Target:
protected Expression getExpressionFromContainer(Container container, long expressionDefinitionId) { return container != null ? container.accept(this, expressionDefinitionId) : null; }