auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected static String commentFormat(String comment) { if (comment == null || comment.isEmpty()) return ""; // truncate comment to 255 Bytes - a tinyblob while (comment.getBytes(ENCODING).length > 255) { comment = comment.substring(0, comment.length() - 1); } return comment; }

Target:
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
Source:
public PageTitle(final String namespace, final String text) { this.namespace = namespace; this.text = text.replaceAll("\\s+", "_"); }

Target:
Does \s include zero-width non-joiner and stuff? Oh, languages, we are such fun. :D
Source:
public void onCatch(Throwable caught) { if (caught instanceof IOException) { // Network IO error, I presume Utils.crossFade(loadProgress, networkError); } }

Target:
Should we log or re-throw any other surprise exceptions?
Source:
public PageTitle(final String namespace, final String text, final Site site) { this.namespace = namespace; this.text = text; this.fragment = null; this.site = site; }

Target:
You could collapse this and the new constructor to one function by using "this(namespace, text, null, site);" here.
Source:
public void bookmarkPage() { new BookmarkPageTask(getActivity(), title) { @Override public void onBeforeExecute() { Toast.makeText(getActivity(), R.string.toast_saving_page, Toast.LENGTH_LONG).show(); } @Override public void onFinish(Void result) { Toast.makeText(getActivity(), R.string.toast_saved_page, Toast.LENGTH_LONG).show(); } }.execute(); }

Target:
Do we really need a toast for "bookmarking..." the page? It's not an expensive operation, especially now.
Source:
public void setEnabled(boolean enabled) { //make sure we close the pane before disabling if (!enabled) slidingPane.closePane(); slidingPane.setSlidingEnabled(enabled); }

Target:
Always enclose if (and other conditional) bodies in curly braces.
Source:
public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("findinpage_text", findInPageInput.getText().toString()); outState.putString("findinpage_enabled", findInPageInput.getText().toString()); }

Target:
Is this being read anywhere? plus we seem to be saving the same thing twice?
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); } }, (long)Math.ceil(0.75 * DateUtils.SECOND_IN_MILLIS)); } }

Target:
I would probably drop the calculation, at least the Math.ceil() call.
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; } return false; }

Target:
This whole last block from line 187 to 191 could be simplified to return skipIfLastMatched != null && skipIfLastMatched && cache.lastMatched;
Source:
private LanguagesAdapter(List<String> languages, WikipediaApp app) { this.originalLanguages = languages; this.languages = languages; this.app = app; }

Target:
A defensive copy of the list would be safer IMO
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(); Log.d(Funnel.ANALYTICS_TAG, "hitting " + dataURL); return HttpRequest.get(dataURL).header("User-Agent", userAgent).code(); }

Target:
If, instead of "dataURL," we output "data", then we'll see all the parameters of the event on one line, and nicely formatted.
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)); } } catch (Exception ex) { LOG.error(ex); } return result; }

Target:
We probably should log and rethrow this exception, correct?
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); fail("UDFArgumentTypeException was not thrown for invalid argument type"); } catch (UDFArgumentTypeException typeEx) { } }

Target:
Let's let exceptions bubble up so we can get a nice stack trace that aids on debugging.
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 { geocodedDataUDF.initialize(initArguments); fail("UDFArgumentLengthException was not thrown for invalid number of arguments"); } catch (UDFArgumentLengthException lenEx) { } }

Target:
Let's let exceptions bubble up so we get a stack trace that aids on debugging.
Source:
public boolean onSearchRequested() { showToolbar(); searchFragment.openSearch(); return false; }

Target:
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()
Source:
public PageTitle getFirstResult() { if (totalResults != null) { return totalResults.get(0); } else { return null; } }

Target:
Should also check that size() > 0, otherwise it crashes when there are no results, and you press Go on the keyboard.
Source:
public Text evaluate(String ip, String xff) { assert ipUtil != null : "Evaluate called without initializing 'ipUtil'"; return new Text(ipUtil.getClientIp(ip, xff)); }

Target:
Could we use String instead of Text? Hive would do the magic for us, and it would keep this method simpler.
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); }

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

Target:
Done
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); geocodedCountryUDF.close(); }

Target:
Yeah, meh. Just removing close()
Source:
private void preRequestReadMoreItems(final LayoutInflater layoutInflater) { if (parentFragment.getPage().getPageProperties().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); } }

Target:
we now have Page.isMainPage()
Source:
public 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); } }

