auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected static String commentFormat(String comment) { START if (comment == null || comment.isEmpty()) return ""; END // truncate comment to 255 Bytes - a tinyblob while (comment.getBytes(ENCODING).length > 255) { comment = comment.substring(0, comment.length() - 1); } return comment; } String.isEmpty() is avaible only as of JDK 1.6. Please use if (comment == null || comment.length() == 0) return ""; to keep this compilable with JDK 1.5

Target:
protected static String commentFormat(String comment) { if (comment == null || comment.length() == 0) return ""; // truncate comment to 255 Bytes - a tinyblob while (comment.getBytes(ENCODING).length > 255) { comment = comment.substring(0, comment.length() - 1); } return comment; }
Source:
public PageTitle(final String namespace, final String text) { this.namespace = namespace; START this.text = text.replaceAll("\\s+", "_"); END } Does \s include zero-width non-joiner and stuff? Oh, languages, we are such fun. :D

Target:
public PageTitle(final String namespace, final String text) { this.namespace = namespace; this.text = text; }
Source:
public void onCatch(Throwable caught) { if (caught instanceof IOException) { // Network IO error, I presume Utils.crossFade(loadProgress, networkError); START } END } Should we log or re-throw any other surprise exceptions?

Target:
public void onCatch(Throwable caught) { // Should check for the source of the error and have different things turn up // But good enough for now Utils.crossFade(loadProgress, networkError); }
Source:
START public PageTitle(final String namespace, final String text, final Site site) { END this.namespace = namespace; this.text = text; this.fragment = null; this.site = site; } You could collapse this and the new constructor to one function by using "this(namespace, text, null, site);" here.

Target:
public PageTitle(final String namespace, final String text, final Site site) { this(namespace, text, null, site); }
Source:
public void bookmarkPage() { new BookmarkPageTask(getActivity(), title) { @Override public void onBeforeExecute() { START Toast.makeText(getActivity(), R.string.toast_saving_page, Toast.LENGTH_LONG).show(); END } @Override public void onFinish(Void result) { Toast.makeText(getActivity(), R.string.toast_saved_page, Toast.LENGTH_LONG).show(); } }.execute(); } Do we really need a toast for "bookmarking..." the page? It's not an expensive operation, especially now.

Target:
public void bookmarkPage() { new BookmarkPageTask(getActivity(), title) { @Override public void onFinish(Void result) { Toast.makeText(getActivity(), R.string.toast_saved_page, Toast.LENGTH_LONG).show(); } }.execute(); }
Source:
public void setEnabled(boolean enabled) { //make sure we close the pane before disabling if (!enabled) START slidingPane.closePane(); END slidingPane.setSlidingEnabled(enabled); } Always enclose if (and other conditional) bodies in curly braces.

Target:
public void setEnabled(boolean enabled) { //make sure we close the pane before disabling if (!enabled) { slidingPane.closePane(); } slidingPane.setSlidingEnabled(enabled); }
Source:
public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("findinpage_text", findInPageInput.getText().toString()); START outState.putString("findinpage_enabled", findInPageInput.getText().toString()); END } Is this being read anywhere? plus we seem to be saving the same thing twice?

Target:
public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("findinpage_text", findInPageInput.getText().toString()); }
Source:
public void onChangeTextSize(ChangeTextSizeEvent event) { if (curPageFragment != null && curPageFragment.getWebView() != null) { themeChooser.updateButtonState(true); curPageFragment.updateFontSize(); Handler uiThread = new Handler(Looper.getMainLooper()); uiThread.postDelayed(new Runnable() { @Override public void run() { themeChooser.updateButtonState(false); } START }, (long)Math.ceil(0.75 * DateUtils.SECOND_IN_MILLIS)); END } } I would probably drop the calculation, at least the Math.ceil() call.

Target:
public void onChangeTextSize(ChangeTextSizeEvent event) { if (curPageFragment != null && curPageFragment.getWebView() != null) { themeChooser.updateButtonState(true); curPageFragment.updateFontSize(); Handler uiThread = new Handler(Looper.getMainLooper()); uiThread.postDelayed(new Runnable() { @Override public void run() { themeChooser.updateButtonState(false); } }, (long)(0.75 * DateUtils.SECOND_IN_MILLIS)); } }
Source:
private boolean shouldSkip() { // Maintain lastMatched - it should be false if we shift to a new doc. if (cache.lastDocId != context.hitContext.docId()) { cache.lastMatched = false; cache.lastDocId = context.hitContext.docId(); } Boolean skipIfLastMatched = (Boolean)getOption("skip_if_last_matched"); if (skipIfLastMatched == null ? false : skipIfLastMatched && cache.lastMatched) { return true; } START return false; END } This whole last block from line 187 to 191 could be simplified to return skipIfLastMatched != null && skipIfLastMatched && cache.lastMatched;

Target:
private boolean shouldSkip() { // Maintain lastMatched - it should be false if we shift to a new doc. if (cache.lastDocId != context.hitContext.docId()) { cache.lastMatched = false; cache.lastDocId = context.hitContext.docId(); } Boolean skipIfLastMatched = (Boolean)getOption("skip_if_last_matched"); return skipIfLastMatched == null ? false : skipIfLastMatched && cache.lastMatched; }
Source:
private LanguagesAdapter(List<String> languages, WikipediaApp app) { this.originalLanguages = languages; START this.languages = languages; END this.app = app; } A defensive copy of the list would be safer IMO

Target:
private LanguagesAdapter(List<String> languages, WikipediaApp app) { this.originalLanguages = languages; this.languages = new ArrayList<String>(); this.languages.addAll(languages); this.app = app; }
Source:
public Integer performTask() throws Throwable { String elUrl = WikipediaApp.getInstance().getSslFailCount() < 2 ? EVENTLOG_URL : EVENTLOG_URL.replace("https", "http"); String dataURL = Uri.parse(elUrl) .buildUpon().query(data.toString()) .build().toString(); START Log.d(Funnel.ANALYTICS_TAG, "hitting " + dataURL); END return HttpRequest.get(dataURL).header("User-Agent", userAgent).code(); } If, instead of "dataURL," we output "data", then we'll see all the parameters of the event on one line, and nicely formatted.

Target:
public Integer performTask() throws Throwable { String elUrl = WikipediaApp.getInstance().getSslFailCount() < 2 ? EVENTLOG_URL : EVENTLOG_URL.replace("https", "http"); String dataURL = Uri.parse(elUrl) .buildUpon().query(data.toString()) .build().toString(); return HttpRequest.get(dataURL).header("User-Agent", userAgent).code(); }
Source:
public Object evaluate(DeferredObject[] arguments) throws HiveException { result.clear(); try { if (arguments.length == 1 && argumentOI != null && arguments[0] != null) { String ip = ((StringObjectInspector) argumentOI).getPrimitiveJavaObject(arguments[0].get()); result.set(geocode.getCountryCode(ip)); } START } catch (Exception ex) { END LOG.error(ex); } return result; } We probably should log and rethrow this exception, correct?

Target:
public Object evaluate(DeferredObject[] arguments) throws HiveException { result.clear(); if (arguments.length == 1 && argumentOI != null && arguments[0] != null) { String ip = ((StringObjectInspector) argumentOI).getPrimitiveJavaObject(arguments[0].get()); result.set(geocode.getCountryCode(ip)); } return result; }
Source:
public void testWrongTypeOfArguments() throws URISyntaxException, HiveException { ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaIntObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1}; GeocodedCountryUDF geocodedCountryUDF = new GeocodedCountryUDF( TestGeocodedCountryUDF.class.getResource(defaultDatabaseFile).getFile()); try { geocodedCountryUDF.initialize(initArguments); START fail("UDFArgumentTypeException was not thrown for invalid argument type"); END } catch (UDFArgumentTypeException typeEx) { } } Let's let exceptions bubble up so we can get a nice stack trace that aids on debugging.

Target:
public void testWrongTypeOfArguments() throws HiveException { ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaIntObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1}; GeocodedCountryUDF geocodedCountryUDF = new GeocodedCountryUDF(); geocodedCountryUDF.initialize(initArguments); }
Source:
public void testBadNumberOfArguments() throws URISyntaxException, HiveException { ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector value2 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1, value2}; GeocodedDataUDF geocodedDataUDF = new GeocodedDataUDF( TestGeocodedDataUDF.class.getResource(defaultDatabaseFile).getFile()); try { START geocodedDataUDF.initialize(initArguments); END fail("UDFArgumentLengthException was not thrown for invalid number of arguments"); } catch (UDFArgumentLengthException lenEx) { } } Let's let exceptions bubble up so we get a stack trace that aids on debugging.

Target:
public void testBadNumberOfArguments() throws HiveException { ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector value2 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1, value2}; GeocodedDataUDF geocodedDataUDF = new GeocodedDataUDF(); geocodedDataUDF.initialize(initArguments); }
Source:
public boolean onSearchRequested() { showToolbar(); searchFragment.openSearch(); START return false; END } It works and I'm not sure what difference it actually makes, but the doc seems to imply to return true: "Returns true if search launched, and false if the activity does not respond to search." http://developer.android.com/reference/android/app/Activity.html#onSearchRequested()

Target:
public boolean onSearchRequested() { showToolbar(); searchFragment.openSearch(); return true; }
Source:
public PageTitle getFirstResult() { START if (totalResults != null) { END return totalResults.get(0); } else { return null; } } Should also check that size() > 0, otherwise it crashes when there are no results, and you press Go on the keyboard.

Target:
public PageTitle getFirstResult() { if (totalResults != null && !totalResults.isEmpty()) { return totalResults.get(0); } else { return null; } }
Source:
START public Text evaluate(String ip, String xff) { END assert ipUtil != null : "Evaluate called without initializing 'ipUtil'"; return new Text(ipUtil.getClientIp(ip, xff)); } Could we use String instead of Text? Hive would do the magic for us, and it would keep this method simpler.

Target:
public String evaluate(String ip, String xff) { assert ipUtil != null : "Evaluate called without initializing 'ipUtil'"; return ipUtil.getClientIp(ip, xff); }
Source:
START public void testBadNumberOfArguments() throws HiveException, IOException { END ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector value2 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1, value2}; GeocodedCountryUDF geocodedCountryUDF = new GeocodedCountryUDF(); geocodedCountryUDF.initialize(initArguments); } Done

Target:
public void testBadNumberOfArguments() throws HiveException { ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector value2 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1, value2}; GeocodedCountryUDF geocodedCountryUDF = new GeocodedCountryUDF(); geocodedCountryUDF.initialize(initArguments); }
Source:
START public void testWrongTypeOfArguments() throws HiveException, IOException { END ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaIntObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1}; GeocodedCountryUDF geocodedCountryUDF = new GeocodedCountryUDF(); geocodedCountryUDF.initialize(initArguments); } Done

