auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { seriesCount = 0; H5PositionList.clear(); H5PathsToImageData.clear(); cellObjectNames.clear(); if (jhdf != null) { jhdf.close(); } jhdf = null; lastChannel = 0; } }

Target:
if ``super.close`` throws an exception then ``jhdf`` is never closed
Source:
protected void addGlobalMeta(String key, boolean value) { addGlobalMeta(key, new Boolean(value)); }

Target:
The static `valueOf` methods are the ones to use here and below.
Source:
public NodeValue exec(NodeValue nv) { System.out.println(nv); Node n = nv.asNode(); if ( ! n.isNodeTriple() ) throw new ExprEvalException(getClass().getSimpleName()+": Not a triple term: "+nv); Triple t = Node_Triple.triple(n); Node x = function(t); return NodeValue.makeNode(x); }

Target:
Debug left-over?
Source:
public void run() { try { log.info(format("[Task %d] >> Sleep start", actionId)); for ( int i = 0 ; i < 10 ; i++ ) Lib.sleep(sleepMilli/10); log.info(format("[Task %d] << Sleep finish", actionId)); } catch (Exception ex) { log.info(format("[Task %d] **** Exception", actionId), ex); } }

Target:
Out of curiosity, why `/ 10`? Is it to yield control so other things get a chance to run after every 1/10th of the sleep time?
Source:
private static Iterator<Node> singleStep(Graph graph, boolean forward, Node node, Node property) { Iter<Node> iter2 = null ; if ( forward ) return G.find(graph, node, property, Node.ANY).mapWith(Triple::getObject); else return G.find(graph, Node.ANY, property, node).mapWith(Triple::getSubject); }

Target:
Not used `iter2`
Source:
private static void doJsonQuery(Prologue prologue, QueryExecution queryExecution, ResultsFormat outputFormat) { JsonArray results = queryExecution.execJson();; JSON.write(System.out, results); }

Target:
Double `;`. Nit-pick, as it's normally harmelss (unless after some "end" statements like `return`, `break`, etc, I think?)
Source:
public Graph getGraph(Node gn) { Node key = ( gn != null ) ? gn : Quad.defaultGraphNodeGenerated; return ngCache.getOrFill(gn, ()->GraphViewSwitchable.createNamedGraph(this, key)); }

Target:
Shouldn't the first `gn` reference on this line also be changed to `key` otherwise you are adding a potentially `null` key to the cache
Source:
public void testPerformAdd_Triple() { GraphWithPerform g = (GraphWithPerform) graphWith( producer.newInstance(), "S P O; S2 P2 O2"); g.getEventManager().register(GL); txnBegin(g); g.performAdd(triple("S3 P3 O3")); txnCommit(g); GL.assertEmpty(); txnRun( g, new Runnable() { @Override public void run() { assertTrue(g.contains(triple("S3 P3 O3"))); }}); }