Target:
private?
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 return new PageTitle(internalLink.replaceFirst("/wiki/", "").replaceAll("_", " "), this); }

Target:
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.
Source:
public boolean onTouchEvent(MotionEvent event) { try { return super.onTouchEvent(event); } catch (RuntimeException e) { return true; } }

Target:
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)
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 { throw new RuntimeException("Unknown abusefilter response!"); } }

Target:
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.
Source:
protected void run(Date lastRun) { try { ShareUtils.clearFolder(getContext()); } catch (Exception e) { // 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); } }

Target:
I would prefer to move the catch block inside the clearFolder implementation since that one is called from another place as well.
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); if (!networkPresent) { errorMessage.setText(R.string.error_network_error); } else { errorMessage.setText(R.string.generic_page_error); } hidePageContent(); ViewAnimations.fadeIn(networkError); }

Target:
You could inline networkPresent
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(); return isConnected; }

Target:
You could inline the variable isConnected.
Source:
public void onCatch(Throwable caught) { if (Utils.throwableContainsSpecificType(caught, SSLException.class) && WikipediaApp.getInstance().incSslFailCount() < 2) { WikipediaApp.getInstance().setSslFallback(true); NetworkUtils.toastFail(); cancel(); return; } throw new RuntimeException(caught); }

Target:
Not every SaneAsyncTask does networking. Look at ApiTask instead.
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( CommonValues.VIAF_HTTP.length())); if (localNameIv == null) { return null; } return new URIExtensionIV(localNameIv, namespaceIV); } } return next.createInlineIV(uri); }

Target:
Why VIAF_HTTP? Did you mean prefix.length()?
Source:
public String evaluate(String url) throws HiveException { RefererClassification kind = Webrequest.classifyReferer(url); switch (kind) { case UNKNOWN: return "UNK"; case INTERNAL: return "INT"; case EXTERNAL: return "EXT"; } return "UNK"; }

Target:
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?
Source:
private static boolean isExternalStorageWritable() { return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); }

Target:
again reverse the order of equals()
Source:
public PageProperties getProperties() { if (hasProperties()) { return properties; } else { return null; } }

Target:
Super minor but no conditional needed here since properties is either null or non-null.
Source:
public void writeToParcel(Parcel parcel, int flags) { parcel.writeString(namespace); parcel.writeString(text); parcel.writeString(fragment); parcel.writeParcelable(site, flags); if (hasProperties()) { parcel.writeParcelable(properties, flags); } parcel.writeString(thumbUrl); parcel.writeString(description); }

Target:
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.
Source:
public void writeToParcel(Parcel parcel, int flags) { parcel.writeString(namespace); parcel.writeString(text); parcel.writeString(fragment); parcel.writeParcelable(site, flags); parcel.writeString(thumbUrl); parcel.writeString(description); }

Target:
add properties
Source:
public boolean isDisambiguationPage() { if (hasProperties()) { return properties.isDisambiguationPage(); } else { throw new NullPointerException("No PageProperties object exists for this PageTitle!"); } }

Target:
I think the most unsurprising behavior for the client would be to just returning false / null as appropriate.
Source:
public int getLicenseIcon() { if (isLicensePD()) { return R.drawable.ic_license_pd; } else if (isLicenseCC()) { return R.drawable.ic_license_cc; } else { return R.drawable.ic_license_cite; } }

Target:
Very minor: elses are unnecessary.
Source:
public ImageLicense processPage(int pageId, PageTitle pageTitle, JSONObject result) { try { if (result.getJSONArray("imageinfo") != null) { 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; } }

Target:
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"); } }
Source:
public boolean isCloseEnough() { return true; }

Target:
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.
Source:
public ApiException(String code, String info) { super(info); this.code = code; this.info = info; }

Target:
Since we pass info as the message param to the super, do we need a copy in the subclass?
Source:
public void onActionModeShown(ActionMode mode) { // make sure we have a page loaded, since shareHandler makes references to it. if (model.getPage() == null) { return; } shareHandler.onTextSelected(mode); }

Target:
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.
Source:
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; } }

Target:
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;
Source:
private void setToCButtonFadedIn(boolean shouldFadeIn) { if (!ApiUtil.hasHoneyComb()) { 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; } }

Target:
How about (!ApiUtil.hasHoneyComb || shouldFadeIn == isTocButtonFadedIn)?
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(); } dailyEventTask = new DailyEventTask(getActivity()); }

