auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public final int hashCode() { if (hashCode == Utils.NO_HASHCODE) { hashCode = computeHash(); } return hashCode; }

Target:
I believe this was a suggestion of @dwightguth: if computeHash() returns 0, set the hashCode to 1.
Source:
public TermCons(String psort, List<Term> contents, Production production) { super(psort); cons = ""; this.contents = contents; this.production = production; }

Target:
don't forget this
Source:
public String toString() { return "" + key; }

Target:
Integer.toString?
Source:
public ASTNode visit(TermCons tc, Void _) throws ParseFailedException { ASTNode vis; if (!tc.getProduction().containsAttribute("klabel")) vis = super.visitNode(tc.getContents().get(0), _); else vis = super.visit(tc, _); return vis; }

Target:
this.visitNode?
Source:
public int hashCode() { if (upToDateHash) { cachedHashCode = cons != null ? cons.hashCode() : 0; cachedHashCode = 31 * cachedHashCode + production.hashCode(); for (Term t : contents) cachedHashCode = 31 * cachedHashCode + t.hashCode(); upToDateHash = true; } return cachedHashCode; }

Target:
Well, there's actually a bug here which causes the hashCode returned by this function to always be zero. I suspect if you fix this bug (line 160 should contain the ! operator), you will find that the code no longer works. So yes, technically it's safe, but only because you are currently hashing everything into the same bucket.
Source:
public boolean add(NonTerminal newNT) { if (startNonTerminals.containsKey(newNT.nonTerminalId)) { return false; } else { startNonTerminals.put(newNT.nonTerminalId, newNT); return true; } }

Target:
I don't like that NonTerminal contains a NonTerminalId field, and you also have a Map<NonTerminalId, NonTerminal>. What stops the Map from connecting one NonTerminalId to a NonTerminal with a different NonTerminalId? If you want to maintain a bijection between NonTerminals and their Ids, then you should maintain that bijection in one place, as a BiMap, and then use that as the authoritative source for all ID information. You could even make this class implement BiMap...
Source:
public ASTNode transform(KApp node) throws TransformerException { ASTNode rez = node.getChild().accept(this); if (rez == null) node.setChild(KList.EMPTY); else if (rez instanceof KList) node.setChild((KList) rez); else { KList contents = new KList(); contents.getContents().add((Term) rez); node.setChild(contents); } return node; }

Target:
This seems really weird to me. Better for a transformation of a KList to return a KList than to return an element that gets turned back into a KList by the caller.
Source:
public String toString() { String content = ""; for (Term term : contents) if (term != null) content += term + ","; if (content.length() > 1) content = content.substring(0, content.length() - 2); return "'amb(" + content + ")"; }

Target:
this should not be here anymore if you reverted the change with only 1 comma
Source:
public static BoolToken matchable(Term subject, Term pattern, TermContext context) { PatternMatcher matcher = new PatternMatcher(context); try { matcher.match(subject, pattern); } catch (PatternMatchingFailure e) { return BoolToken.FALSE; } return BoolToken.TRUE; }

Target:
Same question, why a third Exception class?
Source:
public boolean isUnifiable(Index index) { return index instanceof TopIndex || equals(index) || (index instanceof KLabelIndex && ((KLabelIndex) index).kLabel().sorts().contains(sort)); }

Target:
same question
Source:
public boolean isUnifiable(Index index) { return index instanceof TopIndex || equals(index) || (index instanceof TokenIndex && kLabel.sorts().contains(((TokenIndex) index).sort())); }

Target:
I think `syntax Name ::= "$h"`` should actually be `syntax Name ::= Token{$h}`` We should probably have a check in compile for this.
Source:
private static boolean isOptionalProperty(Class beanClass, PropertyDescriptor beanProp) { Field field = getField(beanClass, beanProp.getName()); return field != null ? beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0 || field.getAnnotationsByType(Optional.class).length > 0 : beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0; }

