auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testCreatePointStyle(){ // The following is complex, and should be built from // an SLD document and not by hand PointSymbolizer pointsym = sf.createPointSymbolizer(); pointsym.setGraphic(sf.getDefaultGraphic()); NumberRange<Double> scaleRange = NumberRange.create( 1.0,50000.0); Style2D style = sld.createPointStyle(null, pointsym, scaleRange); assertNotNull( style ); PointStyle2D ps = (PointStyle2D) style; assertEquals(0.0f, ps.getAnchorPointX(), 0.0f); START assertEquals(0.5f, ps.getAnchorPointY(), 0.0f); END } okay so you already have this covered, no need for AnchorPointTest above?

Target:
public void testCreatePointStyle(){ // The following is complex, and should be built from // an SLD document and not by hand PointSymbolizer pointsym = sf.createPointSymbolizer(); pointsym.setGraphic(sf.getDefaultGraphic()); NumberRange<Double> scaleRange = NumberRange.create( 1.0,50000.0); Style2D style = sld.createPointStyle(null, pointsym, scaleRange); assertNotNull( style ); }
Source:
public Number getLineRoundLimit() { START if (paint.get("line-round_limit") != null) { END return (Number) paint.get("line-round-limit"); } else { return 1.05; } } This underscore should also be a dash

Target:
public Number getLineRoundLimit() { if (paint.get("line-round-limit") != null) { return (Number) paint.get("line-round-limit"); } else { return 1.05; } }
Source:
public void visit(PolygonSymbolizer poly) { super.visit(poly); PolygonSymbolizer copy = (PolygonSymbolizer) pages.peek(); Unit<Length> uom = copy.getUnitOfMeasure(); rescaleStroke(copy.getStroke(), uom); rescaleFill(copy.getFill(), uom); START scaleIntArrayOption(copy.getOptions(), TextSymbolizer.GRAPHIC_MARGIN_KEY, uom); END copy.setUnitOfMeasure(NonSI.PIXEL); } While it's the same value, it's confusing to see TextSymbolizer referenced here, PolygonSymbolizer gets the right constant in this same pull request.

Target:
public void visit(PolygonSymbolizer poly) { super.visit(poly); PolygonSymbolizer copy = (PolygonSymbolizer) pages.peek(); Unit<Length> uom = copy.getUnitOfMeasure(); rescaleStroke(copy.getStroke(), uom); rescaleFill(copy.getFill(), uom); scaleIntArrayOption(copy.getOptions(), PolygonSymbolizer.GRAPHIC_MARGIN_KEY, uom); copy.setUnitOfMeasure(NonSI.PIXEL); }
Source:
private CoverageSource getGridCoverageSource(final String coverageName) throws IOException { // Preliminar check on name availability checkIsSupported(coverageName); synchronized (coverages) { if (coverages.containsKey(coverageName)) { return coverages.get(coverageName); } // create, cache and return CoverageSource source = access.access(new NameImpl(coverageName), null, AccessType.READ_ONLY, null, null); if (source instanceof NetCDFSource) { } START END coverages.put(coverageName, source); return source; } } What is this block?

Target:
private CoverageSource getGridCoverageSource(final String coverageName) throws IOException { // Preliminar check on name availability checkIsSupported(coverageName); synchronized (coverages) { if (coverages.containsKey(coverageName)) { return coverages.get(coverageName); } // create, cache and return CoverageSource source = access.access(new NameImpl(coverageName), null, AccessType.READ_ONLY, null, null); coverages.put(coverageName, source); return source; } }
Source:
private GroupByVisitor buildVisitor(String aggregateAttribute, String aggregateVisitor, String[] groupByAttributes) { GroupByVisitorBuilder visitorBuilder = new GroupByVisitorBuilder() .withAggregateAttribute(aggregateAttribute, buildingType) .withAggregateVisitor(aggregateVisitor); for (String groupByAttribute : groupByAttributes) { visitorBuilder.withGroupByAttribute(groupByAttribute, buildingType); } GroupByVisitor visitor = visitorBuilder.build(); START return visitor; END } The visitor variable is not need could simply be: `return visitorBuilder.build();`

Target:
private GroupByVisitor buildVisitor(String aggregateAttribute, String aggregateVisitor, String[] groupByAttributes) { GroupByVisitorBuilder visitorBuilder = new GroupByVisitorBuilder() .withAggregateAttribute(aggregateAttribute, buildingType) .withAggregateVisitor(aggregateVisitor); for (String groupByAttribute : groupByAttributes) { visitorBuilder.withGroupByAttribute(groupByAttribute, buildingType); } return visitorBuilder.build(); }
Source:
public F next() throws NoSuchElementException { if(next==null&&this.hasNext()==false) { START throw new NoSuchElementException(); END } F f = next; next = null; return f; } minor suggestions: please, check the formatting (need some whitespaces). I would also personally use !this.hasNext() instead of explicit check with false. if (next == null && !this.hasNext()) {

Target:
public F next() throws NoSuchElementException { if(next==null && !this.hasNext()) { throw new NoSuchElementException(); } F f = next; next = null; return f; }
Source:
START public static String getAlternativePath(String path, boolean removeExtension) { END return FOOTPRINTS_DATA_DIR != null ? getAlternativeFile(path, removeExtension).getAbsolutePath() : null; } Public? Does not seem this method is used anywhere else

Target:
private static String getAlternativePath(String path, boolean removeExtension) { return FOOTPRINTS_DATA_DIR != null ? getAlternativeFile(path, removeExtension).getAbsolutePath() : null; }
Source:
START private static void checkAllInserted(int[] inserts, int size) throws IOException { END int sum = 0; for (int cur: inserts) { if (cur == PreparedStatement.SUCCESS_NO_INFO) { return; // cannot check } else if (cur == PreparedStatement.EXECUTE_FAILED) { throw new IOException("Failed to insert some features"); } sum += cur; } if (sum != size) { throw new IOException("Failed to insert some features"); } } Why static, only this class seems to be using it

Target:
static void checkAllInserted(int[] inserts, int size) throws IOException { int sum = 0; for (int cur: inserts) { if (cur == PreparedStatement.SUCCESS_NO_INFO) { return; // cannot check } else if (cur == PreparedStatement.EXECUTE_FAILED) { throw new IOException("Failed to insert some features"); } sum += cur; } if (sum != size) { throw new IOException("Failed to insert some features"); } }
Source:
public ImageWorker(RenderingHints hints) { START setRenderingHints(hints); END } Shouldn't this call the empty constructor? Or the empty constructor has useless code inside of it?

Target:
public ImageWorker(RenderingHints hints) { this(); setRenderingHints(hints); }
Source:
public boolean hasNext() throws IOException { if( csvWriter == null ){ START throw new IOException("Writer has been closed"); END } if (this.appending) { return false; // reader has no more contents } return iterator.hasNext(); } @tbarsballe has gone through and done a QA run to ensure closed writers return hasNext(): false (rather than thrown an IOException). Lets stick with that for consistency (principle of least surprise)

Target:
public boolean hasNext() throws IOException { if( csvWriter == null ){ return false; } if (this.appending) { return false; // reader has no more contents } return iterator.hasNext(); }
Source:
public StringBuilder dateToText( Date date, StringBuilder output ){ START DateFormat formatter; END // If the Date has millisecond resolution, print the millis. if (date.getTime() % 1000 == 0) { formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz"); } else { formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz"); } formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00")); String text = formatter.format(date); // GMT is not part of CQL syntax so it is removed text = text.replace("GMT", ""); output.append( text ); return output; } add a final to ensure it is set: `final DateFormat formatter`

Target:
public StringBuilder dateToText( Date date, StringBuilder output ){ final DateFormat formatter; // If the Date has millisecond resolution, print the millis. if (date.getTime() % 1000 == 0) { formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz"); } else { formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz"); } formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00")); String text = formatter.format(date); // GMT is not part of CQL syntax so it is removed text = text.replace("GMT", ""); output.append( text ); return output; }
Source:
protected EnvVars buildEnv(AbstractProject<?, ?> job) { EnvVars env = new EnvVars(); for (EnvironmentContributor contributor : EnvironmentContributor.all()) { try { contributor.buildEnvironmentFor(job, env, TaskListener.NULL); START } catch (Throwable t) { END LOGGER.debug("{} failed to build env ({}), skipping", contributor.getClass(), t.getMessage(), t); } } return env; } After the discussions in other PRs we agreed that this approach is not good, because it suppresses various kinds of system <code>Error</code>s, which are supposed to be system failures

Target:
protected EnvVars buildEnv(AbstractProject<?, ?> job) { EnvVars env = new EnvVars(); for (EnvironmentContributor contributor : EnvironmentContributor.all()) { try { contributor.buildEnvironmentFor(job, env, TaskListener.NULL); } catch (Exception e) { LOGGER.debug("{} failed to build env ({}), skipping", contributor.getClass(), e.getMessage(), e); } } return env; }
Source:
public static Predicate<GHEventsSubscriber> isApplicableFor(final AbstractProject<?, ?> project) { return new Predicate<GHEventsSubscriber>() { @Override public boolean apply(GHEventsSubscriber subscriber) { Validate.notNull(subscriber); START return subscriber.isApplicable(project); END } }; } You can write it directly `notNull(subscriber).isApplicable(project);` (Same with other places, with static imports)

Target:
public static Predicate<GHEventsSubscriber> isApplicableFor(final AbstractProject<?, ?> project) { return new Predicate<GHEventsSubscriber>() { @Override public boolean apply(GHEventsSubscriber subscriber) { return notNull(subscriber).isApplicable(project); } }; }
Source:
public void parseAssociatedNames(Job<?, ?> job, Collection<GitHubRepositoryName> result) { START ParameterizedJobMixIn.ParameterizedJob p = (ParameterizedJobMixIn.ParameterizedJob) job; END for (GitHubTrigger ght : Util.filter(p.getTriggers().values(),GitHubTrigger.class)) { result.addAll(ght.getGitHubRepositories()); } } Maybe a type-check here first?

Target:
public void parseAssociatedNames(Job<?, ?> job, Collection<GitHubRepositoryName> result) { if (job instanceof ParameterizedJobMixIn.ParameterizedJob) { ParameterizedJobMixIn.ParameterizedJob p = (ParameterizedJobMixIn.ParameterizedJob) job; // TODO use standard method in 1.621+ for (GitHubTrigger ght : Util.filter(p.getTriggers().values(),GitHubTrigger.class)) { result.addAll(ght.getGitHubRepositories()); } } }
Source:
public void visitLineNumber(int line, Label start) { START _lineNumber = line; END } As a safety precaution, should we make this assignment just once to grab only the very first line number in case generated synthetic lambda method contains more than one line numbers?

Target:
public void visitLineNumber(int line, Label start) { if (_lineNumber == -1) { _lineNumber = line; } }
Source:
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { switch (opcode) { case Opcodes.INVOKEVIRTUAL: case Opcodes.INVOKESPECIAL: case Opcodes.INVOKESTATIC: _methodInsnName = name; _methodInsnOwner = owner; _methodInsnDesc = desc; _methodInsnOpcode = opcode; break; default: //TODO: throw an exception that couldn't infer operation START LOGGER.debug("Unexpected opcode, falling back"); END break; } super.visitMethodInsn(opcode, owner, name, desc, itf); } TODO + logger level to DEBUG

Target:
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { switch (opcode) { case Opcodes.INVOKEVIRTUAL: case Opcodes.INVOKESPECIAL: case Opcodes.INVOKESTATIC: _methodInsnName = name; _methodInsnOwner = owner; _methodInsnDesc = desc; _methodInsnOpcode = opcode; break; default: System.out.println("Unexpected opcode, falling back"); break; } super.visitMethodInsn(opcode, owner, name, desc, itf); }
Source:
protected Promise<? extends T> run(Context context) { _startedAt = System.currentTimeMillis(); START Task<T> task = wrap(0); END context.run(task); return task; } Nope. I missed that.

Target:
private Promise<? extends T> run(Context context) { _startedAt = System.currentTimeMillis(); Task<T> task = wrap(0); context.run(task); return task; }
Source:
START public void shutdown() throws InterruptedException { END if (_zkClient != null) { _zkClient.close(); _reaper.shutdown(); } } return Promise just to symmetric with start()...

Target:
public void shutdown() throws InterruptedException { if (_zkClient != null) { _zkClient.close(); } }
Source:
public void start() { if (stepClassWithSpringContext != null) { testContextManager = new CucumberTestContextManager(stepClassWithSpringContext); } else { if (beanFactory == null) { beanFactory = createFallbackContext(); } } notifyContextManagerAboutTestClassStarted(); if (beanFactory == null || isNewContextCreated()) { beanFactory = testContextManager.getBeanFactory(); START synchronized (beanFactory) { END for (Class<?> stepClass : stepClasses) { registerStepClassBeanDefinition(beanFactory, stepClass); } } } GlueCodeContext.getInstance().start(); } We also have a synchronization step a few lines up inside `CucumberTestContextManager`. For clarity we could synchronize all operations in the start method.

Target:
public void start() { // registerStepClassBeanDefinition and // CucumberTestContextManager.registerGlueCodeScope manipulate the the // application context. These operations are not thread-safe. So the // SpringFactory must be started serially. synchronized (monitor) { if (stepClassWithSpringContext != null) { testContextManager = new CucumberTestContextManager(stepClassWithSpringContext); } else { if (beanFactory == null) { beanFactory = createFallbackContext(); } } notifyContextManagerAboutTestClassStarted(); if (beanFactory == null || isNewContextCreated()) { beanFactory = testContextManager.getBeanFactory(); for (Class<?> stepClass : stepClasses) { registerStepClassBeanDefinition(beanFactory, stepClass); } } GlueCodeContext.getInstance().start(); } }
Source:
private void handleWrite(WriteEvent event) { out.println(); try(BufferedReader lines = new BufferedReader(new StringReader(event.text))) { String line = lines.readLine(); while(line != null) { out.println(STEP_SCENARIO_INDENT + line); line = lines.readLine(); } START } catch (IOException e) { END throw new CucumberException(e); } out.println(); } The canonical way to write this avoids the repetition of `readLine`. It is a little bit less error prone. ``` String line; while ((line = lines.readLine()) != null) { out.println(STEP_SCENARIO_INDENT + line); } ``` Aside from that: looks good! Don't forget to indent your code properly.

Target:
private void handleWrite(WriteEvent event) { out.println(); try(BufferedReader lines = new BufferedReader(new StringReader(event.text))) { String line; while ((line = lines.readLine()) != null) { out.println(STEP_SCENARIO_INDENT + line); } } catch (IOException e) { throw new CucumberException(e); } out.println(); }
Source:
private String describeNote() { START return String.join("\n", this.notes); END } With the exception of constructors, non-static inner classes and setters the `this` key word isn't usually needed.

Target:
private String describeNote() { return String.join("\n", notes); }
Source:
public void shouldSetStrictOnPlugin() { RuntimeOptions runtimeOptions = new RuntimeOptions("--strict"); Plugins plugins = new Plugins(getSystemClassLoader(), pluginFactory, runtimeOptions); StrictAware plugin = Mockito.mock(StrictAware.class); plugins.addPlugin(plugin); START plugins.setSerialEventBusOnEventListenerPlugins(rootEventPublisher); END verify(plugin).setStrict(true); } ```suggestion ```

Target:
public void shouldSetStrictOnPlugin() { RuntimeOptions runtimeOptions = new RuntimeOptions("--strict"); Plugins plugins = new Plugins(getSystemClassLoader(), pluginFactory, runtimeOptions); StrictAware plugin = Mockito.mock(StrictAware.class); plugins.addPlugin(plugin); verify(plugin).setStrict(true); }
Source:
public byte exitStatus(boolean isStrict) { byte result = 0x0; START if (!failedScenarios.isEmpty() || (isStrict && (!pendingScenarios.isEmpty() || !undefinedScenarios.isEmpty() || !ambiguousScenarios.isEmpty()))) { END result |= ERRORS; } return result; } Looking at [printNonZeroResultScenarios](https://github.com/cucumber/cucumber-jvm/pull/1342/files#diff-9c2af73a8f4e34a02a035f2709e487d5R157) I think `ambiguousScenarios` should be treated the same as `failedScenarios` and always return a non zero exit status.

Target:
public byte exitStatus(boolean isStrict) { byte result = 0x0; if (!failedScenarios.isEmpty() || !ambiguousScenarios.isEmpty() || (isStrict && (!pendingScenarios.isEmpty() || !undefinedScenarios.isEmpty()))) { result |= ERRORS; } return result; }
Source:
public void addStepDefinition(StepDefinition stepDefinition) { StepDefinition previous = stepDefinitionsByPattern.get(stepDefinition.getPattern()); START if (previous == null || haveSameLocation(previous, stepDefinition)) { END stepDefinitionsByPattern.put(stepDefinition.getPattern(), stepDefinition); } else { throw new DuplicateStepDefinitionException(previous, stepDefinition); } } It is a matter of taste, but I would probably have used: ``` if (previous == null) { stepDefinitionsByPattern.put(stepDefinition.getPattern(), stepDefinition); } else if (!haveSameLocation(previous, stepDefinition)) { throw new DuplicateStepDefinitionException(previous, stepDefinition); } ``` In a method named addStepDefinition, the `if (previous == null || haveSameLocation(previous, stepDefinition))` triggered a "no, it is not right to add the stepDefinition in both these cases" in me, but it is actually ok, since put overwrites the previous step definition with the new one.

Target:
public void addStepDefinition(StepDefinition stepDefinition) { StepDefinition previous = stepDefinitionsByPattern.get(stepDefinition.getPattern()); if (previous == null) { stepDefinitionsByPattern.put(stepDefinition.getPattern(), stepDefinition); } else if (!haveSameLocation(previous, stepDefinition)) { throw new DuplicateStepDefinitionException(previous, stepDefinition); } }
Source:
private void printSummary(cucumber.runtime.Runtime runtime) { START runtime.getSummaryCounter().printSummary(out); END } Tell don't ask. Remove `getSummaryCounter()` and add a `Runtime.printSummary(out)` method instead.

Target:
private void printSummary(cucumber.runtime.Runtime runtime) { runtime.printSummary(out); }
Source:
public void generatesPlainSnippet() { Step step = new Step(Collections.<Comment>emptyList(), "Given ", "I have 4 cukes in my \"big\" belly", 0, null, null); String snippet = new SnippetGenerator(new ClojureSnippet()).getSnippet(step); String expected = "" + "(Given #\"^I have (\\d+) cukes in my \"([^\"]*)\" belly$\" [arg1, arg2]\n" + START <<<<<<< HEAD END " (comment Express the Regexp above with the code you wish you had ))\n"; assertEquals(expected, snippet); } Looks like you keft this one out.

Target:
public void generatesPlainSnippet() { Step step = new Step(Collections.<Comment>emptyList(), "Given ", "I have 4 cukes in my \"big\" belly", 0, null, null); String snippet = new SnippetGenerator(new ClojureSnippet()).getSnippet(step); String expected = "" + "(Given #\"^I have (\\d+) cukes in my \"([^\"]*)\" belly$\" [arg1, arg2]\n" + " (comment Express the Regexp above with the code you wish you had ))\n"; assertEquals(expected, snippet); }
Source:
private final boolean isDateInvalid(Elements elements) { boolean result = false; START if (!elements.isEmpty()) { END Element dcTermsDateElement = elements.get(0); try { new SimpleDateFormat(MrrtReportTemplateConstants.DATE_FORMAT).parse(dcTermsDateElement.attr("content")); } catch (ParseException ex) { result = true; } } return result; } @ivange94 can you turn this into a positive check/guard clause. so ```java if (elements.isEmpty()) { return false; } ``` this removes one level of nesting and makes it easier to read, since the reader see's immediately that if the elements is empty we return.

Target:
private final boolean isDateInvalid(Elements elements) { boolean result = false; if (elements.isEmpty()) { return result; } Element dcTermsDateElement = elements.get(0); try { new SimpleDateFormat(MrrtReportTemplateConstants.DATE_FORMAT).parse(dcTermsDateElement.attr("content")); } catch (ParseException ex) { result = true; } return result; }
Source:
public void search_shouldReturnAllReportTemplatesByGivenPublisher() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter(MrrtReportTemplateSearchHandler.REQUEST_PARAM_PUBLISHER, PUBLISHER_QUERY); RequestContext requestContext = new RequestContext(); START requestContext.setRequest(request); END when(mrrtReportTemplateService.getMrrtReportTemplates(any(MrrtReportTemplateSearchCriteria.class))) .thenReturn(mrrtReportTemplates); PageableResult pageableResult = mrrtReportTemplateSearchHandler.search(requestContext); assertThat(pageableResult, is(instanceOf(NeedsPaging.class))); } can you move the boilerplate out of all tests add ``` java MockHttpServletRequest request; RequestContext requestContext; ``` as class fields. and ``` java request = new MockHttpServletRequest(); requestContext.setRequest(request); ``` into the setUp method. makes our tests cleaner and contain only the diferences in the request.setParameter()

Target:
public void search_shouldReturnAllReportTemplatesByGivenPublisher() throws Exception { request.setParameter(MrrtReportTemplateSearchHandler.REQUEST_PARAM_PUBLISHER, PUBLISHER_QUERY); when(mrrtReportTemplateService.getMrrtReportTemplates(any(MrrtReportTemplateSearchCriteria.class))) .thenReturn(mrrtReportTemplates); PageableResult pageableResult = mrrtReportTemplateSearchHandler.search(requestContext); assertThat(pageableResult, is(instanceOf(NeedsPaging.class))); }
Source:
public void search_shouldReturnEmptySearchResultIfTitleDoesNotExist() throws Exception { request.setParameter(MrrtReportTemplateSearchHandler.REQUEST_PARAM_TITLE, NON_EXISTING_TITLE); START requestContext.setRequest(request); END PageableResult pageableResult = mrrtReportTemplateSearchHandler.search(requestContext); assertThat(pageableResult, is(instanceOf(EmptySearchResult.class))); } this is already done in setUp.

Target:
public void search_shouldReturnEmptySearchResultIfTitleDoesNotExist() throws Exception { request.setParameter(MrrtReportTemplateSearchHandler.REQUEST_PARAM_TITLE, NON_EXISTING_TITLE); PageableResult pageableResult = mrrtReportTemplateSearchHandler.search(requestContext); assertThat(pageableResult, is(instanceOf(EmptySearchResult.class))); }
Source:
public void build_createANewRadiologyOrderSearchCriteriaInstanceWithAccessionNumberIfAccessionNumberIsSet() throws Exception { String accessionNumber = "1"; radiologyOrderSearchCriteria = new RadiologyOrderSearchCriteria.Builder().withAccessionNumber(accessionNumber) .build(); START assertTrue(radiologyOrderSearchCriteria.getAccessionNumber() END .equals(accessionNumber)); assertNull(radiologyOrderSearchCriteria.getPatient()); assertFalse(radiologyOrderSearchCriteria.getIncludeVoided()); assertNull(radiologyOrderSearchCriteria.getUrgency()); assertNull(radiologyOrderSearchCriteria.getFromEffectiveStartDate()); assertNull(radiologyOrderSearchCriteria.getToEffectiveStartDate()); } @bgeVam assertThat(, is())

Target:
public void build_createANewRadiologyOrderSearchCriteriaInstanceWithAccessionNumberIfAccessionNumberIsSet() throws Exception { String accessionNumber = "1"; radiologyOrderSearchCriteria = new RadiologyOrderSearchCriteria.Builder().withAccessionNumber(accessionNumber) .build(); assertThat(radiologyOrderSearchCriteria.getAccessionNumber(), is(accessionNumber)); assertNull(radiologyOrderSearchCriteria.getPatient()); assertFalse(radiologyOrderSearchCriteria.getIncludeVoided()); assertNull(radiologyOrderSearchCriteria.getUrgency()); assertNull(radiologyOrderSearchCriteria.getFromEffectiveStartDate()); assertNull(radiologyOrderSearchCriteria.getToEffectiveStartDate()); }
Source:
public void getRadiologyOrders_shouldReturnAllRadiologyOrdersForGivenAccessionNumberIfAccessionNumberIsSpecified() throws Exception { RadiologyOrderSearchCriteria radiologyOrderSearchCriteria = new RadiologyOrderSearchCriteria.Builder().withAccessionNumber(EXISTING_RADIOLOGY_ORDER_ACCESSION_NUMBER) .build(); List<RadiologyOrder> radiologyOrders = radiologyOrderService.getRadiologyOrders(radiologyOrderSearchCriteria); assertThat(radiologyOrders.size(), is(1)); START for (RadiologyOrder radiologyOrder : radiologyOrders) { END assertThat(radiologyOrder.getAccessionNumber(), is(EXISTING_RADIOLOGY_ORDER_ACCESSION_NUMBER)); } } @bgeVam why loop? size is 1

Target:
public void getRadiologyOrders_shouldReturnAllRadiologyOrdersForGivenAccessionNumberIfAccessionNumberIsSpecified() throws Exception { RadiologyOrderSearchCriteria radiologyOrderSearchCriteria = new RadiologyOrderSearchCriteria.Builder().withAccessionNumber(EXISTING_RADIOLOGY_ORDER_ACCESSION_NUMBER) .build(); List<RadiologyOrder> radiologyOrders = radiologyOrderService.getRadiologyOrders(radiologyOrderSearchCriteria); assertThat(radiologyOrders.size(), is(1)); assertThat(radiologyOrders.get(0) .getAccessionNumber(), is(EXISTING_RADIOLOGY_ORDER_ACCESSION_NUMBER)); }
Source:
public void build_createANewRadiologyOrderSearchCriteriaInstanceWithFromEffectiveStartDateIfFromEffectiveStartDateIsSet() throws Exception { DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date fromEffectiveStartDate = format.parse("2016-05-01"); radiologyOrderSearchCriteria = new RadiologyOrderSearchCriteria.Builder().withFromEffectiveStartDate(fromEffectiveStartDate) .build(); START assertTrue(radiologyOrderSearchCriteria.getFromEffectiveStartDate() END .equals(fromEffectiveStartDate)); assertNull(radiologyOrderSearchCriteria.getPatient()); assertFalse(radiologyOrderSearchCriteria.getIncludeVoided()); assertNull(radiologyOrderSearchCriteria.getUrgency()); assertNull(radiologyOrderSearchCriteria.getToEffectiveStartDate()); } @bgeVam assertThat(,is())

Target:
public void build_createANewRadiologyOrderSearchCriteriaInstanceWithFromEffectiveStartDateIfFromEffectiveStartDateIsSet() throws Exception { DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date fromEffectiveStartDate = format.parse("2016-05-01"); radiologyOrderSearchCriteria = new RadiologyOrderSearchCriteria.Builder().withFromEffectiveStartDate(fromEffectiveStartDate) .build(); assertThat(radiologyOrderSearchCriteria.getFromEffectiveStartDate(), is(fromEffectiveStartDate)); assertNull(radiologyOrderSearchCriteria.getPatient()); assertFalse(radiologyOrderSearchCriteria.getIncludeVoided()); assertNull(radiologyOrderSearchCriteria.getUrgency()); assertNull(radiologyOrderSearchCriteria.getToEffectiveStartDate()); }
Source:
private void addDefaultProperties(DelegatingResourceDescription description) { description.addProperty("uuid"); description.addProperty("radiologyOrder", Representation.REF); description.addProperty("reportDate"); description.addProperty("reportStatus"); description.addProperty("reportBody"); START description.addProperty("principalResultsInterpreter", Representation.REF); END description.addProperty("display"); } @Schwasrz94 move principalResultsInterpreter before reportStatus so we have same order as in the object itself: https://github.com/openmrs/openmrs-module-radiology/blob/master/api/src/main/java/org/openmrs/module/radiology/report/RadiologyReport.java

Target:
private void addDefaultProperties(DelegatingResourceDescription description) { description.addProperty("uuid"); description.addProperty("radiologyOrder", Representation.REF); description.addProperty("reportDate"); description.addProperty("principalResultsInterpreter", Representation.REF); description.addProperty("reportStatus"); description.addProperty("reportBody"); description.addProperty("display"); }
Source:
public void getMrrtReportTemplateByIdentifier_shouldFindObjectGivenValidIdentifier() throws Exception { MrrtReportTemplate template = mrrtReportTemplateService.getMrrtReportTemplateByIdentifier("identifier1"); assertNotNull(template); assertThat(template.getDcTermsIdentifier(), is("identifier1")); START assertThat(template.getDcTermsTitle(), is("title1")); END } @ivange94 remove assertion for title, just do the identifier

Target:
public void getMrrtReportTemplateByIdentifier_shouldFindObjectGivenValidIdentifier() throws Exception { MrrtReportTemplate template = mrrtReportTemplateService.getMrrtReportTemplateByIdentifier("identifier1"); assertNotNull(template); assertThat(template.getDcTermsIdentifier(), is("identifier1")); }
Source:
START public String getReportTemplateHome() { END Path templatesPath = Paths.get(getGlobalProperty(RadiologyConstants.GP_MRRT_REPORT_TEMPLATE_DIR, true)); if (!templatesPath.isAbsolute()) { templatesPath = Paths.get(OpenmrsUtil.getApplicationDataDirectory(), templatesPath.toString()); } if (!templatesPath.toFile() .exists()) { templatesPath.toFile() .mkdirs(); } return templatesPath.toString(); } @ivange94 why not return a java File ? you already ensure it exists and the GP_MRRT_REPORT_TEMPLATE_DIR is writable, return java file so the user of this method doesnt have to deal with some of the things you do here.

Target:
public File getReportTemplateHome() { Path templatesPath = Paths.get(getGlobalProperty(RadiologyConstants.GP_MRRT_REPORT_TEMPLATE_DIR, true)); if (!templatesPath.isAbsolute()) { templatesPath = Paths.get(OpenmrsUtil.getApplicationDataDirectory(), templatesPath.toString()); } if (!templatesPath.toFile() .exists()) { templatesPath.toFile() .mkdirs(); } return templatesPath.toFile(); }
Source:
public List<RadiologyOrder> getRadiologyOrdersByPatients(List<Patient> patients) { final Criteria radiologyOrderCriteria = createRadiologyOrderCriteria(); addRestrictionOnPatients(radiologyOrderCriteria, patients); START List<RadiologyOrder> result = (List<RadiologyOrder>) radiologyOrderCriteria.list(); END return result == null ? new ArrayList<RadiologyOrder>() : result; } use final

Target:
public List<RadiologyOrder> getRadiologyOrdersByPatients(List<Patient> patients) { final Criteria radiologyOrderCriteria = createRadiologyOrderCriteria(); addRestrictionOnPatients(radiologyOrderCriteria, patients); final List<RadiologyOrder> result = (List<RadiologyOrder>) radiologyOrderCriteria.list(); return result == null ? new ArrayList<RadiologyOrder>() : result; }
Source:
public void findEncounter_shouldThrowIllegalArgumentExceptionIfGivenVisitIsNull() throws Exception { // given EncounterParameters encounterParameters = EncounterParameters.instance() .setEncounterType(radiologyProperties.getRadiologyOrderEncounterType()) .setEncounterUuid(VOIDED_ENCOUNTER_UUID); START Visit visit = null; END expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("visit is required"); radiologyEncounterMatcher.findEncounter(visit, encounterParameters); } @bgeVam just inline null

Target:
public void findEncounter_shouldThrowIllegalArgumentExceptionIfGivenVisitIsNull() throws Exception { // given EncounterParameters encounterParameters = EncounterParameters.instance() .setEncounterType(radiologyProperties.getRadiologyOrderEncounterType()) .setEncounterUuid(VOIDED_ENCOUNTER_UUID); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("visit is required"); radiologyEncounterMatcher.findEncounter(null, encounterParameters); }
Source:
public void findEncounter_shouldThrowIllegalArgumentExceptionIfGivenEncounterParametersIsNull() throws Exception { // given EncounterParameters encounterParameters = null; Visit visit = visitService.getVisit(VISIT_ID_WITH_VOIDED_ENCOUNTER); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("encounterParameters are required"); START radiologyEncounterMatcher.findEncounter(visit, encounterParameters); END } @bgeVam just inline null

Target:
public void findEncounter_shouldThrowIllegalArgumentExceptionIfGivenEncounterParametersIsNull() throws Exception { // given Visit visit = visitService.getVisit(VISIT_ID_WITH_VOIDED_ENCOUNTER); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("encounterParameters are required"); radiologyEncounterMatcher.findEncounter(visit, null); }
Source:
public String getDicomViewerUrl(Study study) { if (study == null) throw new IllegalArgumentException("study cannot be null"); else if (study.getStudyInstanceUid() == null) throw new IllegalArgumentException("studyInstanceUid cannot be null"); else { if (this.radiologyProperties == null) START return "http://localhost:8081/weasis-pacs-connector/viewer?" + "studyUID=" + study.getStudyInstanceUid(); END else return this.radiologyProperties.getDicomViewerUrl() + "studyUID=" + study.getStudyInstanceUid(); } } you shouldnt do that. hardcoding the URL here.

Target:
public String getDicomViewerUrl(Study study) { if (study == null) throw new IllegalArgumentException("study cannot be null"); else if (study.getStudyInstanceUid() == null) throw new IllegalArgumentException("studyInstanceUid cannot be null"); return radiologyProperties.getDicomViewerUrl() + "studyUID=" + study.getStudyInstanceUid(); }
Source:
START Study getMockStudy() throws Exception { END Study mockStudy = new Study(); mockStudy.setStudyId(1); mockStudy.setStudyInstanceUid("1.2.826.0.1.3680043.8.2186.1.1"); return mockStudy; } does this really need `throws Exception`

Target:
Study getMockStudy() { Study mockStudy = new Study(); mockStudy.setStudyId(1); mockStudy.setStudyInstanceUid("1.2.826.0.1.3680043.8.2186.1.1"); return mockStudy; }
Source:
public void started() { START try { END startDicomOrderFiller(); } catch (Exception e) { // Just prints in console } typeAndRoles(); } The try-catch block is redundant here, since the appropriate exceptions are caught and logged in the startDicomOrderFiller method

Target:
public void started() { startDicomOrderFiller(); typeAndRoles(); }
Source:
START public void disableDarkTheme(boolean disabled) { END darkThemeDisabled = disabled; } Make this method `synchronized`.

Target:
public synchronized void disableDarkTheme(boolean disabled) { darkThemeDisabled = disabled; }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); START Boolean isDarkTheme = SalesforceSDKManager.getInstance().isDarkTheme(getActivity()); END // Do not create a new Fragment when the Activity is re-created such as orientation changes. setRetainInstance(true); setStyle(DialogFragment.STYLE_NORMAL, (isDarkTheme ? R.style.SalesforceSDK_Dialog_Dark : R.style.SalesforceSDK_Dialog)); } Lowercase `boolean` - use the primitive type.

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); boolean isDarkTheme = SalesforceSDKManager.getInstance().isDarkTheme(getActivity()); // Do not create a new Fragment when the Activity is re-created such as orientation changes. setRetainInstance(true); setStyle(DialogFragment.STYLE_NORMAL, (isDarkTheme ? R.style.SalesforceSDK_Dialog_Dark : R.style.SalesforceSDK_Dialog)); }
Source:
public void storeMobilePolicyForOrg(UserAccount account, int timeout, int passLen) { if (account == null) { return; } final Context context = SalesforceSDKManager.getInstance().getAppContext(); final SharedPreferences sp = context.getSharedPreferences(MOBILE_POLICY_PREF + account.getOrgLevelFilenameSuffix(), Context.MODE_PRIVATE); final Editor e = sp.edit(); e.putInt(KEY_TIMEOUT, timeout); e.putInt(KEY_PASSCODE_LENGTH, passLen); START e.commit(); END } <table data-meta="generated_by_SalesforceSDK"> <tbody> <tr> <td>:warning:</td> <td width="100%" data-sticky="false"><span data-href="https://github.com/forcedotcom/SalesforceMobileSDK-Android/blob/e8a63cd04088a6f062240bd7f6b8ab8629bcec98/libs/SalesforceSDK/src/com/salesforce/androidsdk/security/PasscodeManager.java#L195"></span>Consider using <code>apply()</code> instead; <code>commit</code> writes its data to persistent storage immediately, whereas <code>apply</code> will handle it in the background</td> </tr> </tbody> </table>

Target:
public void storeMobilePolicyForOrg(UserAccount account, int timeout, int passLen) { storeMobilePolicyForOrg(account, timeout, passLen, true); }
Source:
START public static synchronized String getUniqueId(String name) { END return getUniqueId(name, 256); } Remove `synchronized` keyword from this method and move it to the method below.

Target:
public static String getUniqueId(String name) { return getUniqueId(name, 256); }
Source:
public void tearDown() throws Exception { START testContext = null; END } Don't you need a `super.tearDown()` call here at the end?

Target:
public void tearDown() throws Exception { testContext = null; super.tearDown(); }
Source:
private void loadRemoteStartPage(boolean loadThroughFrontDoor) { assert !bootconfig.isLocal(); String startPage = bootconfig.getStartPage(); String url = startPage; if (loadThroughFrontDoor) { url = getFrontDoorUrl(url, false); } START SalesforceHybridLogger.i(TAG, "loadRemoteStartPage called - loading: " + startPage); END loadUrl(url); webAppLoaded = true; } Minor: change this log line to `url` to correctly reflect the URL being loaded.

Target:
private void loadRemoteStartPage(boolean loadThroughFrontDoor) { assert !bootconfig.isLocal(); String startPage = bootconfig.getStartPage(); String url = startPage; if (loadThroughFrontDoor) { url = getFrontDoorUrl(url, false); } SalesforceHybridLogger.i(TAG, "loadRemoteStartPage called - loading: " + url); loadUrl(url); webAppLoaded = true; }
Source:
START public static SmartSyncSDKManager getInstance() { END if (INSTANCE != null) { SalesforceSDKManager.getInstance().registerUsedAppFeature(FEATURE_SMART_SYNC); return (SmartSyncSDKManager) INSTANCE; } else { throw new RuntimeException("Applications need to call SmartSyncSDKManager.init() first."); } } Any app compiled with smartstore/smartsync will use SmartSyncSDKManager. Instead you should set that flag from SyncManager.java getInstance

Target:
public static SmartSyncSDKManager getInstance() { if (INSTANCE != null) { return (SmartSyncSDKManager) INSTANCE; } else { throw new RuntimeException("Applications need to call SmartSyncSDKManager.init() first."); } }
Source:
private void removeAllGlobalStores(JSONArray args, CallbackContext callbackContext) throws JSONException { START List<String> globalDBNames = SmartStoreSDKManager.getInstance().getGlobalStoresPrefixList(); END for(String storeName : globalDBNames) { SmartStoreSDKManager.getInstance().removeGlobalSmartStore(storeName); } PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, true); callbackContext.sendPluginResult(pluginResult); } Should we have a removeAllGlobalStores method on SmartStoreSDKManager like we do on iOS?

Target:
private void removeAllGlobalStores(JSONArray args, CallbackContext callbackContext) throws JSONException { SmartStoreSDKManager.getInstance().removeAllGlobalStores(); PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, true); callbackContext.sendPluginResult(pluginResult); }
Source:
START public List<String> getGlobalStoresPrefixList() throws JSONException { END UserAccount userAccount = getUserAccountManager().getCurrentUser(); String communityId = userAccount!=null?userAccount.getCommunityId():null; List<String> globalDBNames = DBOpenHelper.getGlobalDatabasePrefixList(context,getUserAccountManager().getCurrentUser(),communityId); return globalDBNames; } Should we call that method getGlobalStoreNames() instead?

Target:
public List<String> getGlobalStoresPrefixList(){ UserAccount userAccount = getUserAccountManager().getCurrentUser(); String communityId = userAccount!=null?userAccount.getCommunityId():null; List<String> globalDBNames = DBOpenHelper.getGlobalDatabasePrefixList(context,getUserAccountManager().getCurrentUser(),communityId); return globalDBNames; }
Source:
START public boolean loadSqlCipher(Context context) { END try { loadLibs(context); } catch (UnsatisfiedLinkError ule) { // We are assuming the library loaded by sql cipher failed return extractAndLoadAgain(context, DATABASE_SQLCIPHER, getSupportedAbis()); } catch (Exception ex) { Log.e(TAG, "Error loading native libraries for Sqlcipher", ex); return false; } return true; } This can be `static`.

Target:
public static boolean loadSqlCipher(Context context) { try { loadLibs(context); } catch (UnsatisfiedLinkError ule) { // We are assuming the library loaded by sql cipher failed return extractAndLoadAgain(context, DATABASE_SQLCIPHER, getSupportedAbis()); } catch (Exception ex) { Log.e(TAG, "Error loading native libraries for Sqlcipher", ex); return false; } return true; }
Source:
START public void loadLibs(Context context) throws UnsatisfiedLinkError { END SQLiteDatabase.loadLibs(context); } `static`.

Target:
public static void loadLibs(Context context) throws UnsatisfiedLinkError { SQLiteDatabase.loadLibs(context); }
Source:
START public boolean canReadFile(File file) { END return file.canRead(); } `static`.

Target:
public static boolean canReadFile(File file) { return file.canRead(); }
Source:
START public String[] getSupportedAbis() { END if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.SUPPORTED_ABIS.length > 0) { return Build.SUPPORTED_ABIS; } else { return new String[] { Build.CPU_ABI, Build.CPU_ABI2 }; } } `static`.

Target:
public static String[] getSupportedAbis() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.SUPPORTED_ABIS.length > 0) { return Build.SUPPORTED_ABIS; } else { return new String[] { Build.CPU_ABI, Build.CPU_ABI2 }; } }
Source:
protected void loadLibs(Context context) { START new SqliteLibraryLoader().loadSqlCipher(context); END } Use `static` call. There's no need to instantiate this util class every time.

Target:
protected void loadLibs(Context context) { SqliteLibraryLoader.loadSqlCipher(context); }
Source:
START protected TokenEndpointResponse performRequest(LoginOptions options) throws Exception { END try { return OAuth2.swapJWTForTokens(HttpAccess.DEFAULT, new URI(options.loginUrl), options.jwt); } catch (Exception e) { onAuthFlowError("jwt_oauth_error", e.getLocalizedMessage()); callback.finish(); } return null; } We should remove `throws Exception` here, since we're catching it anyway and triggering `onAuthFlowError`.

Target:
protected TokenEndpointResponse performRequest(LoginOptions options) { try { return OAuth2.swapJWTForTokens(HttpAccess.DEFAULT, new URI(options.loginUrl), options.jwt); } catch (Exception e) { onAuthFlowError("jwt_oauth_error", e.getLocalizedMessage()); callback.finish(); } return null; }
Source:
public Bundle asBundle() { START bundle.putString(JWT, jwt); //jwt can be updated during flow END return bundle; } I don't think we should muck around with this in this part.

Target:
public Bundle asBundle() { return bundle; }
Source:
public static TokenEndpointResponse swapJWTForTokens(HttpAccess httpAccessor, URI loginServerUrl, String jwt) throws IOException, URISyntaxException, OAuthFailedException { // call the token endpoint, and swap jwt for an access tokens. FormBody.Builder formBodyBuilder = new FormBody.Builder() .add(GRANT_TYPE, JWT_BEARER) .add(ASSERTION, jwt); TokenEndpointResponse tr = makeTokenEndpointRequest(httpAccessor, loginServerUrl, formBodyBuilder); START return tr; END } `return` directly.

Target:
public static TokenEndpointResponse swapJWTForTokens(HttpAccess httpAccessor, URI loginServerUrl, String jwt) throws IOException, URISyntaxException, OAuthFailedException { // call the token endpoint, and swap jwt for an access tokens. FormBody.Builder formBodyBuilder = new FormBody.Builder() .add(GRANT_TYPE, JWT_BEARER) .add(ASSERTION, jwt); return makeTokenEndpointRequest(httpAccessor, loginServerUrl, formBodyBuilder); }
Source:
public void testResponseStreamIsReadable() throws Exception { final RestResponse response = getStreamTestResponse(); START try (InputStream in = response.asInputStream()) { END assertStreamTestResponseStreamIsValid(in); } catch (IOException e) { fail("The InputStream should be readable and an IOException should not have been thrown"); } catch (JSONException e) { fail("Valid JSON data should have been returned"); } finally { response.consumeQuietly(); } } @clibc I don't know if we enforce `Java 7` as a minimum, so it might be best to go with the `Java 6` syntax here.

Target:
public void testResponseStreamIsReadable() throws Exception { final RestResponse response = getStreamTestResponse(); try { InputStream in = response.asInputStream(); assertStreamTestResponseStreamIsValid(in); } catch (IOException e) { fail("The InputStream should be readable and an IOException should not have been thrown"); } catch (JSONException e) { fail("Valid JSON data should have been returned"); } finally { response.consumeQuietly(); } }
Source:
public void testResponseStreamConsumedByReadingStream() throws Exception { final RestResponse response = getStreamTestResponse(); try { START InputStream in = response.asInputStream() END inputStreamToString(in); } catch (IOException e) { fail("The InputStream should be readable and an IOException should not have been thrown"); } // We read the entire stream but forgot to call consume() or consumeQuietly() - can another REST call be made? final RestResponse anotherResponse = getStreamTestResponse(); assertNotNull(anotherResponse); } Missing semi-colon at the end. No compilation error? ;-)

Target:
public void testResponseStreamConsumedByReadingStream() throws Exception { final RestResponse response = getStreamTestResponse(); try { InputStream in = response.asInputStream(); inputStreamToString(in); } catch (IOException e) { fail("The InputStream should be readable and an IOException should not have been thrown"); } // We read the entire stream but forgot to call consume() or consumeQuietly() - can another REST call be made? final RestResponse anotherResponse = getStreamTestResponse(); assertNotNull(anotherResponse); }
Source:
public UserAccount getCurrentUser() { final Account account = getCurrentAccount(); START return account == null ? null : buildUserAccount(account); END } You don't need this. `buildUserAccount()` has a `null` check.

Target:
public UserAccount getCurrentUser() { return buildUserAccount(getCurrentAccount()); }
Source:
public String toString() { try { return asString(); } catch (Exception e) { START Log.e("RestResponse: toString()", "Exception caught while calling asString()"); END return ((response == null) ? "" : response.toString()); } } Could you log the exception too: Log.e("RestResponse: toString()", "Exception caught while calling asString()", e);

Target:
public String toString() { try { return asString(); } catch (Exception e) { Log.e("RestResponse: toString()", "Exception caught while calling asString()", e); return ((response == null) ? "" : response.toString()); } }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sf__inspector); START smartStore = SalesforceSDKManagerWithSmartStore.getInstance() END .getSmartStore(); queryText = (MultiAutoCompleteTextView) findViewById(R.id.sf__inspector_query_text); pageSizeText = (EditText) findViewById(R.id.sf__inspector_pagesize_text); pageIndexText = (EditText) findViewById(R.id.sf__inspector_pageindex_text); resultGrid = (GridView) findViewById(R.id.sf__inspector_result_grid); setupAutocomplete(queryText); } You might want to move this call to `onResume()`. The reason is that, with fast user switching, if an account switch occurs, when you come back to this activity, you'll be stuck with a handle on the old SmartStore (the variable `smartStore` won't be updated).

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sf__inspector); queryText = (MultiAutoCompleteTextView) findViewById(R.id.sf__inspector_query_text); pageSizeText = (EditText) findViewById(R.id.sf__inspector_pagesize_text); pageIndexText = (EditText) findViewById(R.id.sf__inspector_pageindex_text); resultGrid = (GridView) findViewById(R.id.sf__inspector_result_grid); }
Source:
public Op subtract(Op otherOp) { START return new DoubleOp(this.val - ((DoubleOp)otherOp).val); END } Any reason for doing the instanceof check in add but not subtract?

Target:
public Op subtract(Op otherOp) { if(!(otherOp instanceof DoubleOp)) { throw new RuntimeException(); } return new DoubleOp(this.val - ((DoubleOp)otherOp).val); }