auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private String sourceName(Token t) { START CharStream input = t.getInputStream(); String srcName = null; if ( input!=null ) { srcName = input.getSourceName(); if ( srcName!=null ) srcName = Misc.getFileName(srcName); } return srcName; END } Overall I like the refactoring, especially the deduplication! However, I suggest using early return as well as braces for all if statements: ```suggestion CharStream input = t.getInputStream(); if ( input==null ) { return null; } String srcName = input.getSourceName(); if ( srcName!=null ) { srcName = Misc.getFileName(srcName); } return srcName; ```

Target:
private String sourceName(Token t) { CharStream input = t.getInputStream(); if ( input==null ) { return null; } String srcName = input.getSourceName(); if ( srcName!=null ) { srcName = Misc.getFileName(srcName); } return srcName; }
Source:
START public <T> AttributeRenderer<? super T> getAttributeRenderer(Class<? extends T> attributeType) { END if ( renderers==null ) { return null; } //noinspection unchecked return renderers.get(attributeType); } The attribute type needs to be exact here. ```suggestion public <T> AttributeRenderer<? super T> getAttributeRenderer(Class<T> attributeType) { ```

Target:
public <T> AttributeRenderer<? super T> getAttributeRenderer(Class<? extends T> attributeType) { if ( renderers==null ) { return null; } //noinspection unchecked return (AttributeRenderer<? super T>) renderers.get(attributeType); }
Source:
public String toString(Object o, String formatString, Locale locale) { // o will be instanceof Number if ( formatString==null ) return o.toString(); Formatter f = new Formatter(locale); f.format(formatString, o); START String str = f.toString(); END f.close(); return str; } :bulb: This code should be in a try/finally for exception-safe closing of the `Formatter` instance.

Target:
public String toString(Object o, String formatString, Locale locale) { // o will be instanceof Number if ( formatString==null ) return o.toString(); Formatter f = new Formatter(locale); try { f.format(formatString, o); return f.toString(); } finally { f.close(); } }
Source:
public String toString(Object o, String formatString, Locale locale) { // o will be instanceof Number if ( formatString==null ) return o.toString(); START Formatter f = null; END String str = ""; try { f = new Formatter(locale); f.format(formatString, o); str = f.toString(); } finally { if (f != null) f.close(); } return str; } :bulb: Slight simplification ``` java Formatter f = new Formatter(locale); try { f.format(formatString, o); return f.toString(); } finally { f.close(); } ```

Target:
public String toString(Object o, String formatString, Locale locale) { // o will be instanceof Number if ( formatString==null ) return o.toString(); Formatter f = new Formatter(locale); try { f.format(formatString, o); return f.toString(); } finally { f.close(); } }
Source:
protected void onResume() { super.onResume(); if (mAppAdapter != null) mAppAdapter.notifyDataSetChanged(); // Set up the progress bar final View vProgressEmpty = (View) findViewById(R.id.vProgressEmpty); START vProgressEmpty.post(new Runnable() { END @Override public void run() { mProgressWidth = vProgressEmpty.getMeasuredWidth(); updateProgress(); } }); } Why is there a runnable needed here? Are you sure this will work on all devices? (the runnable does UI work)

Target:
protected void onResume() { super.onResume(); if (mAppAdapter != null) mAppAdapter.notifyDataSetChanged(); }
Source:
public FongoDBCollection(FongoDB db, String name) { super(db, name); this.fongoDb = db; this.nonIdCollection = name.startsWith("system"); this.expressionParser = new ExpressionParser(); this.updateEngine = new UpdateEngine(); this.objectComparator = expressionParser.buildObjectComparator(true); START this._idIndex = new Index("_id", new BasicDBObject("_id", 1), true); END this.indexes.put(Collections.singleton("_id"), _idIndex); } You probably don't want this if this is a nonIdCollection

Target:
public FongoDBCollection(FongoDB db, String name) { super(db, name); this.fongoDb = db; this.nonIdCollection = name.startsWith("system"); this.expressionParser = new ExpressionParser(); this.updateEngine = new UpdateEngine(); this.objectComparator = expressionParser.buildObjectComparator(true); this._idIndex = new Index("_id", new BasicDBObject("_id", 1), true, true); this.indexes.add(_idIndex); }
Source:
public synchronized void sendUpdates(Map<String, Object> state, Set<String> changed) { if (state.get("ScoreBoard.CurrentPeriodNumber") != "0") { // If the jam has just ended or the score is now official, write out a file. if ((inJam && !bool(state.get("ScoreBoard.InJam"))) START || (bool(state.get("ScoreBoard.OfficialScore")) END && !bool(state.get("ScoreBoard.StatsLocked")) && containsRelevantUpdate(changed))) { writeFile(state); } } inJam = bool(state.get("ScoreBoard.InJam")); } A simpler way to do this would be to make this just `bool(state.get("ScoreBoard.OfficialScore")` without the state. We can then filter out the Clock changes if we want to.

Target:
public synchronized void sendUpdates(Map<String, Object> state, Set<String> changed) { if (state.get("ScoreBoard.CurrentPeriodNumber") != "0") { // If the jam has just ended or the score is now official, write out a file. if ((inJam && !bool(state.get("ScoreBoard.InJam"))) || (bool(state.get("ScoreBoard.OfficialScore")) && containsRelevantUpdate(changed))) { writeFile(state); } } inJam = bool(state.get("ScoreBoard.InJam")); }
Source:
public void restoreSnapshot(PeriodSnapshot s) { synchronized (coreLock) { if (s.getId() != getId()) { return; } if (getCurrentJam() != s.getCurrentJam()) { set(Value.CURRENT_JAM, s.getCurrentJam()); START getLast(NChild.JAM).unlink(); END } } } The jam should be moved, not deleted. Deleting will remove all the lineups etc that have been entered for the jam.

Target:
public void restoreSnapshot(PeriodSnapshot s) { synchronized (coreLock) { if (s.getId() != getId()) { return; } if (getCurrentJam() != s.getCurrentJam()) { remove(NChild.JAM, getCurrentJam()); set(Value.CURRENT_JAM, s.getCurrentJam()); } } }
Source:
String getPath(ScoreBoardEventProvider p) { String path = ""; if (p.getParent() != null) { path = getPath(p.getParent()) + "."; } path = path + p.getProviderName(); START if (!"".equals(p.getProviderId()) && p.getProviderId() != null) { END path = path + "(" + p.getProviderId() + ")"; } return path; } This is a bit odd. p.getProviderId() != null && !p.getProviderId().isEmpty() I think there may also be cases where an empty value is valid

Target:
String getPath(ScoreBoardEventProvider p) { String path = ""; if (p.getParent() != null) { path = getPath(p.getParent()) + "."; } path = path + p.getProviderName(); if (!"".equals(p.getId()) && p.getId() != null) { path = path + "(" + p.getId() + ")"; } return path; }
Source:
public static ScoreBoardClock getInstance() { START if (instance == null) { END instance = new ScoreBoardClock(); } return instance; } If you're doing this you need locking. A static initialiser might be simpler.

Target:
public static ScoreBoardClock getInstance() { return instance; }
Source:
START public void registerClient(ScoreBoardClockClient client) { END clients.add(client); } This should be synchronized

Target:
public synchronized void registerClient(ScoreBoardClockClient client) { clients.add(client); }
Source:
public void timeout() { synchronized (runLock) { createSnapshot(ACTION_TIMEOUT); START requestBatchStart(); END _startTimeout(); requestBatchEnd(); ScoreBoardManager.gameSnapshot(); } } You use a batch here for a single call that also starts a batch, but not in stopJamTO which does similar.

Target:
public void timeout() { synchronized (runLock) { createSnapshot(ACTION_TIMEOUT); _startTimeout(); ScoreBoardManager.gameSnapshot(); } }
Source:
public void ensureAtLeastNPeriods(int n) { START synchronized (this) { END while (periods.size() < n) { PeriodStatsModel psm = new DefaultPeriodStatsModel(periods.size() + 1); psm.addScoreBoardListener(this); periods.add(psm); } } } Is there a reason to go with `synchronized (this)` in this file instead of just adding the `synchronized` keyword to the method signature?

Target:
public synchronized void ensureAtLeastNPeriods(int n) { while (periods.size() < n) { PeriodStatsModel psm = new DefaultPeriodStatsModel(periods.size() + 1); psm.addScoreBoardListener(this); periods.add(psm); } }
Source:
protected void initializeType(File typeDir) { Iterator<File> files = Arrays.asList(typeDir.listFiles((FileFilter)mediaFileFilter)).iterator(); while (files.hasNext()) addMediaElement(typeDir.getName(), files.next()); // Ensure we have an entry, even if dir is empty. synchronized (updateLock) { START update(createTypeElement(typeDir.getName())); END } } There should be brackets on the preceding while in order to make clear that the new code is intended to not be part of the loop.

Target:
protected void initializeType(File typeDir) { Iterator<File> files = Arrays.asList(typeDir.listFiles((FileFilter)mediaFileFilter)).iterator(); while (files.hasNext()) { addMediaElement(typeDir.getName(), files.next()); } // Ensure we have an entry, even if dir is empty. synchronized (updateLock) { update(createTypeElement(typeDir.getName())); } }
Source:
public HCatClient getHCatClient() throws InterruptedException { HCatClient hcatClient = null; int retryCount = 0; while (hcatClient == null && retryCount < numOfRetries) { START hcatClient = hcatUtil.getHCatClient(); END retryCount++; } return hcatClient; } don't retry here as for getting hcatclient blocking queue with timeout is being used

Target:
protected HCatClient getHCatClient() throws InterruptedException { return hcatUtil.getHCatClient(); }
Source:
private ForkliftConsumerI getGroupedTopic(GroupedTopicSource source) throws ConnectorException { if (!source.groupSpecified()) throw new ConnectorException("No consumer group specified"); // Sanitize the group and topic names so that group and topic names don't accidentally // mess up ActiveMQ's pattern matching final String groupName = source.getGroup().replaceAll("\\.", "_"); final String topicName = source.getName().replaceAll("\\.", "_"); START return getConsumerForSource(new QueueSource("Consumer." + groupName + ".VirtualTopic." + topicName)); END } should this be `new GroupedTopicSource`?

Target:
private ForkliftConsumerI getGroupedTopic(GroupedTopicSource source) throws ConnectorException { if (!source.groupSpecified()) throw new ConnectorException("No consumer group specified"); // Sanitize the group and topic names so that group and topic names don't accidentally // mess up ActiveMQ's pattern matching (e.g. by making a group name of // "test.VirtualTopic.blah" and a topic of "topic", which would cause AMQ to look for a topic // named "blah.VirtualTopic.topic" and a group of "test") final String groupName = source.getGroup().replaceAll("\\.", "_"); final String topicName = source.getName(); return getConsumerForSource(new QueueSource("Consumer." + groupName + ".VirtualTopic." + topicName)); }
Source:
public synchronized void stop() throws ConnectorException { try { if (controller != null) { START this.controller.stop(2000, TimeUnit.MILLISECONDS); END this.controller = null; } } catch (InterruptedException e) { log.error("KafkaConnector interrupted while stopping"); } if (kafkaProducer != null) { this.kafkaProducer.close(); this.kafkaProducer = null; } } Minor nit: there are a lot of redundant `this` references lying around.

Target:
public synchronized void stop() throws ConnectorException { try { if (controller != null) { controller.stop(2000, TimeUnit.MILLISECONDS); controller = null; } } catch (InterruptedException e) { log.error("KafkaConnector interrupted while stopping"); } if (kafkaProducer != null) { kafkaProducer.close(); kafkaProducer = null; } }
Source:
private OffsetAndMetadata greaterOffset(OffsetAndMetadata a, OffsetAndMetadata b) { START if (a == null) { END return b; } else if (b == null) { return a; } return a.offset() > b.offset() ? a : b; } You shouldn't _need_ to check for null here, since the merge function will only be called if there is an existing value (which should always be non-null).

Target:
private OffsetAndMetadata greaterOffset(OffsetAndMetadata a, OffsetAndMetadata b) { return a.offset() > b.offset() ? a : b; }
Source:
public KafkaForkliftProducer(String topic, KafkaProducer<?, ?> kafkaProducer) { this.kafkaProducer = kafkaProducer; this.topic = topic; Schema.Parser parser = new Schema.Parser(); START this.forkliftSchema = parser.parse( END "{\"type\":\"record\",\"name\":\"ForkliftMessage\"," + " \"doc\":\"Non-Avro messages sent through forklift use this schema.\",\"fields\":" + "[{\"name\":\"forkliftValue\",\"type\":\"string\",\"default\":\"\", \"doc\":\"The forklift message. " + "3 formats are supported. 1: string value, 2: Json object," + "3: Map represented by key,value entries delimited with newline\"}," + "{\"name\":\"forkliftProperties\",\"type\":\"string\",\"default\":\"\"," + "\"doc\":\"Properties added to support forklift interfaces. Format is key,value entries delimited with new lines\"}]}"); } Isn't this constant and shared across all producers? Then can't it be static?

Target:
public KafkaForkliftProducer(String topic, KafkaProducer<?, ?> kafkaProducer) { this.kafkaProducer = kafkaProducer; this.topic = topic; }
Source:
public String getString (String name, String def) { String value = (String)_data.get(name); START return StringUtil.isBlank(value) ? def : value; END } This is another behavioral change that I don't want to see in an unrelated PR.

Target:
public String getString (String name, String def) { String value = (String)_data.get(name); return value == null ? def : value; }
Source:
public ShellSpout(String... command) { _command = command; START _process = new ShellProcess(new JsonSerializer(), _command); END } hardcoded `JsonSerializer` should not be here, we might have a `default serializer` specified in `defaults.yaml`

Target:
public ShellSpout(String... command) { _command = command; }
Source:
private void handleError(Map action) { String msg = (String) action.get("msg"); START if (msg != null) { END _collector.reportError(new Exception("Shell Process Exception: " + msg)); } } Why do you have to check for null here?

Target:
private void handleError(Map action) { String msg = (String) action.get("msg"); _collector.reportError(new Exception("Shell Process Exception: " + msg)); }
Source:
START @Nullable public LatLng parseLatLng(String value) { END if (value == null) { return null; } String[] components = value.split(","); if (components.length != 2) { return null; } try { return new LatLng(Double.valueOf(components[0]), Double.valueOf(components[1])); } catch (NumberFormatException e) { return null; } } Shouldn't it be `static`?

Target:
@Nullable public static LatLng parseLatLng(String value) { if (value == null) { return null; } String[] components = value.split(","); if (components.length != 2) { return null; } try { return new LatLng(Double.valueOf(components[0]), Double.valueOf(components[1])); } catch (NumberFormatException e) { return null; } }
Source:
protected byte[] searchRaw(Query query) throws AlgoliaException { String paramsString = query.getQueryString(); START if (paramsString.length() > 0) END return client.getRequestRaw("/1/indexes/" + encodedIndexName + "?" + paramsString, true); else return client.getRequestRaw("/1/indexes/" + encodedIndexName, true); } brackets :wink:

Target:
protected byte[] searchRaw(Query query) throws AlgoliaException { String paramsString = query.getQueryString(); if (paramsString.length() > 0) { return client.getRequestRaw("/1/indexes/" + encodedIndexName + "?" + paramsString, true); } else { return client.getRequestRaw("/1/indexes/" + encodedIndexName, true); } }
Source:
public void run() { countDown--; if (countDown == 0) { START System.out.println("## interrupt"); END Thread.currentThread().interrupt(); } } I don't think we need to keep this println.

Target:
public void run() { countDown--; if (countDown == 0) { Thread.currentThread().interrupt(); } }
Source:
public void blockingStreamShouldNotPreventDiagnosis() throws Exception { FastPipedInputStream in = new FastPipedInputStream(); START try (FastPipedOutputStream out = new FastPipedOutputStream(in)) { END out.write(payload); } ClassicCommandTransport ct = (ClassicCommandTransport) new ChannelBuilder("dummy",null) .withMode(Mode.BINARY) .withBaseLoader(getClass().getClassLoader()) .negotiate(in, new NullOutputStream()); verify(ct); } Shouldn't both the stream opening statements be inside the try with resources? ```suggestion try (FastPipedInputStream in = new FastPipedInputStream(); FastPipedOutputStream out = new FastPipedOutputStream(in)) { ```

Target:
public void blockingStreamShouldNotPreventDiagnosis() throws Exception { try (FastPipedInputStream in = new FastPipedInputStream(); FastPipedOutputStream out = new FastPipedOutputStream(in)) { out.write(payload); ClassicCommandTransport ct = (ClassicCommandTransport) new ChannelBuilder("dummy",null) .withMode(Mode.BINARY) .withBaseLoader(getClass().getClassLoader()) .negotiate(in, new NullOutputStream()); verify(ct); } }
Source:
private FastPipedInputStream sink() throws IOException { FastPipedInputStream s = sink.get(); START if (s==null) throw (IOException) new IOException("Reader side has already been abandoned", allocatedAt); END return s; } ```suggestion if (s==null) throw new IOException("Reader side has already been abandoned", allocatedAt); ```

Target:
private FastPipedInputStream sink() throws IOException { FastPipedInputStream s = sink.get(); if (s==null) throw new IOException("Reader side has already been abandoned", allocatedAt); return s; }
Source:
public void testDeadWriterNotification() throws Exception { final OutputStream os = new RemoteOutputStream(new OutputStream() { @Override public void write(int b) throws IOException { System.gc(); START throw (IOException) new IOException(MESSAGE, (Exception) DummyClassLoader.apply(TestCallable.class)); END } }); channel.call(new DeadWriterCallable(os)); } ```suggestion throw new IOException(MESSAGE, (Exception) DummyClassLoader.apply(TestCallable.class)); ```

Target:
public void testDeadWriterNotification() throws Exception { final OutputStream os = new RemoteOutputStream(new OutputStream() { @Override public void write(int b) throws IOException { System.gc(); throw new IOException(MESSAGE, (Exception) DummyClassLoader.apply(TestCallable.class)); } }); channel.call(new DeadWriterCallable(os)); }
Source:
protected void finalize() throws Throwable { super.finalize(); // if we haven't done so, release the exported object on the remote side. // if the object is auto-unexported, the export entry could have already been removed. START if(channel!=null) { END channel.send(new Unexport(channel.newIoId(),oid)); oid = -1; } } `&& oid != -1`

Target:
protected void finalize() throws Throwable { super.finalize(); // if we haven't done so, release the exported object on the remote side. // if the object is auto-unexported, the export entry could have already been removed. if(channel != null && oid != -1) { channel.send(new Unexport(channel.newIoId(),oid)); oid = -1; } }
Source:
public FileSystemJarCache(@Nonnull File rootDir, boolean touch) { this.rootDir = rootDir; this.touch = touch; if (rootDir==null) throw new IllegalArgumentException("Root directory is null"); try { Util.mkdirs(rootDir); } catch (IOException ex) { START throw new IllegalArgumentException("Root directory not writable: " + rootDir); END } } Can we append cause so admins has a chance to identify the cause and fix?

Target:
public FileSystemJarCache(@Nonnull File rootDir, boolean touch) { this.rootDir = rootDir; this.touch = touch; if (rootDir==null) throw new IllegalArgumentException("Root directory is null"); try { Util.mkdirs(rootDir); } catch (IOException ex) { throw new IllegalArgumentException("Root directory not writable: " + rootDir, ex); } }
Source:
START public synchronized Object getProperty(Object key) { END return properties.get(key); } Hmmm are we sure we want to depend on the `Channel` monitor... for property access it may be preferential to use `properties` as the monitor object

Target:
public Object getProperty(Object key) { return properties.get(key); }
Source:
/*package*/ static ClassFilter createDefaultInstance() { List<Pattern> patternOverride = loadPatternOverride(); try { if (patternOverride != null) { LOGGER.log(Level.FINE, "Using user specified overrides for class blacklisting"); return new RegExpClassFilter(patternOverride); } else { LOGGER.log(Level.FINE, "Using default in built class blacklisting"); return new RegExpClassFilter(DEFAULT_PATTERNS); } } catch (Error e) { // when being used by something like XStream the actual cause gets swallowed START LOGGER.log(Level.SEVERE, "Failed to initialize the default class filter", e); END throw e; } } I'm not a big fan of this construct, because it may hide the original OOM if a new one happens within Logger listeners. But good for other error types

Target:
/*package*/ static ClassFilter createDefaultInstance() { try { List<Pattern> patternOverride = loadPatternOverride(); if (patternOverride != null) { LOGGER.log(Level.FINE, "Using user specified overrides for class blacklisting"); return new RegExpClassFilter(patternOverride); } else { LOGGER.log(Level.FINE, "Using default in built class blacklisting"); return new RegExpClassFilter(DEFAULT_PATTERNS); } } catch (Error e) { // when being used by something like XStream the actual cause gets swallowed LOGGER.log(Level.SEVERE, "Failed to initialize the default class filter", e); throw e; } }
Source:
public void putWithAuthentication(String url, String username, String password, int id, Model model, AsyncHttpResponseHandler response) throws UnsupportedEncodingException { Header[] headers = { createBasicAuthenticationHeader(username, password) }; START String body = model.getData().toString().substring(0); END put(url, id, new ArrayList<Header>(Arrays.asList(headers)), body, response); } Why the `.substring(0)`?

Target:
public void putWithAuthentication(String url, String username, String password, int id, Model model, AsyncHttpResponseHandler response) throws UnsupportedEncodingException { Header[] headers = { createBasicAuthenticationHeader(username, password) }; String body = model.getData().toString(); put(url, id, new ArrayList<Header>(Arrays.asList(headers)), body, response); }
Source:
public Variable getVariableInstance(){ if(v_inst == null){ v_inst = new Variable(getVariableIdentifierInstance(), getTypeExpression()); } return v_inst; START } END Why do you need to lazily create the variable instance? I think our convention so far has been that the `get*Instance()` methods always create a new instance and tests that require the same instance multiple times just hold a local copy.

Target:
public Variable getVariableInstance(){ return new Variable(getVariableIdentifierInstance(), getTypeExpression()); }
Source:
private NamespaceIdentifier getNamespaceIdentifierInstance() { if (namespaceIdentifierInstance == null) { ArrayList<String> name = new ArrayList<String>(1); name.add("whdl"); namespaceIdentifierInstance = new NamespaceIdentifier(name); } return namespaceIdentifierInstance; START } END Same feedback as above

Target:
private NamespaceIdentifier getNamespaceIdentifierInstance() { ArrayList<String> name = new ArrayList<String>(1); name.add("whdl"); return new NamespaceIdentifier(name); }
Source:
public Variable getVariable(VariableIdentifier identifier) throws VariableNotDefinedException{ // FIXME this does not handle namespaces correctly Variable v = symbolTable.get(identifier); if(v == null){ // no such variable in this scope; check parent scope if(parentScope == null){ throw new VariableNotDefinedException(identifier); } START return parentScope.getVariable(identifier); END }else{ return v; } } Throw this in an `else` clause

Target:
public Variable getVariable(VariableIdentifier identifier) throws VariableNotDefinedException { // FIXME this does not handle namespaces correctly Variable v = symbolTable.get(identifier); if (v == null) { // no such variable in this scope; check parent scope if (parentScope == null) { throw new VariableNotDefinedException(identifier); } else { return parentScope.getVariable(identifier); } } else { return v; } }
Source:
public static boolean validQuestionGroups(final Survey survey){ START return survey.getQuestionGroupMap().values().stream().filter(i -> i.getRepeatable().booleanValue()).collect(Collectors.toList()).size() == 0; END } Why do we need an explicit `boolean` primitive? .... using `i.getRepeatable()` does the trick

Target:
public static boolean validQuestionGroups(final Survey survey) { return survey.getQuestionGroupMap().values().stream().filter(i -> i.getRepeatable()).collect(Collectors.toList()).size() == 0; }
Source:
private Entity event(Entity entity) { String kind = entity.getKey().getKind(); final EventTypes eventTypes = EventUtils .getEventAndActionType(kind); if (eventTypes != null) { Map<String, Object> event = updateOrCreateEvent(entity, eventTypes); try { return EventUtils.createEventLogEntity(event, new Date()); } catch (IOException e) { throw new RuntimeException(e); } } START return entity; END } Does this mean if no event type is found then the entity would get stored as is in the event queue?

Target:
private Entity event(Entity entity) { String kind = entity.getKey().getKind(); final EventTypes eventTypes = EventUtils .getEventAndActionType(kind); if (eventTypes == null) { return null; } else { Map<String, Object> event = updateOrCreateEvent(entity, eventTypes); try { return EventUtils.createEventLogEntity(event, new Date()); } catch (IOException e) { throw new RuntimeException(e); } } }
Source:
void testValidSheets() throws IOException { DataImporter dimp = new RawDataSpreadsheetImporter(); //Check that a canonical file passes File file1 = createValidTestSpreadsheet("/tmp/valid1.xlsx"); Map<Integer,String> errors = dimp.validate(file1); for (Integer i: errors.keySet()) { START System.out.printf("Unexpected error, row %d: %s", i, errors.get(i)); END } assertEquals(0, errors.size()); } In this case rather than print out the errors, since it’s supposed to be a valid test sheet, you should assert that errors is empty and that should be enough. If it isn’t empty I believe it prints out the error map

Target:
public void testValidSheets() throws IOException { DataImporter dimp = new RawDataSpreadsheetImporter(); //Check that a canonical file passes File file1 = createValidTestSpreadsheet("/tmp/valid1.xlsx"); Map<Integer,String> errors = dimp.validate(file1); assertEquals(0, errors.size()); }
Source:
START public void setGeoLocation(String geoLocationString) { END String[] geoParts = geoLocationString.split("\\|"); if (geoParts == null || geoParts.length < 2 || geoParts[0] == null || geoParts[1] == null) return; this.latitude = Double.parseDouble(geoParts[0]); this.longitude = Double.parseDouble(geoParts[1]); } Just in case: is it possible that geoLocationString is null?

Target:
public void setGeoLocation(String geoLocationString) { if (geoLocationString == null) { return; } String[] geoParts = geoLocationString.split("\\|"); if (geoParts == null || geoParts.length < 2 || geoParts[0] == null || geoParts[1] == null) { return; } this.latitude = Double.parseDouble(geoParts[0]); this.longitude = Double.parseDouble(geoParts[1]); }
Source:
private SurveyAssignment marshallToDomain(SurveyAssignmentDto dto) { //String[] handsOff = {"keyId", "key"}; final SurveyAssignment sa = new SurveyAssignment(); BeanUtils.copyProperties(dto, sa); START sa.setKey(KeyFactory.createKey("SurveyAssignment", dto.getKeyId())); END sa.setDeviceIds(dto.getDevices()); sa.setSurveyIds(dto.getSurveys()); return sa; } Perhaps only set the key when `keyId != null`.

Target:
private SurveyAssignment marshallToDomain(SurveyAssignmentDto dto) { final SurveyAssignment sa = new SurveyAssignment(); BeanUtils.copyProperties(dto, sa); if (dto.getKeyId() != null) { sa.setKey(KeyFactory.createKey("SurveyAssignment", dto.getKeyId())); } sa.setDeviceIds(dto.getDevices()); sa.setSurveyIds(dto.getSurveys()); return sa; }
Source:
protected List<QuestionDto> parseQuestions(String response) throws Exception { final ObjectMapper JSON_RESPONSE_PARSER = new ObjectMapper(); List<QuestionDto> dtoList = new ArrayList<QuestionDto>(); final JsonNode questionListNode = JSON_RESPONSE_PARSER.readTree(response).get("dtoList"); final List<QuestionDto> qList = JSON_RESPONSE_PARSER.readValue( questionListNode, new TypeReference<List<QuestionDto>>() { }); START dtoList.addAll(qList); //Why? END return dtoList; } Returning `qList`here should be enough, unless `qList` is null

Target:
protected List<QuestionDto> parseQuestions(String response) throws Exception { final ObjectMapper JSON_RESPONSE_PARSER = new ObjectMapper(); final JsonNode questionListNode = JSON_RESPONSE_PARSER.readTree(response).get("dtoList"); final List<QuestionDto> qList = JSON_RESPONSE_PARSER.readValue( questionListNode, new TypeReference<List<QuestionDto>>() { }); return qList; }
Source:
public static Map<String, Object> parseCaddisflyResponseValue(String caddisflyValue) { START Map<String, Object> caddisflyResponseMap = new HashMap<String, Object>(); END try { caddisflyResponseMap = JSON_OBJECT_MAPPER.readValue(caddisflyValue, Map.class); } catch (IOException e) { log.error("Failed to parse the caddisfly response"); } if (caddisflyResponseMap != null) { return caddisflyResponseMap; } else { return Collections.emptyMap(); } } new HashMap<>(), explicit type is no longer necessary

Target:
public static Map<String, Object> parseCaddisflyResponseValue(String caddisflyValue) { Map<String, Object> caddisflyResponseMap = new HashMap<>(); try { caddisflyResponseMap = JSON_OBJECT_MAPPER.readValue(caddisflyValue, Map.class); } catch (IOException e) { log.error("Failed to parse the caddisfly response"); } if (caddisflyResponseMap != null) { return caddisflyResponseMap; } else { return Collections.emptyMap(); } }
Source:
private boolean areLeafNodes(CascadeNodeDao dao, Long cascadeResourceId, List<CascadeNode> nodes) { if (nodes.size() == 0) { START return true; END } else { CascadeNode firstNode = nodes.get(0); List<CascadeNode> childNodes = dao.listCascadeNodesByResourceAndParentId( cascadeResourceId, firstNode.getKey().getId()); return childNodes.size() == 0; } } Perhaps you can move the `nodes.size() == 0` branch to just before the `if(!areLeafNodes())`. This way the meaning of the `areLeafNodes()` function is not mixed with checking if the list of nodes is empty.

Target:
private boolean areLeafNodes(CascadeNodeDao dao, Long cascadeResourceId, List<CascadeNode> nodes) { CascadeNode firstNode = nodes.get(0); List<CascadeNode> childNodes = dao.listCascadeNodesByResourceAndParentId( cascadeResourceId, firstNode.getKey().getId()); return childNodes.size() == 0; }
Source:
public List<SurveyGroup> listByProjectFolderId(Long parentId) { START parentId = parentId < 0 ? null : parentId; END return super.listByProperty("parentId", parentId, "Long"); } It's not a good practice to override a parameter, create a local variable to default `parentId` to `null`

Target:
public List<SurveyGroup> listByProjectFolderId(Long parentId) { return super.listByProperty("parentId", parentId, "Long"); }
Source:
private String[] parseCredentials(String credentialsString) { if (credentialsString == null) throw new BadCredentialsException("Authorization required"); String[] credentials = credentialsString.split(":"); if (credentials.length != 2) throw new BadCredentialsException("Authorization required"); START return credentials; END } Do we want to `.trim()` the 2 parts to avoid possible problems if an `Authorization` header comes like `<key> : <signature>` ?

Target:
private String[] parseCredentials(String credentialsString) { if (credentialsString == null) throw new BadCredentialsException("Authorization required"); String[] credentials = credentialsString.split(":"); if (credentials.length != 2) { throw new BadCredentialsException("Authorization required"); } credentials[0] = credentials[0].trim(); credentials[1] = credentials[1].trim(); return credentials; }
Source:
public void existsByExampleShouldReturnNonExistingWithoutThrowException() { Example<ReactivePerson> example = Example.of(new ReactivePerson("foo", "bar", -1)); START StepVerifier.create(repository.findOne(example)).expectNextCount(0).verifyComplete(); END } `.expectNextCount(0)` can be omitted and simplified to `StepVerifier.create(repository.findOne(example)).verifyComplete();`

Target:
public void existsByExampleShouldReturnNonExistingWithoutThrowException() { Example<ReactivePerson> example = Example.of(new ReactivePerson("foo", "bar", -1)); StepVerifier.create(repository.findOne(example)).verifyComplete(); }
Source:
public DBObject fetch(DBRef dbRef) { START return ReflectiveDBRefResolver.fetch(MongoClientVersion.isMongo3Driver() ? mongoDbFactory.getDb() : null, dbRef); END } Wouldn't the test case become much simple if we just handed the factory into the fetch method? `ReflectiveDbRefResolver` does an `isMongo3Driver()` anyway, so why not just lookup the `DB` within that guard? That would be a simple unit test for `ReflectiveDbRefResolver.fetch(MongoDbFactory, DBRef)` then, wouldn't i?

Target:
public DBObject fetch(DBRef dbRef) { return ReflectiveDBRefResolver.fetch(mongoDbFactory, dbRef); }
Source:
public void updateFirstShouldDoNothingWhenCalledForEntitiesThatDoNotExist() { Query q = query(where("id").is(Long.MIN_VALUE)); START assumeThat(template.findOne(q, VersionedPerson.class), nullValue()); END template.updateFirst(q, Update.update("lastname", "supercalifragilisticexpialidocious"), VersionedPerson.class); assertThat(template.findOne(q, VersionedPerson.class), nullValue()); } Do we need that `assumeThat(…)` here? I'm not a big fan of them as they essentially express: "we expect the precondition to fail but don't want the test to fail then" which is not really what we're doing here, right?

Target:
public void updateFirstShouldDoNothingWhenCalledForEntitiesThatDoNotExist() { Query q = query(where("id").is(Long.MIN_VALUE)); template.updateFirst(q, Update.update("lastname", "supercalifragilisticexpialidocious"), VersionedPerson.class); assertThat(template.findOne(q, VersionedPerson.class), nullValue()); }
Source:
public String getServerVersion() { if (getStorageState() != State.UPDATED) { return NEED_UPDATE; } START String version = updateStatus.getServerVersion(); END return version == null ? "Unknown" : version; } I made this change because the `GlobalStorageStatus.getServerVersion()` method is annotated with `@CheckForNull` and I got an issue, that's why I added the check. So we can just ignore the issue ?

Target:
public String getServerVersion() { if (getStorageState() != State.UPDATED) { return NEED_UPDATE; } return updateStatus.getServerVersion(); }
Source:
public UserRole[] getAllowedRoles() { START return new UserRole[] { UserRole.MANAGER, UserRole.ADMINISTRATOR }; END } Probably smarter that way yes

Target:
public UserRole[] getAllowedRoles() { return new UserRole[] { UserRole.ADMINISTRATOR }; }
Source:
private SourceSystemId parseSource(String lahdeJarjestelmaId) { START if (StringUtils.isNotBlank(lahdeJarjestelmaId) && lahdeJarjestelmaId.contains(":")) { END KoskiStudyProgrammeHandler handler = KoskiStudyProgrammeHandler.valueOf(StringUtils.substringBefore(lahdeJarjestelmaId, ":")); Long studentId = Long.valueOf(StringUtils.substringAfter(lahdeJarjestelmaId, ":")); return new SourceSystemId(handler, studentId); } return null; } No biggie but StringUtils.contains(lahdeJarjestelmaId, ":") should work just the same.

Target:
private SourceSystemId parseSource(String lahdeJarjestelmaId) { if (StringUtils.contains(lahdeJarjestelmaId, ":")) { KoskiStudyProgrammeHandler handler = KoskiStudyProgrammeHandler.valueOf(StringUtils.substringBefore(lahdeJarjestelmaId, ":")); Long studentId = Long.valueOf(StringUtils.substringAfter(lahdeJarjestelmaId, ":")); return new SourceSystemId(handler, studentId); } return null; }
Source:
private Enum reverseLookup(Class enumClass, String enumValue) { try { Method reverseLookupMethod = enumClass.getMethod("reverseLookup", String.class); START if (reverseLookupMethod != null) { END Enum e = (Enum) reverseLookupMethod.invoke(null, enumValue); return e; } } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) { } return null; } I suppose null check is irrelevant, as getMethod would have thrown an exception about a missing method already?

Target:
private Enum reverseLookup(Class enumClass, String enumValue) { try { Method reverseLookupMethod = enumClass.getMethod("reverseLookup", String.class); Enum e = (Enum) reverseLookupMethod.invoke(null, enumValue); return e; } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) { } return null; }
Source:
protected String getDiaarinumero(Student student) { Long studyProgrammeId = student.getStudyProgramme() != null ? student.getStudyProgramme().getId() : null; Long curriculumId = student.getCurriculum() != null ? student.getCurriculum().getId() : null; if ((studyProgrammeId != null) && (curriculumId != null)) START return settings.getDiaariNumero(studyProgrammeId, curriculumId); END else return null; } Use braces - see https://www.dwheeler.com/essays/apple-goto-fail.html

Target:
protected String getDiaarinumero(Student student) { Long studyProgrammeId = student.getStudyProgramme() != null ? student.getStudyProgramme().getId() : null; Long curriculumId = student.getCurriculum() != null ? student.getCurriculum().getId() : null; if ((studyProgrammeId != null) && (curriculumId != null)) { return settings.getDiaariNumero(studyProgrammeId, curriculumId); } else { return null; } }
Source:
protected boolean isPakollinenOppiaine(Student student, KoskiOppiaineetYleissivistava oppiaine) { Set<KoskiOppiaineetYleissivistava> pakollisetOppiaineet = settings.getPakollisetOppiaineet(student.getStudyProgramme().getId()); if (pakollisetOppiaineet != null) START return pakollisetOppiaineet.contains(oppiaine); END // TODO Vapautetut aineet return false; } Use braces - see https://www.dwheeler.com/essays/apple-goto-fail.html

Target:
protected boolean isPakollinenOppiaine(Student student, KoskiOppiaineetYleissivistava oppiaine) { Set<KoskiOppiaineetYleissivistava> pakollisetOppiaineet = settings.getPakollisetOppiaineet(student.getStudyProgramme().getId()); if (pakollisetOppiaineet != null) { return pakollisetOppiaineet.contains(oppiaine); } return false; }
Source:
public static ArviointiasteikkoYleissivistava bestGrade(Collection<ArviointiasteikkoYleissivistava> collection) { ArviointiasteikkoYleissivistavaComparator comparator = new ArviointiasteikkoYleissivistavaComparator(); ArviointiasteikkoYleissivistava bestGrade = null; for (ArviointiasteikkoYleissivistava grade : collection) { if (bestGrade == null || comparator.compare(grade, bestGrade) > 0) START bestGrade = grade; END } return bestGrade; } Braces

Target:
public static ArviointiasteikkoYleissivistava bestGrade(Collection<ArviointiasteikkoYleissivistava> collection) { ArviointiasteikkoYleissivistavaComparator comparator = new ArviointiasteikkoYleissivistavaComparator(); ArviointiasteikkoYleissivistava bestGrade = null; for (ArviointiasteikkoYleissivistava grade : collection) { if (bestGrade == null || comparator.compare(grade, bestGrade) > 0) { bestGrade = grade; } } return bestGrade; }
Source:
public UserRole[] getAllowedRoles() { START return new UserRole[] { UserRole.MANAGER, UserRole.STUDY_PROGRAMME_LEADER, UserRole.ADMINISTRATOR }; END } Should be limited to just UserRole.ADMINISTRATOR, just in case.

Target:
public UserRole[] getAllowedRoles() { return new UserRole[] { UserRole.ADMINISTRATOR }; }
Source:
private void execute(IExecution<DB> execution, boolean asTransaction) { query( db -> { execution.execute(db); START return Optional.empty(); END }, asTransaction ); } ```suggestion return null; ``` Nitpick: returning `null` also works, and is slightly simpler.

Target:
private void execute(IExecution<DB> execution, boolean asTransaction) { query( db -> { execution.execute(db); return null; }, asTransaction ); }
Source:
public DbMetricsImpl(int maxTotalConnections, int minIdleConnections, long maxWaitMillis, long keepAliveMillis) { START startTime = System.currentTimeMillis(); END this.maxTotalConnections = maxTotalConnections; this.minIdleConnections = minIdleConnections; this.maxWaitMillis = maxWaitMillis; this.keepAliveMillis = keepAliveMillis; } Since all the other parameters here are referred to with `this.`, let's keep the same style for `startTime`.

Target:
public DbMetricsImpl(int maxTotalConnections, int minIdleConnections, long maxWaitMillis, long keepAliveMillis) { this.startTime = System.currentTimeMillis(); this.maxTotalConnections = maxTotalConnections; this.minIdleConnections = minIdleConnections; this.maxWaitMillis = maxWaitMillis; this.keepAliveMillis = keepAliveMillis; }
Source:
public T get() { if (persistence == null) { START synchronized (this) { END this.persistence = build(conn, databases); } } if (disableCaching) { persistence.disableCaching(); } return persistence; } is the synchronization around trying to prevent people from simultaneously using the database connection? if so, I think there's a case where you call get() on two persistences simultaneously and it'll use it at the same time. if that's the goal then synchronizing on conn seems safer.

Target:
public T get() { if (persistence == null) { synchronized (this) { if (persistence == null) { this.persistence = build(conn, databases); } } } if (disableCaching) { persistence.disableCaching(); } return persistence; }
Source:
START public DatabasesImpl() { END this(new DatabaseConnection("database1")); } I don't think this will do what we want though, because new DatabaseConnection("database1") will try to load the db's properties from the yaml. We need that connection to be lazily instantiated.

Target:
public DatabasesImpl() { }
Source:
private boolean hasContextMultipleReferences(Context context) { int counter = 0; Iterator<Context> iterator = context.getHost().getContexts().iterator(); while (counter <= 1) { START if (!iterator.hasNext()) break; END if (context.getPath().equals(iterator.next().getPath())) { ++counter; } } return counter > 1; } This can be moved to the while condition to avoid unnecessary break.

Target:
private boolean hasContextMultipleReferences(Context context) { int counter = 0; Iterator<Context> iterator = context.getHost().getContexts().iterator(); while (counter <= 1 && iterator.hasNext()) { if (context.getPath().equals(iterator.next().getPath())) { ++counter; } } return counter > 1; }
Source:
public void should_throw_error_if_consumer_array_is_null() { // GIVEN Consumer<String>[] consumers = null; START Object o = null; END String message = "The Consumer<? super E>... expressing the assertions consumers must not be null"; // WHEN/THEN assertThatNullPointerException().isThrownBy(() -> assertThat(actual).satisfy(consumers)) .withMessage(message); } Object ```o``` is never used. ```suggestion ```

Target:
public void should_throw_error_if_consumer_array_is_null() { // GIVEN Consumer<String>[] consumers = null; String message = "The Consumer<? super E>... expressing the assertions consumers must not be null"; // WHEN/THEN assertThatNullPointerException().isThrownBy(() -> assertThat(actual).satisfy(consumers)) .withMessage(message); }
Source:
public AbstractStringAssert<?> asHexString() { objects.assertNotNull(info, actual); START return Assertions.assertThat(Hexadecimals.toHexString(actual)); END } static imports

Target:
public AbstractStringAssert<?> asHexString() { objects.assertNotNull(info, actual); return Assertions.assertThat(toHexString(actual)); }
Source:
START private short toShort(int value) { END return (short) value; } minor: make it static

Target:
private static short toShort(int value) { return (short) value; }
Source:
public final boolean equals(Object obj) { START if (this == obj) return true; END if (!(obj instanceof Tuple)) return false; Tuple other = (Tuple) obj; return Arrays.deepEquals(values.toArray(), other.values.toArray()); } I'm ok with that, we might even put the class as final, I don't see why people would subclass `Tuple` it's really an immutable data class.

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Tuple)) return false; Tuple other = (Tuple) obj; return Arrays.deepEquals(values.toArray(), other.values.toArray()); }
Source:
public void assertHasSuperclass(AssertionInfo info, Class<?> actual, Class<?> superclass) { assertNotNull(info, actual); Class<?> actualSuperclass = actual.getSuperclass(); START if (actualSuperclass == null && superclass != null || actualSuperclass != null && !actualSuperclass.equals(superclass)) { END throw failures.failure(info, shouldHaveSuperclass(actual, superclass)); } } add `()` to group && conditions for clarity

Target:
public void assertHasSuperclass(AssertionInfo info, Class<?> actual, Class<?> superclass) { assertNotNull(info, actual); Class<?> actualSuperclass = actual.getSuperclass(); if ((actualSuperclass == null && superclass != null) || (actualSuperclass != null && !actualSuperclass.equals(superclass))) { throw failures.failure(info, shouldHaveSuperclass(actual, superclass)); } }
Source:
private ShouldHaveMessage(Throwable actual, String expectedMessage) { super("%n" + "Expecting message to be:%n" + " <%s>%n" + "but was:%n" + " <%s>%n" + "%n" + "Throwable that failed the check:%n" + START "%n" + Strings.escapePercent(getStackTrace(actual)), // to avoid AssertJ default String formatting END expectedMessage, actual.getMessage()); } style: prefer static import

Target:
private ShouldHaveMessage(Throwable actual, String expectedMessage) { super("%n" + "Expecting message to be:%n" + " <%s>%n" + "but was:%n" + " <%s>%n" + "%n" + "Throwable that failed the check:%n" + "%n" + escapePercent(getStackTrace(actual)), // to avoid AssertJ default String formatting expectedMessage, actual.getMessage()); }
Source:
START private boolean hasCharacteristic(int characteristics, int characteristic) { END return (characteristics & characteristic) == characteristic; } can be static

Target:
private static boolean hasCharacteristic(int characteristics, int characteristic) { return (characteristics & characteristic) == characteristic; }
Source:
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { if (parameterContext.getParameter().getType() == SoftAssertions.class) { return getStore(extensionContext).getOrComputeIfAbsent(SoftAssertions.class); } START return getStore(extensionContext).getOrComputeIfAbsent(BDDSoftAssertions.class); END } Done in latest commit: 21f5677

Target:
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { // The parameter type is guaranteed to be either SoftAssertions or BDDSoftAssertions return getStore(extensionContext).getOrComputeIfAbsent(parameterContext.getParameter().getType()); }
Source:
START public SELF isBefore(LocalDateTime other) { END Objects.instance().assertNotNull(info, actual); assertLocalDateTimeParameterIsNotNull(other); comparables.assertIsBefore(info, actual, other); return myself; } Mentioning and explaining the breaking change should be done for all changed assertions, I know that's a bit of work but I think it is necessary.

Target:
public SELF isBefore(LocalDateTime other) { assertLocalDateTimeParameterIsNotNull(other); comparables.assertIsBefore(info, actual, other); return myself; }
Source:
public <T extends Comparable<? super T>> void assertLessThan(AssertionInfo info, T actual, T other) { START this.assertLessThan(info, actual, other, ShouldBeLess::shouldBeLess); END } minor: remove `this.`

Target:
public <T extends Comparable<? super T>> void assertLessThan(AssertionInfo info, T actual, T other) { assertLessThan(info, actual, other, ShouldBeLess::shouldBeLess); }
Source:
public void check(ThrowingRunnable assertion) { try { assertion.run(); } catch (AssertionError error) { proxies.collectError(error); } catch (Exception e) { START throw new RuntimeException(e); END } } it would be nice to catch runtime and rethrow them as is instead wrapping in them in another runtime.

Target:
public void check(ThrowingRunnable assertion) throws Exception { try { assertion.run(); } catch (AssertionError error) { proxies.collectError(error); } }