auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public EquivalenceUpdatingWorker(ContentResolver contentResolver, LookupEntryStore entryStore, EquivalenceResultStore resultStore, EquivalenceUpdater<Content> equivUpdater, Predicate<Content> filter) { this.contentResolver = checkNotNull(contentResolver); this.entryStore = checkNotNull(entryStore); this.resultStore = checkNotNull(resultStore); this.equivUpdater = checkNotNull(equivUpdater); this.filter = checkNotNull(filter); this.telescopeProxy = OwlTelescopeReporter.create( OwlTelescopeReporters.EQUIVALENCE_UPDATING_WORKER, Event.Type.EQUIVALENCE ); }

Target:
Doesn't this mean you'll have a single reporter for the whole life of the worker (and a single reporter means a single task I think?) I thought it had been talked about having a new task every hour or similar?
Source:
private void rotateTelescope() { if (telescope == null) { telescope = OwlTelescopeReporter.create( OwlTelescopeReporters.EQUIVALENCE_UPDATING_WORKER, Event.Type.EQUIVALENCE ); telescope.startReporting(); timeSinceTelescopeRotated = DateTime.now(); } else if (timeSinceTelescopeRotated.plusHours(1).isBeforeNow()) { telescope.endReporting(); telescope.startReporting(); } }