Target:
What's the advantage of this vs. adding it to RecurringTasksExecutor and why is this an instance variable?
Source:
public BasicScoreBasedSnippetChooser(boolean scoreOrdered, SnippetWeigher snippetWeigher, int maxSnippetsChecked) { super(); this.scoreOrdered = scoreOrdered; this.maxSnippetsChecked = maxSnippetsChecked; this.snippetWeigher = snippetWeigher; }

Target:
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.
Source:
public boolean hasLicenseInfo() { return !(license.equals("") && licenseShortName.equals("") & licenseUrl.equals("")); }

Target:
I think you want logical AND, so double ampersands. Can we use !license.isEmpty && !licenseShortName.isEmpty && !licenseUrl.isEmpty() instead?
Source:
private void setToCButtonFadedIn(boolean shouldFadeIn) { if (shouldFadeIn) { tocButton.removeCallbacks(hideToCButtonRunnable); tocButton.show(); } else { tocButton.postDelayed(hideToCButtonRunnable, TOC_BUTTON_HIDE_DELAY); } }

Target:
Should we remove callbacks in either case to prevent accidental double posting?
Source:
private void openInNewTab(PageTitle title, HistoryEntry entry) { // create a new tab Tab tab = new Tab(); // put this tab behind the current tab if (tabList.size() > 0) { 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(); }

Target:
Nice corner case handling. Nothing to block review: How about tabList.add(Math.min(0, tabList.size() - 1), tab) instead of a conditional?
Source:
public int calculateLeadImageWidth() { Resources res = app.getResources(); return (int) (res.getDimension(R.dimen.leadImageWidth) / res.getDisplayMetrics().density); }

Target:
How about calling getDimensionPixelSize() instead? We can remove the cast and density division.
Source:
public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = super.onCreateDialog(savedInstanceState); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); return dialog; }

Target:
Should we call super?
Source:
private void checkIfPageIsSaved() { if (getTitle() != null) { getActivity().getSupportLoaderManager().restartLoader(LOADER_ID, null, savedPageCheckCallbacks); } }

Target:
We might want to add a null check on getActivity() here since the clients of displayNewPage have no idea about Fragment lifecycles.
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( callingFragment.getActivity(), Uri.parse(SavedPage.PERSISTENCE_HELPER.getBaseContentURI().toString()), null, selection, selectionArgs, null); }

Target:
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.
Source:
public void namespaceAwareUpsert(SavedPage savedPage) { namespaceAwareUpsert( WikipediaApp.getInstance().getDbOpenHelper().getWritableDatabase(), savedPage, getTableName(), getPrimaryKeySelection(), getPrimaryKeySelectionArgs(savedPage) ); }

Target:
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.
Source:
public static void showMessage(Activity activity, int resId, int duration) { showMessage(findBestView(activity), activity.getString(resId), duration); }

Target:
Should we call the function below instead?
Source:
public static void showMessage(Activity activity, int resId) { showMessage(findBestView(activity), activity.getString(resId), Snackbar.LENGTH_LONG); }

Target:
Sorry, same feedback for this function. We should leverage showMessage(Activity, int, int) instead of repeating findBestView() and getString() here.
Source:
public SimpleDateFormat getSimpleDateFormat() { if (simpleDateFormat == null) { simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); } return simpleDateFormat; }

Target:
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
Source:
public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); WikipediaApp.getInstance().checkCrashes(this); ActivityUtil.requestFullUserOrientation(this); setTheme(WikipediaApp.getInstance().getCurrentTheme().getResourceId()); removeSplashBackground(); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } forceOverflowMenuIcon(this); }

Target:
Do we really need this in every ThemedActionBarActivity or is PageActivity enough?
Source:
public LinkPreviewFunnel(WikipediaApp app) { super(app, SCHEMA_NAME, REV_ID, app.isProdRelease() ? Funnel.SAMPLE_LOG_100 : Funnel.SAMPLE_LOG_ALL); version = PROD_LINK_PREVIEW_VERSION; }

Target:
Can we remove the version variable since it's always equal to the constant?
Source:
public static boolean isRestBaseEnabled() { if (Prefs.forceRestBase()) { return Prefs.useRestBase(); } boolean useRestBase = shouldUseRestBase(); Prefs.setUseRestBase(useRestBase); return useRestBase; }