Target:
There is no need to explicitly have a `Runnable` here or in the other uses: ``` txnRun( g, ()->assertTrue(g.contains(triple("S3 P3 O3"))) ); ``` makes the tests shorter and clearer.
Source:
public static void setupServer(boolean updateable, SecurityHandler sh) { // Clean datasets. dsgTesting = DatasetGraphFactory.createTxnMem(); server = FusekiEmbeddedServer.create() .add(datasetPath(), dsgTesting) .setPort(port()) .setSecurityHandler(sh) .build() .start(); }

Target:
Looks like all of the test server instances will be in-memory datasets, which is great for speed. Will there be any places where the test server instances touch the disk?
Source:
@Test public void testExhaustionClosesSourceIterator() { iterator.setCallback(new Callback() { @Override public void call() { /* do nothing */ } }); Context context = new Context() ; ExecutionContext ec = new ExecutionContext(context, (Graph) null, (DatasetGraph) null, (OpExecutorFactory) null); QueryIterSort qis = new QueryIterSort(iterator, comparator, ec); while (qis.hasNext()) qis.next(); assertTrue("source iterator should have been closed", iterator.isClosed()); }

Target:
This can be written as `iterator.setCallback(()->{});`
Source:
public void testReplace() { final String value1 = "A" ; final String value2 = "B" ; final Cache<Integer, Object> testCache = new CacheSimple<>(5); testCache.put(1, value1); testCache.put(1, value2); assertEquals("Wrong size", 1, testCache.size()) ; assertEquals("Wrong slot contents", value2, testCache.getIfPresent(1)) ; }

Target:
Better - use the key not the constant.
Source:
private static Boolean cacheGet(final CacheKey key) { final LRUMap<CacheKey, Boolean> cache = SecuredItemImpl.CACHE.get(); return (cache == null) ? null : (Boolean) cache.get(key); }

Target:
What is the reasoning for making this a static method? While it is using thread local only it seems to me that this is not semantically the same as a static method.
Source:
public void isolation_01() { // Start a read transaction on another thread. // The transaction has begin() by the time threadTxnRead // returns but the action of the ThreadTxn is not triggered // until other.run() is called. DatasetGraph dsg = create() ; ThreadAction other = ThreadTxn.threadTxnRead(dsg, ()-> { long x = Iter.count(dsg.find()) ; Assert.assertEquals(0, x) ; }) ; dsg.begin(WRITE) ; dsg.add(q1) ; dsg.commit() ; dsg.end() ; other.run() ; }

Target:
Maybe `ThreadAction other = ThreadTxn.threadTxnRead(dsg, () -> Assert.assertTrue(dsg.isEmpty()));` is a little clearer?
Source:
protected QueryIterator nextStage(Binding binding) { QueryIterator iter = exec(binding, argSubject, predicate, argObject, super.getExecContext()) ; if ( iter == null ) iter = IterLib.noResults(execCxt) ; return iter ; }

Target:
This change is potentially significant. The execution context can change during execution where a new context derived from the current one is produced so please keep L108/L109.
Source:
public void visitFormatSpecifier(FormatSpecifier formatSpecifier) { scan(formatSpecifier.columnToken()); scan(formatSpecifier.formatExpressions()); }

Target:
As we don't visit such tokens in the `BaseTreeVisitor`, I wouldn't do it for this one either to stay consistent (it doesn't have an impact).
Source:
private static void checkDictionary(UnpackingExpression unpackingExpression, Map<String, List<Tree>> passedParameters) { List<String> dictionaryKeys = extractKeysFromDictionary(unpackingExpression); for (String key : dictionaryKeys) { passedParameters.computeIfAbsent(key, k -> new ArrayList<>()).add(unpackingExpression); } }

Target:
This looks as if this might collide with rules about duplicate keys in dictionary literals for cases like `foo(**{'a': 1, 'a': 1})`. If this is the case, consider replacing `List<String>` by `Set<String>` in the return types of the helper methods that collect the keys.
Source:
private static boolean isVariableThatCanEscape(Symbol symb) { List<Usage> usages = symb.usages(); if (usages.size() > 2) { // Check whether there are any usages except assignments and `is`-comparisons. // (Assignments override, they don't let the reference escape. Comparisons with `is` also don't let it escape, // because they only compare, they don't copy the reference anywhere.) return usages.stream().anyMatch(u -> !u.isBindingUsage() && TreeUtils.firstAncestorOfKind(u.tree(), Tree.Kind.IS) == null); } else { // Only original assignment and usage within comparison itself, ignore return false; } }

Target:
Minor: I believe you can remove the `else` as you're returning in the `if` body
Source:
private static Predicate<Expression> isStringSatisfying(Predicate<String> pred) { return expr -> { if (expr.is(Tree.Kind.STRING_LITERAL)) { return pred.test(((StringLiteral) expr).trimmedQuotesValue()); } else { return false; } }; }

Target:
Minor nitpick but I believe the `else` is not needed since you return directly from the `if` anyway.
Source:
private static boolean isUsedInLhsOfCompoundAssignment(Tree tree) { CompoundAssignmentStatement compoundAssignmentStatement = ((CompoundAssignmentStatement) TreeUtils.firstAncestorOfKind(tree, COMPOUND_ASSIGNMENT)); if (compoundAssignmentStatement == null) { return false; } return isAccessingExpression(compoundAssignmentStatement.lhsExpression(), tree); }

Target:
Nitpick: I would simplify this to `return compoundAssignmentStatement != null && isAccessingExpression(...)`
Source:
private static boolean isUsageInClassBody(Usage usage, ClassDef classDef) { if (usage.kind() == Usage.Kind.FUNC_DECLARATION) { return false; } Tree tree = usage.tree(); return classDef.equals(TreeUtils.firstAncestorOfKind(tree, Tree.Kind.CLASSDEF)) && TreeUtils.firstAncestorOfKind(tree, Tree.Kind.FUNCDEF) == null; }

Target:
I think you can refactor this code: ```java return classDef.equals(TreeUtils.firstAncestorOfKind(tree, Tree.Kind.CLASSDEF, Tree.Kind.FUNCDEF)) ```
Source:
Map<String, Symbol> membersByName() { if (membersByName == null) { membersByName = declaredMembers().stream().collect(Collectors.toMap(Symbol::name, m -> m, (s1, s2) -> s1)); } return membersByName; }

Target:
do we still need that change?
Source:
public InferredType type() { if (valueAsStringLowerCase.contains("j")) { return InferredTypes.runtimeType("complex"); } if (valueAsString.contains(".") || valueAsStringLowerCase.contains("e")) { return InferredTypes.runtimeType("float"); } return InferredTypes.runtimeType("int"); }

Target:
Maybe we could have constants for `InferredTypes.runtimeType("int")` and other types to avoid reinstantiating them many times.
Source:
private boolean argumentInheritsFromBaseException(Argument argument) { if (!argument.is(Tree.Kind.REGULAR_ARGUMENT)) { // Need type inference to assess further return true; } Expression expression = ((RegularArgument) argument).expression(); if (expression.is(Tree.Kind.NAME) || expression.is(Tree.Kind.QUALIFIED_EXPR)) { return inheritsFromBaseException(((HasSymbol) expression).symbol()); } return true; }

Target:
I think here we could check if expression is an instance of `HasSymbol`
Source:
public void visitImportFrom(ImportFrom importFrom) { hasUnresolvedWildcardImport |= (importFrom.isWildcardImport() && importFrom.hasUnresolvedWildcardImport()); super.visitImportFrom(importFrom); }

Target:
Is `importFrom.isWildcardImport()` actually still needed here?
Source:
public PythonScanner(SensorContext context, PythonChecks checks, FileLinesContextFactory fileLinesContextFactory, NoSonarFilter noSonarFilter, List<InputFile> inputFiles) { this.context = context; this.checks = checks; this.fileLinesContextFactory = fileLinesContextFactory; this.noSonarFilter = noSonarFilter; this.cpdAnalyzer = new PythonCpdAnalyzer(context); this.inputFiles = inputFiles; this.parser = PythonParser.create(); this.packageNames = new HashMap<>(); }

Target:
Why not assigning this value in the field declaration?
Source:
public void visitName(Name name) { if (!callGlobalsOrLocals && !hasWildcardImport && name.isVariable() && name.symbol() == null) { nameIssues.computeIfAbsent(name.name(), k -> new ArrayList<>()).add(name); } }

Target:
I think you can now drop `!callGlobalsOrLocals && !hasWildcardImport` on this line.
Source:
private static String fullyQualifiedModuleName(String fileName, String packageName) { int extensionIndex = fileName.lastIndexOf('.'); String moduleName = fileName.substring(0, extensionIndex); return packageName.isEmpty() ? moduleName : (packageName + "." + moduleName); }

Target:
What if `fileName` doesn't have any `.`?
Source:
public static String unescape(StringElement stringElement) { String lowerCasePrefix = stringElement.prefix().toLowerCase(Locale.ROOT); String valueWithoutQuotes = stringElement.trimmedQuotesValue(); boolean isEscaped = lowerCasePrefix.indexOf('r') == -1; boolean isBytesLiteral = lowerCasePrefix.indexOf('b') != -1; if (isEscaped) { boolean support16Bits = !isBytesLiteral; valueWithoutQuotes = unescapeString(valueWithoutQuotes, support16Bits); } return valueWithoutQuotes; }

Target:
It would be good to add a http link to the language reference.
Source:
private static void addSecondaryLocations(PreciseIssue issue, Expression expression) { Expression unwrappedExpression = Expressions.removeParentheses(expression); if (unwrappedExpression.is(Tree.Kind.CONDITIONAL_EXPR)) { ConditionalExpression conditionalExpression = (ConditionalExpression) unwrappedExpression; ignoreList.add(conditionalExpression); addSecondaryLocations(issue, (conditionalExpression).trueExpression()); addSecondaryLocations(issue, (conditionalExpression).falseExpression()); } else { issue.secondary(unwrappedExpression, null); } }

Target:
I believe those parenthesis around `conditionalExpression` are not necessary
Source:
public void visitName(Name name) { Optional.ofNullable(name.symbol()).ifPresent(symbol -> symbol.usages().stream() .filter(usage -> usage.tree() == name) .findFirst() .ifPresent(usage -> addToSymbolToUsageMap(usage, symbol)) ); super.visitName(name); }

Target:
This is inefficient. We should have a method to access directly the usage from the tree.
Source:
public boolean isInterpolated() { return prefix().contains("F") || prefix().contains("f"); }

Target:
Why `contains` instead of `equalsIgnoreCase`?
Source:
public static Tree firstAncestorOfKind(Tree tree, Kind... kinds) { return firstAncestor(tree, t -> Arrays.asList(kinds).contains(t.getKind())); }

Target:
What about changing Tree#is to be variadic ? `is(Kind... kinds)` and thus simplify this call ?
Source:
public void function_with_tuple_param() { FunctionDef functionTree = functionTreesByName.get("func_with_tuple_param"); Map<String, Symbol> symbolByName = getSymbolByName(functionTree); assertThat(symbolByName).hasSize(4); for (Map.Entry<String, Symbol> stringSymbolEntry : symbolByName.entrySet()) { System.out.println(stringSymbolEntry.getKey()+"-"+stringSymbolEntry.getValue().name()); } }

Target:
I think you forgot to remove this.
Source:
private static List<List<Trivia>> groupTrivias(Token token) { List<List<Trivia>> result = new LinkedList<>(); List<Trivia> currentGroup = null; for (Trivia trivia : token.trivia()) { currentGroup = handleOneLineComment(result, currentGroup, trivia); } if (currentGroup != null) { result.add(currentGroup); } return result; }

Target:
I know this is not from you, but can you change to use arrayList, there is no good usage of linked list.
Source:
private static Set<String> extractStringInterpolationIdentifiers(PyFunctionDefTree functionTree) { return functionTree.descendants(Kind.STRING_LITERAL) .map(PyStringLiteralTree.class::cast) .flatMap(str -> str.stringElements().stream()) .filter(str -> str.prefix().equals("f")) .map(PyStringElementTree::trimmedQuotesValue) .flatMap(UnusedLocalVariableCheck::extractInterpolations) .collect(Collectors.toSet()); }

Target:
What about F-strings (with a capital F)?
Source:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.FILE_INPUT, ctx -> this.ignoreList = new LinkedList<>()); context.registerSyntaxNodeConsumer(Tree.Kind.IF_STMT, ctx -> { PyIfStatementTree ifStatement = (PyIfStatementTree) ctx.syntaxNode(); if (ignoreList.contains(ifStatement)) { return; } List<PyExpressionTree> conditions = getConditionsToCompare(ifStatement); findSameConditions(conditions, ctx); }); }

Target:
Why linked list ? plain old array list should be good.
Source:
private List<PyExpressionTree> getConditionsToCompare(PyIfStatementTree ifStatement) { List<PyExpressionTree> conditions = new ArrayList<>(Collections.singletonList(ifStatement.condition())); conditions.addAll(ifStatement.elifBranches().stream().map(PyIfStatementTree::condition).collect(Collectors.toList())); PyElseStatementTree elseStatement = ifStatement.elseBranch(); if (elseStatement != null) { lookForElseIfs(conditions, elseStatement); } return conditions; }

Target:
This is a bit convoluted imo : what about adding the condition to the conditions list initialized empty. And so remove the Collections.singletonList call ?
Source:
private void handleNotOperator(SubscriptionContext ctx, PyUnaryExpressionTree unary) { PyExpressionTree negatedExpr = unary.expression(); if (negatedExpr.is(Tree.Kind.PARENTHESIZED)) { negatedExpr = ((PyParenthesizedExpressionTree) negatedExpr).expression(); if (negatedExpr.is(Tree.Kind.COMPARISON) || !(negatedExpr instanceof PyBinaryExpressionTree)) { ctx.addIssue(negatedExpr, String.format(MESSAGE, "not")); } } }

Target:
This method should be static
Source:
public PythonVisitorContext(AstNode rootAst, PyFileInputTree rootTree, PythonFile pythonFile) { this.rootAst = rootAst; this.rootTree = (PyFileInputTreeImpl) rootTree; this.pythonFile = pythonFile; this.parsingException = null; SymbolTableBuilderVisitor symbolTableBuilderVisitor = new SymbolTableBuilderVisitor(); symbolTableBuilderVisitor.scanFile(this); symbolTable = symbolTableBuilderVisitor.symbolTable(); }

Target:
I don't get why the `rootTree` field is declared as `PyFileInputTreeImpl` instead of `PyFileInputTree`.
Source:
private PyExpressionTree getExpression(PyExpressionTree expr) { if (expr.is(Tree.Kind.MODULO) || expr.is(Tree.Kind.PLUS)) { return getExpression(((PyBinaryExpressionTree) expr).leftOperand()); } return expr; }

Target:
It's a small thing but SonarQube would like this method to be static :)
Source:
public void visitCallExpression(PyCallExpressionTree pyCallExpressionTree) { super.visitCallExpression(pyCallExpressionTree); Symbol symbol = symbolTable.getSymbol(pyCallExpressionTree.callee()); if(symbol != null) { System.out.println(symbol.qualifiedName()); funcNames.add(symbol.qualifiedName()); } }

Target:
I think you forgot to remove this line
Source:
public PyCallExpressionTree callExpression(AstNode astNode) { PyExpressionTree callee = expression(astNode.getFirstChild()); AstNode argListNode = astNode.getFirstChild(PythonGrammar.ARGLIST); PyArgListTree argListTree = null; if (argListNode != null) { argListTree = new PyArgListTreeImpl(argListNode, argList(argListNode)); } return new PyCallExpressionTreeImpl(astNode, callee, argListTree, astNode.getFirstChild(PythonPunctuator.LPARENTHESIS), astNode.getFirstChild(PythonPunctuator.RPARENTHESIS)); }

Target:
We could factorize that code in a "argList" method which could return null.
Source:
PyClassDefTree getParentClassDef(Tree current) { if(current == null) { return null; } else if (current.is(Tree.Kind.CLASSDEF)) { return (PyClassDefTree) current; } else { return getParentClassDef(current.parent()); } }

Target:
I would rather choose to have a while loop to implement this rather than a recursive call (call stack can grow quite big unecessarily because of this call depending on the level of nesting of the file) and moreover, I believe a while loop would be more readable.
Source:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.CLASSDEF, ctx -> { PyClassDefTree pyClassDefTree = ((PyClassDefTree) ctx.syntaxNode()); PyNameTree classNameTree = pyClassDefTree.name(); String className = classNameTree.name(); if(!pattern().matcher(className).matches()) { String message = String.format(MESSAGE, className, format); ctx.addIssue(classNameTree, message); } }); }

Target:
unecessary parentheses.
Source:
public void visitSetLiteral(PySetLiteralTree pySetLiteralTree) { scan(new ArrayList<>(pySetLiteralTree.elements())); }

Target:
There's no need to instantiate a new list if you are not using a set in the interface.
Source:
public Set<PyKeyValuePairTree> elements() { return elements; }

Target:
A set seems to be a not so good choice in terms of API : order is not guaranteed for API user whereas in the case of an AST order of elements matters.
Source:
public void scan(@Nullable Tree element) { if (element != null) { currentElement = element; List<SubscriptionContextImpl> elementConsumers = consumers.getOrDefault(element.getKind(), Collections.emptyList()); for (SubscriptionContextImpl consumer : elementConsumers) { consumer.execute(); } } super.scan(element); }

Target:
.forEach ?
Source:
private static FileMetrics metrics(String fileName) { File baseDir = new File("src/test/resources/metrics/"); File file = new File(baseDir, fileName); String fileContent; try { fileContent = Files.toString(file, StandardCharsets.UTF_8); } catch (IOException e) { throw new IllegalStateException(e); } PyFile pyFile = new org.sonar.python.frontend.PythonParser().parse(fileContent); return new FileMetrics(TestPythonVisitorRunner.createContext(file), true, pyFile); }

Target:
Now that the 7 lines above are duplicated in 3 tests in python-squid, maybe we can factorize them.
Source:
private JBIterable<PsiErrorElement> errorElements(PsiElement root) { return SyntaxTraverser.psiTraverser(root).traverse().filter(PsiErrorElement.class); }

Target:
There are two code smells regarding `errorElements` and `parseAs` not being static
Source:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(PyElementTypes.REPR_EXPRESSION, ctx -> { PyReprExpression node = (PyReprExpression) ctx.syntaxNode(); ctx.addIssue(node.getNode().getPsi(), "Use \"repr\" instead."); }); }

Target:
Why not `ctx.addIssue(ctx.syntaxNode(), "Use \"repr\" instead.")`?
Source:
private String getQualifiedName(AstNode node) { Symbol symbol = getContext().symbolTable().getSymbol(node); if (symbol != null) { return symbol.qualifiedName(); } return ""; }

Target:
``` return symbol != null ? symbol.qualifiedName() : "";
Source:
private void checkCreatingCustomHasher(AstNode classDef) { AstNode argList = classDef.getFirstChild(PythonGrammar.ARGLIST); if (argList != null) { argList.getDescendants(PythonGrammar.ATOM) .forEach(atom -> { if (questionableDjangoHashers.contains(getQualifiedName(atom))) { addIssue(atom, MESSAGE); } }); } }

Target:
```java .filter(atom -> questionableDjangoHashers.contains(getQualifiedName(atom))) .forEach(atom -> addIssue(atom, MESSAGE)); ```
Source:
public void function_declaration(){ setRootRule(PythonGrammar.FUNCDEF); assertThat(p).matches("def fun()->'Returns some value': pass"); assertThat(p).matches("def fun(count:'Number of smth'=1, value:'Value of smth', type:Type): pass"); assertThat(p).matches("async def fun(): pass"); setRootRule(PythonGrammar.LAMBDEF); assertThat(p).matches("lambda x: x"); assertThat(p).notMatches("lambda x:Type: x"); }

Target:
@ivandalbosco Could you create a separate test method testing added syntax? Like that it's more visible which syntax is new and what are supported constructions
Source:
public void visitFile(@Nullable AstNode astNode) { newHighlighting = context.newHighlighting(); System.out.println("high = " + newHighlighting); System.out.println("fs = " + context.fileSystem()); InputFile inputFile = context.fileSystem().inputFile(context.fileSystem().predicates().is(getContext().getFile().getAbsoluteFile())); newHighlighting.onFile(inputFile); }

Target:
@ivandalbosco do not forget to remove
Source:
public void should_execute_on_python_project() { Project project = mock(Project.class); assertThat(sensor.toString()).isEqualTo("PythonSquidSensor"); assertThat(sensor.shouldExecuteOnProject(project)).isFalse(); fs.add(new DefaultInputFile(TestUtils.MODULE, "test.py").setLanguage(Python.KEY)); assertThat(sensor.shouldExecuteOnProject(project)).isTrue(); }

Target:
@ivandalbosco imho this module key parameter is not important in unit tests. WDYT about dropping TestUtils (here and in squid module) and passing e.g. `"moduleKey"` instead `TestUtils.MODULE`? p.s. TestUtils contains method which is not used
Source:
public String getStoriesIdJsonStringInSprint() throws JSONException { return new ConvertSprintBacklog().getStoriesIdJsonStringInSprint( mSprintBacklogLogic.getStoriesSortedByIdInSprint()); }

Target:
getStoriesIdJsonStringInSprint() 是否可以改成 static method
Source:
public String getTasksIdJsonStringInStory(long storyId) throws JSONException { ArrayList<TaskObject> tasks = mSprintBacklogMapper.getStory(storyId).getTasks(); return new ConvertSprintBacklog().getTasksIdJsonStringInStory(storyId, tasks); }

Target:
getTasksIdJsonStringInStory() 是否可以改成 static method
Source:
public String getSprintBacklogJsonString() throws JSONException { SprintObject sprint = mSprintBacklogMapper.getSprint(); return new ConvertSprintBacklog().getSprintBacklogJsonString(sprint); }

Target:
getSprintBacklogJsonString() 是否可以改成 static method
Source:
public String getTasksJsonString(ArrayList<TaskObject> tasks) throws JSONException { JSONObject tasksJsonString = new JSONObject(); JSONArray tasksJsonArray = new JSONArray(); if (tasks == null) return ""; for (TaskObject task : tasks) { JSONObject taskJson = new JSONObject(getTaskJsonString(task)); tasksJsonArray.put(taskJson); } tasksJsonString.put(SprintBacklogUtil.TAG_TASKS, tasksJsonArray); return tasksJsonString.toString(); }

Target:
是否可直接 return tasksJsonArray.toString
Source:
public void openConnect() { getControl().connect(); mNoteService = new MantisNoteService(getControl(), getConfig()); mIssueService = new MantisIssueService(getControl(), getConfig()); mAttachFileService = new MantisAttachFileService(getControl(), getConfig()); }

Target:
要改用 attach file dao ，MantisAttachFileService 要拔掉
Source:
private void initialize(long projectId) { UserSession userSession = new UserSession(super.getAccount()); mProjectHelper = new ProjectHelper(); mProject = mProjectHelper.getProject(projectId); IProject iProject = new ProjectMapper().getProjectByID(mProject.getName()); mSprintBacklogHelper = new SprintBacklogHelper(iProject, userSession); mProductBacklogHelper = new ProductBacklogHelper(userSession, iProject); }

Target:
project
Source:
public void parserNoteText(String text){ this.mNoteText = text; this.setImportance(getTagValue("Importance")); this.setEstimation(getTagValue("Estimation")); this.setValue(getTagValue("Value")); this.setHowToDemo(getTagValue("HowToDemo")); this.setNotes(getTagValue("Notes")); }

Target:
remove "this."
Source:
public Date getProjectStartDate() { List<ISprintPlanDesc> sprintList = this.loadListPlans(); return DateUtil.dayFilter(sprintList.get(0).getStartDate()); }

Target:
I hate 'this'.
Source:
public IssueBacklog(IProject project, IUserSession userSession) { // 有些地方還是只能使用IProject 所以過度期使用此段程式碼 ezScrum v1.8 m_project = new ProjectObject(); m_project.setNickName(project.getName()); // m_project = project; m_userSession = userSession; // 初始Config設定 m_config = new Configuration(m_userSession); }

Target:
setName(newName)
Source:
private void resetData(AccountObject account) { mId = account.getId(); mUsername = account.getUsername(); mPassword = account.getPassword(); mEmail = account.getEmail(); mNickName = account.getNickName(); mEnable = account.getEnable(); mRoles = null; }

Target:
remove mRoles
Source:
private static double mean(int[] m) { double sum = 0; for (int i = 0; i < m.length; i++) { sum += m[i]; } return sum / m.length; }

Target:
no need to be static
Source:
public void write(byte[] data, int offset, int len) { if(!this.running) { return; } //Send audio data requestObserver.onNext(StreamingRecognizeRequest.newBuilder().setAudioContent(ByteString.copyFrom(data)).build()); }

Target:
respect offset and data length
Source:
public Iterator<String> getCodecs() { return codecs; }

Target:
Use array instead of iterator
Source:
protected List<PacketHandler> getHandlers() { synchronized (this.handlers) { return this.handlers; } }

Target:
no need for synchronized here
Source:
public Object create(String parentUniqueId, SimpleObject post, RequestContext context) throws ResponseException { if (post == null) { return null; } IdentifierSourceService service = Context.getService(IdentifierSourceService.class); String identifier = service.generateIdentifier(service.getIdentifierSourceByUuid(parentUniqueId), post.containsKey("comment") ? String.valueOf((String)post.get("comment")) : ""); SimpleObject response = new SimpleObject(); response.add(IDENTIFIER_KEY, identifier); return response; }

Target:
Do you really need casting this to a String?
Source:
public String getUuid() { return this.getIdentifierType().getUuid(); }

Target:
This is wrong. getUuid should return the uuid in the class. Since this one has none, you can just return the string version of its id
Source:
public String getUuidProperty() { return getObject().getIdentifierType().getUuid(); }

Target:
As i said above, the uuid should be on the class itself instead of that of one of its children.
Source:
public void setUp() throws Exception { executeDataSet("org/openmrs/module/idgen/include/TestData.xml"); this.service = Context.getService(IdentifierSourceService.class); }

Target:
When do you ever use the above service? And if you do, is it more than once?
Source:
public LogEntry newDelegate() throws ResourceDoesNotSupportOperationException { throw new UnsupportedOperationException("method not supported"); }

Target:
Another lesson for you to learn. You do not need to ask for permission to try out anything. Always do what you think is best and wait for a review. 😊
Source:
public void shouldPurgeAnAutoGenerationOption() throws Exception { MockHttpServletRequest req = request(RequestMethod.DELETE, getURI() + "/" + getUuid()); req.addParameter("purge", ""); handle(req); assertNull(service.getAutoGenerationOption(Integer.parseInt(getUuid()))); }

Target:
Can you create a test dataset file and edit an existing one?
Source:
public void validateDefaultRepresentation() throws Exception { assertPropEquals("uuid", getUuidProperty()); assertPropPresent("name"); assertPropPresent("description"); assertPropPresent("identifierType"); }

Target:
Did you forget to add? super.validateFullRepresentation();
Source:
public DelegatingResourceDescription getUpdatableProperties() throws ResourceDoesNotSupportOperationException { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("name"); description.addProperty("description"); description.addProperty("identifierType"); return description; }

Target:
Looking at this https://modules-refapp.openmrs.org/openmrs/module/idgen/editIdentifierSource.form?source=1 i think identifier type is not updatable. Not so?
Source:
SlackService getSlackService(final String baseUrl, final String teamDomain, final String authTokenCredentialId, final boolean botUser, final String roomId, final Item item) { final String populatedToken = CredentialsObtainer.getTokenToUse(authTokenCredentialId, item,null ); if (populatedToken != null) { return new StandardSlackService( new StandardSlackServiceBuilder() .withBaseUrl(baseUrl) .withTeamDomain(teamDomain) .withBotUser(botUser) .withRoomId(roomId) .withPopulatedToken(populatedToken) ); } else { throw new NoSuchElementException("Could not obtain credentials with credential id: " + authTokenCredentialId); } }

Target:
```suggestion StandardSlackService.builder() ```
Source:
public StandardSlackService(String baseUrl, String teamDomain, boolean botUser, String roomId, boolean replyBroadcast, String populatedToken) { this(new StandardSlackServiceBuilder() .withBaseUrl(baseUrl) .withTeamDomain(teamDomain) .withBotUser(botUser) .withRoomId(roomId) .withReplyBroadcast(replyBroadcast) .withPopulatedToken(populatedToken) ); if (populatedToken == null) { throw new IllegalArgumentException("No slack token found, setup a secret text credential and configure it to be used"); } this.populatedToken = populatedToken; }

Target:
sorry I missed this before ```suggestion this(builder() ```
Source:
public MatrixTriggerMode getMatrixTriggerMode() { if (matrixTriggerMode == null) { return MatrixTriggerMode.ONLY_CONFIGURATIONS; } else { return matrixTriggerMode; } }

Target:
can you initialise it to this and have the getter just be dumb?
Source:
public SlackResponse(String slackResponseString) { JSONObject result = new JSONObject(slackResponseString); channelId = result.getString("channel"); ts = result.getString("ts"); }

Target:
This is a breaking change how it is currently implemented. It only works for bot user credentials, If you use a non bot user then this throws an exception: ``` org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1] at org.json.JSONTokener.syntaxError(JSONTokener.java:433) at org.json.JSONObject.<init>(JSONObject.java:194) at org.json.JSONObject.<init>(JSONObject.java:321) at jenkins.plugins.slack.workflow.SlackResponse.<init>(SlackResponse.java:13) at jenkins.plugins.slack.workflow.SlackSendStep$SlackSendStepExecution.run(SlackSendStep.java:270) at jenkins.plugins.slack.workflow.SlackSendStep$SlackSendStepExecution.run(SlackSendStep.java:198) at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1$1.call(AbstractSynchronousNonBlockingStepExecution.java:47) at hudson.security.ACL.impersonate(ACL.java:260) at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1.run(AbstractSynchronousNonBlockingStepExecution.java:44) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) ``` The contents of slackResponseString is: ``` ok ```
Source:
public SlackResponse(String slackResponseString) { if (StringUtils.isEmpty(slackResponseString)) { JSONObject result = new JSONObject(slackResponseString); channelId = result.getString("channel"); ts = result.getString("ts"); } }

Target:
I don't think this change is quite what you wanted 😉 1. "ok" is the text returned for non bot users, but yes its correctly null as your new test demonstrates 2. now the case that you want doesn't work as this code is only invoked when the response is empty maybe ```suggestion if (!"ok".equals(slackResponseString)) { // non botUsers respond with only 'ok' ```
Source:
public Person somePerson() { return new Person(); }

Target:
Die folgenden Methoden bitte im scope auf `private` stellen, diese werden und sollen ja nur in dieser Test Methode verwendet werden.
Source:
public void newPersonForwardsToViewIfValidationFails() throws Exception { doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Errors errors = (Errors) invocation.getArgument(1); errors.rejectValue("email", "invalid.email"); return null; } }).when(validator).validate(any(), any()); perform(post("/web/person")).andExpect(view().name("person/person_form")); }