Target:
I'd personally do a 'timeToNextRotate' method, then you don't need the +1 each time, but that's just me nitpicking
Source:
private static Process getProcess(IngesterName name) { Environment environment; try { environment = Environment.valueOf(TelescopeConfiguration.ENVIRONMENT); } catch (IllegalArgumentException e) { //add stage as the default environment, which is better than crashing log.error("Could not find a telescope environment with the given name, name={}. Falling back to STAGE.", TelescopeConfiguration.ENVIRONMENT); e.printStackTrace(); environment = Environment.STAGE; } return Process.create(name.getIngesterKey(), name.getIngesterName(), environment); }

Target:
this shouldn't be necessary and if people aren't watching the logs carefully enough this could cause an ingest to stage without someone realising
Source:
private String extractBaseIdFromUri(Channel channel) { return channel.getUri() .replace(uriPrefix, "") .trim(); }

Target:
could the URI ever have a trailing '/' or similar cruft?
Source:
private Optional<Channel> updateChannelWithAdvertisedDates( Channel channel, DateTime advertiseFromDate, DateTime advertiseToDate ) { if (advertiseFromDate != null && advertiseFromDate.getMillis() > 0) { channel.setAdvertiseFrom(advertiseFromDate); } else { channel.setAdvertiseFrom(null); } if (advertiseToDate != null && advertiseToDate.getMillis() > 0) { channel.setAdvertiseTo(advertiseToDate); } else { channel.setAdvertiseTo(null); } channelWriter.createOrUpdate(channel); return Optional.of(channel); }

Target:
why bother re-wrapping this to be returned, when it's not passed to this method as an Optional, so it must always be present?
Source:
private void removeStaleAliasesFromChannel( Set<Long> channelIdsThatHaveAliasesAdded, Iterable<Channel> channels ) { for (Channel channel : channels) { if(!channelIdsThatHaveAliasesAdded.contains(channel.getId())) { channel.setAliases( channel.getAliases() .stream() .filter(alias -> !alias.getNamespace().equals(aliasNamespace)) .collect(Collectors.toList()) ); } channelWriter.createOrUpdate(channel); } }

Target:
should this use Objects.equals JIC null safety is required?
Source:
private boolean titlesEqual(String subjectTitle, String candidateTitle) { return false && subjectTitle.equals(candidateTitle); }

Target:
wouldn't false and something always be false?
Source:
public void scheduleUpdater() { ExecutorService executorService = Executors.newFixedThreadPool(STARTUP_THREAD_COUNT); Set<ScheduledTask> jobsAtStartup = Sets.newHashSet(); if (Boolean.parseBoolean(updaterEnabled) && Boolean.parseBoolean(channelEquivEnabled)) { log.info("Channel equivalence enabled"); addEquivalenceJobs(jobsAtStartup); } for (ScheduledTask scheduledTask : jobsAtStartup) { executorService.submit(scheduledTask); } }

Target:
can this be streamed?
Source:
private ItunesEpfFileUpdater( String username, String password, String feedPath, String localFilesPath, S3Client s3Client ) { this.username = checkNotNull(username); this.password = checkNotNull(password); this.feedPath = checkNotNull(feedPath); this.localFilesPath = checkNotNull(localFilesPath); this.s3client = s3Client; }

Target:
`checkNotNull`
Source:
public EquivGraphController(LookupEntryStore lookupStore) { this.lookupStore = checkNotNull(lookupStore); this.codec = SubstitutionTableNumberCodec.lowerCaseOnly(); }

Target:
convert to private constructor and a static create method
Source:
public ExclusionListFilter(Iterable<String> excludedUris, Iterable<String> excludedIds) { this.excludedUris = ImmutableSet.copyOf(excludedUris); this.excludedIds = ImmutableSet.copyOf(excludedIds); this.codec = SubstitutionTableNumberCodec.lowerCaseOnly(); }

Target:
convert to private constructor and a static create method
Source:
public EquivalenceGenerators( Iterable<? extends EquivalenceGenerator<T>> generators, Set<String> excludedUris, Set<String> excludedIds ) { this.generators = ImmutableList.copyOf(generators); this.excludedUris = excludedUris; this.excludedIds = excludedIds; this.codec = SubstitutionTableNumberCodec.lowerCaseOnly(); }

Target:
convert to private constructor and a static create method
Source:
public void generatorCreatesCandidatesForNonExcludedUri() { Item item = new Item(); item.setId(12345678L); item.setCanonicalUri("notexcluded"); generators.generate(item, resultDescription); verify(generator).generate(item, resultDescription); }

Target:
I'd write some explicit tests for your ID list instead of adding id's into the uri tests. It's quick and a lot clearer what you're testing. Also, decoding the string representation of an ID to a long and using that variable in the tests would be a lot clearer to show which ID matches.
Source:
private ContentWriteController contentWriteController() { return ContentWriteController.create( configFetcher, contentWriteExecutor, lookupBackedContentIdGenerator, contentWriteMessageSender, contentModelOutputter(), lookupStore, contentResolver, contentWriter, new EquivalenceBreaker( contentResolver, entryStore, lookupWriter ), new OldContentDeactivator( new MongoContentLister( mongo, new MongoContentResolver(mongo, lookupStore) ), contentWriter, contentResolver ) ); }

Target:
If any of these classes are part of the `atlas` repo let's change them to have static factory methods as per the code style
Source:
private ContentWriteController contentWriteController() { return ContentWriteController.create( configFetcher, contentWriteExecutor, lookupBackedContentIdGenerator, contentWriteMessageSender, contentModelOutputter(), lookupStore, contentResolver, contentWriter, new EquivalenceBreaker( contentResolver, entryStore, lookupWriter ), oldContentDeactivator, configFetcher ); }

Target:
already passed in
Source:
public void testConvertsPcOdToBrandIosUri() { map.put("dc:relation.programmeId", "338672-002"); Assert.assertThat( C4AtomApi.iOsUriFromPcUri("http://www.channel4.com/programmes/come-dine-with-me/on-demand/338672-002", map), is("all4://views/brands?brand=come-dine-with-me&programme=338672-002")); }

Target:
Needs a static import.
Source:
private ChannelWriteController channelWriteController() { return new ChannelWriteController( configFetcher, channelStore, new DefaultGsonModelReader(), new ChannelModelTransformer( v4ChannelCodec(), new ImageModelTranslator() ) ); }

Target:
Code style. Use static factory methods or builders for all classes. Constructors should be private
Source:
private Iterable<NitroItemSource<Episode>> toItemSources(Iterable<Episode> episodes) throws GlycerinException, NitroException { return new PaginatedNitroItemSources( episodes, NITRO_BATCH_SIZE, pageSize, executor, glycerin ); }

Target:
This used to be an unused member inside it, is this actually used now or just left here?
Source:
public boolean hasNext() { if (episodes.hasNext()) { return true; } return false; }

Target:
Again, just return the boolean value.
Source:
public List<Clip> getClips(String pid, String uri) { PidReference pidReference = new PidReference(); pidReference.setPid(pid); pidReference.setHref(uri); List<Clip> clips; try { clips = clipsAdapter.clipsFor(pidReference); } catch (NitroException e) { throw Throwables.propagate(e); } return clips; }

Target:
Could simplify to `try { return clipsAdapter.clipsFor(pidReference); ...`
Source:
private void setTags(ProgData progData, Content content) { Set<String> tagsFromGenres = paTagMap.map(content.getGenres()); if (!tagsFromGenres.isEmpty()) { content.setTags(tagsFromGenres); } }

Target:
Why do we need this guard?
Source:
protected boolean subjectAndCandidateMatch(Item subject, Item candidate) { ImmutableSet<String> aliasesOfCandidateBroadcasts = FluentIterable.from(candidate.flattenBroadcasts()) .transformAndConcat(BROADCAST_TO_ALIAS_STRING_ITERABLE) .toSet(); ImmutableSet<String> aliasesOfSubjectBroadcasts = FluentIterable.from(subject.flattenBroadcasts()) .transformAndConcat(BROADCAST_TO_ALIAS_STRING_ITERABLE) .toSet(); if (!Sets.intersection(aliasesOfCandidateBroadcasts, aliasesOfSubjectBroadcasts).isEmpty()) { return true; } return false; }

Target:
you could eliminate the `if` here, and just do: `return !Sets.intersection(aliasesOfCandidateBroadcasts, aliasesOfSubjectBroadcasts).isEmpty();`
Source:
public C4AtomEntryVersionExtractor(Optional<Platform> platform, C4LocationPolicyIds locationPolicyIds, boolean createIosBrandLocations) { this.platform = checkNotNull(platform); this.locationPolicyIds = checkNotNull(locationPolicyIds); this.createIosBrandLocations = checkNotNull(createIosBrandLocations); }

Target:
it's a primitive
Source:
public void handle(EquivalenceResult<T> result) { try { sender.sendMessage(messageFrom(result));; } catch (Exception e) { log.error("Failed to send equiv update message: " + result.subject(), e); } }

Target:
double semi-colon
Source:
public BaseContentPopulator(Optional<RoviProgramLine> program, Iterable<RoviProgramDescriptionLine> descriptions, ContentResolver contentResolver) { checkArgument(!isDelete(program), "It's not possible to populate from a program delete action"); checkNotNull(descriptions); checkNotNull(contentResolver); this.optionalProgram = program; this.descriptions = descriptions; this.contentResolver = contentResolver; }

Target:
`checkNotNull`?
Source:
public ContentBuffer(ContentResolver contentResolver, ContentWriter contentWriter, ItemsPeopleWriter peopleWriter) { this.resolver = Preconditions.checkNotNull(contentResolver); this.writer = Preconditions.checkNotNull(contentWriter); this.peopleWriter = Preconditions.checkNotNull(peopleWriter); }

Target:
static import?
Source:
private boolean isUserRoleChanged(User posted, User existing) { return posted.getRole().equals(existing.getRole()); }

Target:
isn't this `isUserRoleNotChanged`?
Source:
private XMLReader createReader() { try { JAXBContext context; context = JAXBContext.newInstance("org.atlasapi.remotesite.pa.features.bindings"); Unmarshaller unmarshaller = context.createUnmarshaller(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); XMLReader reader = factory.newSAXParser().getXMLReader(); reader.setContentHandler(unmarshaller.getUnmarshallerHandler()); unmarshaller.setListener(featuresProcessingListener()); return reader; } catch (Exception e) { throw new RuntimeException(e); } }

Target:
minor thing... why is this broken into two lines?
Source:
private boolean hasBrandSummary(ProgData progData) { if (Strings.isNullOrEmpty(progData.getSeriesSummary())) { return false; } return true; }

Target:
if ([boolean condition]) return boolean... REALLY? in other news, you could just do return !Strings.isNullOrEmpty(progData.getSeriesSummary());
Source:
private boolean hasSeriesSummary(ProgData progData) { if (progData.getSeason() != null && !Strings.isNullOrEmpty(progData.getSeason().getSeasonSummary())) { return true; } return false; }

Target:
Another instance of returning boolean on the result of a boolean check. THIS IS BAD.
Source:
public void write(ByteBuffer buffer) { buffer.putLong(offset); buffer.rewind(); }

Target:
why rewind?
Source:
public FetchedDataChunk(ByteBufferMessageSet messages, PartitionTopicInfo topicInfo, long fetchOffset) { super(); this.messages = messages; this.topicInfo = topicInfo; this.fetchOffset = fetchOffset; }

Target:
remove
Source:
public Void visit(Boolean inTailPosition, FieldGet fieldGet) { fieldGet.getObjectExpr().acceptVisitor(this, inTailPosition); return null; }

Target:
The recursive call should pass "false" because we have to get a field from any result
Source:
public ASTNode() { this((FileLocation)null); location = null; }

Target:
This duplicates the initialization of location in the other constructor that's called in the previous line
Source:
public boolean containsResource() { return this.hasResource; }

Target:
Declare this abstract or with a default implementation, then override in subclasses. VarDeclaration always contains a resource; ValDeclaration contains one depending on it's type; TypeDeclaration never contains a resource.
Source:
public void setHasResource(boolean hasResource) { this.hasResource = hasResource; }

Target:
This should be private, as we don't want the resource attribute to be set externally.
Source:
public Set<String> getFreeVariables() { // Get free variables in the sub-expressions. Set<String> freeVars = toReplace.getFreeVariables(); freeVars.addAll(inExpr.getFreeVariables()); // Remove the name that just became bound. freeVars.remove(varName); return freeVars; }

Target:
Technically bind has exactly the free variables that are in the "toReplace" part. The inExpr can use varName, and nothing else.
Source:
public Set<String> getFreeVariables() { // Get all free variables in the body of the method. Set<String> freeVars = body.getFreeVariables(); // Remove variables that became bound in this method's scope. freeVars.remove(this.getName()); for (FormalArg farg : formalArgs) { freeVars.remove(farg.getName()); } return freeVars; }

Target:
Actually the name of the definition is not bound in the body --- at the level of the Core IL, recursive calls must be of the form "this.mymethod(...)" not just "mymethod(...)" [there is a sugar that makes this work at the source level but it goes away in translation to the core]
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if(obj == null) { return false; } if(this.getClass() != obj.getClass()) { return false; } try { StringLiteral other = (StringLiteral) obj; return this.equals(other); } catch(ClassCastException e) { return false; } }

Target:
Instead of this, check if the String values are equal.
Source:
private boolean indexIsOutOfRange(List<Element> elements) { return elements.size() <= 0 || elementIndex >= elements.size(); }

Target:
Could use `elements.isEmpty()` instead of checking size `<= 0`.
Source:
public ZestLoopState<String> deepCopy() { ZestLoopStateFile copy = new ZestLoopStateFile(); if(this.convertedState==null){ System.err.println("this converted state is null? "); } copy.convertedState = (ZestLoopStateString) this.convertedState .deepCopy(); return copy; }

Target:
We shouldnt use System.out.println / System.out.err.println anywhere apart from the CmdLine.java or ZestPrinter.java. If its an indication of a serious problem then throw an exception :)
Source:
public boolean isTrue(ZestResponse response) { boolean toReturn = true; for (ZestExpressionElement con : getChildrenCondition()) { toReturn = toReturn && con.evaluate(response);// compute AND for each child if(!toReturn) break;//lazy evaluation } return toReturn; }

Target:
Again, I'd default to false - I think 'nothing' makes more sense as false...
Source:
public ZestExpressionURL deepCopy() { ZestExpressionURL copy = new ZestExpressionURL(); List<String> copyIncludeRegex = new ArrayList<>(includeRegexes); List<String> copyExcludeRegex = new ArrayList<>(excludeRegexes); List<Pattern> copyIncludePatterns = new ArrayList<>(includePatterns); List<Pattern> copyExcludePatterns = new ArrayList<>(excludePatterns); copy.excludePatterns = copyExcludePatterns; copy.includePatterns = copyIncludePatterns; copy.includeRegexes = copyIncludeRegex; copy.excludeRegexes = copyExcludeRegex; return copy; }

Target:
Dont these all need to be deepCopy'ed?
Source:
private String getGMTOffsetString(long millis) { long absmillis = (millis < 0) ? -millis : millis; int minutes = (int) ((absmillis / (1000 * 60)) % 60); int hours = (int) ((absmillis / (1000 * 60 * 60)) % 24); return String.format("(GMT%c%02d:%02d) ", millis >= 0 ? '+' : '-', hours, minutes) }

Target:
And I just copy / pasted :innocent:
Source:
public TasksView(String authority, ContentProviderClient client) { super(new BaseView<TaskContract.Tasks>(client, TaskContract.Properties.getContentUri(authority))); }

Target:
This creates a `Properties` table. Copy'n'paste? ;-)
Source:
public void testAddingFlag() { assertTrue(containsFlag( new Toggled(Notification.DEFAULT_SOUND, true, new NoSignal()).value(), Notification.DEFAULT_SOUND)); assertFalse(containsFlag( new Toggled(Notification.DEFAULT_SOUND, false, new NoSignal()).value(), Notification.DEFAULT_SOUND)); }

Target:
don't use `containsFlag` here, instead test the expected outcome like so ```java assertThat(new Toggled(Notification.DEFAULT_SOUND, true, new NoSignal()).value(), is(new NoSignal().value() | Notification.DEFAULT_SOUND)); assertThat(new Toggled(Notification.DEFAULT_SOUND, false, new NoSignal()).value(), is(new NoSignal().value())); ```
Source:
protected double convertDuration(double duration) { return duration / durationFactor; LOG.error("Exception thrown from {}#report. Exception was suppressed.", ScheduledReporter.this.getClass().getSimpleName(), ex); }

Target:
Accidental copy & paste error?
Source:
public String getStatementName(StatementContext statementContext) { final String rawSql = statementContext.getRawSql(); if (rawSql == null || rawSql.length() == 0) { return "sql.empty"; } return null; }

Target:
`rawSql.isEmpty()` ?
Source:
private int traverse(Deque<Chunk> traversedChunksDeque) { Chunk currentChunk; activeChunkLock.lock(); try { currentChunk = activeChunk; } finally { activeChunkLock.unlock(); } int valuesSize = 0; while (true) { valuesSize += currentChunk.cursor - currentChunk.startIndex; if (traversedChunksDeque != null) { traversedChunksDeque.addLast(currentChunk); } if (currentChunk.tailChunk == null) { break; } currentChunk = currentChunk.tailChunk; } return valuesSize; }

Target:
Reading mutable fields without synchronization. ```trim``` and ```put``` do mutation of: - cursor - startIndex - tailChunk So result can be totaly wrong, even negative.
Source:
public void close() throws IOException { datagramChannel.socket().close(); datagramChannel = null; }

Target:
I think it's better to dereference the channel in a finally block in case the socket failed to close.
Source:
public synchronized static MetricRegistry setDefault(String name) { if (defaultRegistryName == null) { final MetricRegistry registry = getOrCreate(name); defaultRegistryName = name; return registry; } throw new IllegalStateException("Default metric registry name is already set."); }

Target:
Should there be another method for instances when you already have the MetricRegistry? I am using Dropwizard where a metrics registry is created by the framework and I would like to make that instance the default. As proposed: ``` java SharedMetricRegistries.add("default", bootstrap.getMetricRegistry()); SharedMetricRegistries.setDefault("default"); ``` With the overloaded setDefault method. ``` java SharedMetricRegistries.setDefault("default", bootstrap.getMetricRegistry()); ```
Source:
public void add(Entry entry) { if (queue.size() >= maxSize) { queue.poll(); } queue.add(entry); }

Target:
IMO while would be better here
Source:
protected ScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit) { ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory(name + '-' + FACTORY_ID.incrementAndGet())); this(registry, name, filter, rateUnit, durationUnit, executor); }

Target:
Build fails with `ScheduledReporter.java:[72,21] call to this must be first statement in constructor`, this should fix it: ``` java this(registry, name, filter, rateUnit, durationUnit, Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory(name + '-' + FACTORY_ID.incrementAndGet()))); ```
Source:
private <T> Collection<? extends Callable<T>> instrument(Collection<? extends Callable<T>> tasks) { List<InstrumentedCallable<T>> instrumented = new ArrayList<InstrumentedCallable<T>>(); for (Callable<T> task : tasks) { instrumented.add(new InstrumentedCallable(task)); } return instrumented; }

Target:
Make this `final` and since we know how many tasks we're dealing with, make sure we're creating a list with the right capacity.
Source:
public void run() { running.inc(); Timer.Context context = duration.time(); try { task.run(); } finally { context.stop(); running.dec(); completed.mark(); } }

Target:
Make this final.
Source:
public T call() throws Exception { running.inc(); Timer.Context context = duration.time(); try { return callable.call(); } finally { context.stop(); running.dec(); completed.mark(); } }

Target:
Make this final.
Source:
public InstrumentedHandler(MetricRegistry registry, Handler underlying) { this(registry, underlying, underlying.getClass().getName()); }

Target:
This should be `name(underlying.getClass())`.
Source:
public static OsAppCredentials anonymous() { return new OsAppCredentials(nativeCreate(TYPE_ANONYMOUS), Credentials.IdentityProvider.ANONYMOUS); }

Target:
I think it would be cleaner if `Credentials.IdentityProvider.ANONYMOUS` was defined in the factory constructor of `AppCredentials`. `OsAppCredentials` is there to map to the underlying type, but us making a shortcut is not the responsibility of the Os class but our own `AppCredentials`. The same everywhere else.
Source:
public void setVersion(long version) { OsObjectStore.setSchemaVersion(sharedRealm, version); }

Target:
Having this public feels problematic. What classes need to call this that don't live in `io.realm` ?
Source:
public Task<MongoCursor<ResultT>> iterator() { return dispatcher.dispatchTask(() -> new MongoCursor<>(getCollection().iterator(), dispatcher) ); }

Target:
Is it intended that calling this multiple times should trigger multiple remote operations? Maybe I am still a bit confused with the various _collection/iterable_ terms.
Source:
public void setUp() { app = new TestRealmApp(); RealmUser user = SyncTestUtils.Companion.createTestUser(app); config = configFactory.createSyncConfigurationBuilder(user).build(); }

Target:
You can annotate `createTestUser` with `@JvmStatic` and call it as a static method ```Kotlin RealmUser user = SyncTestUtils.createTestUser(app); ```
Source:
public void queryFrozenRealmAcrossThreads() throws InterruptedException { final Realm frozenRealm = createDataForFrozenRealm(DATA_SIZE); Thread t = new Thread(() -> { RealmResults<AllTypes> results = frozenRealm.where(AllTypes.class).findAll(); assertEquals(DATA_SIZE, results.size()); }); t.start(); t.join(); frozenRealm.close(); }

Target:
you're already closing it in the `tearDown`
Source:
public void addReference(NativeObject referent) { new NativeObjectReference(this, referent, referenceQueue); }

Target:
why public?
Source:
public long getTablePtr() { return table.getNativePtr(); }

Target:
why public? you can still call it from JNI even if it's private
Source:
public int getCount() { return cities == null ? 0 : cities.size(); }

Target:
This can never be null given the code in `setData` above?
Source:
private void setupViews() { backgroundJobStartStop = findViewById(R.id.backgroundJobStartStop); backgroundJobStartStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!backgroundTask.isStarted()) { backgroundTask.start(); } else { backgroundTask.stop(); } updateJobButton(); } }); }

