auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void instrument(final InputStream input, final OutputStream output, final String name) throws IOException { try { output.write(instrument(input, name)); } catch (final RuntimeException e) { throw instrumentError(name, e); } }

Target:
IMO addition of this is an indication of regression in `instrument(InputStream, String)`.
Source:
public byte[] instrument(final byte[] buffer, final String name) throws IOException { try { if (Java9Support.isPatchRequired(buffer)) { final byte[] result = instrument( new ClassReader(Java9Support.downgrade(buffer))); Java9Support.upgrade(result); return result; } else { return instrument(new ClassReader(buffer)); } } catch (final RuntimeException e) { throw instrumentError("class " + name, e); } }

Target:
@Godin Absolutely! In the context of the agent and the class name it should be obvious that classes get instrumented.
Source:
private static boolean isSame(final int size, AbstractInsnNode e, AbstractInsnNode n) { for (int i = 0; i < size; i++) { if (e.getOpcode() != n.getOpcode()) { return false; } e = next(e); n = next(n); } return true; }

Target:
What about also checking operands here? Should be the same except for labels.
Source:
public void testSetPredecessor() { final Instruction predecessor = new Instruction( new InsnNode(Opcodes.NOP), 122); instruction.setPredecessor(predecessor, 0); assertEquals(1, predecessor.getBranches()); try { instruction.setPredecessor(predecessor, 0); fail("exception expected"); } catch (IllegalStateException e) { // expected } }

Target:
@Godin Why not `@Test(expected=IllegalStateException.class)`?
Source:
protected void skipMojo() { final String name = getEffectivePropertyName(); final Properties projectProperties = getProject().getProperties(); final String oldValue = projectProperties.getProperty(name); if (oldValue == null) { getLog().info(name + " set to empty"); projectProperties.setProperty(name, ""); } else { getLog().info(name + " set to " + oldValue); } }

Target:
Actually we don't set anything here: Either we don't log at all or we log something like: "Keep [property] as [oldValue]".
Source:
public void testDestFileWithComma() { AgentOptions options = new AgentOptions(); AgentOptions options = new AgentOptions("destfile=build/jacoco/foo, bar.exec"); assertEquals("build/jacoco/foo, bar.exec", options.getDestfile()); }

Target:
This line should be removed
Source:
public double getRatio(final CounterEntity entity) { double ratio = DEFAULT_RATIO; if (this.configuration.get(entity) != null) { ratio = this.configuration.get(entity).doubleValue(); } return ratio; }

Target:
Avoid two lookup, what about this? ``` final Double ratio = this.configuration.get(entity); return ratio == null ? DEFAULT_RATIO : ratio.doubleValue(); ```
Source:
public MetadataTermMapping(MetadataSource metadataSource, String metadataTermCode, OpenmrsMetadata referredObject) { this(); ArgUtil.notNull(metadataSource, "metadataSource"); ArgUtil.notNull(metadataTermCode, "metadataTermCode"); setMetadataSource(metadataSource); setCode(metadataTermCode); if (referredObject != null) { setMappedObject(referredObject); } }

Target:
Any chance you could add a constructor which takes just metadatsource and metadataTermCode?
Source:
public void addEntity(Query query, String alias, Class<?> type) { if (query instanceof NativeQuery) { query.unwrap(NativeQuery.class).addEntity(alias, type); } else { throw new IllegalArgumentException(String.format("invalid Query type `%s` in HibernateHandler", query.getClass())); } }

Target:
When `unwrap` is used, it doesnt have to be cast to a `NativeQuery` in the first place. In fact, unwrap was introduced to prevent the need for casts, which is important in i.e. J2EE environments where the `Query` may be wrapped in a proxy that does not implement `NativeQuery`. `unwrap` will throw a `PersistenceException` if the implementation is not of the requested type. This would be the exception to catch and rethrow in the `IllegalArgumentException`. Or just let it be a `PersistenceException`.
Source:
private static String escapeName(String name) { if (JavaSyntaxUtils.isReserved(name)) { name = name + "$"; } if (!Character.isJavaIdentifierStart(name.charAt(0))) { name = "_" + name; } return name; }

Target:
They are mutually exclusive? Or is that a micro optimization?
Source:
public EntityType(Type type, Set<Supertype> superTypes, Function<EntityType, String> variableNameFunction) { super(type); this.modifiedSimpleName = variableNameFunction.apply(this); this.superTypes = superTypes; this.variableNameFunction = variableNameFunction; }

Target:
Maybe getUncapSimpleName could be deprecated and the transformation done outside of EntityType? ``` java String variableName = variableNameFunction(type.getSimpleName()); if (JavaSyntaxUtils.isReserved(name)) { variableName = variableName + "$"; } ```
Source:
public EntityType(Type type, Set<Supertype> superTypes) { super(type); this.superTypes = superTypes; this.modifiedSimpleName = new DefaultVariableNameFunction().apply(this); }

Target:
Could you maybe look if this could be removed? I mean the `new DefaultVariableNameFunction().apply(this)`. It's already handled in the other constructor.
Source:
private <A> Cases<A, SimpleExpression<A>> thenSimple(Expression<A> expr) { return new Cases<A, SimpleExpression<A>>((Class)expr.getType()) { @Override protected SimpleExpression<A> createResult(Class<A> type, Expression<A> last) { return Expressions.operation(type, Ops.CASE, last); } }.addCase(when, expr); }

Target:
I think relaxing the type parameter in `Cases`' `type`,`createResult` and constructor to `Class<? extends A>` helps a lot too to eliminate these casts **and** `@SuppressWarnings`.
Source:
public static String createRootVariable(Path<?> path, int suffix) { String variable = path.accept(ToStringVisitor.DEFAULT, TEMPLATES).replace('.', '_'); return variable + "_" + suffix; }

Target:
The templates used are already UnderscoreTemplates, so is it necessary to replace '.' with '_'?
Source:
private String serialize(Expression<?> expression) { CollectionAnyVisitor visitor = new CollectionAnyVisitor() { @Override protected Predicate exists(Context c, Predicate condition) { return condition; } }; Expression<?> transformed = expression.accept(visitor, new Context()); return transformed.toString(); }

Target:
Keep in mind, that collectionAnyVisitor is now stateful. The tests should reflect that as well.
Source:
public void Case() { <<<<<<< HEAD assertEquals(ImmutableList.of(1, 2, 2, 2, 2, 2), query().from(cat).orderBy(cat.id.asc()) .select(cat.name.when("Bob123").then(1).otherwise(2)).fetch()); }

Target:
You committed merge markers
Source:
public static boolean isEmpty(Object[] array) { return array == null ? true : array.length == 0; }

Target:
return array == null || array.length == 0
Source:
public void noteOpenConnection(ServerStats serverStats) { if (serverStats == null) { return; } try { serverStats.incrementActiveRequestsCount(); } catch (Error ex) { logger.error("Error noting stats for client {}", clientName, ex); } }

Target:
I noticed a bunch of these transitioned from Throwable to Error. Should that be Exception?
Source:
private VipAddressResolver getVipAddressResolver() { if (resolver == null) { synchronized (this) { if (resolver == null) { try { resolver = (VipAddressResolver) Class.forName( (String) getProperty(CommonClientConfigKey.VipAddressResolverClassName)).newInstance(); } catch (InstantiationException|IllegalAccessException|ClassNotFoundException e) { LOG.error("Cannot instantiate VipAddressResolver", e); } } } } return resolver; }

Target:
This doesn't look like a recoverable scenario, should you be re-throwing this one? Or is there some default/fallback VipAddressResolver if the instantiation fails here?
Source:
public void stopServerListRefreshing() { if (eurekaClientProvider != null) { EurekaClient eurekaClient = eurekaClientProvider.get(); if (eurekaClient != null) { eurekaClient.unregisterEventListener(updateListener); } } serverListUpdateService.shutdown(); }

Target:
This will end up doing multiple shutdowns of the shared executor (if used). You may want to track a 'sharedExecutor' variable that is null if the sharedExecutor is not used.
Source:
ExecutionContext<T> getChildContext(Object obj) { if (subContexts == null) { return null; } ChildContext<T> subContext = subContexts.get(obj); if (subContext == null) { subContext = new ChildContext<T>(this); } ChildContext<T> old = subContexts.putIfAbsent(obj, subContext); if (old != null) { return old; } else { return subContext; } }

Target:
Shouldn't this be inside the if above?
Source:
public void onExecutionStart() { if (onStartInvoked.compareAndSet(false, true)) { for (ExecutionListener<I, O> listener : listeners) { try { listener.onExecutionStart(context.getChildContext(listener)); } catch (Throwable e) { if (e instanceof AbortExecutionException) { throw (AbortExecutionException) e; } logger.error("Error invoking listener " + listener, e); } } } }

Target:
Should calling this more than once throw an exception? Seems like an invalid state.
Source:
void restOfInit(IClientConfig clientConfig) { refeshIntervalMills = Integer.parseInt(clientConfig.getProperty( CommonClientConfigKey.ServerListRefreshInterval, LISTOFSERVERS_CACHE_REPEAT_INTERVAL).toString()); boolean primeConnection = this.isEnablePrimingConnections(); // turn this off to avoid duplicated asynchronous priming done in BaseLoadBalancer.setServerList() this.setEnablePrimingConnections(false); enableAndInitLearnNewServersFeature(); updateListOfServers(); if (primeConnection && this.getPrimeConnections() != null) { this.getPrimeConnections() .primeConnections(getServerList(true)); } this.setEnablePrimingConnections(primeConnection); }

Target:
Since we support typed property, this can be simply ``` java clientConfig.get(CommonClientConfigKey.ServerListRefreshInterval, LISTOFSERVERS_CACHE_REPEAT_INTERVAL); ```
Source:
static List<Date> getDays(long endTs, @Nullable Long lookback) { List<Date> result = new ArrayList<>(); for (Long epochMillis : DateUtil.epochDays(endTs, lookback)) { result.add(new Date(epochMillis)); } return result; }

Target:
Accidental box?
Source:
Optional<String> getCredentials() { return Optional.ofNullable(basicCredentials); }

Target:
Let's just make this `@Nullable` instead of using `Optional`
Source:
public void setCredentialsRefreshInterval( Integer credentialsRefreshInterval) { // Convert seconds to milliseconds this.credentialsRefreshInterval = credentialsRefreshInterval * 1000; }

Target:
this is a surprising hack. please change the place where it is used instead as it doesn't make sense for a property to be manipulated like this. The scheduled expression might accept seconds expression like `s`.
Source:
public HttpResponse execute(ClientRequestContext ctx, HttpRequest req) throws Exception { String credentials = basicCredentials.getCredentials(); if (Objects.nonNull(credentials)) { ctx.addAdditionalRequestHeader(HttpHeaderNames.AUTHORIZATION, credentials); } return delegate().execute(ctx, req); }

Target:
```suggestion if (credentials != null) { ```
Source:
@Override public Call<Void> accept(List<Span> spans) { Call<Void> call = delegate.accept(spans); if (isSpanReporterThread()) return call; return new TracedCall<>(tracer, delegate.accept(spans), "accept-spans"); }

Target:
I'm probably wrong but I thought since we don't sample client spans, calls from the span reporter thread wouldn't be sampled anyways, they originate from the flush thread not server requests. Why is this check necessary?
Source:
@Override protected void doEnqueue(Callback<V> callback) { sendRequest().handle((response, t) -> { if (t != null) { callback.onError(t); } else { try { callback.onSuccess(parseResponse(response, bodyConverter)); } catch (Throwable e) { callback.onError(e); } } return null; }); }

Target:
usually I do either ` IOException|RuntimeException` or if doing Throwable, use propagateIfFatal
Source:
public static JsonParser enterPath(JsonParser parser, String path) throws IOException { if (!parser.isExpectedStartObjectToken()) return null; JsonToken value; while ((value = parser.nextValue()) != JsonToken.END_OBJECT) { if (value == null) { // End of input. throw new IOException("End of input while parsing object."); } if (parser.getCurrentName().equals(path) && value != JsonToken.VALUE_NULL) { return parser; } else { parser.skipChildren(); } } return null; }

Target:
our old code didn't throw I think, rather returned null
Source:
public HttpResponse handleException(RequestContext ctx, HttpRequest req, Throwable cause) { ZipkinHttpCollector.metrics.incrementMessagesDropped(); LOGGER.warn("Unexpected error handling request.", cause); String message = cause.getMessage() != null ? cause.getMessage() : ""; if (cause instanceof IllegalArgumentException) { return HttpResponse.of(BAD_REQUEST, MediaType.ANY_TEXT_TYPE, message); } else { return HttpResponse.of(INTERNAL_SERVER_ERROR, MediaType.ANY_TEXT_TYPE, message); } }

Target:
I'm not sure we want to add this logging in all cases. It seems too verbose to me for bad requests.
Source:
@Override final String doReadUtf8(int length) { String result = new String(buf, pos, length, UTF_8); pos += length; return result; }

Target:
`require(length)`
Source:
public void close() { ExecutorService maybeNull = maybeNull(); if (maybeNull != null) { maybeNull.shutdownNow(); try { maybeNull.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { // at least we tried } } }

Target:
I think we usually wait 1 second by default now.. though it is arbitrary anyway
Source:
ElasticsearchHttpSpanConsumer(ElasticsearchHttpStorage es) { this.es = es; this.indexNameFormatter = es.indexNameFormatter(); this.indexToServiceSpansCache = Collections.synchronizedMap(new LinkedHashMap<String, Set<Pair<String>>>() { @Override protected boolean removeEldestEntry(Map.Entry<String, Set<Pair<String>>> eldest) { return size() > MAX_CACHE_DAYS; } }); }

Target:
if static, should be initialized outside the ctor.. maybe make it final static.
Source:
public void setLogsUrl(String logsUrl) { this.logsUrl = logsUrl; }

Target:
set if not null or empty
Source:
public void annotationKeys() { assertThat(CassandraUtil.annotationKeys(QueryRequest.builder() .lookback(86400000L) .serviceName("service") .addAnnotation(Constants.ERROR) .addBinaryAnnotation(TraceKeys.HTTP_METHOD, "GET").build())) .containsExactly("service", "error", "http.method:GET"); }

Target:
interesting.. surprised this works, but maybe I shouldn't be
Source:
public void correctHttpResponse() throws Exception { final PublicMetrics publicMetrics = () -> Collections.singleton(new Metric<Number>("mem.free", 1024)); final ResponseEntity<String> response = responseForMetrics(publicMetrics); assertThat(response.getStatusCode(), equalTo(HttpStatus.OK)); assertThat(response.getHeaders().getContentType().toString(), equalTo("text/plain;version=0.0.4;charset=utf-8")); }

Target:
no big deal, but we don't put final on variables even if it is explicit and there are good reasons why some folks make conventions like that. leaving them out keeps line shorter and focuses more attention on the test code (at risk of someone doing the shell-game with references)
Source:
private boolean isJodaTimeInClasspath() { if ( jodaTimeInClassPath != null ) { return jodaTimeInClassPath.booleanValue(); } jodaTimeInClassPath = isClassPresent( JODA_TIME_CLASS_NAME ); return jodaTimeInClassPath.booleanValue(); }

Target:
Some nitpicking (for a change!); I usually see this pattern written that way: ``` if ( jodaTimeInClassPath == null ) { jodaTimeInClassPath = isClassPresent( JODA_TIME_CLASS_NAME ); } return jodaTimeInClassPath.booleanValue(); ```
Source:
default S locales(Locale... locales) { locales( new HashSet<>( Arrays.asList( locales ) ) ); return (S) this; }

Target:
You could do this instead, and avoid the unchecked cast: ``` return locales( new HashSet<>( Arrays.asList( locales ) ) ); ```
Source:
protected int compare(Number number) { // At this point number can be a floating point number and it should be treated differently in such case: if ( number instanceof Double ) { return NumberComparatorHelper.compare( (Double) number, maxValue, InfinityNumberComparatorHelper.GREATER_THAN ); } if ( number instanceof Float ) { return NumberComparatorHelper.compare( (Float) number, maxValue, InfinityNumberComparatorHelper.GREATER_THAN ); } return NumberComparatorHelper.compare( number, maxValue ); }

Target:
Is there a reason why you split this logic in two? I would have put everything in `NumberComparatorHelper#compare(Number, long)`.
Source:
public Optional<JavaBeanField> findDeclaredField(Class<?> declaringClass, String property) { Contracts.assertNotNull( declaringClass, MESSAGES.classCannotBeNull() ); Field field = run( GetDeclaredField.action( declaringClass, property ) ); String resolvedName = propertyNodeNameProvider.getName( javaBeanPropertyFrom( declaringClass, property ) ); return Optional.ofNullable( field ).map( f -> new JavaBeanField( f, resolvedName ) ); }

Target:
if `field` at this point is `null` - there's not need to do any additional work we should just return `Optional.empty()`. Otherwise we can find the resolved name and use `Optional.of()`. Something like: ```java Field field = run( GetDeclaredField.action( declaringClass, property ) ); if ( field == null ) { return Optional.empty(); } else { String resolvedName = propertyNodeNameProvider.getName( new JavaBeanPropertyImpl( declaringClass, property ) ); return Optional.of( new JavaBeanField( field, resolvedName ) ); } ```
Source:
@Override public Type[] getParameterTypes() { return method.getParameterTypes(); }

Target:
The `@Override` annotations should be on their own line.
Source:
public JavaBeanExecutable<?> executable(Executable executable) { if ( executable instanceof Constructor ) { return new JavaBeanConstructor( (Constructor<?>) executable ); } return executable( executable.getDeclaringClass(), ( (Method) executable ) ); }

Target:
Can't you just call `executable(Class<?> declaringClass, Executable executable)` and remove the `if()`?
Source:
@Override public Class<?> getDeclaringClass() { return declaringClass; }

Target:
Fixed.
Source:
private boolean isAnnotationAllowed(Annotation annotationToCheck, Set<Annotation> processedAnnotations) { // need to have this to prevent infinite loops for example on annotations like @Target if ( !processedAnnotations.add( annotationToCheck ) ) { return false; } Class<? extends Annotation> annotationType = annotationToCheck.annotationType(); return ALLOWED_ANNOTATIONS.contains( annotationType ) || Arrays.stream( annotationType.getDeclaredAnnotations() ) .anyMatch( annotation -> isAnnotationAllowed( annotation, processedAnnotations ) ); }

Target:
Same here, not sure this construct buys us much.
Source:
ReturnValueExecutableValidationContext( ConstraintValidatorManager constraintValidatorManager, ConstraintValidatorFactory constraintValidatorFactory, ValidatorScopedContext validatorScopedContext, TraversableResolver traversableResolver, HibernateConstraintValidatorInitializationContext constraintValidatorInitializationContext, T rootBean, Class<T> rootBeanClass, BeanMetaData<T> rootBeanMetaData, Executable executable, Optional<ExecutableMetaData> executableMetaData, Object executableReturnValue ) { super( constraintValidatorManager, constraintValidatorFactory, validatorScopedContext, traversableResolver, constraintValidatorInitializationContext, rootBean, rootBeanClass, rootBeanMetaData, buildDisableAlreadyValidatedBeanTracking( executableMetaData ) ); this.executable = executable; this.executableReturnValue = executableReturnValue; this.executableMetaData = executableMetaData; }

Target:
Very minor but let's try to be consistent with the order of the method parameters.
Source:
public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || o.getClass() != BeanGroupProcessedUnit.class ) { return false; } BeanGroupProcessedUnit that = (BeanGroupProcessedUnit) o; if ( bean != that.bean ) { // instance equality return false; } if ( !group.equals( that.group ) ) { return false; } return true; }

Target:
Annoying one... Please make it a separate JIRA and commit.
Source:
public boolean equals(Object o) { // no need to check for instance equality or if the calss match because of // how this class is used in the set. BeanPathMetaConstraintProcessedUnit that = (BeanPathMetaConstraintProcessedUnit) o; if ( bean != that.bean ) { // instance equality return false; } if ( metaConstraint != that.metaConstraint ) { return false; } if ( !path.equals( that.path ) ) { return false; } return true; }

Target:
Can't you keep that one at the top? Let's avoid the cast if we can.
Source:
public void initialize(ConstraintDescriptor<ParameterScriptAssert> constraintDescriptor, HibernateConstraintValidatorInitializationContext initializationContext) { ParameterScriptAssert constraintAnnotation = constraintDescriptor.getAnnotation(); validateParameters( constraintAnnotation ); this.languageName = constraintAnnotation.lang(); this.script = constraintAnnotation.script(); this.escapedScript = InterpolationHelper.escapeMessageParameter( constraintAnnotation.script() ); initializeScriptContext( initializationContext ); }

Target:
As mentioned above, let's move these 3 to the super `initialize()` method.
Source:
public <T> T getMandatoryParameter(String parameterName, Class<T> type) { if ( !parameters.containsKey( parameterName ) ) { throw LOG.getUnableToFindAnnotationParameterException( parameterName, null ); } Object parameter = parameters.get( parameterName ); if ( !type.isAssignableFrom( parameter.getClass() ) ) { throw LOG.getWrongParameterTypeException( type, parameter.getClass() ); } return (T) parameter; }

Target:
We could avoid the `containsKey()` + `get()` cascade by just checking the result of the latter on being null.
Source:
private static int buildHashCode(ConstraintLocation delegate, TypeVariable<?> typeParameter) { int result = delegate != null ? delegate.hashCode() : 0; result = 31 * result + typeParameter.hashCode(); return result; }

Target:
Didn't we agree that the null check on delegate isn't needed (sambe above)?
Source:
public BeanMetaData<T> getRootBeanMetaData() { if ( rootBeanClass != null && rootBeanMetaData == null ) { rootBeanMetaData = beanMetaDataManager.getBeanMetaData( rootBeanClass ); } return rootBeanMetaData; }

Target:
What's the reasoning for initializing it lazily instead of doing it in the constructor and making the field truly final? Btw. can `rootBeanClass()` ever be null?
Source:
private static int buildHashCode(ConstraintDescriptorImpl<?> constraintDescriptor, ConstraintLocation location, List<ValueExtractorDescriptor> valueExtractorDescriptors) { final int prime = 31; int result = 1; result = prime * result + ( constraintDescriptor != null ? constraintDescriptor.hashCode() : 0 ); result = prime * result + ( location != null ? location.hashCode() : 0 ); return result; }

Target:
Are the null checks really needed?
Source:
public static <T> ArrayList<T> newArrayList(int size) { return new ArrayList<T>( getInitialCapacityFromExpectedSize( size ) ); }

Target:
Why are you doing it for a list type?
Source:
Type getExtractedType() { return extractedType; }

Target:
Missing new line.
Source:
private ClockProvider createClockProvider(Configuration<?> config) { BootstrapConfiguration bootstrapConfiguration = config.getBootstrapConfiguration(); String clockProviderFqcn = bootstrapConfiguration.getClockProviderClassName(); if ( clockProviderFqcn == null ) { return config.getDefaultClockProvider(); } @SuppressWarnings("unchecked") Class<ClockProvider> clockProviderClass = (Class<ClockProvider>) run( LoadClass.action( clockProviderFqcn, null ) ); return createInstance( clockProviderClass ); }

Target:
Technically, wouldn't it be `Class<? extends ClockProvider>`?
Source:
public void testValidatePropertyWithNestedPathAndNullPropertyInTheWay() { Validator validator = getValidator(); X someX = new X(); Set<ConstraintViolation<X>> constraintViolationsX = validator.validateProperty( someX, "list[0].foo" ); assertNumberOfViolations( constraintViolationsX, 1 ); assertCorrectPropertyPaths( constraintViolationsX, "list[0].foo" ); }

Target:
Seems these assertions are never reached due to the (expected) exception before?
Source:
public void reportErrors(Collection<ConstraintCheckIssue> errors) { errors.forEach( this::reportError ); }

Target:
Looks like there is a Java 8 construct left.
Source:
protected boolean canCheckThisAnnotation(AnnotationMirror annotation) { return annotationClasses.contains( annotation.getAnnotationType().asElement().toString() ); }

Target:
Seems that's never overridden. Should it be private then?
Source:
protected ConstraintViolationSetAssert(Set<? extends ConstraintViolation<?>> actualViolations) { super( new ArrayList(actualViolations) ); this.actualViolations = actualViolations; }

Target:
Have you checked if IterableAssert could be sufficient as a base class? It would avoid this conversion.
Source:
protected GroupConversionDescriptorSetAssert(Set<GroupConversionDescriptor> actual) { super( new ArrayList( actual ) ); this.actual = actual; }

Target:
Same question here.
Source:
private ExecutableElement getValidationAppliesToMethod(Element annotation) { for ( Element e : annotation.getEnclosedElements() ) { ExecutableElement method = e.accept( new ElementKindVisitor6<ExecutableElement, Void>() { @Override public ExecutableElement visitExecutableAsMethod(ExecutableElement e, Void p) { if ( e.getSimpleName().contentEquals( "validationAppliesTo" ) ) { return e; } return super.visitExecutableAsMethod( e, p ); } }, null ); if ( method != null ) { return method; } } return null; }

Target:
I don't think the call to the super method is needed?
Source:
public static String join(Iterable<?> iterable, String separator) { StringBuilder sb = new StringBuilder(); boolean isFirst = true; for ( Object object : iterable ) { if ( !isFirst ) { sb.append( separator ); } else { isFirst = false; } sb.append( object ); } return sb.toString(); }

Target:
Does that handle 'null' properly?
Source:
public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) { if ( resolve( context, base, method ) ) { throw new ValidationException( "Invalid property" ); } Object returnValue = null; // due to bugs in most EL implementations when it comes to evaluating varargs we take care of the formatter call // ourselves. if ( base instanceof FormatterWrapper ) { returnValue = evaluateFormatExpression( context, base, method, paramTypes, params ); } return returnValue; }

Target:
Couldn't also other methods be invoked, e.g. `${'FooBar'.subString(3)}`? I guess it doesn't make awfully lots of sense, but I think it is legal. WDYT?
Source:
public void EdgeReached(Direction edge) { postEvent(this, "EdgeReached", edge); }

Target:
Note that one of the reasons I chose to use the `@EnumeratedBy` annotation was due to the fact that we don't know if there are extensions out there that are calling the `int` version of this method. Using the annotation allows us to keep the signature of the function the same at runtime. By outright changing this, if such an extension exists it would result in a NoSuchMethodError after this change is published. I would recommend we also have an `int` version to maintain backward compatibility.
Source:
public void updateMenuState(int numSelectedProjects, int numProjects) { boolean allowDelete = !isReadOnly && numSelectedProjects > 0; boolean allowExport = numSelectedProjects > 0; boolean allowExportAll = numProjects > 0; String exportProjectLabel = numSelectedProjects > 1 ? MESSAGES.exportSelectedProjectsMenuItem() : MESSAGES.exportProjectMenuItem(); fileDropDown.setItemHtmlById(WIDGET_NAME_EXPORTPROJECT, exportProjectLabel); fileDropDown.setItemEnabled(MESSAGES.deleteProjectMenuItem(), allowDelete); fileDropDown.setItemEnabledById(WIDGET_NAME_EXPORTPROJECT, allowExport); fileDropDown.setItemEnabled(MESSAGES.exportAllProjectsMenuItem(), allowExportAll); }

Target:
It'd be nice if we change the message so that it takes the numeric argument so the string is something like "Export N selected projects"
Source:
public final boolean IsConnected() { if (sdkLevel >= SdkLevel.LEVEL_ICE_CREAM_SANDWICH) { return (connectedBluetoothSocket != null && BluetoothReflection.isBluetoothSocketConnected(connectedBluetoothSocket)); } else return (connectedBluetoothSocket != null); }

Target:
`else` case should still have curly braces even for a single statement ([Google Java Style Guide](https://google.github.io/styleguide/javaguide.html#s4.1.1-braces-always-used)).
Source:
public int getLeftX() { try { return (int) Math.round(Double.parseDouble(getPropertyValue(PROPERTY_NAME_X))); } catch (NumberFormatException e) { // Ignore this. If we throw an exception here, the project is unrecoverable. return 0; } }

Target:
Shouldn't this return `x` rather than re-parsing the property?
Source:
public int getTopY() { try { return (int) Math.round(Double.parseDouble(getPropertyValue(PROPERTY_NAME_Y))); } catch (NumberFormatException e) { // Ignore this. If we throw an exception here, the project is unrecoverable. return 0; } }

Target:
Return `y` instead of re-parsing?
Source:
public void OriginAtCenter(boolean b) { originAtCenter = b; }

Target:
I'm thinking that we should make this `protected` so that it can't be inadvertently called unless the subclass explicitly makes it `public` and provides the right Simple annotations.
Source:
public MockBarChartDataModel(MockBarChartView view) { super(view.getChartWidget().getData()); // Set local view variable (needed to invoke the updateLabels method) this.view = view; // Create the Data Series object dataSeries = new BarDataset(); // Set the default style properties for the Data Series setDefaultStylingProperties(); // Adds the Data Series to the Chart. addDataSeriesToChart(); }

Target:
Something to think about: if all of the DataModel types have a specific view type, then you could add an additional generic parameter to MockChartDataModel for the view type in addition to the dataset. This would allow you to move the view field up to the superclass.
Source:
public void addDataFile(MockDataFile dataFileSource) { List<String> columnNames = dataFileSource.getColumnNames(); for (String column : columnNames) { // Create a new MockChartData2D component and attach it to the Chart // TODO: More data component support MockChartData2D data = new MockChartData2D(editor); addComponent(data); data.addToChart(MockChart.this); // Change the properties of the instantiated data component data.changeProperty("DataFileYColumn", column); data.changeProperty("Label", column); data.changeProperty("Source", dataFileSource.getName()); } }

Target:
Is qualifying `this` here necessary? The context looks to be `MockChart` already.
Source:
public List<List<String>> getColumns(List<String> columns) { ArrayList<List<String>> dataColumns = new ArrayList<List<String>>(); for (String column : columns) { // Get the index of the column and get the column itself int index = columnNames.indexOf(column); List<String> dataColumn = getColumn(index); // Add the column to the result dataColumns.add(dataColumn); } return dataColumns; }

Target:
Local variable could be declared List instead of ArrayList. Is this worth caching?
Source:
public void onColumnsChange(MockDataFile dataFile) { // Edge case: Event originates from the wrong MockDataFile source if (!this.dataFile.equals(dataFile)) { return; } // Update the column entries updateColumns(); }

Target:
It seems like `==` would be sufficient and faster than `.equals()` here since we'd be testing identity of the component rather than equality?
Source:
public void removeDataObserver(ChartDataBase dataComponent) { dataSourceObservers.remove(dataComponent); // No more Data Source observers exist; // Shut down polling service and null it // (the reason for nulling is so that a new // service could be created upon adding a new // observer) if (dataSourceObservers.isEmpty()) { dataPollService.shutdown(); dataPollService = null; } }

Target:
Have add and remove synchronized on dataSourceObservers just on the off chance an extension tries to do something on a separate thread introducing a race condition.
Source:
public void Namespace(String namespace) { this.namespace = namespace; sharedPreferences = context.getSharedPreferences(namespace, Context.MODE_PRIVATE); // SharedPreferences listener currently exists; Unregister it if (sharedPreferenceChangeListener != null) { sharedPreferences.unregisterOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); } // Create a new SharedPreferences change listener sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // Upon value change, notify the observers with the key and the value notifyDataObservers(key, GetValue(key, null)); } }; // Register the SharedPreferences change listener sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener); }

Target:
You will need to unregister before line 94, otherwise you're calling unregister on a different sharedPreferences object than the register call was made on.
Source:
public List getDataValue(String key) { // Get the value from the TinyDB data with the specified key Object value = GetValue(key, new ArrayList()); // Check if value is of type List, and return it if that is the case. if (value instanceof List) { return (List)value; } // Default option (could not parse data): return empty ArrayList return new ArrayList(); }

Target:
Consider switching this to `List<Object>` instead of the unspecified `List` type.
Source:
public synchronized T getDataset() { return dataset; }

Target:
It's not clear that dataset is updated other than being set in the constructors of subclasses. I don't see what synchronizing this method actually gains for the performance loss.
Source:
private YailList getYailListPropertyHelper(Callable<YailList> propertyCallable) { // Since reading might be in progress, the task of // getting a DataFile property should be queued so that the // thread is blocked until the reading is finished. try { return threadRunner .submit(propertyCallable) // Run the callable async (and queued) .get(); // Get the property (blocks thread until previous threads finish) } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return new YailList(); // Return empty list (default option) }

Target:
This could potentially block the UI thread for long enough time that an ANR appears, depending on the size of the file being read.
Source:
public void changePreviewSize(int width, int height, int idx) { // It will definitely be modified in the future to add more options. PORTRAIT_WIDTH = width; PORTRAIT_HEIGHT = height; LANDSCAPE_WIDTH = height; LANDSCAPE_HEIGHT = width; idxPhoneSize = idx; setPhoneStyle(); if (landscape) resizePanel(LANDSCAPE_WIDTH, LANDSCAPE_HEIGHT); else resizePanel(width, height); }

Target:
Code style: Curly braces after if and around else statements.
Source:
private void updateLayoutType(String value) { layout = value; YoungAndroidListViewAddDataPropertyEditor editor = (YoungAndroidListViewAddDataPropertyEditor) properties.getProperty(PROPERTY_NAME_LISTVIEW_ADD_DATA).getEditor(); editor.setLayout(layout); if(!currentItems.isEmpty()) { createLabelItem(currentItems); } }

Target:
Code style: space after `if`
Source:
public void TextSize(int fontSize) { if(fontSize>1000) textSize = 999; else textSize = fontSize; setAdapterData(); }

Target:
See earlier notes about code style with if statements.
Source:
public void resultReturned(int requestCode, int resultCode, Intent data) { if (requestCode == this.requestCode && resultCode == Activity.RESULT_OK) { if (data.hasExtra(RecognizerIntent.EXTRA_RESULTS)) { ArrayList<String> results = data.getExtras().getStringArrayList(RecognizerIntent.EXTRA_RESULTS); result = results.get(0); speechListener.onResult(result); } else { result = ""; } } }

Target:
In the current version of the code, the result is reported regardless of which branch is taken here. I recommend you keep the semantics consistent and move the call to `onResult` here rather than in the if branch.
Source:
public void onPartialResult(String text) { result = text; AfterGettingText(result); }

Target:
While I thought this was pretty cool to see having my label updated as I spoke, I'm a bit concerned that apps might not be programmed correctly for the logic of `AfterGettingText` being called multiple times per call to `GetText`. I conferred with the team here and the consensus is that we should continue to use `AfterGettingText`, but add a new parameter called `partial` that should be `true` if the call is in response to `onPartialResult` and `false` if it is called from `onResult`. This would allow developers to determine whether the app user has finished speaking.
Source:
public void onResult(String text) { result = text; AfterGettingText(result, false); onDelete(); }

Target:
Is it necessary to do this here? The semantics of onDelete are supposed to be such that it's only called when the component is being removed from the screen in the companion app.
Source:
public DialogBox createNoProjectsDialog(boolean showDialog) { final NoProjectDialogBox dialogBox = new NoProjectDialogBox(); dialogBox.show(); return dialogBox; }

Target:
At the moment this results in the dialog showing unconditionally. You should wrap this in a check against `showDialog` like the old code.
Source:
private Integer generateHashCode(AndroidViewComponent component, PercentStorageRecord.Dim dim) { if (dim == PercentStorageRecord.Dim.HEIGHT) { return (component.hashCode() + dim.hashCode()) * 2 + 1; } else { return (component.hashCode() + dim.hashCode()) * 2; } }

Target:
You don't need to add `dim.hashCode()` here (or the next line). By virtue of adding 0 or 1 we are encoding the dimension information perfectly.
Source:
public void unregisterPercentLength(AndroidViewComponent component, PercentStorageRecord.Dim dim) { // iterate map, remove all entry match this for (Integer key : dimChanges.keySet()) { dimChanges.remove(generateHashCode(component, dim)); } }

Target:
You don't need the for loop here any more. The call to `remove` on line 716 either will remove the entry if it exists or do nothing if it doesn't exist. Because it changes the map, it will result in a `ConcurrentModificationException` as written since you're modifying the loop while iterating over it.
Source:
private ServerPing getPingInfo( String motd, int protocol ) { new ServerPing( new ServerPing.Protocol( bungee.getName() + " " + bungee.getGameVersion(), protocol ), new ServerPing.Players( listener.getMaxPlayers(), bungee.getOnlineCount(), null ), motd, BungeeCord.getInstance().config.getFaviconObject() ); }

Target:
You're kind of missing a return here...................
Source:
public ComponentBuilder append(BaseComponent component, FormatRetention retention) { BaseComponent previous = parts.get( parts.size() - 1 ); if ( previous == null ) { previous = dummy; dummy = null; } if ( previous != null ) { component.copyFormatting( previous, retention, false ); } parts.add( component ); resetCursor(); return this; }

Target:
Can throw exception when created with no args constructor
Source:
Configuration(Configuration defaults) { this(); setDefaults(defaults); }

Target:
Why remove public?
Source:
public void handle(LegacyHandshake legacyHandshake) throws Exception { this.legacy = true; ch.close( bungee.getTranslation( "outdated_client", BungeeCord.getInstance().getGameVersion() ) ); }

Target:
Use bungee field
Source:
public void copyFormatting(BaseComponent component) { copyFormatting( component, FormatRetention.ALL, false ); }

Target:
I think old behaviour was to replace?
Source:
public void setTabHeader(BaseComponent header, BaseComponent footer) { header = ChatComponentTransformer.getInstance().transform( getServerSentScoreboard(), this, header )[0]; footer = ChatComponentTransformer.getInstance().transform( getServerSentScoreboard(), this, footer )[0]; unsafe().sendPacket( new PlayerListHeaderFooter( ComponentSerializer.toString( header ), ComponentSerializer.toString( footer ) ) ); }

Target:
Same thing with mutation
Source:
public ComponentBuilder append(String text, FormatRetention retention) { parts.add( current ); TextComponent component = new TextComponent( current ); component.setText( text ); current = component; retain( retention ); return this; }

Target:
Fair enough, my bad
Source:
public boolean hasChatColors() { return ( settings != null ) ? settings.isChatColours() : true; }

Target:
`return settings == null || settings.isChatColours()`?
Source:
public TooltipImpl(Element element, TooltipOptions options) { this.$element = $(element); this.options = getOptions(options); //Is GWT optimization works here ? if (options.getResources() != null){ this.style = options.getResources().css(); } else{ this.style = getDefaultResources().css(); } init(); }

Target:
That's a good question that I don't know the answer, this pattern is commonly used by gwt widgets. You would maybe remove the If if you have more than one ctor and I think that in that case, it would prune what isn't used.
Source:
public Integer convert(String s) { try{ return Integer.parseInt(s); }catch(NumberFormatException e){ GWT.log("Impossible to convert the string'"+s+"' to an integer."); return null; } }

Target:
missing spaces in format
Source:
public static XmlHighlighting highlight(SensorContext context, XmlFile xmlFile) { XmlHighlighting highlighting = new XmlHighlighting(xmlFile); highlighting.highlight(context); return highlighting; }

Target:
Why returning XmlHighlighting instead of void? I haven't seen it used anywhere
Source:
private static OutermostChildElements getOutermostChildElements(List<Node> children) { Element firstChildElement = null; Element lastChildElement = null; for (Node child : children) { if (child.getNodeType() == Node.ELEMENT_NODE) { if (firstChildElement == null) { firstChildElement = (Element) child; } lastChildElement = (Element) child; } } return new OutermostChildElements(firstChildElement, lastChildElement); }

Target:
It seems to me that the only cases where first and last will be null is when there is no children being ELEMENT. In such case, we are not reporting anything through `checkChildrenLine`. Instead of having `@Nullable` first/last I would simply not create the object if both are null, and return null.
Source:
private static void processException(Exception e, SensorContext context, InputFile inputFile) { reportAnalysisError(e, context, inputFile); throw new IllegalStateException("Unable to analyse file " + inputFile.uri(), e); }

Target:
Ok as you need to rework the PR, i would go for a log instead of throwing the ISE here.
Source:
private void saveSyntaxHighlighting(SensorContext context, List<HighlightingData> highlightingDataList, InputFile inputFile) { NewHighlighting highlighting = context.newHighlighting().onFile(inputFile); for (HighlightingData highlightingData : highlightingDataList) { highlighting.highlight(highlightingData.startOffset(), highlightingData.endOffset(), highlightingData.highlightCode()); } highlighting.save(); }

Target:
![MINOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-minor.png 'Severity: MINOR') Remove this use of "highlight"; it is deprecated. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3ACallToDeprecatedMethod)
Source:
private static boolean isFileBeginning(int line, int column, boolean hasBOM) { if (line == 1) { return column > (hasBOM ? 1 : 0); } return true; }

Target:
@pynicolas Are you sure about this method name? As I understand, it does the opposite
Source:
public List getExtensions() { return ImmutableList.of( PropertyDefinition.builder(XmlPlugin.FILE_SUFFIXES_KEY) .name("File suffixes") .description("Comma-separated list of suffixes for files to analyze.") .defaultValue(".xml") .category("XML") .onQualifiers(Qualifiers.PROJECT) .build(), Xml.class, XmlRulesDefinition.class, XmlSonarWayProfile.class, // Sensors XmlSensor.class, LineCounter.class, XmlCodeColorizerFormat.class); }

Target:
@lindamartin I don't get how it works if LineCounter doesn't extend any interface (e.g. sensor)
Source:
protected TraceeMessagePropertiesConverter(TraceeBackend backend, HttpHeaderTransport transportSerialization, String profile) { this.backend = backend; this.transportSerialization = transportSerialization; this.profile = profile; }

Target:
This constructor should be moved to package-scope. Then you're able to insert an mocked TraceeBackend in test-cases -- you could spy on backend-calls and use the `SimpleTraceeBackend.createNonLoggingAllPermittingBackend()`instead of the ThreadLocalBackend.
Source:
public void addParentLevel(ParentKey parent) { this.parentLevels.add(parent); parent.getKey().childLevels.add(this); }

Target:
Speaking of access modifiers, this could probably be package private, as this should only be called when constructing the key graph.
Source:
private Maybe<User> getUserByEmail(String userEmail) throws NoResultException { User user; try { user = entityManagerProvider.get().createQuery( "SELECT u FROM User u " + "WHERE u.email = :email", User.class) .setParameter("email", userEmail) .getSingleResult(); return Maybe.of(user); } catch (NoResultException e) { return Maybe.notFound(); } }

Target:
Use java.util.Optional here instead of Maybe. We use the Maybe type for results which could have *one* of the following states: visible, forbidden, non-existant,or deleted. Here the user is either present or not.
Source:
public Quantity(double value) { this(value, UNKNOWN_UNITS); }

Target:
Why is this constructor deprecated?
Source:
protected void onLoad() { super.onLoad(); Iterator<MatrixChildParametersAction> i = this.getActions(MatrixChildParametersAction.class).iterator(); while(i.hasNext()) { MatrixChildParametersAction a = i.next(); a.onLoad(this); } }

Target:
Why using iterator and not the for each loop?
Source:
public MatrixBuild getMatrixBuild() { if( parent == null ) { try { parent = (MatrixBuild)Run.fromExternalizableId(parentId); } catch (Exception e) { parent = null; } } return parent; }

Target:
Please, respect surrounding code style (`() {`).
Source:
public void delete() throws IOException { super.delete(); for(MatrixRun run : getExactRuns()) { if (run.getWhyKeepLog() != null) continue; run.delete(); } }

Target:
I would expect that `MatrixBuild.getWhyKeepLog` would return non-null in this case, so that the whole thing is kept as a unit.
Source:
public Iterable<String> getKeysToRemove() { return KEYS_TO_REMOVE; }

Target:
Make this protected (and in the `@Overriden`)
Source:
public Maybe<Channel> fromKey(String key) { for (Channel channel : channels.get()) { if (Objects.nonNull(channel.getKey()) && channel.getKey().equals(key)) { return Maybe.just(channel); } } return Maybe.nothing(); }

Target:
I'd just do `if (Objects.equals(channel.get(), key)) {` then it does all the null checking for you. `Objects.nonNull` is only really useful where a function is required (e.g. stream.filter) as all it does is add an extra method call that the jit then has to decide whether to inline or not (as compared to `obj != null').
Source:
private void decodeDistribution(DBObject dbObject, Described entity) { entity.setDistributions(TranslatorUtils.toIterable(dbObject, DISTRIBUTION_KEY, new Function<DBObject, Distribution>() { @Override public Distribution apply(DBObject input) { return distributionTranslator.fromDBObject(input, new Distribution()); } }).or(ImmutableSet.<Distribution>of())); }

Target:
lambda
Source:
public QueueingOrganisationStore(MessageSender<EntityUpdatedMessage> sender, OrganisationStore delegate) { this.delegate = checkNotNull(delegate); this.sender = checkNotNull(sender); clock = new SystemClock(); entityIdCodec = SubstitutionTableNumberCodec.lowerCaseOnly(); }

Target:
Inconsistent use of `this`.
Source:
protected String generateApiKey() { return new UUIDGenerator().generate(); }

Target:
Can this be private?
Source:
private MessageBuffer getNextBuffer() throws IOException { MessageBuffer next = in.next(); if (next == null) { throw new MessageInsufficientBufferException(); } totalReadBytes += buffer.size(); return next; }

Target:
Check if `buffer` is not null.
Source:
public Value getOrNilValue(int index) { if (array.length < index && index >= 0) { return array[index]; } return ImmutableNilValueImpl.get(); }

Target:
This condition seems to be backwards. I think it should be `index < array.length`