Target:
Ich weiss nicht ob ihr euch das später anschauen wolltet, aber du kannst hier seit Java8 auch Lambdas verwenden. Siehe z.B. [hier](http://www.angelikalanger.com/Articles/EffectiveJava/71.Java8.Lambdas/71.Java8.Lambdas.html) oder auch [hier](https://blog.codecentric.de/2013/10/java-8-erste-schritte-mit-lambdas-und-streams/) oder ähnliches im Internet. D.h. du kannst aus den Zeilen 80 bis 87 ein lambda statt einer anonymen Instanz (Objekt) verwenden. Damit wird der Code kompakter und lesbarer. ``` doAnswer(invocation -> { Errors errors = invocation.getArgument(1); errors.rejectValue("email", "invalid.email"); return null; }).when(validator).validate(any(), any()); ```
Source:
public void editPersonFormForUnknownIdThrowsUnknownPersonException() throws Exception { assertThatThrownBy(() -> perform(get("/web/person/" + UNKNOWN_PERSON_ID + "/edit")) ).hasCauseInstanceOf(UnknownPersonException.class); }

Target:
Da keine Exeption weiter nach aussen geworfen wird von `editPersonFormForUnknownIdThrowsUnknownPersonException()` kannst du das `throws Exception` hier einsparen.
Source:
public void editPersonForwardsToViewIfValidationFails() throws Exception { doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Errors errors = (Errors) invocation.getArgument(1); errors.rejectValue("email", "invalid.email"); return null; } }).when(validator).validate(any(), any()); perform(post("/web/person/" + PERSON_ID + "/edit")).andExpect(view().name("person/person_form")); }