Target:
I meant, `beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0` could be evaluated at the beginning of method: ``` if (beanProp.getReadMethod().getAnnotationsByType(Optional.class).length > 0) return true; Field field = getField(...); return field != null && ...
Source:
public static Config defaultOverrides() { if (!getOverrideWithEnv()) { return systemProperties(); } else { return systemEnvironmentOverrides().withFallback(systemProperties()); } }

Target:
Think it's easier to read if you reverse the if/else to avoid the `!`
Source:
public static ConfigSyntax syntaxFromExtension(String filename) { if (filename == null) return null; if (filename.endsWith(".json")) return ConfigSyntax.JSON; else if (filename.endsWith(".conf")) return ConfigSyntax.CONF; else if (filename.endsWith(".properties")) return ConfigSyntax.PROPERTIES; else return null; }

Target:
this could be an "else if" I think?
Source:
private static boolean isOptionalProperty(Class beanClass, PropertyDescriptor beanProp) { Field field = getField(beanClass, beanProp.getName()); if (field == null) { throw new ConfigException.BadBean("Bean property '" + beanProp + "' of class " + beanClass.getName() + " does not exist"); } return (field.getAnnotationsByType(Optional.class).length > 0); }

Target:
this this exception possible? How did we get beanProp if there's no associated field?
Source:
public Iterable<AbstractConfigNode> children() { return children; }

Target:
this can be final I guess
Source:
static String render(Iterator<Token> tokens) { String renderedText = ""; while (tokens.hasNext()) { renderedText += tokens.next().tokenText(); } return renderedText; }

Target:
StringBuilder would seem more natural for this maybe? Passing in an iterable rather than an iterator might also avoid some bugs (since iterator is mutable and caller may forget to make a copy)
Source:
Substitution(ConfigOrigin origin, boolean optional, List<Token> expression) { super(TokenType.SUBSTITUTION, origin, "${" + (optional? "?" : "") + Tokenizer.render(expression.iterator()) + "}"); this.optional = optional; this.value = expression; }

Target:
this makes me wonder if tokenText() should be virtual instead of final, so we don't need to precompute and keep around a field here that's completely derivable from the other fields we already have.
Source:
public HoeUpgrade() { super(UPGRADE_NAME, "enderio.darksteel.upgrade.hoe", new ItemStack(Items.DIAMOND_HOE), DarkSteelConfig.darkSteelHoeCost.get()); }

Target:
use the `super(String, String, ItemStack, IValue<Integer>)` here, not the `super(String, String, ItemStack, int)` one
Source:
public @Nonnull ItemStack getStackInSlot(int index) { final ItemStack itemStack = items.get(index); return itemStack.isEmpty() ? master.getStackInSlot(index) : itemStack; }

Target:
This actually is a logic error. It must be possible to have an empty itemstack in the shadow inventory override an existing one in the shadowed one...
Source:
public void removeTarget(TelepadTarget target) { if (target == null) { return; } for (TelepadTarget t : targets) { if (target.equals(t)) { targets.remove(t); } } markDirty(); }

Target:
* CME? * Isn't that exactly what remove() does? Removing on equals()...
Source:
public IItemFilter read(@Nonnull Registry registry, @Nonnull Set<NBTAction> phase, @Nonnull NBTTagCompound nbt, @Nullable Field field, @Nonnull String name, @Nullable IItemFilter object) throws IllegalArgumentException, IllegalAccessException, InstantiationException, NoHandlerFoundException { if (object == null) { // Note: This will be called with no nbt when a fresh itemstack is placed---output should be null! if (nbt.hasKey(name)) { object = FilterRegistry.loadFilterFromNbt(nbt.getCompoundTag(name)); } else { return object; } } object.readFromNBT(nbt.getCompoundTag(name)); return object; }

Target:
fallthrough to `readFromNBT` in line 47. Intended?
Source:
public final void updateEntity() { if (Config.allowExternalTickSpeedup || worldObj == null || worldObj.getTotalWorldTime() != lastUpdate) { lastUpdate = worldObj.getTotalWorldTime(); doUpdate(); if (isProgressTile && !worldObj.isRemote) { int curScaled = getProgressScaled(16); if (++ticksSinceLastProgressUpdate >= getProgressUpdateFreq() || curScaled != lastProgressScaled) { sendTaskProgressPacket(); lastProgressScaled = curScaled; } } } }

Target:
OR if `worldObj == null`? This means this is getting called if the world object is null..... I guess you want ANDs here.
Source:
public static void addCommonTooltipFromResources(List list, ItemStack itemstack) { if(itemstack.getItem() == null) { return; } String unloc = null; if (itemstack.getItem() instanceof IResourceTooltipProvider) { unloc = ((IResourceTooltipProvider)itemstack.getItem()).getUnlocalizedNameForTooltip(itemstack); } if(unloc == null) { unloc = itemstack.getItem().getUnlocalizedName(itemstack); } addCommonTooltipFromResources(list, unloc); }

Target:
This is now duplicated code from below. Should extract this into a private helper method that is called from multiple places.
Source:
public void stopQueue() { if (isStarted.compareAndSet(true, false)) { isInitialized.set(false); super.stopQueue(); reaper.stop(); dao.close(); dispatcher.stop(); } }

Target:
Not sure if it matters but shouldn't the reaper be stopped first (so it doesn't move entries after the queue is stopped)? Also, shouldn't the `dao` be the last one to stop?
Source:
private static boolean copyDescription( RtpDescriptionPacketExtension description, ColibriConferenceIQ.Channel channel) { boolean added = false; for (PayloadTypePacketExtension payloadType : description.getPayloadTypes()) { channel.addPayloadType(payloadType); added = true; } for (RTPHdrExtPacketExtension rtpHdrExt : description.getExtmapList()) { channel.addRtpHeaderExtension(rtpHdrExt); added = true; } return added; }

Target:
my only hesitation with 'copy' was that we don't actually do a deep copy of the header extensions (just add the references), but if you don't think that's a big deal then i'm fine with `copyDescriptionToChannel`
Source:
public void setUp() { try { xmlPullParserFactory = XmlPullParserFactory.newInstance(); xmlPullParserFactory.setNamespaceAware(true); xmlPullParser = xmlPullParserFactory.newPullParser(); } catch (XmlPullParserException e) AbstractSmackInteroperabilityLayer.setImplementationClass( SmackV3InteroperabilityLayer.class); colibriIQProvider = new ColibriIQProvider(); }

Target:
While we're at it, please move the braces to new lines (and the identation is wrong too).
Source:
public Object[] getExpectedResultsForHive() { return new Object[]{ new Integer(1), new BigDecimal("100"), new BigDecimal("1000000"), new BigDecimal("1000000.05000"), new BigDecimal("1000000"), new BigDecimal("1000000.05000"), new BigDecimal("100"), new BigDecimal("1000000"), new BigDecimal("1000000.05000"), new BigDecimal("1000000"), new BigDecimal("1000000.05000") }; }

Target:
Source of code duplication again! I would move these expected values into a helper class or a super class (choice is up to you).
Source:
public void testImportWithPadding() throws IOException { if(failWithPadding){ thrown.expect(IOException.class); thrown.expectMessage("Failure during job; return status 1"); NumericTypesTestUtils.configureJunitToExpectFailure(thrown); } ArgumentArrayBuilder builder = getArgsBuilder(); NumericTypesTestUtils.addPadding(builder); runImport(builder.build()); if (!failWithPadding) { verify(); } }

Target:
This method seems to be doing the same thing as the previous line.
Source:
public PDataType getDataType() { // WE need to implement getDataType for which need to check the datatype if (baseType == null) { PDataType elementType = null; for (int i = 0; i < children.size(); i++) { Expression child = children.get(i); // Should we check for mismatch here? I think not needed here if (child.getDataType() != elementType) { elementType = child.getDataType(); } } baseType = elementType; } return PDataType.fromTypeId(baseType.getSqlType() + Types.ARRAY); }

Target:
Do this check in the constructor instead (or a static factory method). You'll want to be careful in how you calculate the baseType and you'll definitely want to throw if you can't find a baseType for which all elements are coercibleTo. You basically want to find the common base PDataType. Something like the first loop in CaseExpression: ``` private static List<Expression> coerceIfNecessary(List<Expression> children) throws SQLException { ```
Source:
public boolean evalToNullIfParamIsNull(StatementContext context, int index) throws SQLException { return false; }

Target:
Though not strictly necessary, I think this would read better as return index == 0, as this indicates that other parameters are ok to be null.
Source:
public ExpressionProjector(String name, String tableName, Expression expression, boolean isCaseSensitive) { this.name = name; this.expression = expression; this.tableName = tableName; this.isCaseSensitive = isCaseSensitive; this.arrayIndex = -1; }

Target:
Remove this change please, as it should not be necessary.
Source:
public static Expression create(Expression expression, PDataType toType) throws SQLException { final PDataType dataType = expression.getDataType(); if (toType != null && !dataType.isCoercibleTo(toType)) { throw new TypeMismatchException(dataType, toType, expression.toString()); } return toType == dataType ? expression : expression instanceof LiteralExpression ? LiteralExpression.newConstant(((LiteralExpression)expression).getValue(), toType) : new CoerceExpression(expression, toType); }

Target:
Let's move the isCoercibleTo check from the CoerceExpression.create() to the visit method for your CastParseNode in ExpressionCompiler. There are cases where we know we'll be able to coerce, even though it's not always allowed.
Source:
public Object toObject(String value) { // TODO: How can this be done? throw new IllegalDataException("This operation is not suppported"); }

Target:
This is basically like a load of a String in CSV format. Take a look at CSVLoader for how we use au.com.bytecode.opencsv.CSVReader (an open source CSV reader). This isn't crucial, though, so how about if we just TODO it for now?
Source:
public KeyValueColumnExpression(PColumn column) { super(column); this.cf = column.getFamilyName().getBytes(); this.cq = column.getName().getBytes(); this.maxLength = column.getMaxLength(); this.scale = column.getScale(); }

Target:
I think this logic should be in the super class b/c it'll apply for RowKeyColumnExpression too
Source:
public PTableStatsImpl() { regionGuidePosts = new HashMap<String, byte[][]>(); }

Target:
Don't need this - regionGuidePosts is either set in the other constructor or set in the readFields method.
Source:
public ReadOnlyTableException(String message) { super(SQLExceptionInfo.getNewInfoObject(code).setMessage(message).toString(), code.getSQLState()); }

Target:
Here too for message - remove if we can get away with it.
Source:
public static boolean delete(File file) { Assert.notNull(file, "File to delete must not be null."); return delete(file, false); }

Target:
This could be replaced by this code: http://www.adam-bien.com/roller/abien/entry/java_7_deleting_recursively_a
Source:
protected boolean matchesSafely(T item) { if (condition.matches(itemToMatchCondition)) { return matcher.matches(item); } else { Description conditionDescription = new StringDescription() .appendValue(itemToMatchCondition) .appendDescriptionOf(condition); throw new AssumptionViolatedException( String.format("Condition is not satisfied: %s", conditionDescription)); } }

Target:
no need to define `else` explicitly
Source:
protected void damageTool(GlowPlayer player, ItemStack holding, int damage) { if (player.getGameMode() == GameMode.CREATIVE || damage == 0) { return; } holding.setDurability((short) (holding.getDurability() + damage)); if (holding.getDurability() == maxDurability + damage) { EventFactory.callEvent(new PlayerItemBreakEvent(player, holding)); player.getInventory().remove(holding); } }

Target:
Why `damage == 0`?
Source:
protected boolean canTakeDamage(EntityDamageEvent.DamageCause damageCause) { return gameMode == GameMode.SURVIVAL || gameMode == GameMode.ADVENTURE && super.canTakeDamage(damageCause); }

Target:
This will evaluate incorrectly
Source:
public Rotation getRotation() { switch (rot) { case 0: return Rotation.NONE; case 1: return Rotation.NONE; case 2: return Rotation.CLOCKWISE; case 3: return Rotation.CLOCKWISE; case 4: return Rotation.FLIPPED; case 5: return Rotation.FLIPPED; case 6: return Rotation.COUNTER_CLOCKWISE; case 7: return Rotation.COUNTER_CLOCKWISE; } return Rotation.NONE; }

Target:
This switch can be reduced as follows: ``` java case 0: case 1: return Rotation.NONE; case 2: case 3: return Rotation.CLOCKWISE; // ... ```
Source:
public void playSound(Location location, Sound sound, float volume, float pitch) { if (location == null || sound == null) return; final double radiusSquared = Math.pow(volume > 1 ? volume * 16 : 16, 2); for (Player player : getRawPlayers()) { if (player.getLocation().distanceSquared(location) <= radiusSquared) { player.playSound(location, sound, volume, pitch); } } }

Target:
What was the issue?
Source:
ToolType(Material bukkitMaterial, ToolType better) { this.bukkitMaterial = bukkitMaterial; this.better = better; }

Target:
Should be `private`
Source:
private void traceBlockPowerStartSolid(GlowBlock srcBlock, RSManager rsManager, BlockFace toDir, boolean isDirect) { // Get the destination block and ensure that it is suitable. GlowBlock destBlock = srcBlock.getRelative(toDir); if (destBlock == null) { return; } Material destMat = destBlock.getType(); if (destMat == Material.REDSTONE_WIRE) { // Will trace } else { return; } // Trace to target. rsManager.traceFromBlock(srcBlock, toDir, 15, isDirect); }

Target:
Reduces to `if (destMat != Material.REDSTONE_WIRE) return;`
Source:
public void sendBlockEntityChange(Location location, CompoundTag nbt, GlowBlockEntity type) throws NullPointerException { Validate.notNull(location, "Location cannot be null"); Validate.notNull(nbt, "NBT cannot be null"); Validate.notNull(type, "Type cannot be null"); afterBlockChanges.add(new UpdateBlockEntityMessage(location.getBlockX(), location.getBlockY(), location.getBlockZ(), type.getValue(), nbt)); }

Target:
throws is not required
Source:
public boolean add(E object) { switch (additionMode) { case ALL: { int modified = 0; for (Collection<E> parent : parents) { if (parent.add(object)) { modified++; } } return resultBoolean(modified); } case LAST: { return parents.get(parents.size() - 1).add(object); } } throw new IllegalStateException("This SuperCollection has an invalid addition mode!"); }

Target:
We don't use braces on case statements. Please don't use them and use break/return where needed.
Source:
public GlowHorse(Location location) { super(location, EntityType.HORSE); Random rand = new Random(); // Todo make this cleaner and safer to use for spawning random horses this.variant = Variant.HORSE; this.horseStyle = Style.values()[rand.nextInt(4)]; this.horseColor = Color.values()[rand.nextInt(6)]; }

Target:
Why not call the other constructor?
Source:
public void updatePhysics(GlowBlock me) { Block below = me.getRelative(BlockFace.DOWN); switch (below.getType()) { case AIR: FIRE: WATER: LAVA: transformToFallingEntity(me); } }

Target:
Missing `case` x3 as these are labels, not cases.
Source:
public Material getType() { Material mat = Material.getMaterial(getTypeId()); return (mat == null ? Material.AIR : mat); }

Target:
Something that is an unknown type is not air.
Source:
public int getBlockPower(BlockFace face) { BlockType type = ItemTable.instance().getBlock(getType()); if(type == null) { return 0; } return (type.canBlockEmitPower(this, face, false) ? getWorld().getRSManager().getBlockPower(this) : 0); }

Target:
It doesn't fit the style guidelines. Also the parenthesis need to be removed.
Source:
public void onlyApprovedCode() { onlyApprovedCode(true); }

Target:
should this be false here?
Source:
private boolean containsComment(GHPullRequest ghPullRequest, String expectedBody) { List<GHIssueComment> prComments = null; try { prComments = ghPullRequest.getComments(); } catch (IOException e) { logger.log(Level.WARNING, "Failed to get comments for PR " + ghPullRequest, e); return false; } for (GHIssueComment comment : prComments) { if (comment.getBody() != null && comment.getBody().contains(expectedBody)) { return true; } } return false; }

Target:
i think contains is not the thing we are looking for. the body should exactly match the expected content, no?
Source:
public GhprbGitHubAuth getGitHubApiAuth() { if (gitHubAuthId == null) { GhprbGitHubAuth auth = getDescriptor().getGithubAuth().get(0); gitHubAuthId = auth.getId(); getDescriptor().save(); return auth; } return getDescriptor().getGitHubAuth(gitHubAuthId); }

Target:
This assumes that there will always be at least one entry, which it is possible there may not be.
Source:
public String postBuildComment(AbstractBuild<?, ?> build, TaskListener listener) { return "\nRefer to this link for build results (access rights to CI server needed): \n" + generateCustomizedMessage(build) + "\n"; }

Target:
The StringBuilder is cleaner and more readable. It also allows for easier expansion or editing.
Source:
public void check(GHPullRequest ghpr) { setPullRequest(ghpr); if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring pull request"); return; } try { getPullRequest(false); } catch (IOException e) { logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e); return; } updatePR(pr, pr.getUser()); checkSkipBuild(pr); tryBuild(); }

Target:
I think this (and tryBuild) needs to be under a synch too, because shouldRun will be updated.
Source:
public boolean matches(ScriptPath path) { String mob = path.eventArgLowerAt(1); if (!mob.equals("mob") && runGenericCheck(mob, mythicmob.getMobType().getInternalName())) { return false; } if (!runInCheck(path, location)) { return false; } return super.matches(path); }

Target:
weird newline
Source:
private void reloadData(Quester quester) { if (quester == null) return; quester.saveData(); quester.loadData(); }

Target:
use `{}` for all if statements, even single-line ones.
Source:
public String getAttribute(Attribute attribute) { if (attribute == null) { return null; } //Getting the ViaVersion API object ViaAPI api = Via.getAPI(); // <--[tag] // @attribute <PlayerTag.viaversion> // @returns ElementTag(Number) // @description // Returns the protocol version number of the player's client. // See https://wiki.vg/Protocol_version_numbers as a reference list. // @Plugin Depenizen, ViaVersion. // --> if (attribute.startsWith("viaversion")) { return new ElementTag(api.getPlayerVersion(player.getOfflinePlayer().getUniqueId())) .getAttribute(attribute.fulfill(1)); } return null; }

Target:
This should be INSIDE the attribute `if` block, not outside.
Source:
protected TreeSet<CClassType> getTypes() { TreeSet<CClassType> t = new TreeSet<>(Comparator.comparing(CClassType::getFQCN)); for(FullyQualifiedClassName type : types) { try { t.add(CClassType.get(type)); } catch (ClassNotFoundException ex) { // This can't happen, because throw new Error(ex); } } return t; }

Target:
[Dependency Inversion](https://en.wikipedia.org/wiki/Dependency_inversion_principle) is the preferred approach here, so still want to return Set, as well as use Set on the lhs of the assignment.
Source:
public boolean modifyEvent(String key, Construct value, BindableEvent event) { if(event instanceof MCPlayerVelocityEvent) { if(key.equalsIgnoreCase("velocity")) { Vector3D v3d = ObjectGenerator.GetGenerator().vector(value, Target.UNKNOWN); Vector vector = new Vector(v3d.X(), v3d.Y(), v3d.Z()); ((MCPlayerVelocityEvent) event).setVelocity(vector); return true; } } return false; }

Target:
Part 4: This particular usage can be avoided... (see part 5)
Source:
public void setGlowing(Boolean glow) { if(ReflectionUtils.hasMethod(e.getClass(), "setGlowing", null)) { // Added around 1.9 e.setGlowing(glow); } }

Target:
These (glowing methods) were added on day 1 of 1.9 builds, so no check is required here.
Source:
public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "char_is_uppercase('a')"), new ExampleScript("", "char_is_uppercase('D')"),}; }

Target:
Also need "Basic usage" here too
Source:
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { MCLivingEntity e = Static.getLivingEntity(args[0], t); boolean glide = Static.getBoolean(args[1]); if (e.isOnGround()) { throw new CREException("The specified entity cannot glide right now", t); } e.setGliding(glide); return CVoid.VOID; }

Target:
If we're going to do this, it should probably be mentioned in the docs. Do we need to check if grounded? As far as I can tell, it would just revert to not gliding immediately.
Source:
public Construct exec(Target target, Environment environment, Construct... args) throws ConfigRuntimeException { MCPlayer player = environment.getEnv(CommandHelperEnvironment.class).GetPlayer(); MCWorld world = null; if(player != null) { world = player.getWorld(); } MCLocation loc = ObjectGenerator.GetGenerator().location(args[0], world, target); double temp; temp = loc.getBlock().getTemperature(); return new CDouble(temp, target); }

Target:
In this case, you can combine that last 3 lines into "return new CDouble(loc.getBlock().getTemperature(), target);
Source:
public Boolean runAsync() { return true; }

Target:
Does this NEED to be async?
Source:
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException { if (args.length < 1) { throw new ConfigRuntimeException("bit_xor requires at least one argument", ExceptionType.InsufficientArgumentsException, t); } long val = Static.getInt(args[0], t); for (int i = 1; i < args.length; i++) { val = val ^ Static.getInt(args[i], t); } return new CInt(val, t); }

Target:
Does this make sense with just one value? Also, here's a neat trick, you can turn insufficient arguments into a compiler error. implement optimizeDynamic, throw a ConfigCompileException if children.size() < minSize, then return null.
Source:
MCCriteria(String crit) { this.criteria = crit; }

Target:
Should be private, not package protected.
Source:
public void onTrimMemory(int level) { if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) { //Log.d(TAG, "app went to background"); isInBackground = true; } if (level >= android.content.ComponentCallbacks2.TRIM_MEMORY_MODERATE) { MemoryCacheHelper.trimMemory(); } }

Target:
> I'm sure There are better ways of doing this but this is what came to me at that moment. You shouldn't code like that, it makes the code worse than the best you can achieve.
Source:
static Spanned enrichText(String text, List<Pair<Integer, Integer>> positions, Context context) { SpannableString enriched = new SpannableString(text); int primaryColor = UIColors.getPrimaryColor(context); for (Pair<Integer, Integer> position : positions) { enriched.setSpan( new ForegroundColorSpan(primaryColor), position.first, position.second, Spannable.SPAN_INCLUSIVE_INCLUSIVE ); } return enriched; }

Target:
do you need to create a new one everytime?
Source:
public static int getPrimaryColor(Context context) { if (primaryColor == -1) { String primaryColorStr = PreferenceManager.getDefaultSharedPreferences(context).getString("primary-color", COLOR_DEFAULT_STR); // Transparent can't be displayed for text color, replace with light gray. if (primaryColorStr.equals("#00000000") || primaryColorStr.equals(("#AAFFFFFF"))) { return 0xFFBDBDBD; } primaryColor = Color.parseColor(primaryColorStr); } return primaryColor; }

Target:
You probably shouldn't return anymore
Source:
public void setTags(String tags) { // Set the actual user-friendly name this.tags = tags; if (tags != null) { this.tags = this.tags.replaceAll("<", "&lt;"); // Normalize name for faster searching Pair<String, int[]> normalized = StringNormalizer.normalizeWithMap(this.tags); this.tagsNormalized = normalized.first; this.tagsPositionMap = normalized.second; } }

Target:
Check with `this.tags`?
Source:
public int mapTagsPosition(int position) { if (this.tagsPositionMap != null) { if (position < this.tagsPositionMap.length) { return this.tagsPositionMap[position]; } else { return this.tags.length(); } } else { // No mapping defined if (position < this.tags.length()) { return position; } else { return this.tags.length(); } } }

Target:
No need for else if you return in the previous if
Source:
private void updatePrimaryButtonEnabledStatus() { View view = getView(); if (view != null) { String currentPassword = mPasswordInput.getEditText().getText().toString(); getPrimaryButton().setEnabled(!currentPassword.trim().isEmpty()); } }

Target:
Why exactly do we need to check this here?
Source:
private void performPrimaryAction() { switch (getPrimaryAction()) { case PUBLISH_NOW: case UPDATE: case SCHEDULE: case SUBMIT_FOR_REVIEW: mAnalyticsTrackerWrapper.track(Stat.EDITOR_POST_PUBLISH_TAPPED); showPrepublishingNudgeBottomSheet(); return; case SAVE: uploadPost(false); break; } }

Target:
I might have asked this already, but I forgot the explanation, sorry. Is it okay that we track `EDITOR_POST_PUBLISH_TAPPED` for all the actions (not just "publish")?
Source:
protected void next(String email) { if (!NetworkUtils.checkConnection(getActivity())) { return; } if (isValidEmail(email)) { clearEmailError(); startProgress(); mRequestedEmail = email; mDispatcher.dispatch(AccountActionBuilder.newIsAvailableEmailAction(email)); mAnalyticsListener.trackEmailFilled(); } else { showEmailError(R.string.email_invalid); } }

Target:
Since we're tracking this event after the user taps the next button and only when the email is valid, maybe we shouldn't call it "email filled", as it may be misinterpreted as the user just filling in the email input. Does that make sense to you? To be honest, I'm not even sure why we need this event. 🤔 What's the idea here?
Source:
public MePage go() { // Using the settings button as a marker for successfully navigating to the page while (!isElementDisplayed(appSettings)) { clickOn(R.id.nav_sites); clickOn(onView(allOf(withId(R.id.me_item), withEffectiveVisibility(Visibility.VISIBLE)))); } if (!isSelfHosted()) { displayName.check(matches(isDisplayed())); } return this; }

Target:
Given that `clickOn` is our own custom click action, I don't love modifying the element we're passing it here. It feels cleaner to update the `clickOn` method itself to better handle scenarios like this. What do you think?
Source:
public static boolean isPublishDateInTheFuture(String dateCreated) { Date pubDate = DateTimeUtils.dateFromIso8601(dateCreated); Date now = new Date(); return pubDate != null && pubDate.after(now); }

Target:
We might want to consider calling the new method from this one so we don't duplicate code `isPublishDateInTheFuture(dateCreated, new Date())` wdyt?
Source:
public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_SMARTLOCK_HELPER_STATE, mSmartLockHelperState.name()); outState.putBoolean(KEY_SIGNUP_FROM_LOGIN_ENABLED, mIsSignupFromLoginEnabled); outState.putBoolean(KEY_SIGNUP_FROM_LOGIN_ENABLED, mIsSignupFromLoginEnabled); }

Target:
This looks like a copy/paste typo maybe?
Source:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); if (args != null) { mIsSignupFromLoginEnabled = args.getBoolean(ARG_SIGNUP_FROM_LOGIN_ENABLED, false); } }

Target:
These `Override`s are generally on separate lines (I don't think our styles are set up correctly but check the rest of this file)
Source:
public void configureResources(Context context) { if (context == null) { return; } mNormalTextColor = ContextExtensionsKt.getColorFromAttribute(context, R.attr.colorOnSurface); mNormalBackgroundColor = ContextExtensionsKt.getColorFromAttribute(context, R.attr.colorSurface); mAgoTextColor = ContextExtensionsKt.getColorFromAttribute(context, R.attr.wpColorOnSurfaceMedium); mUnapprovedTextColor = ContextExtensionsKt.getColorFromAttribute(context, R.attr.wpColorWarningDark); // Double margin_extra_large for increased indent in comment replies mIndentedLeftPadding = context.getResources().getDimensionPixelSize(R.dimen.margin_extra_large) * 2; }

Target:
I think this white line can be removed.
Source:
public void updateFeaturedImage(long featuredImageId) { EditPostRepository postRepository = getEditPostRepository(); if (postRepository == null) { return; } postRepository.update(postModel -> { postModel.setFeaturedImageId(featuredImageId); updateFeaturedImageView(); if (featuredImageId != 0) { mFeaturedImageHelper.trackFeaturedImageEvent( FeaturedImageHelper.TrackableEvent.IMAGE_PICKED, postModel, OriginType.EDIT_POST_SETTINGS ); } return true; }); }

Target:
It seems `updateFeaturedImage` is called from `EditPostActivity` when 1) media which exists in the remote gets selected 2) after a media which doesn't exist in the remote gets uploaded Case `1` is fine, but I'm wondering if case `2` is what we want to track. Or do we rather want to track the actual click/selection of the media - no matter what happens with the upload? Wdyt?
Source:
public void onContinue() { if (mSiteStore.hasSite()) { setResult(RESULT_OK); } else if (AppPrefs.shouldShowPostSignupInterstitial()) { ActivityLauncher.showPostSignupInterstitial(this); } finish(); }

Target:
Here, I think we shouldn't check for the preference value and always show the interstitial. I can't think of any use case where we shouldn't nudge new users to create a new site.
Source:
private static String toHtml(SpannableStringBuilder builder, AztecParser parser) { clearMetaSpans(builder); parser.syncVisualNewlinesOfBlockElements(builder); Format.postProcessSpannedText(builder, true); return EndOfBufferMarkerAdder.removeEndOfTextMarker(parser.toHtml(builder, false, false)); }

Target:
I think we can use the `@JvmOverloads` annotation in the Aztec method in Kotlin to allow the Java side to call the method without the new extra parameter). Check out [this answer on SO](https://stackoverflow.com/a/34518024).
Source:
private void viewPages() { requestNextStepOfActiveQuickStartTask(); SiteModel selectedSite = getSelectedSite(); if (selectedSite != null) { ToastUtils.showToast(getActivity(), R.string.site_cannot_be_loaded); ActivityLauncher.viewCurrentBlogPages(requireActivity(), selectedSite); } }

Target:
Shouldn't this line be in an `else` clause? Wdyt?
Source:
@NonNull @Override public String getEditorName() { return AZTEC_EDITOR_NAME; }

Target:
NIT: move these to separate lines?
Source:
@Override public void helpHandleDiscoveryError( String siteAddress, String endpointAddress, String username, String password, String userAvatarUrl, int errorMessage) { // Not used in WordPress app }

Target:
I think the annotations should be on separate lines
Source:
public boolean isAtLeastOneSettingsEnabled( JSONObject settingsJson, String[] settingsArray, String[] settingsValues ) { boolean atLeastOneOptionEnabled = false; if (settingsJson != null && settingsArray.length == settingsValues.length) { for (int i = 0; i < settingsArray.length; i++) { String settingValue = settingsValues[i]; boolean isChecked = JSONUtils.queryJSON(settingsJson, settingValue, true); if (isChecked) { atLeastOneOptionEnabled = true; } } } return atLeastOneOptionEnabled; }

Target:
NIT: you can `return true` at this point and `return false` at the end of this method.
Source:
public static void addPostWithHWAccelerationOff(int localSiteId, int localPostId) { if (localSiteId == 0 || localPostId == 0 || isPostWithHWAccelerationOff(localSiteId, localPostId)) { return; } String key = localSiteId + "-" + localPostId; List<String> currentIds = getPostWithHWAccelerationOff(); currentIds.add(key); // store in prefs String idsAsString = TextUtils.join(",", currentIds); setString(DeletablePrefKey.AZTEC_EDITOR_DISABLE_HW_ACC_KEYS, idsAsString); }

Target:
Let's make this line `List<String> currentIds = new ArrayList<String>(getPostWithHWAccelerationOff());`, given `getPostWithHWAccelerationOff()` returns an `Arrays.asList()` which is a "fixed-size list" as per [the docs](https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...)), and thus the following line of code `currentIds.add(key);` will crash otherwise
Source:
protected void onPostExecute(UploadPostTaskResult result) { switch (result) { case ERROR: mPostUploadNotifier.incrementUploadedPostCountFromForegroundNotification(mPost); mPostUploadNotifier.updateNotificationErrorForPost(mPost, mSite, mErrorMessage, 0); finishUpload(); break; case NOTHING_TO_UPLOAD: mPostUploadNotifier.incrementUploadedPostCountFromForegroundNotification(mPost); finishUpload(); break; case PUSH_POST_DISPATCHED: // will be handled in OnPostChanged break; } }

Target:
I am guessing the work we do in this `case` is necessary for cleanup. (just trying to make sure I am not missing anything in the review)
Source:
private void primaryAction() { switch (getPrimaryAction()) { case UPDATE: showUpdateConfirmationDialogAndUploadPost(); return; case PUBLISH_NOW: showPublishConfirmationDialogAndPublishPost(); return; case SCHEDULE: uploadPost(false); return; // In other cases, we'll upload the post without changing its status case SUBMIT_FOR_REVIEW: case SAVE: uploadPost(false); break; } }

Target:
We can move this to the "other cases" below: ```java // In other cases, we'll upload the post without changing its status case SCHEDULE: case SUBMIT_FOR_REVIEW: case SAVE: uploadPost(false); break; ```
Source:
private void checkIfUsernameCanBeChanged() { AccountModel account = mAccountStore.getAccount(); mUsernamePreference.setEnabled(account.getUsernameCanBeChanged()); mUsernamePreference.setOnPreferenceClickListener(preference -> { showUsernameChangerFragment(); return false; }); }

Target:
I'm wondering if we should return "true" here. Wdyt?
Source:
public void onBackPressed() { androidx.fragment.app.Fragment fragment = getSupportFragmentManager() .findFragmentByTag(ImageSettingsDialogFragment.IMAGE_SETTINGS_DIALOG_TAG); if (fragment != null && fragment.isVisible()) { ((ImageSettingsDialogFragment) fragment).dismissFragment(); } else { super.onBackPressed(); } }

Target:
I think that there is no need for a full package path as we already have import on the top of the file?
Source:
public void start(ArrayList<Object> unsupportedBlocksList) { if (!mStarted) { Map<String, Object> properties = getCommonProperties(); mHasUnsupportedBlocks = unsupportedBlocksList != null && unsupportedBlocksList.size() > 0; properties.put(KEY_UNSUPPORTED_BLOCKS, unsupportedBlocksList != null ? unsupportedBlocksList : new ArrayList<>()); AnalyticsTracker.track(Stat.EDITOR_SESSION_START, properties); mStarted = true; } else { AppLog.w(T.EDITOR, "An editor session cannot be attempted to be started more than once, " + "unless it's due to rotation or Editor switch"); } }

Target:
Hmm, actually, we need to compute `mHasUnsupportedBlocks` before the getCommonProperties() call because it's used there.
Source:
public void setUp() { logoutIfNecessary(); stubFor(get(urlEqualTo("/rest/v1.1/me/")) .inScenario("Sign up") .whenScenarioStateIs(Scenario.STARTED)); }

Target:
We probably shouldn't use the WireMock Java API like this as it will not be possible to do for iOS. It should be possible to do this from the JSON files.
Source:
public void setup() { stubFor(get(urlEqualTo("/rest/v1.1/me/")) .inScenario("Sign up") .whenScenarioStateIs("No")); mAppContext = (WordPress) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext(); mMockedAppComponent = DaggerAppComponentTest.builder() .application(mAppContext) .build(); }

Target:
Here as well. We will need to replace this with the equivalent JSON mock.
Source:
private void showDomainCreditsCheckProgressDialog() { if (mCheckingDomainCreditsProgressDialog == null) { mCheckingDomainCreditsProgressDialog = new ProgressDialog(this); mCheckingDomainCreditsProgressDialog.setCancelable(false); mCheckingDomainCreditsProgressDialog.setIndeterminate(true); mCheckingDomainCreditsProgressDialog .setMessage(getString(R.string.plugin_check_domain_credits_progress_dialog_message)); } if (!mCheckingDomainCreditsProgressDialog.isShowing()) { mCheckingDomainCreditsProgressDialog.show(); } }

Target:
I think setting cancelable to false can result in an infinite dialog since the `OnPlansFetched` event may get lost during a configuration change. I think this isn't handled in many places in the app, but I just wanted to mention it. We may want to consider either allowing the user to cancel the dialog or setting @Subscribe(sticky=true,..) and handle it appropriately. Wdyt?
Source:
protected void onPostExecute(Spanned spanned) { if (mPost != null && spanned != null) { mTextView.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); mWebView.loadDataWithBaseURL("file:///android_asset/", spanned.toString(), "text/html", "utf-8", null); } mLoadTask = null; }

Target:
I think we can remove `mTextView` now since we always end up hiding it. It might be a good opportunity to clean up this `Fragment` a bit. I ended up making a bunch of changes while I was trying things out, so I thought to just commit it somewhere to share some proposed changes with you: https://github.com/wordpress-mobile/WordPress-Android/commit/c52dfc0100d36276d67465113ad85b607c44461c We don't have to make any of those changes of course, so it's totally up to you. Feel free to cherry-pick the commit or just re-commit in this branch if you do like it.
Source:
public void onCompletedTasksListToggled(boolean isExpanded) { if (!mQuickStartStore.getUncompletedTasksByType(AppPrefs.getSelectedSite(), mTasksType).isEmpty()) { return; } toggleCompletedView(!isExpanded); }

Target:
Exiting early can help flatten multiple nested `if` statements or simplify a complex conditional statement. In this case, there aren't nested statements and the early exit is slightly more complicated than not. What do you think about this? ```java @Override public void onCompletedTasksListToggled(boolean isExpanded) { if (mQuickStartStore.getUncompletedTasksByType(AppPrefs.getSelectedSite(), mTasksType).isEmpty()) { toggleCompletedView(!isExpanded); } } ```
Source:
private static IAtomContainer parseSmiles(String smiles) throws CDKException { parser = new SmilesParser(SilentChemObjectBuilder.getInstance()); IAtomContainer molecule = parser.parseSmiles(smiles); AtomContainerManipulator.percieveAtomTypesAndConfigureUnsetProperties(molecule); CDKHydrogenAdder hAdder = CDKHydrogenAdder.getInstance(molecule.getBuilder()); hAdder.addImplicitHydrogens(molecule); AtomContainerManipulator.convertImplicitToExplicitHydrogens(molecule); Aromaticity.cdkLegacy().apply(molecule); return molecule; }

Target:
Mmm... this should not actually be needed... I think this is actually done by the `SmilesParser` already. @johnmay ?
Source:
public void close() { input.close(); }

Target:
Build failed: Need to throw IOException or catch it ``` public void close(){ try { if (input != null) input.close() } catch (IOException e) { // ignored } } ```
Source:
public void testNumberOfUnplacedHeavyAtoms_IAtomContainer(){ IAtomContainer ac = AtomPlacer3DTest.makeAlphaPinene(); int count=new AtomPlacer3D().numberOfUnplacedHeavyAtoms(ac); Assert.assertEquals(10,count); }

Target:
I would tend to leave off the static class definition such that this would read `IAtomContainer ac = makeAlphaPinene();`. Thoughts?
Source:
private EnvVars buildEnv(final Job<?, ?> job) { EnvVars env = new EnvVars(); for (EnvironmentContributor contributor : EnvironmentContributor.all()) { try { contributor.buildEnvironmentFor(job, env, TaskListener.NULL); } catch (Exception e) { LOGGER.warning("failed to build env, skipping"); } } return env; }

Target:
finals for EnvVars and EnvironmentContributor in the for
Source:
private EnvVars addVarsToBuildEnv(final EnvVars envs, final ArrayList<ParameterValue> vars) { for (ParameterValue p : vars) { envs.putIfNotNull(p.getName(), String.valueOf(p.getValue())); } return envs; }

Target:
final?
Source:
private String getStartedBy(final Run run) { final Cause.UserIdCause cause = (Cause.UserIdCause) run.getCause(Cause.UserIdCause.class); final String startedBy; if (cause != null) { startedBy = cause.getUserId(); } else { startedBy = null; } return startedBy == null ? "" : startedBy; }

Target:
I think this would be simpler without the 'final' and the 'else' clause. Just initialize to 'null'.
Source:
RedirectAuthoritativeDnsServerCache(AuthoritativeDnsServerCache authoritativeDnsServerCache) { // Unwrap to prevent the possibility of an StackOverflowError when wrapping another // RedirectAuthoritativeDnsServerCache. if (authoritativeDnsServerCache instanceof RedirectAuthoritativeDnsServerCache) { this.wrapped = ((RedirectAuthoritativeDnsServerCache) authoritativeDnsServerCache).wrapped; } else { this.wrapped = authoritativeDnsServerCache; } }

Target:
Consider the opposite approach: write a utility method that will wrap only if it's not an instance of `RedirectAuthoritativeDnsServerCache`. That will help to avoid allocation of a new object when it's already wrapped.
Source:
private void deflateJdk11(ByteBuf out) { if (out.isDirect()) { try { int numBytes; do { numBytes = (Integer) DEFLATER_DEFLATE_BYTEBUFFER.invoke(deflater, out.nioBuffer(), Deflater.SYNC_FLUSH); } while (numBytes > 0); } catch (IllegalAccessException e) { throw new Error(e); } catch (InvocationTargetException e) { throw new Error(e); } } else { deflateJdk7(out); } }

Target:
you should call `nioBuffer()` only once: ```java ByteBuffer nioBuffer = out.nioBuffer(); int numBytes; do { numBytes = (Integer) DEFLATER_DEFLATE_BYTEBUFFER.invoke(deflater, nioBuffer, Deflater.SYNC_FLUSH); } while (numBytes > 0); ```
Source:
public static UnixResolverOptions.Builder newBuilder() { return new UnixResolverOptions.Builder(); }

Target:
nit: make all of the methods package-private as the class is package-private as well. This also ensures we no expose these by mistake at some point.
Source:
private static void encodeTlvs(List<HAProxyTLV> haProxyTLVs, ByteBuf out) { for (HAProxyTLV tlv: haProxyTLVs) { encodeTlv(tlv, out); } }

Target:
closing using index based for loop to eliminate GC pressure
Source:
public String toString() { return new StringBuilder(128) .append(StringUtil.simpleClassName(this)) .append("(type: ").append(type()) .append(", typeByteValue: ").append(typeByteValue()) .append(", client: ").append(client()) .append(", verify: ").append(verify()) .append(", numEncapsulatedTlvs: ").append(tlvs.size()) .append(')').toString(); }

Target:
Just use normal string concats...
Source:
protected void encode(ChannelHandlerContext ctx, HAProxyMessage msg, ByteBuf out) throws Exception { if (msg.protocolVersion() == HAProxyProtocolVersion.V1) { encodeV1(msg, out); } else if (msg.protocolVersion() == HAProxyProtocolVersion.V2) { encodeV2(msg, out); } else { throw new HAProxyProtocolException("Unsupported version: " + msg.protocolVersion()); } }

Target:
nit: consider replacing by a switch statement.
Source:
protected void initChannel(SocketChannel channel) throws Exception { channel.pipeline() .addLast(new HttpServerCodec()) .addLast(new HttpObjectAggregator(65536)) .addLast(StompWebSocketClientPageHandler.INSTANCE) .addLast(new WebSocketServerProtocolHandler(chatPath, StompVersion.SUB_PROTOCOLS)) .addLast("stompWebSocketProtocolCodec", stompWebSocketProtocolCodec); }

Target:
nit: why specify an explicit name here ? We dont do this for the other handlers as well.
Source:
public V map(String hostname) { if (hostname != null) { hostname = normalize(hostname); // Let's try an exact match first V value = map.get(hostname); if (value != null) { return value; } // No exact match, let's try a wildcard match. int idx = hostname.indexOf('.'); if (idx != -1) { value = map.get('*' + hostname.substring(idx)); if (value != null) { return value; } } } return defaultValue; }

Target:
Optional idea: If a user adds a wildcard domain `*.netty.io`, it could be normalized to `.netty.io`, and stored in the map. That would make it cheaper for this line to check if it's present, because no string concatenation would be needed. You could just check the substring. I am not sure how fast you want it to go.