Target:
We support Java 8 in the examples, so feel free to use lamdas.
Source:
private static X509Certificate buildCertificateFromPEM(String pem) throws IOException, CertificateException { InputStream stream = new ByteArrayInputStream(pem.getBytes("UTF-8")); X509Certificate x509Certificate = (X509Certificate) CERTIFICATE_FACTORY.generateCertificate(stream); stream.close(); return x509Certificate; }

Target:
This will not be closed if CertificateException is thrown?
Source:
public String getDisplayFileName() { if (displayName == null) { if(name != null) { if (version != null) { return name + ":" + version; } else { return name; } } else { return this.fileName; } } return this.displayName; }

Target:
Minor suggestion/subjective: could get rid of the nesting here using something like: ```java if (displayName != null) { return displayName; } if (name == null) { return fileName; } if (version == null) { return name; } return name + ":" + version; ```
Source:
private static boolean isPositiveInteger(final String str) { if (str == null || str.isEmpty()) { return false; } // numbers/versions with leading zeros should not be treated as numbers // (e.g. when comparing "01" <-> "1") if (str.charAt(0) == '0') { return false; } for (int i = 0; i < str.length(); i++) { final char c = str.charAt(i); if (c < '0' || c > '9') { return false; } } return true; }

Target:
This would treat '0' as a string. We need to add a `&& str.length() > 1`
Source:
public Object getTransactionId() { return tx != null ? tx.getId() : null; }

Target:
Transaction is mandatory. What kind of error we show in case a transaction is not present? If it's not clear enough we can improve it. Anyway, this would be a separate issue
Source:
private void lookupDatabase() { try { log.tracef( "Retrieving MongoDatabase from JNDI at %1$s", config.getNativeClientResource() ); mongoDb = (MongoDatabase) jndiService.locate( config.getNativeClientResource() ); } catch (RuntimeException e) { throw log.errorOnFetchJndiClientProperty( config.getNativeClientResource() ); } // clear resources this.jndiService = null; }

Target:
Not critical but I find it counter intuitive that the lookup method also does the clear, can we move it at the end of the start method?
Source:
private void lookupClient() { try { log.tracef( "Retrieving MongoDatabase from JNDI at %1$s", configuration.getNativeClientResource() ); Driver driver = (Driver) jndiService.locate( configuration.getNativeClientResource() ); this.client = new BoltNeo4jClient( driver ); } catch (RuntimeException e) { throw log.errorOnFetchJndiClientProperty( configuration.getNativeClientResource() ); } // clear resources this.jndiService = null; }

Target:
Not critical but I find it counter intuitive that the lookup method also does the clear, can we move it at the end of the start method?
Source:
public void before() throws Exception { // Synchronize on the static field to defend against concurrent launches, // e.g. the usage as JUnit Rule concurrently with the usage as global test listener in Surefire. synchronized ( running ) { if ( running.compareAndSet( false, true ) ) { RemoteHotRodServerHelper.beforeRun(); StandaloneCommandBuilder builder = StandaloneCommandBuilder .of( "target/infinispan-server" ); builder .setServerReadOnlyConfiguration( DEFAULT_CONFIG_PATH ); if ( portOffset != 0 ) { builder.addJavaOption( "-Djboss.socket.binding.port-offset=" + portOffset ); } Launcher launcher = Launcher.of( builder ); hotRodServer = launcher.inherit().launch(); waitForRunning(); } } }

Target:
this class is also used in integration tests module, where the server is in a different file system position
Source:
public void tearDown() { try { if ( !em.getTransaction().isActive() ) { em.getTransaction().begin(); } Family found = em.find( Family.class, family.getName() ); if ( found != null ) { em.remove( found ); } em.getTransaction().commit(); } finally { em.close(); } }

Target:
Wondering if we should fix that or the test itself as it's not a good example of how things should be done. But maybe we have all our tests like that and it's not worth fixing.
Source:
private void initEnumValues() { if ( enumValues == null ) { Class<Enum<?>> returnedClass = coreEnumType.returnedClass(); this.enumValues = returnedClass.getEnumConstants(); if ( enumValues == null ) { throw new NullPointerException( "Failed to init enumValues" ); } } }

Target:
I can't see a difference between the 2 codes. But either is OK to me.
Source:
public List getResultList() { log.info( "I am called!" ); if ( isResultSet() ) { return resultList; } return null; }

Target:
Remember to remove this
Source:
public Rule Reserved() { return FirstOf( Aggregate(), Find(), FindOne(), FindAndModify(), Insert(), Remove(), Update(), Count() ); // TODO There are many more query types than what we support. }

Target:
Let's add it at the end instead of at the beginning. It's less common than the other operations.
Source:
public UniqueConstraintDetails(Label label, String property) { super(); this.label = label; this.property = property; }

Target:
Maybe remove the useless `super()`?
Source:
private Object readProperty(Node otherNode, String targetColumnName) { Object value = null; otherNode.getAllProperties(); if ( otherNode.hasProperty( targetColumnName ) ) { value = otherNode.getProperty( targetColumnName ); } return value; }

Target:
The returned value is not used.
Source:
public void testSlice() { System.out.println( "slice" ); String[] strings = new String[]{ "1", "2", "3" }; int begin = 0; int length = 2; String[] expResult = new String[]{ "1", "2" }; String[] result = ArrayHelper.slice( strings, begin, length ); assertArrayEquals( expResult, result ); }

Target:
Can you remove the System.out.? They are unecessary
Source:
public Rule Reserved() { return FirstOf( Sequence( Find(), builder.setOperation( Operation.FIND ) ), Sequence( Count(), builder.setOperation( Operation.COUNT ) ) ); //TODO there is many more than `find` an `count` but as this time we only support `find` and `count` }

Target:
`builder.setOperation()` is already invoked by `Operation()`. I don't think we need to do it here, too?
Source:
public void storeAssociation(EntityKey key, Association document) { byte[] associationId = associationId( key ); connection.del( associationId ); for ( Object row : document.getRows() ) { connection.rpush( associationId, serializationStrategy.serialize( row ) ); } }

Target:
So this does not use JSON? Or am I missing something. Also I think it'd make sense to use the "transaction" semantics to write all rows of one association in one go?
Source:
public EntityManager createEntityManager() { return new OgmEntityManager( this, hibernateEmf.createEntityManager().unwrap( EntityManagerImpl.class ) ); }

Target:
There is no handling for the specific implementation _EntityManagerImpl.class_ in the unwrap() implementation of our EntityManager. This happens to work as unwrap() is able to cast it to _EntityManager_ (the interface), but this only works if the actual implementation happens to be an _EntityManagerImpl_. So.. shouldn't you rather cast explicitly?
Source:
public static PersistenceStrategy<?, ?, ?> getPerTableStrategy(EmbeddedCacheManager externalCacheManager, URL configUrl, JtaPlatform platform, Set<EntityKeyMetadata> entityTypes, Set<AssociationKeyMetadata> associationTypes, Set<IdSourceKeyMetadata> idSourceTypes) { PerTableKeyProvider keyProvider = new PerTableKeyProvider(); PerTableCacheManager cacheManager = externalCacheManager != null ? new PerTableCacheManager( externalCacheManager, entityTypes, associationTypes, idSourceTypes ) : new PerTableCacheManager( configUrl, platform, entityTypes, associationTypes, idSourceTypes ); return new PersistenceStrategy<PersistentEntityKey, PersistentAssociationKey, PersistentIdSourceKey>( cacheManager, keyProvider ); }

Target:
Strange indentation for this method parameters, what happend? :)
Source:
public void initializeSchema(Configuration configuration, SessionFactoryImplementor factory) { SessionFactoryImplementor sessionFactoryImplementor = factory; ServiceRegistryImplementor registry = sessionFactoryImplementor.getServiceRegistry(); Neo4jDatastoreProvider provider = (Neo4jDatastoreProvider) registry.getService( DatastoreProvider.class ); createSequences( sessionFactoryImplementor, provider ); createEntityConstraints( provider.getDataBase(), configuration ); initializeQueries( sessionFactoryImplementor, registry ); }

Target:
I'm wondering why this is triggered by the schema initializer. Couldn't it be done within the dialect itself during construction? The schema initializer really should only create/update persistent structures in the datastore. This would also avoid the need for that `injectQueries()` method.
Source:
public void testGetResultListSizeWithTypedQuery() throws Exception { List<Helicopter> helicopters = em.createQuery( "FROM Helicopter", Helicopter.class ) .getResultList(); Assertions.assertThat( helicopters.size() ).isEqualTo( 2 ); }

Target:
Is there a test for passing the wrong type when creating a typed query?
Source:
public List<Tuple> getTuples() { ArrayList<Tuple> tuples = new ArrayList<Tuple>(); if ( rows.size() > 0 ) { for ( Row row : rows ) { tuples.add( new Tuple( new CouchDBTupleSnapshot( row.getValue().getProperties() ) ) ); } } return tuples; }

Target:
I would use `List<Tuple>` here
Source:
public <R extends Service> void startService(ServiceBinding<R> serviceBinding) { if ( StartStoppable.class.isInstance( serviceBinding.getService() ) ) { ( (StartStoppable) serviceBinding.getService() ).start( configuration, sessionFactory ); } else { super.startService( serviceBinding ); } }

Target:
That's a interesting debate. Should `StartStoppable` be mutually exclusive with `Startable`? It seems to make sense. But then you lose the call in `super` of `Manageable`. Since in the end `Startable` and `StartStoppable` don't make much sense, we could simply always call `super. super.startService`
Source:
public CassandraDatastoreProvider() { try { Class.forName( "org.apache.cassandra.cql.jdbc.CassandraDriver" ); } catch (ClassNotFoundException e) { log.unableToLoadDriver("org.apache.cassandra.cql.jdbc.CassandraDriver") ; } }

Target:
this should be thrown, as it generates an exception
Source:
public Object get(String column) { TupleOperation result = currentState.get( column ); if ( result == null ) { return snapshot.get( column ); } else if ( result.getType() == PUT_NULL || result.getType() == REMOVE ) { return result; } else { return result.getValue(); } }

Target:
shouldn't this return null ? If not, I don't like this API which might return "Object" and with quite a different meaning :)
Source:
public void addDownloadedRecord(ServerReadingListRecord down) { final Boolean deleted = down.fields.getBoolean("deleted"); if (deleted == null || !deleted.booleanValue()) { additionsOrChanges.add(down); } addDeletion(down.getGUID()); }

Target:
Do you want an `else`? (I'll keep reading.)
Source:
protected final AlarmManager getAlarmManager() { return getAlarmManager(this.getApplicationContext()); }

Target:
I would suggest that this, its sibling, and perhaps `createPendingIntent` not be `final`.
Source:
public EngineSettings(ExtendedJSONObject object) throws NumberFormatException { this.syncID = object.getString("syncID"); this.version = object.getIntegerSafely("version").intValue(); }

Target:
Careful. You can also throw a `ClassCastException` in `getString`, and a `NullPointerException` by calling `intValue` on the result of `getIntegerSafely`. I'd be inclined to wrap this whole thing: ``` try { … } catch (Exception e) { throw new IllegalArgumentException(…); // Rethrow with cause. } ``` or a suitable "bad JSON" input. Sure beats having a random NPE if you get a missing version!
Source:
protected void insert(Record record) throws NoGuidForIdException, NullCursorException, ParentNotFoundException { HistoryRecord toStore = (HistoryRecord) prepareRecord(record); enqueueNewRecord(toStore); }

Target:
Again, inline `toStore`.
Source:
public String read(Record record) { UserIdReader userIdReader = new UserIdReader(); ClientSummaryReader clientReader = new ClientSummaryReader(); String timestamp = record.getTimestamp().toString(); String userId = userIdReader.read(record); String client = clientReader.read(record); return timestamp + ":" + userId + ":" + client; }

Target:
Please use Key.SEPARATOR for ":".
Source:
private void onNext() { if (mClientCertificateCheckBox.isChecked()) { // Auto-setup doesn't support client certificates. onManualSetup(); return; } String email = mEmailView.getText().toString(); ConnectionSettings connectionSettings = providersXmlDiscovery.discover(email); if (connectionSettings == null) { connectionSettings = srvServiceDiscovery.discover(email); } if (connectionSettings != null) { finishAutoSetup(connectionSettings); } else { // We don't have default settings for this account, start the manual setup process. onManualSetup(); } }

Target:
Same as `ThunderbirdDiscovery`, I don't want to actually use this just yet. Please leave `AccountSetupBasics` unchanged.
Source:
private NotificationHelper createFakeNotificationHelper(NotificationManagerCompat notificationManager, NotificationCompat.Builder builder) { NotificationHelper notificationHelper = mock(NotificationHelper.class); when(notificationHelper.getContext()).thenReturn(RuntimeEnvironment.application); when(notificationHelper.getNotificationManager()).thenReturn(notificationManager); when(notificationHelper.createNotificationBuilder(any(Account.class), any(NotificationChannelUtils.ChannelType.MISCELLANEOUS.getClass()))) .thenReturn(builder); return notificationHelper; }

Target:
If you want to match on a specific value you can use `ArgumentMatchers.eq()`: ```suggestion eq(NotificationChannelUtils.ChannelType.MISCELLANEOUS))) ``` If any value will do, there's no need to call `getClass()` on an instance. You can write it as: ```suggestion any(NotificationChannelUtils.ChannelType.class))) ```
Source:
public void shouldKeepDirAttribute() { String html = "<html><body>" + "<table><tbody><tr><td dir=\"rtl\"></td></tr></tbody></table>" + "</body></html>"; Document result = htmlSanitizer.sanitize(html); assertEquals("<html><head></head><body>" + "<table><tbody><tr><td dir=\"rtl\"></td></tr></tbody></table>" + "</body></html>", toCompactString(result)); }

Target:
Wouldn't `assertEquals(html, toCompactString(result))` better communicate our expectation? (I realize the input needs to be changed then)
Source:
public abstract void setFlags(List<? extends Message> messages, Set<Flag> flags, boolean value) throws MessagingException; public abstract void setFlags(Set<Flag> flags, boolean value) throws MessagingException; public abstract String getUidFromMessageId(Message message) throws MessagingException; public void expunge(List<Long> knownDeletedUids) throws MessagingException

Target:
With the `Folder` abstraction UIDs are opaque strings. UIDs being numbers is an implementation detail of `ImapFolder`. So until we can replace this interface with something more flexible let's keep this interface clean. Also, sometimes (e.g. when emptying the Trash folder) an unconstrained EXPUNGE makes sense. So I'd keep the original method and add a new one that better describes what it is about. My suggestion: ```java public void expungeUids(List<String> uids) throws MessagingException ```
Source:
public synchronized boolean setFolderSyncMode(FolderMode syncMode) { FolderMode oldSyncMode = folderSyncMode; folderSyncMode = syncMode; if (syncMode == FolderMode.NONE && oldSyncMode != FolderMode.NONE) { return true; } return syncMode != FolderMode.NONE && oldSyncMode == FolderMode.NONE; }

Target:
If you combine the last two `return` statements you might as well only have one. However, I think the old way makes the code easier to read/understand.
Source:
ImapStore getStore() { return store; }

Target:
Why is this necessary?
Source:
public Builder queryString(String queryString) { command.queryString = queryString; return builder; }

Target:
so much boilerplate :\ would this be easier to do with [AutoValue](https://github.com/google/auto/blob/master/value/userguide/index.md)?
Source:
public void copy_to_ClipBoard(Context context,String address){ com.fsck.k9.helper.ClipboardManager clipboardManager = com.fsck.k9.helper.ClipboardManager.getInstance(context); clipboardManager.setText(address,address); }

Target:
Import the class rather than fully-qualifying.
Source:
public void open_withCompressDeflateCapability_shouldEnableCompression() throws Exception { settings.setUseCompression(true); MockImapServer server = new MockImapServer(); simplePreAuthAndLoginDialog(server, "", "COMPRESS=DEFLATE"); server.expect("3 COMPRESS DEFLATE"); server.output("3 OK"); server.enableCompression(); simplePostAuthenticationDialog(server, false, 4); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }

Target:
Please introduce a new method rather than adding a new argument that is the same non-obvious value almost everywhere.
Source:
private void performSaveAfterChecks() { currentMessageBuilder = createMessageBuilder(true); if (currentMessageBuilder != null) { setProgressBarIndeterminateVisibility(true); currentMessageBuilder.setHighPriority(isHighPriority); currentMessageBuilder.buildAsync(this); } }

Target:
this doesn't belong here
Source:
public void performSendAfterChecks() { currentMessageBuilder = createMessageBuilder(false); if (currentMessageBuilder != null) { changesMadeSinceLastSave = false; currentMessageBuilder.setHighPriority(isHighPriority); setProgressBarIndeterminateVisibility(true); currentMessageBuilder.buildAsync(this); } }

Target:
this should be in createMessageBuilder
Source:
private String getSpecialFoldersList() { String builder = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>" + "<propfind xmlns=\"DAV:\">" + "<prop>" + "<" + WebDavConstants.DAV_MAIL_INBOX_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_DRAFTS_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_OUTBOX_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_SENT_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_TRASH_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_SPAM_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "</prop>" + "</propfind>"; // This should always be ##DavMailSubmissionURI## for which we already have a constant // buffer.append("<sendmsg xmlns=\"urn:schemas:httpmail:\"/>"); return builder; }

Target:
The variable name should now probably be something like `specialFoldersListRequest`.
Source:
public int hashCode() { if(getName().equalsIgnoreCase("INBOX")){ String inbox = new String("INBOX") ; return inbox.hashCode(); } return getName().hashCode(); }

Target:
Just do `return "INBOX".hashCode();` Nice approach though 👍 Should be good to push once you've tidied that.
Source:
public void setBccVisibility(boolean visible) { boolean bccAlreadyVisible = isBccVisible(); bccWrapper.setVisibility(visible ? View.VISIBLE : View.GONE); if(visible && !bccAlreadyVisible){ List<Recipient> bccRecipients = getBccRecipients(); bccView.clear(); bccView.addRecipients(bccRecipients.toArray(new Recipient[0])); } bccDivider.setVisibility(visible ? View.VISIBLE : View.GONE); }

Target:
This removes all recipients and re-adds them, fixing the symptom but not the cause. Do you know what causes the underlying problem? Also, this is more logic than an MvpView class should have
Source:
void onClickRecipientExpander() { recipientMvpView.setCcVisibility(true); recipientMvpView.setBccVisibility(true); if(defaultBccAddress != null) addBccAddresses(defaultBccAddress); updateRecipientExpanderVisibility(); }

Target:
Code style - add a space after the `if` and always use a new line and `{}`'s.
Source:
public void updateAttachmentsList(Attachment attachment){ Attachment originalAttachment = attachments.get(attachment.uri); originalAttachment.updateResizeInfo(attachment.resizeFactor, attachment.overrideDefault); Log.d("ATTACH","Yes : " + attachments.size()); }

Target:
Stick to K9.LOG_TAG and change the logging to be more useful. Also, you'll need to rebase this code to use `Timber` sooner or later.
Source:
public static void clearTemporaryAttachmentsCache(Context context){ File cacheDir = context.getCacheDir(); File tempAttachmentsDirectory = new File(cacheDir.getPath() + RESIZED_ATTACHMENTS_TEMPORARY_DIRECTORY); if(tempAttachmentsDirectory.exists()){ try { FileUtils.cleanDirectory(tempAttachmentsDirectory); } catch (IOException e) { Timber.e("Error occurred while cleaning temporary directory for resized attachments"); e.printStackTrace(); } } }

Target:
Pass the exception into Timber and there's no need to print the stack trace.
Source:
private void resetVisibleLimits() { try { getLocalStore().resetVisibleLimits(getDisplayCount()); } catch (MessagingException e) { Timber.e("Unable to reset visible limits", e); } }

Target:
With Timber exceptions are the first argument. Format string arguments go at the end.
Source:
public void updateDownloadProgress(int newProgress) { progress = newProgress; for (int i = progress; i <= newProgress; i++) { dialog.setProgress(i); } }

Target:
Calling `setProgress()` with intermediate values shouldn't be necessary.
Source:
private void initializeActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowCustomEnabled(true); actionBar.setCustomView(R.layout.actionbar_custom); actionBar.setDisplayHomeAsUpEnabled(true); }

Target:
We didn't use the custom action bar before. No need to use it now.
Source:
public RemoteViewsFactory onGetViewFactory(Intent intent) { return new MessageListRemoteViewFactory(this.getApplicationContext()); }

Target:
`this.` seems unnecessary
Source:
public static boolean isApgInstalled(Context context) { Intent intent = new Intent("org.openintents.openpgp.IOpenPgpService"); intent.setPackage(PACKAGE_NAME_APG); List<ResolveInfo> resInfo = context.getPackageManager().queryIntentServices(intent, 0); return !resInfo.isEmpty(); }

Target:
`queryIntentServices()` might return `null`
Source:
public void getTextFromPart_withUnknownEncoding_shouldReturnNull() throws Exception { part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/plain"); BinaryMemoryBody body = new BinaryMemoryBody("Sample text body".getBytes(), "unknown encoding"); part.setBody(body); assertNull(MessageExtractor.getTextFromPart(part)); }

Target:
Arrange, act, assert. ```java … String textFromPart = MessageExtractor.getTextFromPart(part) ; assertNull(textFromPart); ```
Source:
public void delete_notImplemented() throws MessagingException { ImapFolder folder = createFolder("Folder"); try { folder.delete(false); fail("Error expected"); } catch (Error e) { } }

Target:
`@Test(expectedException = Error.class)`
Source:
public void areMoreMessagesAvailable_withIndexOf1_shouldReturnFalseWithoutPerformingSearch() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); folder.open(OPEN_MODE_RW); boolean result = folder.areMoreMessagesAvailable(1, null); //SELECT during OPEN verify(imapConnection, times(1)).executeSimpleCommand(anyString()); assertFalse(result); }

Target:
`assertFalse(folder.areMoreMessagesAvailable(1, null))`
Source:
public boolean isForceTextMessageFormat() { if (!cryptoEnablePgpInline) { return false; } ComposeCryptoStatus cryptoStatus = getCurrentCryptoStatus(); return cryptoStatus.isEncryptionEnabled() || cryptoStatus.isSigningEnabled(); }

Target:
This is a bit double negativey Wouldn't ``` if (cryptoEnablePgpInline) { ComposeCryptoStatus .... } else { return false; } ``` be more readable.
Source:
private static String cssStyleTheme() { if (K9.getK9MessageViewTheme() == K9.Theme.DARK) { return "<style type=\"text/css\">" + "* { background: black ! important; color: #F3F3F3 !important }" + ":link, :link * { color: #CCFF33 !important }" + ":visited, :visited * { color: #551A8B !important }</style> "; } return ""; }

Target:
If you want to use the exit-early "pattern", invert the `if` condition. Otherwise please use an `else` statement.
Source:
public static MessageViewInfo createWithErrorState(Message message) { return new MessageViewInfo(message, null, null, null, null, null, null); }

Target:
Looks ugly and potentially a source of future NPEs.