Target:
Shouldn't this just return true? I thought force meant unconditionally use RESTbase.
Source:
public void onLoadFinished(Loader<Cursor> cursorLoaderLoader, Cursor cursorLoader) { adapter.swapCursor(cursorLoader); boolean visible = recentSearchesList.getCount() > 0; deleteButton.setVisibility(visible ? View.VISIBLE : View.INVISIBLE); if (!isAdded()) { return; } getActivity().supportInvalidateOptionsMenu(); }

Target:
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.
Source:
public void closeSearch() { isSearchActive = false; // invalidate our activity's ActionBar, so that the original action items are restored. getActivity().supportInvalidateOptionsMenu(); getActivity().supportInvalidateOptionsMenu(); ((PageActivity)getActivity()).getSearchBarHideHandler().setForceNoFade(false); setSearchViewEnabled(false); ((PageActivity) getActivity()).getDrawerToggle().setDrawerIndicatorEnabled(true); // hide ourselves searchContainerView.setVisibility(View.GONE); hideSoftKeyboard(getActivity()); addRecentSearch(lastSearchedText); }

Target:
Is this intentional?
Source:
public void onFinish(Map<PageTitle, LinkPreviewContents> result) { if (!isAdded()) { return; } if (result.size() > 0) { progressBar.setVisibility(View.GONE); contents = (LinkPreviewContents) result.values().toArray()[0]; layoutPreview(); } else { loadContentFromCache(); } }

Target:
How about !result.isEmpty() instead?
Source:
public void onActionModeFinished(android.view.ActionMode mode) { nullifyActionMode(); searchBarHideHandler.setForceNoFade(false); super.onActionModeFinished(mode); }

Target:
Since we call the super in onActionModeStarted(), should we call it first here (last in, first out)?
Source:
public boolean await() throws InterruptedException { if (!latch.await(TestConstants.TIMEOUT_DURATION, TestConstants.TIMEOUT_UNIT)) { throw new InterruptedException("Timeout elapsed."); } return latch.await(TestConstants.TIMEOUT_DURATION, TestConstants.TIMEOUT_UNIT); }

Target:
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.
Source:
public void showLinkPreview(PageTitle title, int entrySource, @Nullable Location location) { if (getSupportFragmentManager().findFragmentByTag(LINK_PREVIEW_FRAGMENT_TAG) == null) { DialogFragment linkPreview = app.isLinkPreviewExperimental() ? LinkPreviewDialogB.newInstance(title, entrySource) : LinkPreviewDialog.newInstance(title, entrySource, location); linkPreview.show(getSupportFragmentManager(), LINK_PREVIEW_FRAGMENT_TAG); } }

Target:
Looks like this will need a rebase over the patch removing the a/b test (or vice versa).
Source:
public Object evaluate(DeferredObject[] arguments) throws HiveException { result.clear(); if (arguments.length == 1 && argumentOI != null && arguments[0] != null) { String countryCode = ((StringObjectInspector) argumentOI).getPrimitiveJavaObject(arguments[0].get()); result.set(Geocode.getCountryName(countryCode)); } return result; }

Target:
Arguments.length is already been checked for above, I think there is no need to do it again.
Source:
public synchronized EditTokenStorage getEditTokenStorage() { if (editTokenStorage == null) { editTokenStorage = new EditTokenStorage(this); } return editTokenStorage; }

Target:
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()?
Source:
private MwPageService.MwPageEndpoints createMwService(Site site) { MwPageService.MwPageEndpoints webService; webService = RestAdapterFactory.newInstance(site) .create(MwPageService.MwPageEndpoints.class); return webService; }

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

Target:
This line can be combined with previous line.
Source:
public static boolean isSelectTextTutorialEnabled() { return !getBoolean(R.string.preference_key_select_text_tutorial_enabled, false); }

Target:
What's the reasoning here? This will cause the highlight tooltip to be shown all the time (in 1-minute intervals).
Source:
public static float getDensityScalar() { if (DENSITY_SCALAR == null) { DENSITY_SCALAR = getDisplayMetrics().density; } return DENSITY_SCALAR; }

Target:
Nothing to hang the patch but out of curiosity, why lazy init this but not widthPixels? Is this operation expected to be slow?
Source:
public Api getSiteApi() { return getAPIForSite(new Site("authmanager.wmflabs.org")); //return getAPIForSite(getSite()); }

Target:
Consider reverting this since it's no longer a WIP patch.
Source:
public void writeToParcel(Parcel parcel, int i) { parcel.writeParcelable(amCreateAccountResult, 0); parcel.writeParcelable(legacyCreateAccountResult, 0); }

Target:
I think this second parameter is meant to be flags and should be passed to the parcel.writeParcelable calls.
Source:
public void doCreateAccount() { new AMCreateAccountInfoTask() { @Override public void onCatch(Throwable caught) { L.e("AMCreateAccountInfoTask failed: " + caught.getMessage()); } @Override public void onFinish(AMCreateAccountInfoResult result) { if (result.getEnabled()) { L.i("Creating account with AuthManager"); captchaHandler.handleCaptcha(new CaptchaResult(result.getCaptchaId()), true); } else { L.i("Creating account with legacy API"); doLegacyCreateAccount(); } } }.execute(); }

Target:
Same nit about L.e(caught)
Source:
private void init() { inflate(); bind(); FeedbackUtil.setToolbarButtonLongPressToast(bookmark); FeedbackUtil.setToolbarButtonLongPressToast(navigate); FeedbackUtil.setToolbarButtonLongPressToast(share); }

Target:
This is great! It it worth having a FeedbackUtil.setToolbarButtonLongPressToast() variable arity overload?
Source:
public void setSaveOffline(boolean saved) { if (pages.isEmpty()) { emptyListSavePagesState = saved; return; } for (ReadingListPage page : pages) { page.savedOrSaving(saved); ReadingListPageDao.instance().upsert(page); } }

Target:
I think this can unconditionally be set to saved. (Conditionals are hazardous.) Note: this information is not preserved in the database and will be lost on app restart.
Source:
public boolean getSaveOffline() { if (pages.size() == 0) { return emptyListSavePagesState; } for (ReadingListPage page : pages) { if (!page.savedOrSaving()) { return false; } } return true; }

Target:
isEmpty()
Source:
public ReadingListPageDiskRow(@NonNull ReadingListPage row) { super(row.key(), row); filename = null; }

Target:
It looks filename is derived from page title. Have you considered just calling the new constructor like this(row, filenameAlgorithm(row.title)
Source:
public <T extends Card> void removeCards(Class<T> type, List<Card> items) { Iterator<Card> iterator = items.iterator(); while (iterator.hasNext()) { Card card = iterator.next(); if (type.isInstance(card)) { items.remove(card); } } }

Target:
Sorry, I wrote this wrong earlier. I think you want iterator.remove() to avoid a ConcurrentModificationException.
Source:
public void request(@NonNull Context context, int age, final FeedCoordinator.FeedClientCallback cb) { cb.success(this, new IntegerListCard()); }

Target:
This is a nice test! Now we know it's safe for clients to cache and return results immediately.
Source:
public PageTitle titleForInternalLink(String internalLink) { // FIXME: Handle language variant links properly // Strip the /wiki/ (mobileview) or ./ (parsoid) from the href return new PageTitle(RbSwitch.INSTANCE.isRestBaseEnabled() ? internalLink.replaceFirst("./", "") : internalLink.replaceFirst("/wiki/", ""), this); }

Target:
Can we do both replacements unconditionally? I'm worried about pages cached with one service while the other is actually enabled.
Source:
@NonNull public ListCardItemView setSubtitle(@Nullable CharSequence subtitle) { subtitleView.setText(subtitle); return this; }

Target:
Wouldn't this mean that we're calling the base method of TextView.setText() and bypassing the overridden method in GoneIfEmptyTextView? (it appears that way in testing.)
Source:
public void onPageLoadComplete() { showToCButton(); refreshView.setEnabled(true); editHandler.setPage(model.getPage()); initPageScrollFunnel(); // TODO: update this title in the db to be queued for saving by the service. checkAndShowSelectTextOnboarding(); updateNavDrawerSelection(); if (getMainActivity().pageLoadCallbacks() != null) { getMainActivity().pageLoadCallbacks().onLoadComplete(); } }

Target:
It might be good to check that getMainActivity() itself doesn't return null as well since this method appears to complete asynchronously?
Source:
public void onPageLoadComplete() { showToCButton(); refreshView.setEnabled(true); editHandler.setPage(model.getPage()); initPageScrollFunnel(); // TODO: update this title in the db to be queued for saving by the service. checkAndShowSelectTextOnboarding(); updateNavDrawerSelection(); if (getActivity() != null && getPageLoadCallbacks() != null) { getPageLoadCallbacks().onLoadComplete(); } }

Target:
Should this just be getPageLoadCallbacks() != null?
Source:
public static boolean isTabListEmpty() { List<Tab> tabs = getTabs(); return !tabs.isEmpty() && !tabs.get(0).getBackStack().isEmpty(); }

Target:
The code does the right thing but the name of this method is misleading. It's the opposite of what it name implies.
Source:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_main, menu); viewPager.post(new Runnable() { @Override public void run() { setUpOverflowButton(); } }); }

Target:
Missed this earlier. Should we call the super here and in onOptionsItemSelected?
Source:
public void onSearchOpen() { Callback callback = callback(); if (callback != null) { callback.getActivityToolbar().setVisibility(View.GONE); } }

Target:
Here and elsewhere, the Fragment probably shouldn't force the host to do things by getting its internals and changing them. The dependency on a toolbar is clear because of the callback pattern but exposing the toolbar directly allows any Fragment to change it. It's ok to defer but consider pushing onSearchOpen() into the host and allow it to hide / show the toolbar.
Source:
public void setScrollView(@Nullable ObservableWebView webView) { webview = webView; if (webview != null) { webview.addOnScrollChangeListener(this); webview.addOnDownMotionEventListener(this); webview.addOnUpOrCancelMotionEventListener(this); webview.addOnClickListener(this); } }

Target:
We probably should clear previously set listeners.
Source:
private static OutputWrapper connectMySql(String param) throws IOException { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql:" + param); return new OutputWrapper(conn); } catch (Exception e) { //e.printStackTrace(); throw (IOException)new IOException(e.getMessage()).initCause(e); } }

Target:
throw new IOException(e)
Source:
private static OutputWrapper connectPostgres(String param) throws IOException { try { Class.forName("org.postgresql.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:postgresql:" + param); return new OutputWrapper(conn); } catch (Exception e) { throw new IOException(e.toString()); } }

Target:
throw new IOException(e)
Source:
@OnClick(R.id.reading_list_detail_back_button) protected void onBackPressed(View v) { if (actionListener != null) { actionListener.onBackPressed(); } }

Target:
Any reason not to use package protected? protected means subclasses could override this method which doesn't seem otherwise supported by this class.
Source:
public final <T> TypeAdapter<T> create(@NonNull Gson gson, @NonNull TypeToken<T> typeToken) { Class<?> rawType = typeToken.getRawType(); Set<Field> requiredFields = collectRequiredFields(rawType); if (!requiredFields.isEmpty()) { setFieldsAccessible(requiredFields, true); return new Adapter<>(gson.getAdapter(JsonElement.class), gson.getDelegateAdapter(this, typeToken), requiredFields); } return null; }

Target:
Feel free to ignore: I would handle the null case first because it feels special whereas the nonempty case is generic: if (requiredFields.isEmpty()) { return null } setFieldsAccessible(requiredFields, true); return new Adapter<>(gson.getAdapter(JsonElement.class), gson.getDelegateAdapter(this, typeToken), requiredFields);
Source:
@Override @Nullable public T read(JsonReader in) throws IOException { JsonElement tree = adapter.read(in); T deserialized = delegate.fromJsonTree(tree); return allRequiredFieldsPresent(deserialized, requiredFields) ? deserialized : null; }

Target:
Should this be delegate.read(in)? I'm not sure what it means to get an adapter for JsonElement.class. If we keep the current implementation, does write need to be updated to use adapter.write?
Source:
public void cancel(@Nullable Call<?> call) { if (call == null) { return; } call.cancel(); call = null; }

Target:
Why set a reference copy to null?
Source:
private void saveState(Bundle outState) { outState.putBoolean("pausedZeroEnabledState", isZeroEnabled); outState.putString("pausedZeroConfig", GsonMarshaller.marshal(currentZeroConfig)); outState.putBoolean("isSearching", isSearching()); outState.putString(LANGUAGE_CODE_BUNDLE_KEY, app.getAppOrSystemLanguageCode()); }

Target:
Does this mean your type adapter needs to support write?
Source:
private NearbyPage constructNearbyPage(@NonNull String title, double lat, double lon) { Location location = new Location(title); location.setLatitude(lat); location.setLongitude(lon); return new NearbyPage(location); }

Target:
Although the typing is permissive, I think this is supposed to be a location provider like GPS or network
Source:
private void assertCallbackSuccess(@NonNull Call<DescriptionEdit> call, @NonNull Callback cb) { verify(cb).success(eq(call)); //noinspection unchecked verify(cb, never()).failure(eq(call), any(Throwable.class)); }

Target:
This should probably be any() since we really never want this invoked under any argument.
Source:
public void onResponse(@NonNull Call<ZeroConfig> call, @NonNull Response<ZeroConfig> response) { if (response.isSuccessful()) { if (response.body() == null) { cb.failure(call, new JsonParseException("Response missing required field(s)")); } cb.success(call, response.body()); } else { cb.failure(call, RetrofitException.httpError(response, cachedService.retrofit())); } }

Target:
I think you should return or else case the success.
Source:
public View newView(Context context, Cursor cursor, ViewGroup parent) { return ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)) .inflate(android.R.layout.simple_list_item_1, parent, false); }

Target:
There's a billion of these LayoutInflater methods but I think LayoutInflater.from(context) is the best for this circumstance.
Source:
@Override protected DescriptionEditSuccessFragment createFragment() { DescriptionEditSuccessFragment fragment = DescriptionEditSuccessFragment.newInstance(); fragment.setCallback(this); return fragment; }

Target:
The Fragment should obtain the host by calling FragmentUtil.getCallback(). I think if the Activity is ratained in a Fragment instance, it'll cause a memory leak.
Source:
@Theory public void testWidth(@TestedOn(ints = {WIDTH_DP_XL, WIDTH_DP_L}) int widthDp, @NonNull FontScale fontScale) { setUp(widthDp, LayoutDirection.LOCALE, fontScale, Theme.LIGHT); subject = new DescriptionEditSuccessView(ctx()); snap(subject); }

Target:
You're calling snap but I think you forgot to add the screenshots to this patch.
Source:
@NonNull @Override public CardType type() { return CardType.ANNOUNCEMENT; }

Target:
I guess we're not consistent across the codebase on whether method annotations should be on the same line as the method signature or on their own line(s). Let's pick one or the other and stick to it on at least a per-class basis, though.
Source:
public AnnouncementCardView(Context context) { super(context); inflate(getContext(), R.layout.view_card_announcement, this); ButterKnife.bind(this); }

Target:
How about just context since we have it?
Source:
private String getShareSubject() { if (getArguments().getBoolean(ARG_FEED_FEATURED_IMAGE)) { return ShareUtil.getFeaturedImageShareSubject(getContext(), new UtcDate(age).baseCalendar()); } else if (pageTitle != null) { return pageTitle.getDisplayText(); } return null; }

Target:
Unnecessary else :]
Source:
protected void checkArgType(ObjectInspector[] arguments, int i, PrimitiveCategory type) throws UDFArgumentTypeException{ PrimitiveCategory primitiveCategory = ((PrimitiveObjectInspector) arguments[i]).getPrimitiveCategory(); if (primitiveCategory != type) { throw new UDFArgumentTypeException(0, "A " + type.getClass().getSimpleName() + " argument was expected for " + getFuncName() + " but an argument of type " + arguments[i].getTypeName() + " was given." ); } }

Target:
i? but 0 was used previously... not sure if it's an existing bug or if it was set like that on purpose.
Source:
@VisibleForTesting public void putIdForLanguage(@NonNull String code, int id) { ids.put(code, id); }

Target:
This doesn't seem to be @VisibleForTesting since WikipediaApp requires this method to be public and UserTest only requires package privacy
Source:
public int getIdForLanguage(@NonNull String code) { Integer id = ids.get(code); return id != null ? id : 0; }

Target:
If you flip this conditional, you can use == instead of negated logic
Source:
public static HashMap<String, Integer> getLoginUserIds() { TypeToken<HashMap<String, Integer>> type = new TypeToken<HashMap<String, Integer>>(){}; return GsonUnmarshaller.unmarshal(type, getString(R.string.preference_key_login_user_id_map, "{}")); }

Target:
Can this return a Map instead of a HashMap implementation?
Source:
public void notifyItemChanged(@NonNull Card card) { notifyItemChanged(feedAdapter.getItemPosition(card)); }

Target:
I'm sorry if I missed this earlier but the null check of feedAdapter in the int overload of this method suggests a similar null check is necessary here. Also consider checking the return value of getItemPosition() in case it's not present in the adapter
Source:
public void onBindViewHolder(RecyclerView.ViewHolder holder, int pos) { if (holder instanceof ReadingListPageItemHolder) { ((ReadingListPageItemHolder) holder).bindItem(readingList.getPages().get(pos)); } }

Target:
I believe this will be flagged as a potential NPE by Android Studio. It makes sense that this will never happen so I recommend adding a readingList != null to the conditional, suppressing the warning, or throwing an IllegalStateException if null to show that the author was considering this case and only true warnings are flagged by Android Studio.
Source:
private ErrorType getErrorType(@NonNull Context context, @Nullable Throwable caught) { if (caught != null && !is404(context, caught)) { if (context instanceof PageActivity) { return ErrorType.PAGE_OFFLINE; } else { return ErrorType.OFFLINE; } } return ErrorType.GENERIC; }

Target:
Needless else :]
Source:
public RecentChangesPoller(WikibaseRepository wikibase, Date firstStartTime, int batchSize, Map<Long, Boolean> seenIDs, int tailSeconds) { this.wikibase = wikibase; this.firstStartTime = firstStartTime != null ? new Date(firstStartTime.getTime()) : null; this.batchSize = batchSize; this.seenIDs = seenIDs; this.tailSeconds = tailSeconds; }

Target:
same here about dates - maybe better to move to immutable ones?
Source:
@Override protected void buildScript(int age) { if (age == 0) { addPendingClient(new SearchClient()); addPendingClient(new AnnouncementClient()); } addPendingClient(new AggregatedFeedContentClient()); addPendingClient(new ContinueReadingClient()); if (age == 0) { addPendingClient(new MainPageClient()); } addPendingClient(new BecauseYouReadClient()); if (age == 0) { addPendingClient(new RandomClient()); } // OfflineClient must always come last, since we rely on the last request in the series // being a network request (and not a disk I/O request) to determine online/offline state // for purposes of updating the feed UI. addPendingClient(new OfflineClient()); }

Target:
FWIW, I believe we can observe (be notified and respond to) changes to airplane mode and connectivity state (basically anything you see in your system status bar connectivity icon): https://developer.android.com/reference/android/net/NetworkInfo.DetailedState.html You can also track network successes and failures in the existing Interceptor for RESTBase switching and then rebroadcast those as OFFLINE / ONLINE events on our event bus. Since global network health seems to be what we're after but we still want to avoid mingling responsibilities, intercepting requests might be the way go.
Source:
@Override public void error(@NonNull Throwable caught) { if (caught instanceof OfflineClient.OfflineException) { appendCard(new OfflineCard()); } //noinspection ConstantConditions requestNextCard(wiki); }

Target:
This looks good and will cover us for all usage of the feed.
Source:
public Call<MwQueryResponse<QueryResult>> request(@NonNull WikiSite wiki, @NonNull PageTitle title, @NonNull Callback cb) { List<PageTitle> titles = new ArrayList<>(); titles.add(title); return request(wiki, cachedService.service(wiki), titles, cb); }

Target:
It looks like this client is only ever used for a single title, which is being shared as an image. Let's skip converting to a List and just pass the PageTitle straight though. You can just call service.request(title.toString()) below rather than TextUtils.join as well. (The PageTitle class overrides toString() to return the namespace-prefixed title string.)
Source:
public Model checkSyntax(InputStream dataset, String baseURI, RDFFormat format) { Model parsed = null; try { parsed = Rio.parse(dataset, baseURI, format); } catch (IOException ioe) { log.error("Couldn't read your dataset: {}", ioe.getMessage()); System.exit(1); } catch (RDFParseException rpe) { log.error("Your dataset is not valid RDF. Please fix it: {}", rpe.getMessage()); System.exit(1); return null; } return parsed; }

Target:
Not much use to return null after exit :)
Source:
@Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { actionMode = mode; mode.setTag(getTag()); mode.getMenuInflater().inflate(R.menu.menu_action_mode_reading_list, menu); return true; }

Target:
I think this can be a bit cleaner by calling super.onCreateActionMode(), and not exposing getTag(), and then proceed to inflate the menu. (and remove the default inflating of the menu in super()). Or better yet, create an abstract method that asks for the resource-id of the menu to inflate.
Source:
public void testBadSyntax() throws Exception { InputStream badRDF = openTestDatasetStream(BAD_RDF_FILE_NAME); validator.checkSyntax(badRDF, BASE_URI, RDF_FORMAT); badRDF.close(); }

Target:
close() should be in a finally block, or use try-with-resource
Source:
@Override public void onDestroyView() { recyclerView.setAdapter(null); unbinder.unbind(); unbinder = null; super.onDestroyView(); }

Target:
Needs a line break for consistency
Source:
public InterruptibleCharSequence(CharSequence inner) { super(); this.inner = inner; }

Target:
Call to `super()` is implicit and not required.