auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<Integer> getTransferAbortedOkStatusCodes(final FileSystemOptions opts) { // See VFS-674, its accompanying PR and https://github.com/apache/commons-vfs/pull/51 as to why 426 and 550 are here @SuppressWarnings("unchecked") List<Integer> statusCodes = (List<Integer>) getParam(opts, TRANSFER_ABORTED_OK_STATUS_CODES); return statusCodes != null ? statusCodes : Arrays.asList(FTPReply.TRANSFER_ABORTED, FTPReply.FILE_UNAVAILABLE); }

Target:
@boris-petrov, One more detail. I would also create a protected method called ```getDefault...``` that returns the ```Arrays.asList(FTPReply.TRANSFER_ABORTED, FTPReply.FILE_UNAVAILABLE)``` to make it clear what the defaults are with the possibility of easy override though subclassing. Gary
Source:
public int compareTo(InformationLoss<?> other) { if (!other.getClass().equals(this.getClass())) { throw new IllegalArgumentException("Incompatible class (" + other.getClass().getSimpleName() + ")"); } BigFraction otherValue = ((ILScore)other).getValue(); return value.compareTo(otherValue) * -1; }

Target:
Is this really needed? Maybe this should be removed for efficiency reasons (but I don't know how often this method is actually used...)
Source:
protected ILScore convert(InformationLoss<?> other) { if (other == null) return null; if (!other.getClass().equals(this.getClass())) { throw new IllegalArgumentException("Incompatible class (" + other.getClass().getSimpleName() + ")"); } else { return (ILScore)other; } }

Target:
Is this really needed? Maybe this should be removed for efficiency reasons (but I don't know how often this method is actually used...)
Source:
public ElementData render() { ElementData result = new ElementData("Differential privacy"); result.addProperty("Epsilon", epsilon); result.addProperty("Delta", delta); result.addProperty("Uniqueness threshold (k)", getK()); result.addProperty("Sampling probability (beta)", getBeta()); return result; }

Target:
Catch exception
Source:
public DataDependentEDDifferentialPrivacy(double epsilonAnon, double epsilonSearch, double delta, int steps) { super(delta); this.epsilonAnon = epsilonAnon; this.epsilonSearch = epsilonSearch; this.beta = calculateBeta(epsilonAnon); this.k = calculateK(getDelta(), epsilonAnon, this.beta); this.steps = steps; }

Target:
this(epsilonAnon, epsilonSearch, delta, steps, false); ???
Source:
public Image getImage(AttributeType type) { if (type == AttributeType.IDENTIFYING_ATTRIBUTE) { return getManagedImage("bullet_red.png"); } if (type == AttributeType.INSENSITIVE_ATTRIBUTE) { return getManagedImage("bullet_green.png"); } if (type == AttributeType.SENSITIVE_ATTRIBUTE) { return getManagedImage("bullet_purple.png"); } if (type == AttributeType.QUASI_IDENTIFYING_ATTRIBUTE) { return getManagedImage("bullet_yellow.png"); } throw new IllegalArgumentException("Unknown attribute type '" + type +"'"); }

Target:
Please use a switch statement here
Source:
public int hashCode() { return Objects.hashCode( referenceExpression ); }

Target:
Revert this. `referenceExpression` is non-null AFAICS
Source:
public MappingModelExpressable getExpressionType() { SqlSelection first = selectClause.getSqlSelections().get(0); return ( (SqlSelectionImpl) first ).getWrappedSqlExpression().getExpressionType(); }

Target:
Probably the second makes more sense
Source:
private static void assertRootCause(Exception exception, Class<?> type, String message) { Throwable root = exception; while ( root.getCause() != null ) { root = root.getCause(); } assertTyping( type, root ); assertEquals( root.getMessage(), message ); }

Target:
should we swap method parametrr orders above?
Source:
public static <T> T coalesce(T... values) { if ( values == null ) { return null; } for ( T value : values ) { if ( value != null ) { if ( String.class.isInstance( value ) ) { if ( StringHelper.isNotEmpty( (String) value ) ) { return value; } } else { return value; } } } return null; }

Target:
Minor nitpicking, as I've recently being removing the use of "unnecessary helpers": when you know already that "value" is not null, there is no reason to use the `StringHelper`. Just go with `((String) value).isEmpty()` ?
Source:
private String[] getSubclassNameClosureBySubclassTable(int subclassTableNumber) { final int index = subclassTableNumber - getTableSpan(); if ( index >= subclassNamesBySubclassTable.length ) { throw new IllegalArgumentException( "Given subclass table number is outside expected range [" + subclassNamesBySubclassTable.length + "] as defined by subclassTableNameClosure/subclassClosure" ); } return subclassNamesBySubclassTable[index]; }

Target:
The upper limit should be corrected in the error message to be ```subclassNamesBySubclassTable - 1```.
Source:
protected String[] getPropertyAliases(Loadable persister, int j) { String[] propertyColumnNames = persister.getPropertyColumnNames(j); if (propertyColumnNames!=null && propertyColumnNames.length==1 && propertyColumnNames[0]==null) { return new String[]{ persister.getPropertyNames()[j] }; } return propertyColumnNames; }

Target:
It would be great to use space chars consistently with existing coding format as ` if ( propertyColumnNames != null && propertyColumnNames.length == 1 && propertyColumnNames[0] == null ) `
Source:
public ParametersBuilder addPersistedWithoutHibernate(int yearWhenPersistedWithoutHibernate, int monthWhenPersistedWithoutHibernate, int dayWhenPersistedWithoutHibernate, int hour, int minute, int second, int nanosecond, ZoneId defaultTimeZone) { if ( isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, hour, minute, second, nanosecond, yearWhenPersistedWithoutHibernate, monthWhenPersistedWithoutHibernate, dayWhenPersistedWithoutHibernate ); }

Target:
Should ```if``` condition be: ```if ( !isNanosecondPrecisionSupported() )``` ?
Source:
public ParametersBuilder add(int year, int month, int day, int hour, int minute, int second, int nanosecond, String offset, ZoneId defaultTimeZone) { if ( isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, year, month, day, hour, minute, second, nanosecond, offset ); }

Target:
Should ```if``` condition be: ```if ( !isNanosecondPrecisionSupported() )``` ?
Source:
public ParametersBuilder addPersistedWithoutHibernate(int yearWhenPersistedWithoutHibernate, int monthWhenPersistedWithoutHibernate, int dayWhenPersistedWithoutHibernate, int hour, int minute, int second, int nanosecond, String offset, ZoneId defaultTimeZone) { if ( isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, hour, minute, second, nanosecond, offset, yearWhenPersistedWithoutHibernate, monthWhenPersistedWithoutHibernate, dayWhenPersistedWithoutHibernate ); }

Target:
Should ```if``` condition be: ```if ( !isNanosecondPrecisionSupported() )``` ?
Source:
public ParametersBuilder add(int year, int month, int day, int hour, int minute, int second, int nanosecond, String zone, ZoneId defaultTimeZone) { if ( isNanosecondPrecisionSupported() ) { nanosecond = 0; } return add( defaultTimeZone, year, month, day, hour, minute, second, nanosecond, zone ); }

Target:
Should ```if``` condition be: ```if ( !isNanosecondPrecisionSupported() )``` ?
Source:
void compiled(long microseconds) { log.tracef( "QueryStatistics - query compiled : %s", query ); planCacheMissCount.increment(); planCompilationTotalMicroseconds.addAndGet( microseconds ); }

Target:
We are in the process of removing the other logger calls so let's not add more.
Source:
void incrementPlanCacheHitCount() { log.tracef( "QueryStatistics - plan cache hit : %s", query ); planCacheHitCount.increment(); }

Target:
We are in the process of removing the other logger calls so let's not add more.
Source:
public void setUp() throws Exception { doInHibernate( this::sessionFactory, s -> { Post post = new Post(); post.setDetails(new PostDetails()); post.getDetails().setCreatedBy("ME"); post.getDetails().setCreatedOn(new Date()); post.setTitle("title"); s.persist(post); s.flush(); s.clear(); } ); }

Target:
I don't think you need to flush() and clear(). Considering this init is specific to the test method, I would have moved it to the test method and would remove this setUp() altogether.
Source:
public String getTableName() { Queryable queryable = getQueryable(); return ( queryable != null ) ? queryable.getTableName() : "{none}"; }

Target:
I don't think this is needed?
Source:
public final Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner, Map copyCache) { if ( original == null && target == null ) { return null; } if ( original == LazyPropertyInitializer.UNFETCHED_PROPERTY ) { return target; } if ( target == LazyPropertyInitializer.UNFETCHED_PROPERTY ) { return getReplacement( (T) original, null, session ); } return getReplacement( (T) original, (T) target, session ); }

Target:
You might want to have a look at the other `replace()` method below, which also calls `getReplacement`, but without executing this code. Probably a bug? It might be a dumb suggestion, but couldn't we just move all this code to the caller(s) of `replace()`? Then any type would benefit from this code, not just types extending `AbstractStandardBasicType`. From what I can see it's rather simple, and it would remove the need for type implementations to refer to `LazyPropertyInitializer`, which is an SPI type...
Source:
public void release(Statement statement) { log.tracev( "Releasing statement [{0}]", statement ); final Set<ResultSet> resultSets = xref.get( statement ); if ( resultSets != null ) { closeAll( resultSets ); xref.remove( statement ); } else if ( log.isDebugEnabled() ) { // Keep this at DEBUG level, rather than warn. Numerous connection pool implementations can return a // proxy/wrapper around the JDBC Statement, causing excessive logging here. See HHH-8210. log.unregisteredStatement(); } close( statement ); if ( lastQuery == statement ) { lastQuery = null; } }

Target:
Why not just `final Set<ResultSet> resultSets = xref.remove( statement );` here, and no `remove()` call below? Then you would only need to access the map once. That might change the behavior slightly if `closeAll` throws an exception or somehow uses xref, though. Maybe it's not such a good idea.
Source:
protected void createLoaders() { final Map loaders = getLoaders(); loaders.put( LockMode.NONE, createEntityLoader( LockMode.NONE ) ); noneLockLoader = createEntityLoader( LockMode.NONE ); readLockLoader = createEntityLoader( LockMode.READ ); // The loaders for the other lock modes are loaded lazily. loaders.put( "merge", new CascadeEntityLoader( this, CascadingActions.MERGE, getFactory() ) ); loaders.put( "refresh", new CascadeEntityLoader( this, CascadingActions.REFRESH, getFactory() ) ); }

Target:
This is the second instance of an entity loader for LockMode.NONE. Please move this line and maybe the next line before the line 4118 and reuse the instance.
Source:
private UniqueEntityLoader getLoaderByLockMode(LockMode lockMode) { if ( LockMode.NONE.equals( lockMode ) ) { return noneLockLoader; } else if ( LockMode.READ.equals( lockMode ) ) { return readLockLoader; } return loaders.computeIfAbsent( lockMode, this::createLazyLoadedEntityLoader ); }

Target:
It is common practice in Hibernate to use '==' to compare enum values for equality. You shall follow this practice here too.
Source:
public static String toArrayTypeString(ArrayType type, Context context) { TypeMirror componentMirror = type.getComponentType(); if ( !componentMirror.getAnnotationMirrors().isEmpty() ) { TypeMirror component = type.getComponentType().accept( new SimpleTypeVisitor6<TypeMirror, Void>() { @Override protected TypeMirror defaultAction(TypeMirror e, Void aVoid) { return e; } }, null ); return extractClosestRealTypeAsString( component, context ) + "[]"; } return toTypeString( type ); }

Target:
So in this case, you're not returning an array type?
Source:
public void begin() { if ( !session.isOpen() ) { throw new IllegalStateException( "Cannot begin Transaction on closed Session/EntityManager" ); } if ( transactionDriverControl == null ) { transactionDriverControl = transactionCoordinator.getTransactionDriverControl(); } // per-JPA if ( isActive() ) { throw new IllegalStateException( "Transaction already active" ); } if ( LOG.isDebugEnabled() ) { LOG.debug( "begin" ); } this.transactionDriverControl.begin(); }

Target:
Why are we changing these? Generally this is done to avoid expensive resolution of the message to log. Here, that is not the case. In fact, doesn't this perform worse? IIUC this simply forces 2 "is debug enabled" checks
Source:
public String getMessage() { return message; }

Target:
Can you make all of the accessors `final`?
Source:
public final String getUsername() { return username; }

Target:
Oops, I meant only the accessors in the abstract chat message class to indicate that they should not be overridden. Could you undo all of these except for the ones in the abstract class?
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RequestParam that = (RequestParam) o; return name.equals(that.name); }

Target:
this may be confusing to people. why are params with the same name considered "equal"? what about the value? if some part of the code wants to treat these Params as "equal" as long as they have equal names, it is better to keep this comparison logic close to that area, maybe with a local Comparator class or something, but not inside the data object itself. this would allow reusability for this class in the future.
Source:
public boolean hasSomeResults() { return !results.isEmpty(); }

Target:
I assume the list is never null. right?
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CustomFieldDefinition that = (CustomFieldDefinition) o; if (id != that.id) { return false; } return true; }

Target:
This is an identity comparison. Equal (in sense of .equals()) Integers may be different according to == (and !=). Please, use .equals and provide proper null-handling code.
Source:
public CustomField getCustomFieldById(int customFieldId) { if(customFields == null) return null; for (CustomField customField : customFields) { if (customFieldId == customField.getId()) { return customField; } } return null; }

Target:
no need in null check here, although it's a matter of personal preference
Source:
public void run(final Server server, final CommandSender sender, final String commandLabel, final String[] args) throws Exception { if (args.length > 1) { User target = getPlayer(server, args, 0, true); sender.sendMessage("§7SocialSpy " + (target.toggleSocialSpy() ? _("enabled") : _("disabled"))); } else { throw new NotEnoughArgumentsException(); } }

Target:
This is wrong.
Source:
private static int calculateBinaryShiftCost(State state) { if (state.binaryShiftByteCount > 62) { return 21; // B/S with extended length } else if (state.binaryShiftByteCount > 31) { return 20; // two B/S } else if (state.binaryShiftByteCount > 0) { return 10; // one B/S } else { return 0; } }

Target:
Nit: use 2-space indent here. Also I think you can dispense with the "else" statements and just write: ``` if (...) { return ...; } if (...) { return ...; } ```
Source:
public void testEncodeIllegalCharacters() throws WriterException { int illegalArgument = 0; try { BitMatrix result = new EAN8Writer().encode("96385abc", BarcodeFormat.EAN_8, 0, 0); } catch (IllegalArgumentException e) { illegalArgument = 1; } assertEquals(illegalArgument, 1); }

Target:
You should be able to write `@Test(expected = WriterException.class)` and then the body of the test is just the line that causes the exception.
Source:
protected static int appendPattern(boolean[] target, int pos, int[] pattern, boolean startColor) { int numAdded = 9; for (int bit : pattern) { target[pos++] = bit == 0 ? false : true; } return numAdded; }

Target:
just `= bit != 0`?
Source:
private static int computeChecksumIndex(String contents, int maxWeight) { int weight = 1; int total = 0; for (int i = contents.length()-1; i >= 0; i--) { int indexInString = Code93Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); total += indexInString * weight; if (++weight > maxWeight) { weight = 1; } } int checksum = total % 47; return checksum; }

Target:
Last trivial thing, just return this value directly.
Source:
protected static int appendPattern(boolean[] target, int pos, int[] pattern, boolean startColor) { int numAdded = 9; for (int bit : pattern) { target[pos++] = bit != 0; } return numAdded; }

Target:
This value isn't changed; is it always 9? return 9 directly then.
Source:
public void unset(int x, int y) { int offset = y * rowSize + (x / 32); int intMask = (1 << (x & 0x1f)); if ((bits[offset] & intMask) > 0) { bits[offset] ^= intMask; } }

Target:
I think this method can work just like `set()`. You complement the `intMask` with `~` and then `&=` it.
Source:
protected void setLoadedHostsEntries(Collection<HostEntryPair> keys) { keysSupplier = () -> keys; }

Target:
Update of keysSupplier field is not mutually exclusive...
Source:
public AbstractSecurityKeySignature(String keyType) { this.keyType = keyType; }

Target:
Please make this `protected`
Source:
default T verify(Duration timeout) throws IOException { return verify(timeout.toMillis()); }

Target:
In other locations the code interprets `null` as *forever* - let's maintain this convention (or fix the other code - `ClientChannel#waitFor`) ```java default T verify(Duration timeout) throws IOException { return (duration == null) ? verify() : verify(timeout.toMillis()); } ```
Source:
default boolean await(Duration timeout) throws IOException { return await(timeout.toMillis()); }

Target:
In other locations the code interprets `null` as *forever* - let's maintain this convention (or fix the other code - `ClientChannel#waitFor`)
Source:
private void signalRemoving(Path p, SftpEventListener listener, ServerSession session, boolean isDirectory) throws IOException { if (isDirectory) { listener.removingDirectory(session, p); } else { listener.removingFile(session, p); } }

Target:
protected please - we always try to allow users to override any behavior they like
Source:
private void signalRemoved(Path p, SftpEventListener listener, ServerSession session, boolean isDirectory, Exception e) throws IOException { if (isDirectory) { listener.removedDirectory(session, p, e); } else { listener.removedFile(session, p, e); } }

Target:
protected please - we always try to allow users to override any behavior they like
Source:
private synchronized void asyncAuth(int cmd, Buffer buffer, boolean authed) { try { if (authed) { handleAuthenticationSuccess(cmd, buffer); } else { handleAuthenticationFailure(cmd, buffer); } } catch (Exception e) { log.warn("Error performing async authentication: {}", e.getMessage(), e); } }

Target:
Let's make it _protected_ to allow users to override if they want
Source:
public static String getFileOwner(Path path, LinkOption... options) throws IOException { String owner = null; try { UserPrincipal principal = Files.getOwner(path, options); if (principal != null) { owner = principal.getName(); } } catch (UnsupportedOperationException e) { // ignore } return owner; }

Target:
Simpler code: ``` java try { UserPrincipal principal = Files.getOwner(path, options} return (principal != null) ? principal.getName() : null; } catch (UnsupportedOperationException e) { return null; // ignore } ```
Source:
public Histogram getTemperatures() { Metadata metadata = new Metadata("temperatures", MetricType.HISTOGRAM, "degrees F"); metadata.setDescription("A histogram of recent New York temperatures."); final int[] RECENT_NEW_YORK_TEMPS = { 46, 45, 50, 46, 45, 27, 30, 48, 55, 54, 45, 41, 45, 43, 46 }; histogram = registry.histogram(metadata); for(int temp : RECENT_NEW_YORK_TEMPS) { histogram.update(temp); } return histogram; }

Target:
RECENT_NEW_YORK_TEMPS seems to be a convention of a constant variable. I suggest you move it out of the method and add private along with static to match the java convention.
Source:
public JsonWebToken currentPrincipal() { Objects.requireNonNull(httpServletRequest, "HTTP Servlet Request is required to produce a JSonWebToken principal."); // not very beatiful, but avoids having the MPJWTFilter setting the request or the principal in a thread local // CDI integration already has one - dunno which approach is the best for now final Object tokenAttribute = httpServletRequest.getAttribute(JsonWebToken.class.getName()); if (tokenAttribute != null && Function.class.isInstance(tokenAttribute)) { return (JsonWebToken) Function.class.cast(tokenAttribute).apply(httpServletRequest); } return null; }

Target:
not null check not needed before class.isInstance() call. Method returns false when passing a null argument
Source:
final public boolean equals(Object obj) { if (obj == this) { return true; } else if (obj instanceof ModuleAdapter<?>) { ModuleAdapter<?> that = (ModuleAdapter<?>) obj; return this.moduleClass.equals(that.moduleClass); } else { return false; } }

Target:
JLS order is `public final boolean` and for consistency with other methods
Source:
@Provides @Singleton ManagedServer providesServer(WebConfiguration webConfiguration) { return new WebServer(webConfiguration); }

Target:
nit: wrap +4
Source:
public ContentValuesAssert contains(ContentValuesEntry... entries) { isNotEmptyOrNull(entries); Set<ContentValuesEntry> notFound = new LinkedHashSet<ContentValuesEntry>(); for (ContentValuesEntry entry : entries) { if (!containsEntry(actual, entry)) { notFound.add(entry); } } if (notFound.isEmpty()) { return this; } throw Failures.instance().failure(new WritableAssertionInfo(), shouldContain(actual, entries, notFound)); }

Target:
Logic should be reversed ``` java if (!nf.isEmpty()) { throw; } return this; ```
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ContentValuesEntry other = (ContentValuesEntry) obj; return areEqual(key, other.key) && areEqual(value, other.value); }

Target:
Annotations should go on the same line as the method declaration.
Source:
public void itemWriterForPojos() throws Exception { AvroItemWriter avroItemWriter = new AvroItemWriter(output,plainOldUserSchemaResource, PlainOldUser.class); avroItemWriter.afterPropertiesSet(); avroItemWriter.open(new ExecutionContext()); avroItemWriter.write(this.plainOldUsers()); avroItemWriter.close(); verifyRecordsWithEmbeddedHeader(outputStream.toByteArray(), this.plainOldUsers(), PlainOldUser.class); }

Target:
Should specify the generic type to avoid warnings: `AvroItemWriter< PlainOldUser >`. We have a couple of them in this test class.
Source:
public void itemWriterWithNoEmbeddedHeaders() throws Exception { AvroItemWriter avroItemWriter = new AvroItemWriter(output, plainOldUserSchemaResource,PlainOldUser.class); avroItemWriter.setEmbedHeader(false); avroItemWriter.afterPropertiesSet(); avroItemWriter.open(new ExecutionContext()); avroItemWriter.write(this.plainOldUsers()); avroItemWriter.close(); verifyRecords(outputStream.toByteArray(), this.plainOldUsers(), PlainOldUser.class, false); }

Target:
I'm a bit confused by this test and `shouldFailWitNoSchema` test, especially the following part: ```java AvroItemWriter<PlainOldUser> avroItemWriter = new AvroItemWriter<>(output, plainOldUserSchemaResource,PlainOldUser.class); avroItemWriter.setEmbedHeader(false); ``` Why should I provide a Schema if I can set `embedHeader` to false? For the reader, we can read `PlainOldUser`s from an avro file not containing a schema without providing a schema. In the same way, we should be able to write `PlainOldUser`s to an avro file without embedding any schema. In that case, why is the schema mandatory? To be specific, having a mandatory schema and an option to not embed it is confusing to me.
Source:
RemotePartitioningMasterStepBuilder beanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; return this; }

Target:
Is there a reason this is package private? On a fluent builder this feels odd...
Source:
public BeanValidatingItemProcessor(LocalValidatorFactoryBean localValidatorFactoryBean) throws Exception { super(); Assert.notNull(localValidatorFactoryBean, "localValidatorFactoryBean must not be null"); localValidatorFactoryBean.afterPropertiesSet(); Validator validator = localValidatorFactoryBean.getValidator(); SpringValidatorAdapter springValidatorAdapter = new SpringValidatorAdapter(validator); SpringValidator<T> springValidator = new SpringValidator<>(); springValidator.setValidator(springValidatorAdapter); springValidator.afterPropertiesSet(); setValidator(springValidator); }

Target:
We shouldn't be calling this here. That is the responsibility of the container since it's being injected.
Source:
public ItemWriter<Integer> itemWriter() { MessagingTemplate messagingTemplate = new MessagingTemplate(); messagingTemplate.setDefaultChannel(requests()); ChunkMessageChannelItemWriter<Integer> chunkMessageChannelItemWriter = new ChunkMessageChannelItemWriter<>(); chunkMessageChannelItemWriter.setMessagingOperations(messagingTemplate); chunkMessageChannelItemWriter.setReplyChannel(replies()); return chunkMessageChannelItemWriter; }

Target:
This should, at a minimum, return `ItemStreamWriter` since the `ChunkMessageChannelItemWriter` does implement `ItemStream`. That being said, for components like this, I actually usually recommend returning the concrete type so that Spring can see all interfaces implemented.
Source:
public ClassifierCompositeItemWriterBuilder classifier(Classifier<T, ItemWriter<? super T>> classifier) { Assert.notNull(classifier, "A classifier is required."); this.classifier = classifier; return this; }

Target:
Missing generic on return
Source:
public ClassifierCompositeItemWriterBuilder<T> classifier(Classifier<T, ItemWriter<? super T>> classifier) { Assert.notNull(classifier, "A classifier is required."); this.classifier = classifier; return this; }

Target:
Move this assert into the build. As it sits right now, you can end up with an invalid writer (one with the invalid default) by just doing: ``` new ClassifierCompositeItemWriter().build(); ``` A test case for this condition should also be added.
Source:
public CompositeItemWriterBuilder delegates(List<ItemWriter<? super T>> delegates) { Assert.notNull(delegates, "A list of delegates is required."); Assert.notEmpty(delegates, "The delegates list must have one or more delegates."); this.delegates = delegates; return this; }

Target:
I've been doing all asserts in the build method to prevent the duplication you have here (for the null check). If the user passes in null, that's ok as long as they don't call build until they call it with something else...
Source:
protected Properties initJobParameters() { Properties jobParameters = new Properties(); if (getBeanDefinitionRegistry().containsBeanDefinition(JOB_PARAMETERS_BEAN_DEFINITION_NAME)) { BeanDefinition beanDefintion = getBeanDefinitionRegistry().getBeanDefinition(JOB_PARAMETERS_BEAN_DEFINITION_NAME); Properties properties = (Properties) beanDefintion.getConstructorArgumentValues() .getGenericArgumentValue(Properties.class) .getValue(); if (properties == null) { return new Properties(); } jobParameters.putAll(properties); } return jobParameters; }

Target:
Is this really something we want people to be able to override?
Source:
public void afterPropertiesSet() throws Exception { Assert.isTrue(!(jsrDecider == null), "A decider implementation is required"); Assert.notNull(name, "A name is required for a decision state"); }

Target:
jsrDecider != null or Assert.notNull may be clearer here
Source:
void performComplete(BitmapHunter hunter) { if (shouldWriteToMemoryCache(hunter.getData().memoryPolicy)) { Result result = hunter.getResult(); if (result != null) { if (result instanceof Result.Bitmap) { Bitmap bitmap = ((Result.Bitmap) result).getBitmap(); cache.set(hunter.getKey(), bitmap); } } } hunterMap.remove(hunter.getKey()); deliver(hunter); }

Target:
revert (@JvmField at declaration)
Source:
public Builder executor(@NonNull ExecutorService executorService) { checkNotNull(executorService, "executorService == null"); if (!isChild && this.service != null) { throw new IllegalStateException("Executor service already set."); } this.service = executorService; return this; }

Target:
remove these checks and the isChild flag. the checks don't add any value.
Source:
public MatrixTransformation(Request data) { this.data = data; }

Target:
not public
Source:
static int getExifRotation(int orientation) { int rotation; switch (orientation) { case ORIENTATION_ROTATE_90: case ORIENTATION_TRANSPOSE: rotation = 90; break; case ORIENTATION_ROTATE_180: case ORIENTATION_FLIP_VERTICAL: rotation = 180; break; case ORIENTATION_ROTATE_270: case ORIENTATION_TRANSVERSE: rotation = 270; break; default: rotation = 0; } return rotation; }

Target:
Private
Source:
static int getExifTranslation(int orientation) { int translation; switch (orientation) { case ORIENTATION_FLIP_HORIZONTAL: case ORIENTATION_FLIP_VERTICAL: case ORIENTATION_TRANSPOSE: case ORIENTATION_TRANSVERSE: translation = -1; break; default: translation = 1; } return translation; }

Target:
private
Source:
public void cancelRequest(ImageView view) { // checkMain() is called from cancelExistingRequest() if (view == null) { throw new AssertionError("view cannot be null."); } cancelExistingRequest(view); }

Target:
I'm pretty sure we use IllegalArgumentException for these everywhere else.
Source:
static int getFileExifRotation(Uri uri) throws IOException { ExifInterface exifInterface = new ExifInterface(uri.getPath()); int orientation = exifInterface.getAttributeInt(TAG_ORIENTATION, ORIENTATION_NORMAL); return orientation; }

Target:
nit: inline return with the line above.
Source:
public Builder transform(List<? extends Transformation> transformations) { if (transformations == null) { throw new IllegalArgumentException("Transformation list must not be null."); } for (Object transformation : transformations) { transform((Transformation) transformation); } return this; }

Target:
You want `List<? super Transformation>` here. Then you get `Transformation` objects without casting.
Source:
static boolean isOfflineOnly(int networkPolicy) { return (networkPolicy & NetworkPolicy.OFFLINE.index) == NetworkPolicy.OFFLINE.index; }

Target:
These methods will need to be public, otherwise how do I know what the integer value passed to the `Downloader` means?
Source:
@SuppressWarnings("UnusedDeclaration") public void setLoggingEnabled(boolean enabled) { loggingEnabled = enabled; }

Target:
Also really ugly. Suppressing warning should always come with a comment ``` java @SuppressWarnings("UnusedDeclaration") // Public API. ```
Source:
public RequestCreator memoryPolicy(MemoryPolicy policy, MemoryPolicy... additional) { if (policy == null) { throw new IllegalArgumentException("Memory policy cannot be null."); } this.memoryPolicy |= policy.index; if (additional != null && additional.length > 0) { for (MemoryPolicy memoryPolicy : additional) { if (memoryPolicy == null) { throw new IllegalArgumentException("Memory policy cannot be null."); } this.memoryPolicy |= memoryPolicy.index; } } return this; }

Target:
If this was `null` it would be an explicit choice by the user. Reject it with an exception.
Source:
public void error() { if (callback != null) { callback.onError(); } }

Target:
This should be package scoped, not public.
Source:
public Future<?> submit(Runnable task) { if (task == null) { throw new NullPointerException(); } PicassoFutureTask ftask = new PicassoFutureTask((BitmapHunter) task); execute(ftask); return ftask; }

Target:
`AssertionError` instead? Would this ever really happen?
Source:
@Test public void forOverrideRequest() { Action action = mockAction(ASSET_KEY_1, ASSET_URI_1); AssetRequestHandler handler = new AssetRequestHandler(context); List<RequestHandler> handlers = new ArrayList<RequestHandler>(Arrays.asList(handler)); // must use non-mock constructor because that's where Picasso's list of handlers is created Picasso picasso = new Picasso(context, dispatcher, cache, null, null, handlers, stats, false, false); BitmapHunter hunter = forRequest(picasso, dispatcher, cache, stats, action); assertThat(hunter.requestHandler).isEqualTo(handler); }

Target:
Don't need to wrap in `ArrayList`
Source:
@Override RemoteViewsTarget getTarget() { return new RemoteViewsTarget(remoteViews, viewId); }

Target:
Cache this instance in a field? Or is it only called once?
Source:
public Builder(Context context) { if (context == null) { throw new IllegalArgumentException("Context must not be null."); } if (!hasPermission(context, Manifest.permission.INTERNET)) { throw new IllegalArgumentException("INTERNET permission is required."); } this.context = context.getApplicationContext(); }

Target:
I think this is a bit too early. We support loading from many places other than the internet.
Source:
public NetworkBitmapHunter(Picasso picasso, Dispatcher dispatcher, Cache cache, Stats stats, Action action, Downloader downloader) { super(picasso, dispatcher, cache, stats, action); this.downloader = downloader; this.retryCount = DEFAULT_RETRY_COUNT; if (!hasPermission(picasso.context, Manifest.permission.INTERNET)) { Picasso.HANDLER.post(new Runnable() { @Override public void run() { throw new SecurityException("INTERNET permission is required."); } }); } }

Target:
`IllegalStateException`
Source:
public int hashCode() { int result = remoteViews.hashCode(); result = 31 * result + viewId; return result; }

Target:
Inline method body to one line.
Source:
void detach(Action action) { if (actions != null) { actions.remove(action); } if (this.action == action) { this.action = null; } }

Target:
And then `else if` this
Source:
@Test public void attachMultipleRequests() throws Exception { Action action1 = mockAction(URI_KEY_1, URI_1, mockImageViewTarget()); Action action2 = mockAction(URI_KEY_1, URI_1, mockImageViewTarget()); BitmapHunter hunter = new TestableBitmapHunter(picasso, dispatcher, cache, stats, action1); assertThat(hunter.actions).isNull(); hunter.attach(action2); assertThat(hunter.actions).isNotNull(); assertThat(hunter.actions).hasSize(1); }

Target:
chain with previous line's assertion
Source:
static BitmapFactory.Options createBitmapOptions(Request data) { final boolean justBounds = data.hasSize(); final boolean hasConfig = data.config != null; final boolean instantiate = hasConfig || justBounds; // Only instantiate if we need it final BitmapFactory.Options options = instantiate ? new BitmapFactory.Options() : null; if (justBounds) { options.inJustDecodeBounds = true; } if (hasConfig) { options.inPreferredConfig = data.config; } return options; }

Target:
This is only used once and isn't very descriptive. Can we do: ``` java BitmapFactory.Options options = null; if (hasConfig || justBounds) { options = new.. } ```
Source:
public int getOpacity() { Bitmap bm = bitmap; return (bm == null || bm.hasAlpha() || bitmapPaint.getAlpha() < 255) ? PixelFormat.TRANSLUCENT : PixelFormat.OPAQUE; }

Target:
`bm` should never be `null`.
Source:
@Override public void onReceive(Context context, Intent intent) { // On some versions of Android this may be called with a null Intent if (null == intent) return; String action = intent.getAction(); Bundle extras = intent.getExtras(); if (ACTION_AIRPLANE_MODE_CHANGED.equals(action)) { dispatchAirplaneModeChange(extras.getBoolean(EXTRA_AIRPLANE_STATE, false)); } else if (CONNECTIVITY_ACTION.equals(action)) { dispatchNetworkStateChange(connectivityManager.getActiveNetworkInfo()); } }

Target:
Add `{` and `}`.
Source:
static long calculateDiskCacheSize(File dir) { long size = MIN_DISK_CACHE_SIZE; try { StatFs statFs = new StatFs(dir.getAbsolutePath()); long available = statFs.getBlockCount() * statFs.getBlockSize(); // Target 2% of the total space. size = available / 50; } catch (IllegalArgumentException ignored) { } // Bound inside min/max size for disk cache. return Math.max(Math.min(size, MAX_DISK_CACHE_SIZE), MIN_DISK_CACHE_SIZE); }

Target:
I think this still could overflow since it's coerced to a long at the end. You should cast one of the arguments to a `long` to ensure long multiplication is performed.
Source:
Bitmap quickMemoryCacheCheck(String key) { Bitmap cached = cache.get(key); if (cached != null) { stats.dispatchCacheHit(); } else { stats.dispatchCacheMiss(); } return cached; }

Target:
We need to change the method names to be more descriptive.
Source:
@SuppressWarnings("UnusedDeclaration") public void shutdown() { cache.clear(); cleanupThread.shutdown(); stats.shutdown(); dispatcher.shutdown(); if (this == singleton) { singleton = null; } shutdown = true; }

Target:
What's with the suppression? Also what happens when you call shutdown twice?
Source:
DeferredImageViewRequest(Picasso picasso, Uri uri, int resourceId, ImageView imageView, PicassoBitmapOptions options, List<Transformation> transformations, boolean skipCache, boolean noFade, int errorResId, Drawable errorDrawable, String key, Callback callback) { super(picasso, uri, resourceId, imageView, options, transformations, skipCache, noFade, errorResId, errorDrawable, key, callback); ViewTreeObserver observer = imageView.getViewTreeObserver(); if (observer.isAlive()) { observer.addOnGlobalLayoutListener(this); } }

Target:
I don't think it will ever be false directly after you get it. It can however be when you try to remove it.
Source:
NetworkBroadcastReceiver(Context context) { this.connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE); }

Target:
If you drop the `this.` it should fit on one line!
Source:
static void closeQuietly(InputStream is) { try { if (is != null) { is.close(); } } catch (IOException ignored) { } }

Target:
Nit: use `if (is == null) return;` instead.
Source:
Bitmap execute(Request request) throws IOException { BitmapHunter hunter = BitmapHunter.forRequest(context, this, dispatcher, request, downloader); return hunter.hunt(); }

Target:
Inline `hunter`. `return BH.fR(..).hunt()`
Source:
void submit(Request request) { Object target = request.getTarget(); if (target == null) return; cancelExistingRequest(target, request.uri); targetsToRequests.put(target, request); requestSparseArray.put(request.getTargetRef().hashCode(), request); request.future = service.submit(request); }

Target:
this is very sketchy. Hash codes aren't unique
Source:
Bitmap decodeAsset(Uri uri, PicassoBitmapOptions bitmapOptions) throws IOException { String path = uri.getPath().replaceFirst("/", ""); AssetManager assets = context.getAssets(); if (bitmapOptions != null && bitmapOptions.inJustDecodeBounds) { BitmapFactory.decodeStream(assets.open(path), null, bitmapOptions); calculateInSampleSize(bitmapOptions); } return decodeStream(assets.open(path), bitmapOptions); }

Target:
Use `.substring(1)` so that we don't have to allocate a new `String` instance.
Source:
Bitmap decodeResource(Uri uri, PicassoBitmapOptions bitmapOptions) throws IOException { String path = uri.getPath().replaceFirst("/", ""); try { return decodeResource(Integer.parseInt(path), bitmapOptions); } catch (NumberFormatException ignore) { throw new IOException("\"" + path + "\" isn't a valid resource id"); } }

Target:
Use `.substring(1)` so that we don't have to allocate a new `String` instance.
Source:
private void changeRegion(RateControlRegion region, long nowMs) { if (rateControlRegion == region) { return; } rateControlRegion = region; if (logger.isTraceEnabled()) { logger.trace(Logger.Category.BWE, diagnosticContext .makeTimeSeriesPoint("aimd_region", nowMs) .addKey("aimd", hashCode()) .addField("value", region).toString()); } }

Target:
Are you sure? The trace() methods would have these signatures if we change String to Object: Object Object, Throwable Category, Object Category, Object, Throwable
Source:
public PacketTransformer getRTPTransformer() { return this.retransmissionRequesterDelegate.getRTPTransformer(); }

Target:
I think this hooks up the delagate as the transformer, bypassing RetransmissionRequesterImpl#reverseTransform()
Source:
public RawPacket reverseTransform(RawPacket pkt) { if (extensionId != -1) { RawPacket.HeaderExtension he = pkt.getHeaderExtension((byte) extensionId); if (he != null && he.getExtLength() == 2) { int seq = RTPUtils.readUint16AsInt( he.getBuffer(), he.getOffset() + 1); packetReceived( seq, pkt.getPayloadType(), pkt.isPacketMarked()); } } return pkt; }

Target:
I know the pt is only used in logging, but it's implicitly converted from a byte to an int here
Source:
private static String toHexString(byte b) { char[] hexes = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; StringBuilder hexStringBuilder = new StringBuilder(2); hexStringBuilder.append(hexes[(b & 0xF0) >> 4]); hexStringBuilder.append(hexes[b & 0x0F]); return hexStringBuilder.toString(); }

Target:
Can we make these static? Also, missing docs
Source:
public FrameDesc findFrameDesc(byte[] buf, int off, int len) { RawPacket pkt = new RawPacket(buf, off, len); return findFrameDesc(pkt.getSSRCAsLong(), pkt.getTimestamp()); }

Target:
We could use the static versions of getSSRCAsLong and getTimestamp here
Source:
public byte getAbsSendTimeExtensionID(){ return extensionID == -1 ? extensionID_for_debugging : extensionID ; }

Target:
Can we please remove extensionID_for_debugging? When testing with jitsi-meet abs-send-time is configured with id=3, so you can already test it.
Source:
public <K,V> List<K> Keys(TreeMap<K,V> _map) { ArrayList<K> keys = new ArrayList<K>(); for(Map.Entry<K,V> entry : _map.entrySet()) { keys.add(entry.getKey()); } return keys; }

Target:
private
Source:
long ConvertMsTo24Bits(long timeMs) { long time24Bits = (long)(((timeMs << kAbsSendTimeFraction) + 500) / 1000) & 0x00FFFFFF; return time24Bits; }

Target:
private
Source:
boolean IsWithinClusterBounds(long sendDeltaMs, Cluster clusterAggregate) { if(clusterAggregate.count == 0) { return true; } double clusterMean = clusterAggregate.sendMeanMs / (double)clusterAggregate.count; return Math.abs((double)sendDeltaMs - clusterMean) < 2.5f; }

Target:
private
Source:
void addCluster(List<Cluster> clusters, Cluster cluster) { cluster.sendMeanMs /= (double)cluster.count; cluster.recvMeanMs /= (double)cluster.count; cluster.meanSize /= cluster.count; clusters.add(cluster); }

Target:
private
Source:
public boolean matches(long ssrc) { if (primarySSRC != ssrc && rtxSSRC != ssrc) { return false; } return true; }

Target:
`return (primarySSRC == ssrc || rtxSSRC == ssrc)`?
Source:
public static boolean isKeyframe(ByteArrayBuffer baf) { if (baf.getLength() < 2) return false; // The data follows the one-byte header. byte b = baf.getBuffer()[baf.getOffset() + 1]; return (b & KF_MASK) != 0; }

Target:
Are we sure a `null` never reaches this point?
Source:
public RawPacket reverseTransform(RawPacket pkt) { if (enabled && !closed && pkt != null && pkt.getVersion() == 2) { incomingRawPacketCache.cachePacket(pkt); } return pkt; }

Target:
We could get rid of the checks for pkt if we use the RTPPacketPredicate
Source:
public static boolean isPacketMarked(byte[] buffer, int offset, int length) { return (buffer[offset + 1] & 0x80) != 0; }

Target:
Can we please move this static method to the top of the file and maybe have it sanity check the length?
Source:
public KeyframeRequester(int mediaSenderSSRC) { super(FIR_RETRY_INTERVAL_MS); this.mediaSenderSSRC = mediaSenderSSRC; this.sequenceNumber = new AtomicInteger(0); this.remainingRetries = 0; }

Target:
I'm going to make a very moot point here, I admit. But isn't that easier to read if you initialize sequenceNumber above given that it's final and doesn't get initialized with a constructor argument?
Source:
public Node node() { final Node castCache = Node.class.cast(this.cache); final Node answer; final boolean isDocument = castCache instanceof Document; if (isDocument) { answer = castCache.cloneNode(true); } else { answer = this.createImportedNode(castCache); } return answer; }

Target:
@Suseika please inline `isDocument`
Source:
private Node createImportedNode(final Node node) { assert !(node instanceof Document); final Document document; try { document = DFACTORY.newDocumentBuilder().newDocument(); } catch (final ParserConfigurationException ex) { throw new IllegalStateException(ex); } final Node imported = document.importNode(node, true); document.appendChild(imported); return imported; }

Target:
@Suseika please remove `assert`, we don't use them
Source:
public String getStringData() { try { return IOUtils.toString(this.stream); } catch (final IOException exception) { throw new RuntimeException("Unable to read input", exception); } }

Target:
why throw RuntimeException? Throw IllegalArgumentException and remove SuppressWarnings
Source:
public String toString() { return prependIfDeerInstance("Title-matching Generator"); }

Target:
Just pass in the `name` variable to this
Source:
public String sanitize(String title) { return removeCommonPrefixes(titleTransform.apply(title) .replaceAll(" & ", " and ") .replaceAll("[^\\d\\w\\s]", "").toLowerCase()); }

Target:
Does this need to be public?
Source:
private AliasResolvingEquivalenceGenerator(Builder builder) { this.resolver = checkNotNull(builder.resolver); this.publishers = checkNotNull(builder.publishers); this.lookupEntryStore = checkNotNull(builder.lookupEntryStore); this.namespacesSet = checkNamespacesSet(checkNotNull(builder.namespacesSet)); this.aliasMatchingScore = checkNotNull(builder.aliasMatchingScore); this.includeUnpublishedContent = builder.includeUnpublishedContent; this.cls = checkNotNull(builder.cls); }

Target:
I'd add a checkNotNull here and make the builder field a `Boolean`. This will make sure someone sets the field instead of it defaulting to false.
Source:
public void testRealBbcTxlogRegularExamples() { assertTxlogNitroScore("THE HOUSING ENFORCERS", "Episode 2", "The Housing Enforcers", scoreOnMatch); //will likely add equiv rules for this in future assertTxlogNitroScore("!MPOSSIBLE", "Episode 7", "Impossible", scoreOnMismatch); }

Target:
this should equiv
Source:
private ContentEquivalenceUpdateTask publisherUpdateTask(final Publisher... publishers) { return new ContentEquivalenceUpdateTask( (SelectedContentLister) contentLister, contentResolver, getNewDefaultExecutor(), progressStore(), equivUpdater, ignored ).forPublishers(publishers); }

Target:
This cast feels a bit out of place but I don't really have a better suggestion - maybe where this is autowired we could add a separate bean that has a return type of SelectedContentLister that returns the same object as the normal ContentLister bean?
Source:
@Override public ScoredCandidates<Item> score(Item subject, Set<? extends Item> candidates, ResultDescription desc) { DefaultScoredCandidates.Builder<Item> equivalents = DefaultScoredCandidates.fromSource(NAME); for (Item candidate : candidates) { equivalents.addEquivalent(candidate, score(subject, candidate)); } return equivalents.build(); }

Target:
style: put @override on the line above for method declarations, and if your parameters make the line too long list all parameters line by line e.g. public ScoredCandidates<Item> score( Item subject, Set<? extends Item> candidates, ResultDescription desc ) { ....
Source:
@Override public String toString(){ return NAME; }

Target:
style: stick this at the bottom of the class for neatness, and as above don't forget to move the @override to the line above
Source:
public boolean contains(@Nullable ServiceId serviceId) { return serviceId != null && serviceId.equals(serviceIdMap.get(serviceId.getId())); }

Target:
There are different ServiceId objects with the same serviceId field? e.g. that contain different aliases?
Source:
private EquivalenceUpdatingWorker equivUpdatingWorker() { return new EquivalenceUpdatingWorker( contentResolver, lookupStore, equivalenceResultStore, equivUpdater, Predicates.or(ImmutableList.<Predicate<? super Content>>of( sourceIsIn( BBC_REDUX, YOUVIEW, YOUVIEW_STAGE, YOUVIEW_BT, YOUVIEW_BT_STAGE, BETTY, BT_TVE_VOD, BT_VOD ), Predicates.and( Predicates.instanceOf(Container.class), sourceIsIn( BBC, C4_PMLSD, ITV, FIVE, BBC_REDUX, ITUNES, RADIO_TIMES, LOVEFILM, TALK_TALK, YOUVIEW, NETFLIX, BBC_NITRO ) ) )) ); }

Target:
Why have you only added it to the container part of the or?