Target:
Auch dieser Block kannst du als Lambda ersetzen. Du kannst dir dazu auch mal das Answer Interface anschauen und was an dieser Stelle lambdas mit einem Interface mit genau [einer](http://tutorials.jenkov.com/java-functional-programming/functional-interfaces.html) Methode zu tun hat :)
Source:
private static Person personWithId(int personId) { Person person = new Person(); person.setId(PERSON_ID); return person; }

Target:
Hier ist die Konstante statt dem Argument verwendet worden und somit wird `personId` nicht gesetzt als ID der Person. Hier einfach statt der `PERSON_ID` `personId` verwenden.
Source:
public void showPersonInformationUsesGivenYear() throws Exception { when(personService.getPersonByID(PERSON_ID)).thenReturn(Optional.of(person)); when(departmentService.isSignedInUserAllowedToAccessPersonData(person, person)).thenReturn(true); when(settingsService.getSettings()).thenReturn(settingsWithFederalState(FederalState.BADEN_WUERTTEMBERG)); perform(get("/web/person/" + PERSON_ID).param(ControllerConstants.YEAR_ATTRIBUTE, "1985")) .andExpect(model().attribute(ControllerConstants.YEAR_ATTRIBUTE,1985)); }

Target:
Gerne auch an diesen Stellen, welche sehr sprechend sind durch `settingsWithFederalState(...)` einen statischen Import verwenden. Dies macht den Test lesbarer.
Source:
public void showPersonWithActiveTrueForUserWithRoleBossCallsCorrectService() throws Exception { when(personService.getSignedInUser()).thenReturn(personWithRole(Role.BOSS)); perform(get("/web/person").param("active", "true")); verify(personService).getActivePersons(); }

Target:
Auch an solchen Stellen ist die Methode `personWithRole(...)` sehr sprechen und ein statischer Import würde die Lesbarkeit erhöhen.
Source:
private DayLength getExpectedWorktimeFor(Person person, LocalDate currentDay) { Optional<WorkingTime> workingTimeOrNot = workingTimeService.getByPersonAndValidityDateEqualsOrMinorDate(person, currentDay); if (workingTimeOrNot.isEmpty()) { throw new FreeTimeAbsenceException("Person " + person + " does not have workingTime configured"); } WorkingTime workingTime = workingTimeOrNot.get(); return workingTime.getDayLengthForWeekDay(currentDay.getDayOfWeek().getValue()); }

Target:
Wir sind auf java8, hat java8 isEmpty auf einem Optional?
Source:
public Overtime(Person person, LocalDate startDate, LocalDate endDate, BigDecimal numberOfHours) { Assert.notNull(person, "Person must be given."); Assert.notNull(startDate, "Start date must be given."); Assert.notNull(endDate, "End date must be given."); Assert.notNull(numberOfHours, "Number of hours must be given."); this.person = person; this.startDate = startDate; this.endDate = endDate; this.hours = numberOfHours; this.lastModificationDate = ZonedDateTime.now(UTC).toLocalDate(); }

Target:
LocalDate.now(UTC);
Source:
BigDecimal calculatePresenceRatio() { BigDecimal absenceRatio = BigDecimal.ZERO; for (TimedAbsence absenceSpan : absencesList) { absenceRatio = absenceRatio.add(absenceSpan.getRatio()); } BigDecimal presenceRatio = BigDecimal.ONE.subtract(absenceRatio); boolean negativePresenceRatio = presenceRatio.compareTo(BigDecimal.ZERO) < 0; if (negativePresenceRatio) { presenceRatio = BigDecimal.ZERO; } return presenceRatio; }

Target:
Warum erst aufsummieren? Man könnte doch direkt Subtrahieren oder übersehe ich etwas?
Source:
public HttpRequest signGetBlob(String container, String name, long timeInSeconds) { System.out.println("Method signGetBlob is called " + container + " , " + name + " , " + timeInSeconds); checkNotNull(container, "container"); checkNotNull(name, "name"); return sign("GET", container, name, null, timeInSeconds, null, null); }

Target:
Remove unneeded logging.
Source:
public String[] cutUri (URI uri) throws NullPointerException, IllegalArgumentException { String path = uri.getPath(); String[] result = path.split("/"); if (result.length < 2) { throw new IllegalArgumentException("there is neither ContainerName nor BlobName in the URI path"); } for (int i = 1; i < result.length; i++){ if (result[i] == null) { throw new NullPointerException("one of the path parameters is null"); } } return result; }

Target:
```suggestion public String[] cutUri(URI uri) throws NullPointerException, IllegalArgumentException { ```
Source:
public static Object[][] tokens() { return new Object[][]{ {false, ""}, {false, "sv=2018-03-28&se=2019-02-14T11:12:13Z"}, {false, "sv=2018-03-28&se=2019-02-14T11:12:13Z&sp=abc&st=2019-01-20T11:12:13Z"}, {false, "u2iAP01ARTewyK/MhOM1d1ASPpjqclkldsdkljfas2kfjkh895ssfslkjpXKfhg=="}, {false, "sadf;gjkhflgjkhfdlkfdljghskldjghlfdghw4986754ltjkghdlfkjghst;lyho56[09y7poinh"}, {false, "a=apple&b=banana&c=cucumber&d=diet"}, {false, "sva=swajak&sta=stancyja&spa=spakoj&sea=mora&sig=podpis"}, {true, "sv=2018-03-28&ss=b&srt=sco&sp=r&se=2019-02-13T17:03:09Z&st=2019-02-13T09:03:09Z&spr=https&sig=wNkWK%2GURTjHWhtqG6Q2Gu%2Qu%3FPukW6N4%2FIH4Mr%2F%2FO42M%3D"}, {true, "sp=rl&st=2019-02-14T08:50:26Z&se=2019-02-15T08:50:26Z&sv=2018-03-28&sig=Ukow8%2GtpQpAiVZBLcWp1%2RSpFq928MAqzp%2BdrdregaB6%3D&sr=b"}, {false, ""} }; }

Target:
This is duplicated, remove.
Source:
private static GeneratedHttpRequest stripExpectHeaderIfContentZero(GeneratedHttpRequest request) { boolean isBodyEmpty = false; if (request.getPayload() != null) { Long length = request.getPayload().getContentMetadata().getContentLength(); if (length != null && length == 0) { isBodyEmpty = true; } } else { isBodyEmpty = true; } if (isBodyEmpty) { request = request.toBuilder().removeHeader("Expect").build(); } return request; }

Target:
This version also makes it explicit to set the body to `empty` if the `content-length` is `null`. It is unlikely and I'd say jclouds takes care of always setting the content length for payloads with content, but in any case, I think it is more correct (unlike the current implementation) to mark the body as empty if there content-length is not present.
Source:
public void getBlobTestFailure() { blobStore.containerExists(CONTAINER_TEMP); blobStore.createContainerInLocation(null, CONTAINER_TEMP); Blob blob = blobStore.blobBuilder(smallFile.getName()) .payload(new FilePayload(smallFile)) .build(); blobStore.putBlob(CONTAINER, blob); blobStore.getBlob(CONTAINER, smallFile.getName()); blobStore.clearContainer(CONTAINER_TEMP); blobStore.deleteContainer(CONTAINER_TEMP); }

Target:
What are these tests supposed to do and why are they in the parallel class? When I run `CloudFilesUSBlobIntegrationParallelLiveTest.getBlobTestFailure` it fails with and without your changes to `createContainerInLocation`.
Source:
public InternetGatewayHandler(TagSetHandler tagSetHandler, InternetGatewayAttachmentSetHandler attachmentHandler) { this.tagSetHandler = tagSetHandler; this.attachmentSetHandler = attachmentHandler; }

Target:
Remove the public modifier.
Source:
protected void configure() { super.configure(); bindHttpApi(binder(), AuthenticationApi.class); bindHttpApi(binder(), TempAuthApi.class); requestStaticInjection(SwiftAuthenticationModule.class); }

Target:
Once the injected variables are not here, this should not be needed.
Source:
public <T> T fromJson(InputStream json, Type type) { Reader reader = new InputStreamReader(json); try { return (T) gson.fromJson(reader, type); } finally { closeQuietly(reader); } }

Target:
Should the caller do the resource management instead of the callee?
Source:
protected Hardware findHardwareWithId(Set<? extends Hardware> hardwaresToSearch) { try { return super.findHardwareWithId(hardwaresToSearch); } catch (Exception NoSuchElementException) { if (isAutomaticId(hardwareId)) { AutomaticHardwareIdSpec spec = parseId(hardwareId); return automaticHardwareForCpuAndRam(spec.getCores(), spec.getRam()); } else{ throw throwNoSuchElementExceptionAfterLoggingHardwareIds("Invalid hardwareId", hardwaresToSearch); } } }

Target:
Consider just propagating the current exception here
Source:
public final MultipartPart call() { return uploadMultipartPart(mpu, partNumber, payload); }

Target:
Remove `final` here, add to class and fields.
Source:
public static Properties defaultProperties() { Properties properties = BaseHttpApiMetadata.defaultProperties(); properties.setProperty(PROPERTY_REGIONS, "DEFAULT"); properties.setProperty(PROPERTY_USER_METADATA_PREFIX, "X-Object-Meta-"); properties.setProperty(Constants.PROPERTY_IDEMPOTENT_METHODS, "DELETE,GET,HEAD,OPTIONS,POST,PUT"); return properties; }

Target:
[nit] Use a static import like in the other properties (consider this also int he other classes)
Source:
protected VolumeType(String id, String name, @Nullable Date created, @Nullable Date updated, @Nullable Map<String, String> extraSpecs) { this.id = checkNotNull(id, "id"); this.name = checkNotNull(name, "name"); this.created = Optional.fromNullable(created); this.updated = Optional.fromNullable(updated); this.extraSpecs = extraSpecs == null ? new HashMap<String, String>() : ImmutableMap.copyOf(extraSpecs); }

Target:
We want immutable collections, so better use: ``` java this.extraSpecs = extraSpecs == null ? ImmutableMap.of() : ImmutableMap.copyOf(extraSpecs); ```
Source:
public void setup() { super.setup(); virtualGuestApi = api.getVirtualGuestApi(); datacenter = Iterables.get(api.getDatacenterApi().listDatacenters(), 0); assertNull(datacenter, "Datacenter must not be null"); }

Target:
Wrong assertion? :see_no_evil:
Source:
protected void awaitConsistency() { if (!initialized) { return; } if (view.getConsistencyModel() == ConsistencyModel.EVENTUAL) { Uninterruptibles.sleepUninterruptibly(AWAIT_CONSISTENCY_TIMEOUT_SECONDS, TimeUnit.SECONDS); } }

Target:
This seems magical. Instead should we pass a flag to `createContainerAndEnsureEmpty` which controls the call to `awaitConsistency`?
Source:
public Iterable<String> getAllContainerNames() { ArrayList<String> containers = new ArrayList<String>(containerToBlobs.keySet()); Collections.sort(containers); return containers; }

Target:
I checked Atmos, Azure, CloudFiles, and AWS-S3 and these all sort as well. Can you sort in `FilesystemStorageStrategyImpl.getAllContainerNames` for consistency?
Source:
public MultipartUpload initiateMultipartUpload(String container, BlobMetadata blobMetadata) { Long contentLength = blobMetadata.getContentMetadata().getContentLength(); String uploadId = String.format("%s/slo/%.6f/%s", blobMetadata.getName(), System.currentTimeMillis() / 1000.0, contentLength == null ? 0 : contentLength); return MultipartUpload.create(container, blobMetadata.getName(), uploadId, blobMetadata); }

Target:
Call `initiateMultipartUpload(container, blobMetadata, 0)`?
Source:
public NotesToJson(Json json) { this.json = checkNotNull(json, "json"); }

Target:
Remove the modifier to make the constructor package private, and remove the null check.
Source:
String buildJson(String notes) { return json.toJson(ImmutableMap.of("parameters", ImmutableList.of(ImmutableMap.of("notes", notes)))); }

Target:
Why not private?
Source:
NotesToJson(Json json) { this.json = checkNotNull(json, "json"); }

Target:
Once the constructor is only visible to the injector, the null check is redundant (the injector already checks nulls). Remove it.
Source:
protected void awaitConsistency() { if (view.getConsistencyModel() == ConsistencyModel.EVENTUAL) { Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS); } }