Target:
public void testWrongTypeOfArguments() throws HiveException { ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaIntObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1}; GeocodedCountryUDF geocodedCountryUDF = new GeocodedCountryUDF(); geocodedCountryUDF.initialize(initArguments); }
Source:
public void testBadNumberOfArguments() throws HiveException, IOException { ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector value2 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1, value2}; GeocodedCountryUDF geocodedCountryUDF = new GeocodedCountryUDF(); geocodedCountryUDF.initialize(initArguments); START geocodedCountryUDF.close(); END } Yeah, meh. Just removing close()

Target:
public void testBadNumberOfArguments() throws HiveException, IOException { ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector value2 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1, value2}; GeocodedCountryUDF geocodedCountryUDF = new GeocodedCountryUDF(); geocodedCountryUDF.initialize(initArguments); }
Source:
private void preRequestReadMoreItems(final LayoutInflater layoutInflater) { START if (parentFragment.getPage().getPageProperties().isMainPage()) { END new MainPageReadMoreTopicTask(activity) { @Override public void onFinish(PageTitle myTitle) { requestReadMoreItems(layoutInflater, myTitle); } @Override public void onCatch(Throwable caught) { // Read More titles are expendable. Log.w(TAG, "Error while getting Read More topic for main page.", caught); // but lay out the bottom content anyway: layoutContent(); } }.execute(); } else { requestReadMoreItems(layoutInflater, pageTitle); } } we now have Page.isMainPage()

Target:
private void preRequestReadMoreItems(final LayoutInflater layoutInflater) { if (parentFragment.getPage().isMainPage()) { new MainPageReadMoreTopicTask(activity) { @Override public void onFinish(PageTitle myTitle) { requestReadMoreItems(layoutInflater, myTitle); } @Override public void onCatch(Throwable caught) { // Read More titles are expendable. Log.w(TAG, "Error while getting Read More topic for main page.", caught); // but lay out the bottom content anyway: layoutContent(); } }.execute(); } else { requestReadMoreItems(layoutInflater, pageTitle); } }
Source:
START public android.database.Cursor getInterestedHistoryEntry() { END ContentProviderClient client = context.getContentResolver() .acquireContentProviderClient(HistoryEntry.PERSISTENCE_HELPER.getBaseContentURI()); try { return client.query( HistoryEntry.PERSISTENCE_HELPER.getBaseContentURI(), null, "source != ? AND source != ? ", new String[] {Integer.toString(HistoryEntry.SOURCE_MAIN_PAGE), Integer.toString(HistoryEntry.SOURCE_RANDOM)}, "timestamp DESC"); } catch (RemoteException e) { // This shouldn't really be happening throw new RuntimeException(e); } } private?

Target:
private android.database.Cursor getInterestedHistoryEntry() { ContentProviderClient client = context.getContentResolver() .acquireContentProviderClient(HistoryEntry.PERSISTENCE_HELPER.getBaseContentURI()); try { return client.query( HistoryEntry.PERSISTENCE_HELPER.getBaseContentURI(), null, "source != ? AND source != ? ", new String[] {Integer.toString(HistoryEntry.SOURCE_MAIN_PAGE), Integer.toString(HistoryEntry.SOURCE_RANDOM)}, "timestamp DESC"); } catch (RemoteException e) { // This shouldn't really be happening throw new RuntimeException(e); } }
Source:
public PageTitle titleForInternalLink(String internalLink) { // FIXME: Handle language variant links properly // Strip the /wiki/ from the href, and replace all underscores with spaces for neatness START return new PageTitle(internalLink.replaceFirst("/wiki/", "").replaceAll("_", " "), this); END } replaceAll() doesn't need to be done here. It's done automatically in PageTitle.getDisplayText(). Instead, we should modify DisambigListAdapter:132 to use getDisplayText instead of getPrefixedText.

Target:
public PageTitle titleForInternalLink(String internalLink) { // FIXME: Handle language variant links properly // Strip the /wiki/ from the href return new PageTitle(internalLink.replaceFirst("/wiki/", ""), this); }
Source:
public boolean onTouchEvent(MotionEvent event) { try { return super.onTouchEvent(event); } catch (RuntimeException e) { START return true; END } } Generally agree + good find. This method probably should return false to indicate that we have not handled the event. http://developer.android.com/reference/android/view/View.html#onTouchEvent(android.view.MotionEvent)

Target:
public boolean onTouchEvent(MotionEvent event) { try { return super.onTouchEvent(event); } catch (RuntimeException e) { return false; } }
Source:
public int getType() { if (code.startsWith("abusefilter-warning")) { return TYPE_WARNING; } else if (code.startsWith("abusefilter-disallowed")) { return TYPE_ERROR; } else if (info.startsWith("Hit AbuseFilter")) { // This case is here because, unfortunately, an admin can create an abuse filter which // emits an arbitrary error code over the API. // TODO: More properly handle the case where the AbuseFilter throws an arbitrary error. // Oh, and, you know, also fix the AbuseFilter API to not throw arbitrary error codes. return TYPE_ERROR; } else { START throw new RuntimeException("Unknown abusefilter response!"); END } } Why not simply return TYPE_ERROR for this "else" case, and not worry about the contents of "info"? This would prevent even more possible crashes.

Target:
public int getType() { if (code.startsWith("abusefilter-warning")) { return TYPE_WARNING; } else if (code.startsWith("abusefilter-disallowed")) { return TYPE_ERROR; } else if (info.startsWith("Hit AbuseFilter")) { // This case is here because, unfortunately, an admin can create an abuse filter which // emits an arbitrary error code over the API. // TODO: More properly handle the case where the AbuseFilter throws an arbitrary error. // Oh, and, you know, also fix the AbuseFilter API to not throw arbitrary error codes. return TYPE_ERROR; } else { // We have no understanding of what kind of abuse filter response we got. It's safest // to simply treat these as an error. return TYPE_ERROR; } }
Source:
protected void run(Date lastRun) { try { ShareUtils.clearFolder(getContext()); START } catch (Exception e) { END // There have been a few reports of errors during the clearing process, even though // we check that external storage is mounted properly. For now, we won't worry // about it, since this task will be repeated later. Log.d("SharedImageCleanupTask", "Failed to clear shared image folder.", e); } } I would prefer to move the catch block inside the clearFolder implementation since that one is called from another place as well.

Target:
protected void run(Date lastRun) { ShareUtils.clearFolder(getContext()); }
Source:
private void showNetworkError() { // TODO: Check for the source of the error and have different things turn up // TODO: Change the name of this function to showPageError when the file is not under active development boolean networkPresent = NetworkUtils.isNetworkConnectionPresent(app); TextView errorMessage = (TextView) networkError.findViewById(R.id.page_error_message); START if (!networkPresent) { END errorMessage.setText(R.string.error_network_error); } else { errorMessage.setText(R.string.generic_page_error); } hidePageContent(); ViewAnimations.fadeIn(networkError); } You could inline networkPresent

Target:
private void showNetworkError() { // TODO: Check for the source of the error and have different things turn up // TODO: Change the name of this function to showPageError when the file is not under active development TextView errorMessage = (TextView) networkError.findViewById(R.id.page_error_message); if (!NetworkUtils.isNetworkConnectionPresent(app)) { errorMessage.setText(R.string.error_network_error); } else { errorMessage.setText(R.string.generic_page_error); } hidePageContent(); ViewAnimations.fadeIn(networkError); }
Source:
public static boolean isNetworkConnectionPresent(Context ctx) { ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnected(); START return isConnected; END } You could inline the variable isConnected.

Target:
public static boolean isNetworkConnectionPresent(Context ctx) { ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnected(); }
Source:
public void onCatch(Throwable caught) { if (Utils.throwableContainsSpecificType(caught, SSLException.class) && WikipediaApp.getInstance().incSslFailCount() < 2) { WikipediaApp.getInstance().setSslFallback(true); START NetworkUtils.toastFail(); END cancel(); return; } throw new RuntimeException(caught); } Not every SaneAsyncTask does networking. Look at ApiTask instead.

Target:
public void onCatch(Throwable caught) { }
Source:
protected URIExtensionIV createInlineIV(URI uri) { if (namespaceIV == null) { // Can't do anything without a namespace. return null; } for (String prefix : normalizedPrefixes) { if (uri.stringValue().startsWith(prefix)) { AbstractLiteralIV localNameIv = next.createInlineIV(uri.stringValue().substring( START CommonValues.VIAF_HTTP.length())); END if (localNameIv == null) { return null; } return new URIExtensionIV(localNameIv, namespaceIV); } } return next.createInlineIV(uri); } Why VIAF_HTTP? Did you mean prefix.length()?

Target:
protected URIExtensionIV createInlineIV(URI uri) { if (namespaceIV == null) { // Can't do anything without a namespace. return null; } for (String prefix : normalizedPrefixes) { if (uri.stringValue().startsWith(prefix)) { AbstractLiteralIV localNameIv = next.createInlineIV(uri.stringValue().substring(prefix.length())); if (localNameIv == null) { return null; } return new URIExtensionIV(localNameIv, namespaceIV); } } return next.createInlineIV(uri); }
Source:
public String evaluate(String url) throws HiveException { RefererClassification kind = Webrequest.classifyReferer(url); switch (kind) { START case UNKNOWN: return "UNK"; END case INTERNAL: return "INT"; case EXTERNAL: return "EXT"; } return "UNK"; } I don't really like short names when they aren't really necessary. Can we just use the full titles here? Also, I'm not sure there is a need for capitalizing them. So, 'unknown', 'internal', 'external' should be fine, ja? Let's talk about this. If we are just going to return a string, maybe we should do away with the RefererClassifaction enum, and just declare some constants in Webrequest for this, eh?

Target:
public String evaluate(String url) throws HiveException { return Webrequest.getInstance().classifyReferer(url); }
Source:
private static boolean isExternalStorageWritable() { START return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); END } again reverse the order of equals()

Target:
private static boolean isExternalStorageWritable() { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); }
Source:
public PageProperties getProperties() { if (hasProperties()) { START return properties; END } else { return null; } } Super minor but no conditional needed here since properties is either null or non-null.

Target:
public PageProperties getProperties() { return properties; }
Source:
public void writeToParcel(Parcel parcel, int flags) { parcel.writeString(namespace); parcel.writeString(text); parcel.writeString(fragment); parcel.writeParcelable(site, flags); START if (hasProperties()) { END parcel.writeParcelable(properties, flags); } parcel.writeString(thumbUrl); parcel.writeString(description); } I'm not a Parcel expert but I think we want to write this out unconditionally. If we don't, I think the constructor will byte offsets will be wrong for the other values.

Target:
public void writeToParcel(Parcel parcel, int flags) { parcel.writeString(namespace); parcel.writeString(text); parcel.writeString(fragment); parcel.writeParcelable(site, flags); parcel.writeParcelable(properties, flags); parcel.writeString(thumbUrl); parcel.writeString(description); }
Source:
public void writeToParcel(Parcel parcel, int flags) { parcel.writeString(namespace); parcel.writeString(text); parcel.writeString(fragment); parcel.writeParcelable(site, flags); START parcel.writeString(thumbUrl); END parcel.writeString(description); } add properties

Target:
public void writeToParcel(Parcel parcel, int flags) { parcel.writeString(namespace); parcel.writeString(text); parcel.writeString(fragment); parcel.writeParcelable(properties, flags); parcel.writeParcelable(site, flags); parcel.writeString(thumbUrl); parcel.writeString(description); }
Source:
public boolean isDisambiguationPage() { if (hasProperties()) { return properties.isDisambiguationPage(); } else { throw new NullPointerException("No PageProperties object exists for this PageTitle!"); } START } END I think the most unsurprising behavior for the client would be to just returning false / null as appropriate.

Target:
public boolean isDisambiguationPage() { if (hasProperties()) { return properties.isDisambiguationPage(); } else { return false; } }
Source:
public int getLicenseIcon() { if (isLicensePD()) { return R.drawable.ic_license_pd; } else if (isLicenseCC()) { return R.drawable.ic_license_cc; START } else { END return R.drawable.ic_license_cite; } } Very minor: elses are unnecessary.

Target:
public int getLicenseIcon() { if (isLicensePD()) { return R.drawable.ic_license_pd; } if (isLicenseCC()) { return R.drawable.ic_license_cc; } return R.drawable.ic_license_cite; }
Source:
public ImageLicense processPage(int pageId, PageTitle pageTitle, JSONObject result) { try { START if (result.getJSONArray("imageinfo") != null) { END JSONObject imageInfo = (JSONObject) result.getJSONArray("imageinfo").get(0); ImageLicense license = parseImageLicenseMetadata(imageInfo.getJSONObject("extmetadata")); return license; } return null; } catch (JSONException e) { Log.w(TAG, e); return null; } } I don't think the get* methods can return null. If the field isn't present, they'll throw an exception. Here's the implementation of getJSONArray() (as reported by Android Studio): public JSONArray getJSONArray(String name) throws JSONException { Object object = get(name); if (object instanceof JSONArray) { return (JSONArray) object; } else { throw JSON.typeMismatch(name, object, "JSONArray"); } }

Target:
public ImageLicense processPage(int pageId, PageTitle pageTitle, JSONObject result) { ImageLicense license = new ImageLicense("", "", ""); try { JSONObject imageInfo = (JSONObject) result.getJSONArray("imageinfo").get(0); parseImageLicenseMetadata(license, imageInfo.getJSONObject("extmetadata")); } catch (JSONException e) { Log.w(TAG, e); } return license; }
Source:
public boolean isCloseEnough() { START return true; END } IMHO : there's no need to send an exception here, I would even return false like you did in the previous patch. The caller should be aware of this contract: if a ChangeHandler returns isDocumentNooped == true it must stop everything.

Target:
public boolean isCloseEnough() { return false; }
Source:
public ApiException(String code, String info) { START super(info); END this.code = code; this.info = info; } Since we pass info as the message param to the super, do we need a copy in the subclass?

Target:
public ApiException(String code, String info) { super(); this.code = code; this.info = info; }
Source:
public void onActionModeShown(ActionMode mode) { // make sure we have a page loaded, since shareHandler makes references to it. START if (model.getPage() == null) { END return; } shareHandler.onTextSelected(mode); } Very minor: rather than introducing a second method exit point and an extra line, I recommend inverting the logic and moving the shareHandler invocation here.

Target:
public void onActionModeShown(ActionMode mode) { // make sure we have a page loaded, since shareHandler makes references to it. if (model.getPage() != null) { shareHandler.onTextSelected(mode); } }
Source:
private void setToCButtonFadedIn(boolean shouldFadeIn) { if (!ApiUtil.hasHoneyComb() || shouldFadeIn == isToCButtonFadedIn) { return; } START if (shouldFadeIn) { END Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_in_toc); tocButton.startAnimation(anim); isToCButtonFadedIn = true; } else { Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_out_toc); tocButton.startAnimation(anim); isToCButtonFadedIn = false; } } Sorry, I should have spotted this earlier. Now these conditionals can collapse: Animation anim = AnimationUtils.loadAnimation(getActivity(), shouldFadeIn ? R.anim.fade_in_toc : R.anim.fade_out_to); tocButton.startAnimation(anim); isToCButtonFadedIn = shouldFadeIn;

Target:
private void setToCButtonFadedIn(boolean shouldFadeIn) { if (!ApiUtil.hasHoneyComb() || shouldFadeIn == isToCButtonFadedIn) { return; } Animation anim = AnimationUtils.loadAnimation(getActivity(), shouldFadeIn ? R.anim.fade_in_toc : R.anim.fade_out_toc); tocButton.startAnimation(anim); isToCButtonFadedIn = shouldFadeIn; }
Source:
private void setToCButtonFadedIn(boolean shouldFadeIn) { START if (!ApiUtil.hasHoneyComb()) { END return; } if (shouldFadeIn && !isToCButtonFadedIn) { Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_in_toc); tocButton.startAnimation(anim); isToCButtonFadedIn = true; } else if (!shouldFadeIn && isToCButtonFadedIn) { Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_out_toc); tocButton.startAnimation(anim); isToCButtonFadedIn = false; } } How about (!ApiUtil.hasHoneyComb || shouldFadeIn == isTocButtonFadedIn)?

Target:
private void setToCButtonFadedIn(boolean shouldFadeIn) { if (!ApiUtil.hasHoneyComb() || shouldFadeIn == isToCButtonFadedIn) { return; } if (shouldFadeIn) { Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_in_toc); tocButton.startAnimation(anim); isToCButtonFadedIn = true; } else { Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_out_toc); tocButton.startAnimation(anim); isToCButtonFadedIn = false; } }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); app = (WikipediaApp) getActivity().getApplicationContext(); model = new PageViewModel(); if (Prefs.isExperimentalPageLoadEnabled()) { pageLoadStrategy = new HtmlPageLoadStrategy(); } else { pageLoadStrategy = new JsonPageLoadStrategy(); } START dailyEventTask = new DailyEventTask(getActivity()); END } What's the advantage of this vs. adding it to RecurringTasksExecutor and why is this an instance variable?

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); app = (WikipediaApp) getActivity().getApplicationContext(); model = new PageViewModel(); if (Prefs.isExperimentalPageLoadEnabled()) { pageLoadStrategy = new HtmlPageLoadStrategy(); } else { pageLoadStrategy = new JsonPageLoadStrategy(); } }
Source:
public BasicScoreBasedSnippetChooser(boolean scoreOrdered, SnippetWeigher snippetWeigher, int maxSnippetsChecked) { START super(); END this.scoreOrdered = scoreOrdered; this.maxSnippetsChecked = maxSnippetsChecked; this.snippetWeigher = snippetWeigher; } I never write no-args super constructors because they are implied. I figure its less to read and its "obvious". Not for php developers but for everyone else.

Target:
public BasicScoreBasedSnippetChooser(boolean scoreOrdered, SnippetWeigher snippetWeigher, int maxSnippetsChecked) { this.scoreOrdered = scoreOrdered; this.maxSnippetsChecked = maxSnippetsChecked; this.snippetWeigher = snippetWeigher; }
Source:
public boolean hasLicenseInfo() { START return !(license.equals("") && licenseShortName.equals("") & licenseUrl.equals("")); END } I think you want logical AND, so double ampersands. Can we use !license.isEmpty && !licenseShortName.isEmpty && !licenseUrl.isEmpty() instead?

Target:
public boolean hasLicenseInfo() { return !license.isEmpty() && !licenseShortName.isEmpty() && !licenseUrl.isEmpty(); }
Source:
private void setToCButtonFadedIn(boolean shouldFadeIn) { if (shouldFadeIn) { tocButton.removeCallbacks(hideToCButtonRunnable); tocButton.show(); START } else { END tocButton.postDelayed(hideToCButtonRunnable, TOC_BUTTON_HIDE_DELAY); } } Should we remove callbacks in either case to prevent accidental double posting?

Target:
private void setToCButtonFadedIn(boolean shouldFadeIn) { tocButton.removeCallbacks(hideToCButtonRunnable); if (shouldFadeIn) { tocButton.show(); } else { tocButton.postDelayed(hideToCButtonRunnable, TOC_BUTTON_HIDE_DELAY); } }
Source:
private void openInNewTab(PageTitle title, HistoryEntry entry) { // create a new tab Tab tab = new Tab(); // put this tab behind the current tab START if (tabList.size() > 0) { END tabList.add(tabList.size() - 1, tab); } else { tabList.add(tab); } // add the requested page to its backstack tab.getBackStack().add(new PageBackStackItem(title, entry)); // and... that should be it. tabsProvider.showAndHideTabs(); } Nice corner case handling. Nothing to block review: How about tabList.add(Math.min(0, tabList.size() - 1), tab) instead of a conditional?

Target:
private void openInNewTab(PageTitle title, HistoryEntry entry) { // create a new tab Tab tab = new Tab(); // put this tab behind the current tab tabList.add(Math.max(0, tabList.size() - 1), tab); // add the requested page to its backstack tab.getBackStack().add(new PageBackStackItem(title, entry)); // and... that should be it. tabsProvider.showAndHideTabs(); }
Source:
public int calculateLeadImageWidth() { Resources res = app.getResources(); START return (int) (res.getDimension(R.dimen.leadImageWidth) END / res.getDisplayMetrics().density); } How about calling getDimensionPixelSize() instead? We can remove the cast and density division.

Target:
private int calculateLeadImageWidth() { Resources res = app.getResources(); return (int) (res.getDimension(R.dimen.leadImageWidth) / res.getDisplayMetrics().density); }
Source:
START public Dialog onCreateDialog(Bundle savedInstanceState) { END Dialog dialog = super.onCreateDialog(savedInstanceState); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); return dialog; } Should we call super?

Target:
public Dialog onCreateDialog(Bundle savedInstanceState) { super.onCreateDialog(savedInstanceState); Dialog dialog = super.onCreateDialog(savedInstanceState); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); return dialog; }
Source:
private void checkIfPageIsSaved() { if (getTitle() != null) { START getActivity().getSupportLoaderManager().restartLoader(LOADER_ID, null, savedPageCheckCallbacks); END } } We might want to add a null check on getActivity() here since the clients of displayNewPage have no idea about Fragment lifecycles.

Target:
private void checkIfPageIsSaved() { if (getActivity() != null && getTitle() != null) { getActivity().getSupportLoaderManager().restartLoader(LOADER_ID, null, savedPageCheckCallbacks); } }
Source:
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { SavedPage dummyPage = new SavedPage(callingFragment.getTitle(), null); String selection = SavedPage.PERSISTENCE_HELPER.getPrimaryKeySelection(dummyPage, SavedPage.PERSISTENCE_HELPER.SELECTION_KEYS); String[] selectionArgs = SavedPage.PERSISTENCE_HELPER.getPrimaryKeySelectionArgs(dummyPage); return new CursorLoader( START callingFragment.getActivity(), END Uri.parse(SavedPage.PERSISTENCE_HELPER.getBaseContentURI().toString()), null, selection, selectionArgs, null); } It might be safer to pass in Application context in the constructor. I'm not sure if we're guaranteed that the Fragment will be added in this callback.

Target:
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { SavedPage dummyPage = new SavedPage(callingFragment.getTitle(), null); String selection = SavedPage.PERSISTENCE_HELPER.getPrimaryKeySelection(dummyPage, SavedPage.PERSISTENCE_HELPER.SELECTION_KEYS); String[] selectionArgs = SavedPage.PERSISTENCE_HELPER.getPrimaryKeySelectionArgs(dummyPage); return new CursorLoader( context, Uri.parse(SavedPage.PERSISTENCE_HELPER.getBaseContentURI().toString()), null, selection, selectionArgs, null); }
Source:
public void namespaceAwareUpsert(SavedPage savedPage) { namespaceAwareUpsert( START WikipediaApp.getInstance().getDbOpenHelper().getWritableDatabase(), END savedPage, getTableName(), getPrimaryKeySelection(), getPrimaryKeySelectionArgs(savedPage) ); } Isn't it the content provider's responsibility to call these methods with a reference to the database? I'm definitely vague on this area of the codebase but I think we want to avoid unnecessary dependencies on WikipediaApp wherever possible.

Target:
public void namespaceAwareUpsert(SavedPage savedPage) { super.namespaceAwareUpsert( WikipediaApp.getInstance().getDbOpenHelper().getWritableDatabase(), savedPage, getTableName(), getPrimaryKeySelection(), getPrimaryKeySelectionArgs(savedPage) ); }
Source:
public static void showMessage(Activity activity, int resId, int duration) { START showMessage(findBestView(activity), activity.getString(resId), duration); END } Should we call the function below instead?

Target:
public static void showMessage(Activity activity, int resId, int duration) { showMessage(activity, activity.getString(resId), duration); }
Source:
START public static void showMessage(Activity activity, int resId) { END showMessage(findBestView(activity), activity.getString(resId), Snackbar.LENGTH_LONG); } Sorry, same feedback for this function. We should leverage showMessage(Activity, int, int) instead of repeating findBestView() and getString() here.

Target:
public static void showMessage(Activity activity, int resId) { showMessage(activity, activity.getString(resId), Snackbar.LENGTH_LONG); }
Source:
START public SimpleDateFormat getSimpleDateFormat() { END if (simpleDateFormat == null) { simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); } return simpleDateFormat; } Since more state => more branches => more bugs, is there a strong reason to default to lazy initialization? This can be a stateless final nonnull if we initialize at declaration. That said, we might want to skip the member variable altogether[0] or switch to Joda time[1]. [0] http://stackoverflow.com/questions/6840803/simpledateformat-thread-safety [1] http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html

Target:
public SimpleDateFormat getSimpleDateFormat() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return simpleDateFormat; }
Source:
public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); START WikipediaApp.getInstance().checkCrashes(this); END ActivityUtil.requestFullUserOrientation(this); setTheme(WikipediaApp.getInstance().getCurrentTheme().getResourceId()); removeSplashBackground(); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } forceOverflowMenuIcon(this); } Do we really need this in every ThemedActionBarActivity or is PageActivity enough?

Target:
public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityUtil.requestFullUserOrientation(this); setTheme(WikipediaApp.getInstance().getCurrentTheme().getResourceId()); removeSplashBackground(); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } forceOverflowMenuIcon(this); }
Source:
public LinkPreviewFunnel(WikipediaApp app) { super(app, SCHEMA_NAME, REV_ID, app.isProdRelease() ? Funnel.SAMPLE_LOG_100 : Funnel.SAMPLE_LOG_ALL); START version = PROD_LINK_PREVIEW_VERSION; END } Can we remove the version variable since it's always equal to the constant?

Target:
public LinkPreviewFunnel(WikipediaApp app) { super(app, SCHEMA_NAME, REV_ID, app.isProdRelease() ? Funnel.SAMPLE_LOG_100 : Funnel.SAMPLE_LOG_ALL); }
Source:
public static boolean isRestBaseEnabled() { if (Prefs.forceRestBase()) { START return Prefs.useRestBase(); END } boolean useRestBase = shouldUseRestBase(); Prefs.setUseRestBase(useRestBase); return useRestBase; } Shouldn't this just return true? I thought force meant unconditionally use RESTbase.

Target:
public boolean isRestBaseEnabled() { return Prefs.useRestBase(); }
Source:
public void onLoadFinished(Loader<Cursor> cursorLoaderLoader, Cursor cursorLoader) { adapter.swapCursor(cursorLoader); boolean visible = recentSearchesList.getCount() > 0; deleteButton.setVisibility(visible ? View.VISIBLE : View.INVISIBLE); START if (!isAdded()) { END return; } getActivity().supportInvalidateOptionsMenu(); } Can we move this isAdded() check back to the top of the function? I recall that we placed it here to prevent a crash (that we may or may not have reproduced), and I'd rather err on the side of caution.

Target:
public void onLoadFinished(Loader<Cursor> cursorLoaderLoader, Cursor cursorLoader) { if (!isAdded()) { return; } adapter.swapCursor(cursorLoader); boolean visible = recentSearchesList.getCount() > 0; deleteButton.setVisibility(visible ? View.VISIBLE : View.INVISIBLE); getActivity().supportInvalidateOptionsMenu(); }
Source:
public void closeSearch() { isSearchActive = false; // invalidate our activity's ActionBar, so that the original action items are restored. getActivity().supportInvalidateOptionsMenu(); START getActivity().supportInvalidateOptionsMenu(); END ((PageActivity)getActivity()).getSearchBarHideHandler().setForceNoFade(false); setSearchViewEnabled(false); ((PageActivity) getActivity()).getDrawerToggle().setDrawerIndicatorEnabled(true); // hide ourselves searchContainerView.setVisibility(View.GONE); hideSoftKeyboard(getActivity()); addRecentSearch(lastSearchedText); } Is this intentional?

Target:
public void closeSearch() { isSearchActive = false; // invalidate our activity's ActionBar, so that the original action items are restored. getActivity().supportInvalidateOptionsMenu(); ((PageActivity)getActivity()).getSearchBarHideHandler().setForceNoFade(false); setSearchViewEnabled(false); ((PageActivity) getActivity()).getDrawerToggle().setDrawerIndicatorEnabled(true); // hide ourselves searchContainerView.setVisibility(View.GONE); hideSoftKeyboard(getActivity()); addRecentSearch(lastSearchedText); }
Source:
public void onFinish(Map<PageTitle, LinkPreviewContents> result) { if (!isAdded()) { return; } START if (result.size() > 0) { END progressBar.setVisibility(View.GONE); contents = (LinkPreviewContents) result.values().toArray()[0]; layoutPreview(); } else { loadContentFromCache(); } } How about !result.isEmpty() instead?

Target:
public void onFinish(Map<PageTitle, LinkPreviewContents> result) { if (!isAdded()) { return; } if (!result.isEmpty()) { progressBar.setVisibility(View.GONE); contents = (LinkPreviewContents) result.values().toArray()[0]; layoutPreview(); } else { loadContentFromCache(); } }
Source:
public void onActionModeFinished(android.view.ActionMode mode) { nullifyActionMode(); searchBarHideHandler.setForceNoFade(false); START super.onActionModeFinished(mode); END } Since we call the super in onActionModeStarted(), should we call it first here (last in, first out)?

Target:
public void onActionModeFinished(android.view.ActionMode mode) { super.onActionModeFinished(mode); nullifyActionMode(); searchBarHideHandler.setForceNoFade(false); }
Source:
START public boolean await() throws InterruptedException { END if (!latch.await(TestConstants.TIMEOUT_DURATION, TestConstants.TIMEOUT_UNIT)) { throw new InterruptedException("Timeout elapsed."); } return latch.await(TestConstants.TIMEOUT_DURATION, TestConstants.TIMEOUT_UNIT); } I don't think this is needed. This method already checks the return value of latch.await() and throws on failure. The client doesn't need to assert since returning from the method indicates success.

Target:
public void await() throws InterruptedException { if (!latch.await(TestConstants.TIMEOUT_DURATION, TestConstants.TIMEOUT_UNIT)) { throw new InterruptedException("Timeout elapsed."); } }
Source:
public void showLinkPreview(PageTitle title, int entrySource, @Nullable Location location) { if (getSupportFragmentManager().findFragmentByTag(LINK_PREVIEW_FRAGMENT_TAG) == null) { DialogFragment linkPreview = app.isLinkPreviewExperimental() START ? LinkPreviewDialogB.newInstance(title, entrySource) END : LinkPreviewDialog.newInstance(title, entrySource, location); linkPreview.show(getSupportFragmentManager(), LINK_PREVIEW_FRAGMENT_TAG); } } Looks like this will need a rebase over the patch removing the a/b test (or vice versa).

Target:
public void showLinkPreview(PageTitle title, int entrySource, @Nullable Location location) { if (getSupportFragmentManager().findFragmentByTag(LINK_PREVIEW_FRAGMENT_TAG) == null) { DialogFragment linkPreview = LinkPreviewDialog.newInstance(title, entrySource, location); linkPreview.show(getSupportFragmentManager(), LINK_PREVIEW_FRAGMENT_TAG); } }
Source:
public Object evaluate(DeferredObject[] arguments) throws HiveException { result.clear(); if (arguments.length == 1 && argumentOI != null && arguments[0] != null) { START String countryCode = ((StringObjectInspector) argumentOI).getPrimitiveJavaObject(arguments[0].get()); END result.set(Geocode.getCountryName(countryCode)); } return result; } Arguments.length is already been checked for above, I think there is no need to do it again.

Target:
public Object evaluate(DeferredObject[] arguments) throws HiveException { result.clear(); if (arguments.length == 1 && arguments[0] != null) { String countryCode = argumentOI.getPrimitiveJavaObject(arguments[0].get()); result.set(Geocode.getCountryName(countryCode)); } return result; }
Source:
START public synchronized EditTokenStorage getEditTokenStorage() { END if (editTokenStorage == null) { editTokenStorage = new EditTokenStorage(this); } return editTokenStorage; } Do we have code that we suspect is accessing these methods off the main thread? Either way, is it tolerable to omit the synchronization and initialize these in App.onCreate()?

Target:
public EditTokenStorage getEditTokenStorage() { return editTokenStorage; }
Source:
private MwPageService.MwPageEndpoints createMwService(Site site) { MwPageService.MwPageEndpoints webService; START webService = RestAdapterFactory.newInstance(site) END .create(MwPageService.MwPageEndpoints.class); return webService; } This line can be combined with previous line.

Target:
private MwPageService.MwPageEndpoints createMwService(Site site) { MwPageService.MwPageEndpoints webService = RestAdapterFactory.newInstance(site) .create(MwPageService.MwPageEndpoints.class); return webService; }
Source:
private RbContentService.RbEndpoints createRbService(Site site) { RbContentService.RbEndpoints webService; START webService = RestAdapterFactory.newInstance(site, END String.format(Locale.ROOT, Prefs.getRestbaseUriFormat(), WikipediaApp.getInstance().getNetworkProtocol(), site.getDomain())) .create(RbContentService.RbEndpoints.class); return webService; } This line can be combined with previous line.

Target:
private RbContentService.RbEndpoints createRbService(Site site) { RbContentService.RbEndpoints webService = RestAdapterFactory.newInstance(site, String.format(Locale.ROOT, Prefs.getRestbaseUriFormat(), WikipediaApp.getInstance().getNetworkProtocol(), site.getDomain())) .create(RbContentService.RbEndpoints.class); return webService; }
Source:
public static boolean isSelectTextTutorialEnabled() { START return !getBoolean(R.string.preference_key_select_text_tutorial_enabled, false); END } What's the reasoning here? This will cause the highlight tooltip to be shown all the time (in 1-minute intervals).

Target:
public static boolean isSelectTextTutorialEnabled() { return getBoolean(R.string.preference_key_select_text_tutorial_enabled, true); }
Source:
public static float getDensityScalar() { if (DENSITY_SCALAR == null) { START DENSITY_SCALAR = getDisplayMetrics().density; END } return DENSITY_SCALAR; } Nothing to hang the patch but out of curiosity, why lazy init this but not widthPixels? Is this operation expected to be slow?

Target:
public static float getDensityScalar() { return getDisplayMetrics().density; }