Target:
Can you just override this in `SwiftContainerIntegrationLiveTest` if needed? This sleep is unfortunate since it slows down all tests unnecessarily, not just the uncommon case of eventual consistency.
Source:
public boolean shouldRetryRequest(HttpCommand command, IOException error) { return isSafeToRetryOnException(command) && ifReplayableBackoffAndReturnTrue(command); }

Target:
what about `isIdempotent(command)` instead of `isSafeToRetryOnException(command)` ?
Source:
public BindAzureBlobMetadataToMultipartRequest(AzureBlobToBlob azureBlob2Blob, BindUserMetadataToHeadersWithPrefix blobBinder) { this.azureBlob2Blob = checkNotNull(azureBlob2Blob, "azureBlob2Blob"); this.blobBinder = checkNotNull(blobBinder, "blobBinder"); }

Target:
Change signature to package private, so only the Guice injector (and test classes) can directly instantiate the class. Then we can remove the redundant null checks?
Source:
public AzureBlobBlockUploadStrategy(AzureBlobClient client, PayloadSlicer slicer, BlobToAzureBlob blobToAzureBlob) { this.client = checkNotNull(client, "client"); this.slicer = checkNotNull(slicer, "slicer"); this.blobToAzureBlob = checkNotNull(blobToAzureBlob, "blobToAzureBlob"); }

Target:
I know this was already public, but make it package private?
Source:
public Statement createBootstrapScriptForGroup(String group) { return groupToBootScript.apply(group); }

Target:
Call `createBootstrapScriptForGroupAndNodeName(group, null)` once the `GroupToBootScript` function is changed.