auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void next(String email) { if (!NetworkUtils.checkConnection(getActivity())) { return; } if (isValidEmail(email)) { clearEmailError(); startProgress(); mRequestedEmail = email; mDispatcher.dispatch(AccountActionBuilder.newIsAvailableEmailAction(email)); START mAnalyticsListener.trackEmailFilled(); END } else { showEmailError(R.string.email_invalid); } } Since we're tracking this event after the user taps the next button and only when the email is valid, maybe we shouldn't call it "email filled", as it may be misinterpreted as the user just filling in the email input. Does that make sense to you? To be honest, I'm not even sure why we need this event. 🤔 What's the idea here?

Target:
protected void next(String email) { if (!NetworkUtils.checkConnection(getActivity())) { return; } if (isValidEmail(email)) { clearEmailError(); startProgress(); mRequestedEmail = email; mDispatcher.dispatch(AccountActionBuilder.newIsAvailableEmailAction(email)); } else { showEmailError(R.string.email_invalid); } }
Source:
public MePage go() { // Using the settings button as a marker for successfully navigating to the page while (!isElementDisplayed(appSettings)) { clickOn(R.id.nav_sites); START clickOn(onView(allOf(withId(R.id.me_item), withEffectiveVisibility(Visibility.VISIBLE)))); END } if (!isSelfHosted()) { displayName.check(matches(isDisplayed())); } return this; } Given that `clickOn` is our own custom click action, I don't love modifying the element we're passing it here. It feels cleaner to update the `clickOn` method itself to better handle scenarios like this. What do you think?

Target:
public MePage go() { // Using the settings button as a marker for successfully navigating to the page while (!isElementDisplayed(appSettings)) { clickOn(R.id.nav_sites); clickOn(R.id.me_item); } if (!isSelfHosted()) { displayName.check(matches(isDisplayed())); } return this; }
Source:
public static boolean isPublishDateInTheFuture(String dateCreated) { START Date pubDate = DateTimeUtils.dateFromIso8601(dateCreated); END Date now = new Date(); return pubDate != null && pubDate.after(now); } We might want to consider calling the new method from this one so we don't duplicate code `isPublishDateInTheFuture(dateCreated, new Date())` wdyt?

Target:
public static boolean isPublishDateInTheFuture(String dateCreated) { return isPublishDateInTheFuture(dateCreated, new Date()); }
Source:
public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_SMARTLOCK_HELPER_STATE, mSmartLockHelperState.name()); outState.putBoolean(KEY_SIGNUP_FROM_LOGIN_ENABLED, mIsSignupFromLoginEnabled); START outState.putBoolean(KEY_SIGNUP_FROM_LOGIN_ENABLED, mIsSignupFromLoginEnabled); END } This looks like a copy/paste typo maybe?

Target:
public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_SMARTLOCK_HELPER_STATE, mSmartLockHelperState.name()); outState.putBoolean(KEY_SIGNUP_FROM_LOGIN_ENABLED, mIsSignupFromLoginEnabled); }
Source:
START @Override public void onCreate(Bundle savedInstanceState) { END super.onCreate(savedInstanceState); Bundle args = getArguments(); if (args != null) { mIsSignupFromLoginEnabled = args.getBoolean(ARG_SIGNUP_FROM_LOGIN_ENABLED, false); } } These `Override`s are generally on separate lines (I don't think our styles are set up correctly but check the rest of this file)

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); if (args != null) { mIsSignupFromLoginEnabled = args.getBoolean(ARG_SIGNUP_FROM_LOGIN_ENABLED, false); } }
Source:
public void configureResources(Context context) { if (context == null) { return; } START END mNormalTextColor = ContextExtensionsKt.getColorFromAttribute(context, R.attr.colorOnSurface); mNormalBackgroundColor = ContextExtensionsKt.getColorFromAttribute(context, R.attr.colorSurface); mAgoTextColor = ContextExtensionsKt.getColorFromAttribute(context, R.attr.wpColorOnSurfaceMedium); mUnapprovedTextColor = ContextExtensionsKt.getColorFromAttribute(context, R.attr.wpColorWarningDark); // Double margin_extra_large for increased indent in comment replies mIndentedLeftPadding = context.getResources().getDimensionPixelSize(R.dimen.margin_extra_large) * 2; } I think this white line can be removed.

Target:
public void configureResources(Context context) { if (context == null) { return; } mNormalBackgroundColor = ContextExtensionsKt.getColorFromAttribute(context, R.attr.colorSurface); // Double margin_extra_large for increased indent in comment replies mIndentedLeftPadding = context.getResources().getDimensionPixelSize(R.dimen.margin_extra_large) * 2; }
Source:
public void updateFeaturedImage(long featuredImageId) { EditPostRepository postRepository = getEditPostRepository(); if (postRepository == null) { return; } postRepository.update(postModel -> { postModel.setFeaturedImageId(featuredImageId); updateFeaturedImageView(); START if (featuredImageId != 0) { END mFeaturedImageHelper.trackFeaturedImageEvent( FeaturedImageHelper.TrackableEvent.IMAGE_PICKED, postModel, OriginType.EDIT_POST_SETTINGS ); } return true; }); } It seems `updateFeaturedImage` is called from `EditPostActivity` when 1) media which exists in the remote gets selected 2) after a media which doesn't exist in the remote gets uploaded Case `1` is fine, but I'm wondering if case `2` is what we want to track. Or do we rather want to track the actual click/selection of the media - no matter what happens with the upload? Wdyt?

Target:
public void updateFeaturedImage(long featuredImageId) { EditPostRepository postRepository = getEditPostRepository(); if (postRepository == null) { return; } postRepository.update(postModel -> { postModel.setFeaturedImageId(featuredImageId); updateFeaturedImageView(); return true; }); }
Source:
public void onContinue() { if (mSiteStore.hasSite()) { setResult(RESULT_OK); START } else if (AppPrefs.shouldShowPostSignupInterstitial()) { END ActivityLauncher.showPostSignupInterstitial(this); } finish(); } Here, I think we shouldn't check for the preference value and always show the interstitial. I can't think of any use case where we shouldn't nudge new users to create a new site.

Target:
public void onContinue() { if (!mSiteStore.hasSite()) { ActivityLauncher.showPostSignupInterstitial(this); } setResult(RESULT_OK); finish(); }
Source:
private static String toHtml(SpannableStringBuilder builder, AztecParser parser) { clearMetaSpans(builder); parser.syncVisualNewlinesOfBlockElements(builder); Format.postProcessSpannedText(builder, true); START return EndOfBufferMarkerAdder.removeEndOfTextMarker(parser.toHtml(builder, false, false)); END } I think we can use the `@JvmOverloads` annotation in the Aztec method in Kotlin to allow the Java side to call the method without the new extra parameter). Check out [this answer on SO](https://stackoverflow.com/a/34518024).

Target:
private static String toHtml(SpannableStringBuilder builder, AztecParser parser) { clearMetaSpans(builder); parser.syncVisualNewlinesOfBlockElements(builder); Format.postProcessSpannedText(builder, true); return EndOfBufferMarkerAdder.removeEndOfTextMarker(parser.toHtml(builder, false)); }
Source:
private void viewPages() { requestNextStepOfActiveQuickStartTask(); SiteModel selectedSite = getSelectedSite(); if (selectedSite != null) { START ToastUtils.showToast(getActivity(), R.string.site_cannot_be_loaded); END ActivityLauncher.viewCurrentBlogPages(requireActivity(), selectedSite); } } Shouldn't this line be in an `else` clause? Wdyt?

Target:
private void viewPages() { requestNextStepOfActiveQuickStartTask(); SiteModel selectedSite = getSelectedSite(); if (selectedSite != null) { ActivityLauncher.viewCurrentBlogPages(requireActivity(), selectedSite); } else { ToastUtils.showToast(getActivity(), R.string.site_cannot_be_loaded); } }
Source:
START @NonNull @Override public String getEditorName() { END return AZTEC_EDITOR_NAME; } NIT: move these to separate lines?

Target:
public String getEditorName() { return AZTEC_EDITOR_NAME; }
Source:
START @Override public void helpHandleDiscoveryError( END String siteAddress, String endpointAddress, String username, String password, String userAvatarUrl, int errorMessage) { // Not used in WordPress app } I think the annotations should be on separate lines

Target:
public void helpHandleDiscoveryError( String siteAddress, String endpointAddress, String username, String password, String userAvatarUrl, int errorMessage) { // Not used in WordPress app }
Source:
public boolean isAtLeastOneSettingsEnabled( JSONObject settingsJson, String[] settingsArray, String[] settingsValues ) { boolean atLeastOneOptionEnabled = false; if (settingsJson != null && settingsArray.length == settingsValues.length) { for (int i = 0; i < settingsArray.length; i++) { String settingValue = settingsValues[i]; boolean isChecked = JSONUtils.queryJSON(settingsJson, settingValue, true); if (isChecked) { START atLeastOneOptionEnabled = true; END } } } return atLeastOneOptionEnabled; } NIT: you can `return true` at this point and `return false` at the end of this method.

Target:
public boolean isAtLeastOneSettingsEnabled( JSONObject settingsJson, String[] settingsArray, String[] settingsValues ) { if (settingsJson != null && settingsArray.length == settingsValues.length) { for (int i = 0; i < settingsArray.length; i++) { String settingValue = settingsValues[i]; boolean isChecked = JSONUtils.queryJSON(settingsJson, settingValue, true); if (isChecked) { return true; } } } return false; }
Source:
public static void addPostWithHWAccelerationOff(int localSiteId, int localPostId) { if (localSiteId == 0 || localPostId == 0 || isPostWithHWAccelerationOff(localSiteId, localPostId)) { return; } String key = localSiteId + "-" + localPostId; START List<String> currentIds = getPostWithHWAccelerationOff(); END currentIds.add(key); // store in prefs String idsAsString = TextUtils.join(",", currentIds); setString(DeletablePrefKey.AZTEC_EDITOR_DISABLE_HW_ACC_KEYS, idsAsString); } Let's make this line `List<String> currentIds = new ArrayList<String>(getPostWithHWAccelerationOff());`, given `getPostWithHWAccelerationOff()` returns an `Arrays.asList()` which is a "fixed-size list" as per [the docs](https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...)), and thus the following line of code `currentIds.add(key);` will crash otherwise

Target:
public static void addPostWithHWAccelerationOff(int localSiteId, int localPostId) { if (localSiteId == 0 || localPostId == 0 || isPostWithHWAccelerationOff(localSiteId, localPostId)) { return; } String key = localSiteId + "-" + localPostId; List<String> currentIds = new ArrayList<>(getPostWithHWAccelerationOff()); currentIds.add(key); // store in prefs String idsAsString = TextUtils.join(",", currentIds); setString(DeletablePrefKey.AZTEC_EDITOR_DISABLE_HW_ACC_KEYS, idsAsString); }
Source:
protected void onPostExecute(UploadPostTaskResult result) { switch (result) { case ERROR: mPostUploadNotifier.incrementUploadedPostCountFromForegroundNotification(mPost); mPostUploadNotifier.updateNotificationErrorForPost(mPost, mSite, mErrorMessage, 0); finishUpload(); break; START case NOTHING_TO_UPLOAD: END mPostUploadNotifier.incrementUploadedPostCountFromForegroundNotification(mPost); finishUpload(); break; case PUSH_POST_DISPATCHED: // will be handled in OnPostChanged break; } } I am guessing the work we do in this `case` is necessary for cleanup. (just trying to make sure I am not missing anything in the review)

Target:
protected void onPostExecute(UploadPostTaskResult result) { switch (result) { case ERROR: mPostUploadNotifier.incrementUploadedPostCountFromForegroundNotification(mPost); mPostUploadNotifier.updateNotificationErrorForPost(mPost, mSite, mErrorMessage, 0); finishUpload(); break; case NOTHING_TO_UPLOAD: // we need to force increment the uploaded count as we know the post was enqueued twice. If we // didn't force incremented it, the `PostUploadNotifier.isPostAlreadyInPostCount()` would return // true and we'd end up with a dangling upload notification. mPostUploadNotifier.incrementUploadedPostCountFromForegroundNotification(mPost, true); finishUpload(); break; case PUSH_POST_DISPATCHED: // will be handled in OnPostChanged break; } }
Source:
private void primaryAction() { switch (getPrimaryAction()) { case UPDATE: showUpdateConfirmationDialogAndUploadPost(); return; case PUBLISH_NOW: showPublishConfirmationDialogAndPublishPost(); return; case SCHEDULE: START uploadPost(false); END return; // In other cases, we'll upload the post without changing its status case SUBMIT_FOR_REVIEW: case SAVE: uploadPost(false); break; } } We can move this to the "other cases" below: ```java // In other cases, we'll upload the post without changing its status case SCHEDULE: case SUBMIT_FOR_REVIEW: case SAVE: uploadPost(false); break; ```

Target:
private void primaryAction() { switch (getPrimaryAction()) { case UPDATE: showUpdateConfirmationDialogAndUploadPost(); return; case PUBLISH_NOW: showPublishConfirmationDialogAndPublishPost(); return; // In other cases, we'll upload the post without changing its status case SCHEDULE: case SUBMIT_FOR_REVIEW: case SAVE: uploadPost(false); break; } }
Source:
private void checkIfUsernameCanBeChanged() { AccountModel account = mAccountStore.getAccount(); mUsernamePreference.setEnabled(account.getUsernameCanBeChanged()); mUsernamePreference.setOnPreferenceClickListener(preference -> { showUsernameChangerFragment(); START return false; END }); } I'm wondering if we should return "true" here. Wdyt?

Target:
private void checkIfUsernameCanBeChanged() { AccountModel account = mAccountStore.getAccount(); mUsernamePreference.setEnabled(account.getUsernameCanBeChanged()); mUsernamePreference.setOnPreferenceClickListener(preference -> { showUsernameChangerFragment(); return true; }); }
Source:
public void onBackPressed() { START androidx.fragment.app.Fragment fragment = getSupportFragmentManager() END .findFragmentByTag(ImageSettingsDialogFragment.IMAGE_SETTINGS_DIALOG_TAG); if (fragment != null && fragment.isVisible()) { ((ImageSettingsDialogFragment) fragment).dismissFragment(); } else { super.onBackPressed(); } } I think that there is no need for a full package path as we already have import on the top of the file?

Target:
public void onBackPressed() { Fragment fragment = getSupportFragmentManager().findFragmentByTag(ImageSettingsDialogFragment.IMAGE_SETTINGS_DIALOG_TAG); if (fragment != null && fragment.isVisible()) { ((ImageSettingsDialogFragment) fragment).dismissFragment(); } else { super.onBackPressed(); } }
Source:
public void start(ArrayList<Object> unsupportedBlocksList) { if (!mStarted) { Map<String, Object> properties = getCommonProperties(); START mHasUnsupportedBlocks = unsupportedBlocksList != null && unsupportedBlocksList.size() > 0; END properties.put(KEY_UNSUPPORTED_BLOCKS, unsupportedBlocksList != null ? unsupportedBlocksList : new ArrayList<>()); AnalyticsTracker.track(Stat.EDITOR_SESSION_START, properties); mStarted = true; } else { AppLog.w(T.EDITOR, "An editor session cannot be attempted to be started more than once, " + "unless it's due to rotation or Editor switch"); } } Hmm, actually, we need to compute `mHasUnsupportedBlocks` before the getCommonProperties() call because it's used there.

Target:
public void start(ArrayList<Object> unsupportedBlocksList) { if (!mStarted) { mHasUnsupportedBlocks = unsupportedBlocksList != null && unsupportedBlocksList.size() > 0; Map<String, Object> properties = getCommonProperties(); properties.put(KEY_UNSUPPORTED_BLOCKS, unsupportedBlocksList != null ? unsupportedBlocksList : new ArrayList<>()); AnalyticsTracker.track(Stat.EDITOR_SESSION_START, properties); mStarted = true; } else { AppLog.w(T.EDITOR, "An editor session cannot be attempted to be started more than once, " + "unless it's due to rotation or Editor switch"); } }
Source:
public void setUp() { logoutIfNecessary(); stubFor(get(urlEqualTo("/rest/v1.1/me/")) .inScenario("Sign up") START .whenScenarioStateIs(Scenario.STARTED)); END } We probably shouldn't use the WireMock Java API like this as it will not be possible to do for iOS. It should be possible to do this from the JSON files.

Target:
public void setUp() { logoutIfNecessary(); }
Source:
public void setup() { stubFor(get(urlEqualTo("/rest/v1.1/me/")) .inScenario("Sign up") START .whenScenarioStateIs("No")); END mAppContext = (WordPress) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext(); mMockedAppComponent = DaggerAppComponentTest.builder() .application(mAppContext) .build(); } Here as well. We will need to replace this with the equivalent JSON mock.

Target:
public void setup() { mAppContext = (WordPress) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext(); mMockedAppComponent = DaggerAppComponentTest.builder() .application(mAppContext) .build(); }
Source:
private void showDomainCreditsCheckProgressDialog() { if (mCheckingDomainCreditsProgressDialog == null) { mCheckingDomainCreditsProgressDialog = new ProgressDialog(this); START mCheckingDomainCreditsProgressDialog.setCancelable(false); END mCheckingDomainCreditsProgressDialog.setIndeterminate(true); mCheckingDomainCreditsProgressDialog .setMessage(getString(R.string.plugin_check_domain_credits_progress_dialog_message)); } if (!mCheckingDomainCreditsProgressDialog.isShowing()) { mCheckingDomainCreditsProgressDialog.show(); } } I think setting cancelable to false can result in an infinite dialog since the `OnPlansFetched` event may get lost during a configuration change. I think this isn't handled in many places in the app, but I just wanted to mention it. We may want to consider either allowing the user to cancel the dialog or setting @Subscribe(sticky=true,..) and handle it appropriately. Wdyt?

Target:
private void showDomainCreditsCheckProgressDialog() { if (mCheckingDomainCreditsProgressDialog == null) { mCheckingDomainCreditsProgressDialog = new ProgressDialog(this); mCheckingDomainCreditsProgressDialog.setCancelable(true); mCheckingDomainCreditsProgressDialog.setIndeterminate(true); mCheckingDomainCreditsProgressDialog .setMessage(getString(R.string.plugin_check_domain_credits_progress_dialog_message)); } if (!mCheckingDomainCreditsProgressDialog.isShowing()) { mCheckingDomainCreditsProgressDialog.show(); } }
Source:
protected void onPostExecute(Spanned spanned) { if (mPost != null && spanned != null) { START mTextView.setVisibility(View.GONE); END mWebView.setVisibility(View.VISIBLE); mWebView.loadDataWithBaseURL("file:///android_asset/", spanned.toString(), "text/html", "utf-8", null); } mLoadTask = null; } I think we can remove `mTextView` now since we always end up hiding it. It might be a good opportunity to clean up this `Fragment` a bit. I ended up making a bunch of changes while I was trying things out, so I thought to just commit it somewhere to share some proposed changes with you: https://github.com/wordpress-mobile/WordPress-Android/commit/c52dfc0100d36276d67465113ad85b607c44461c We don't have to make any of those changes of course, so it's totally up to you. Feel free to cherry-pick the commit or just re-commit in this branch if you do like it.

Target:
protected void onPostExecute(Spanned spanned) { if (mPost != null && spanned != null) { mWebView.loadDataWithBaseURL("file:///android_asset/", spanned.toString(), "text/html", "utf-8", null); } mLoadTask = null; }
Source:
public void onCompletedTasksListToggled(boolean isExpanded) { if (!mQuickStartStore.getUncompletedTasksByType(AppPrefs.getSelectedSite(), mTasksType).isEmpty()) { START return; END } toggleCompletedView(!isExpanded); } Exiting early can help flatten multiple nested `if` statements or simplify a complex conditional statement. In this case, there aren't nested statements and the early exit is slightly more complicated than not. What do you think about this? ```java @Override public void onCompletedTasksListToggled(boolean isExpanded) { if (mQuickStartStore.getUncompletedTasksByType(AppPrefs.getSelectedSite(), mTasksType).isEmpty()) { toggleCompletedView(!isExpanded); } } ```

Target:
public void onCompletedTasksListToggled(boolean isExpanded) { if (mQuickStartStore.getUncompletedTasksByType(AppPrefs.getSelectedSite(), mTasksType).isEmpty()) { toggleCompletedView(!isExpanded); } }
Source:
private static IAtomContainer parseSmiles(String smiles) throws CDKException { parser = new SmilesParser(SilentChemObjectBuilder.getInstance()); IAtomContainer molecule = parser.parseSmiles(smiles); AtomContainerManipulator.percieveAtomTypesAndConfigureUnsetProperties(molecule); CDKHydrogenAdder hAdder = CDKHydrogenAdder.getInstance(molecule.getBuilder()); START hAdder.addImplicitHydrogens(molecule); END AtomContainerManipulator.convertImplicitToExplicitHydrogens(molecule); Aromaticity.cdkLegacy().apply(molecule); return molecule; } Mmm... this should not actually be needed... I think this is actually done by the `SmilesParser` already. @johnmay ?

Target:
private static IAtomContainer parseSmiles(String smiles) throws CDKException { parser = new SmilesParser(SilentChemObjectBuilder.getInstance()); IAtomContainer molecule = parser.parseSmiles(smiles); AtomContainerManipulator.percieveAtomTypesAndConfigureUnsetProperties(molecule); AtomContainerManipulator.convertImplicitToExplicitHydrogens(molecule); Aromaticity.cdkLegacy().apply(molecule); return molecule; }
Source:
START public void close() { END input.close(); } Build failed: Need to throw IOException or catch it ``` public void close(){ try { if (input != null) input.close() } catch (IOException e) { // ignored } } ```

Target:
public void close() { try { if (input != null) input.close(); } catch (IOException e) { // ignored } }
Source:
public void testNumberOfUnplacedHeavyAtoms_IAtomContainer(){ START IAtomContainer ac = AtomPlacer3DTest.makeAlphaPinene(); END int count=new AtomPlacer3D().numberOfUnplacedHeavyAtoms(ac); Assert.assertEquals(10,count); } I would tend to leave off the static class definition such that this would read `IAtomContainer ac = makeAlphaPinene();`. Thoughts?

Target:
public void testNumberOfUnplacedHeavyAtoms_IAtomContainer(){ IAtomContainer ac = makeAlphaPinene(); int count=new AtomPlacer3D().numberOfUnplacedHeavyAtoms(ac); Assert.assertEquals(10,count); }
Source:
private EnvVars buildEnv(final Job<?, ?> job) { START EnvVars env = new EnvVars(); END for (EnvironmentContributor contributor : EnvironmentContributor.all()) { try { contributor.buildEnvironmentFor(job, env, TaskListener.NULL); } catch (Exception e) { LOGGER.warning("failed to build env, skipping"); } } return env; } finals for EnvVars and EnvironmentContributor in the for

Target:
private EnvVars buildEnv(final Job<?, ?> job) { final EnvVars env = new EnvVars(); for (final EnvironmentContributor contributor : EnvironmentContributor.all()) { try { contributor.buildEnvironmentFor(job, env, TaskListener.NULL); } catch (Exception e) { LOGGER.warning("failed to build env, skipping"); } } return env; }
Source:
private EnvVars addVarsToBuildEnv(final EnvVars envs, final ArrayList<ParameterValue> vars) { START for (ParameterValue p : vars) { END envs.putIfNotNull(p.getName(), String.valueOf(p.getValue())); } return envs; } final?

Target:
private EnvVars addVarsToBuildEnv(final EnvVars envs, final ArrayList<ParameterValue> vars) { for (final ParameterValue p : vars) { envs.putIfNotNull(p.getName(), String.valueOf(p.getValue())); } return envs; }
Source:
private String getStartedBy(final Run run) { final Cause.UserIdCause cause = (Cause.UserIdCause) run.getCause(Cause.UserIdCause.class); START final String startedBy; END if (cause != null) { startedBy = cause.getUserId(); } else { startedBy = null; } return startedBy == null ? "" : startedBy; } I think this would be simpler without the 'final' and the 'else' clause. Just initialize to 'null'.

Target:
private String getStartedBy(final Run run) { final Cause.UserIdCause cause = (Cause.UserIdCause) run.getCause(Cause.UserIdCause.class); String startedBy = ""; if (cause != null && cause.getUserId() != null) { startedBy = cause.getUserId(); } return startedBy; }
Source:
RedirectAuthoritativeDnsServerCache(AuthoritativeDnsServerCache authoritativeDnsServerCache) { // Unwrap to prevent the possibility of an StackOverflowError when wrapping another // RedirectAuthoritativeDnsServerCache. if (authoritativeDnsServerCache instanceof RedirectAuthoritativeDnsServerCache) { this.wrapped = ((RedirectAuthoritativeDnsServerCache) authoritativeDnsServerCache).wrapped; } else { START this.wrapped = authoritativeDnsServerCache; END } } Consider the opposite approach: write a utility method that will wrap only if it's not an instance of `RedirectAuthoritativeDnsServerCache`. That will help to avoid allocation of a new object when it's already wrapped.

Target:
RedirectAuthoritativeDnsServerCache(AuthoritativeDnsServerCache authoritativeDnsServerCache) { this.wrapped = authoritativeDnsServerCache; }
Source:
private void deflateJdk11(ByteBuf out) { if (out.isDirect()) { try { int numBytes; do { START numBytes = (Integer) DEFLATER_DEFLATE_BYTEBUFFER.invoke(deflater, out.nioBuffer(), END Deflater.SYNC_FLUSH); } while (numBytes > 0); } catch (IllegalAccessException e) { throw new Error(e); } catch (InvocationTargetException e) { throw new Error(e); } } else { deflateJdk7(out); } } you should call `nioBuffer()` only once: ```java ByteBuffer nioBuffer = out.nioBuffer(); int numBytes; do { numBytes = (Integer) DEFLATER_DEFLATE_BYTEBUFFER.invoke(deflater, nioBuffer, Deflater.SYNC_FLUSH); } while (numBytes > 0); ```

Target:
private void deflateJdk11(ByteBuf out) { if (out.isDirect()) { try { ByteBuffer nioBuffer = out.nioBuffer(); int numBytes; do { numBytes = (Integer) DEFLATER_DEFLATE_BYTEBUFFER.invoke(deflater, nioBuffer, Deflater.SYNC_FLUSH); } while (numBytes > 0); } catch (IllegalAccessException e) { throw new Error(e); } catch (InvocationTargetException e) { throw new Error(e); } } else { deflateJdk7(out); } }
Source:
START public static UnixResolverOptions.Builder newBuilder() { END return new UnixResolverOptions.Builder(); } nit: make all of the methods package-private as the class is package-private as well. This also ensures we no expose these by mistake at some point.

Target:
static UnixResolverOptions.Builder newBuilder() { return new UnixResolverOptions.Builder(); }
Source:
private static void encodeTlvs(List<HAProxyTLV> haProxyTLVs, ByteBuf out) { START for (HAProxyTLV tlv: haProxyTLVs) { END encodeTlv(tlv, out); } } closing using index based for loop to eliminate GC pressure

Target:
private static void encodeTlvs(List<HAProxyTLV> haProxyTLVs, ByteBuf out) { for (int i = 0; i < haProxyTLVs.size(); i++) { encodeTlv(haProxyTLVs.get(i), out); } }
Source:
public String toString() { START return new StringBuilder(128) END .append(StringUtil.simpleClassName(this)) .append("(type: ").append(type()) .append(", typeByteValue: ").append(typeByteValue()) .append(", client: ").append(client()) .append(", verify: ").append(verify()) .append(", numEncapsulatedTlvs: ").append(tlvs.size()) .append(')').toString(); } Just use normal string concats...

Target:
public String toString() { return StringUtil.simpleClassName(this) + "(type: " + type() + ", typeByteValue: " + typeByteValue() + ", client: " + client() + ", verify: " + verify() + ", numEncapsulatedTlvs: " + tlvs.size() + ')'; }
Source:
protected void encode(ChannelHandlerContext ctx, HAProxyMessage msg, ByteBuf out) throws Exception { START if (msg.protocolVersion() == HAProxyProtocolVersion.V1) { END encodeV1(msg, out); } else if (msg.protocolVersion() == HAProxyProtocolVersion.V2) { encodeV2(msg, out); } else { throw new HAProxyProtocolException("Unsupported version: " + msg.protocolVersion()); } } nit: consider replacing by a switch statement.

Target:
protected void encode(ChannelHandlerContext ctx, HAProxyMessage msg, ByteBuf out) throws Exception { switch (msg.protocolVersion()) { case V1: encodeV1(msg, out); break; case V2: encodeV2(msg, out); break; default: throw new HAProxyProtocolException("Unsupported version: " + msg.protocolVersion()); } }
Source:
protected void initChannel(SocketChannel channel) throws Exception { channel.pipeline() .addLast(new HttpServerCodec()) .addLast(new HttpObjectAggregator(65536)) .addLast(StompWebSocketClientPageHandler.INSTANCE) .addLast(new WebSocketServerProtocolHandler(chatPath, StompVersion.SUB_PROTOCOLS)) START .addLast("stompWebSocketProtocolCodec", stompWebSocketProtocolCodec); END } nit: why specify an explicit name here ? We dont do this for the other handlers as well.

Target:
protected void initChannel(SocketChannel channel) throws Exception { channel.pipeline() .addLast(new HttpServerCodec()) .addLast(new HttpObjectAggregator(65536)) .addLast(StompWebSocketClientPageHandler.INSTANCE) .addLast(new WebSocketServerProtocolHandler(chatPath, StompVersion.SUB_PROTOCOLS)) .addLast(stompWebSocketProtocolCodec); }
Source:
public V map(String hostname) { if (hostname != null) { hostname = normalize(hostname); // Let's try an exact match first V value = map.get(hostname); if (value != null) { return value; } // No exact match, let's try a wildcard match. int idx = hostname.indexOf('.'); if (idx != -1) { START value = map.get('*' + hostname.substring(idx)); END if (value != null) { return value; } } } return defaultValue; } Optional idea: If a user adds a wildcard domain `*.netty.io`, it could be normalized to `.netty.io`, and stored in the map. That would make it cheaper for this line to check if it's present, because no string concatenation would be needed. You could just check the substring. I am not sure how fast you want it to go.

Target:
public V map(String hostname) { if (hostname != null) { hostname = normalize(hostname); // Let's try an exact match first V value = map.get(hostname); if (value != null) { return value; } // No exact match, let's try a wildcard match. int idx = hostname.indexOf('.'); if (idx != -1) { value = map.get(hostname.substring(idx)); if (value != null) { return value; } } } return defaultValue; }
Source:
public static void tryFailure(Promise<?> p, Throwable cause, InternalLogger logger) { if (!p.tryFailure(cause) && logger != null) { Throwable err = p.cause(); if (err == null) { logger.warn("Failed to mark a promise as failure because it has succeeded already: {}", p, cause); } else { START if (logger.isWarnEnabled()) { END logger.warn( "Failed to mark a promise as failure because it has failed already: {}, unnotified cause: {}", p, ThrowableUtil.stackTraceToString(err), cause); } } } } Just merge this with the else and make it an else if?

Target:
public static void tryFailure(Promise<?> p, Throwable cause, InternalLogger logger) { if (!p.tryFailure(cause) && logger != null) { Throwable err = p.cause(); if (err == null) { logger.warn("Failed to mark a promise as failure because it has succeeded already: {}", p, cause); } else if (logger.isWarnEnabled()) { logger.warn( "Failed to mark a promise as failure because it has failed already: {}, unnotified cause: {}", p, ThrowableUtil.stackTraceToString(err), cause); } } }
Source:
private void parse8(int nameStart, int valueStart, int valueEnd) { if (header.regionMatches(true, nameStart, CookieHeaderNames.HTTPONLY, 0, 8)) { httpOnly = true; } else if (header.regionMatches(true, nameStart, CookieHeaderNames.SAMESITE, 0, 8)) { String sameSiteValue = computeValue(valueStart, valueEnd); try { sameSite = SameSite.of(sameSiteValue); START } catch (IllegalArgumentException e) { END logger.debug("Skipping SameSite attribute because value '{}' is invalid", sameSiteValue); } } } IMHO, you don't need to throw an IllegalArgumentException from SameSite.of and catch it right after. You could just return null.

Target:
private void parse8(int nameStart, int valueStart, int valueEnd) { if (header.regionMatches(true, nameStart, CookieHeaderNames.HTTPONLY, 0, 8)) { httpOnly = true; } else if (header.regionMatches(true, nameStart, CookieHeaderNames.SAMESITE, 0, 8)) { sameSite = SameSite.of(computeValue(valueStart, valueEnd)); } }
Source:
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { START if (writabilityStates.equals("")) { END writabilityStates = String.valueOf(ctx.channel().isWritable()); } else { writabilityStates += "," + ctx.channel().isWritable(); } super.channelWritabilityChanged(ctx); } if there is possibility of `writabilityStates` to be `null`, it might be better to write this as `"".equals(writabilityStates)`

Target:
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { if ("".equals(writabilityStates)) { writabilityStates = String.valueOf(ctx.channel().isWritable()); } else { writabilityStates += "," + ctx.channel().isWritable(); } super.channelWritabilityChanged(ctx); }
Source:
public SSLEngine wrapSslEngine(SSLEngine engine, ByteBufAllocator alloc, JdkApplicationProtocolNegotiator applicationNegotiator, boolean isServer) { if (JettyAlpnSslEngineSubstitution.isAvailable()) { return isServer ? (SSLEngine) (Object) JettyAlpnSslEngineSubstitution.newServerEngine(engine, applicationNegotiator) : (SSLEngine) (Object) JettyAlpnSslEngineSubstitution.newClientEngine(engine, applicationNegotiator); } START throw new RuntimeException("Unable to wrap SSLEngine of type " + engine.getClass().getName()); END } Use `IllegalStateException` ....

Target:
public SSLEngine wrapSslEngine(SSLEngine engine, ByteBufAllocator alloc, JdkApplicationProtocolNegotiator applicationNegotiator, boolean isServer) { if (JettyAlpnSslEngineSubstitution.isAvailable()) { return isServer ? (SSLEngine) (Object) JettyAlpnSslEngineSubstitution.newServerEngine(engine, applicationNegotiator) : (SSLEngine) (Object) JettyAlpnSslEngineSubstitution.newClientEngine(engine, applicationNegotiator); } throw new IllegalStateException("Unable to wrap SSLEngine of type " + engine.getClass().getName()); }
Source:
START public Queue<AbstractMap.SimpleEntry<Object, ChannelPromise>> tempInboundMessages() { END if (tempInboundMessages == null) { tempInboundMessages = new ArrayDeque<AbstractMap.SimpleEntry<Object, ChannelPromise>>(); } return tempInboundMessages; } This is not needed in unit tests... please keep it private

Target:
private Queue<AbstractMap.SimpleEntry<Object, ChannelPromise>> tempInboundMessages() { if (tempInboundMessages == null) { tempInboundMessages = new ArrayDeque<AbstractMap.SimpleEntry<Object, ChannelPromise>>(); } return tempInboundMessages; }
Source:
public ChannelFuture writeOneInbound(Object msg, ChannelPromise promise) { if (checkOpen(true)) { if (!config().isAutoRead()) { Queue<AbstractMap.SimpleEntry<Object, ChannelPromise>> tempInboundMessages = tempInboundMessages(); START if (tempInboundMessages != null) { END tempInboundMessages.add(new AbstractMap.SimpleEntry<Object, ChannelPromise>(msg, promise)); } return promise; } else { pipeline().fireChannelRead(msg); } } return checkException(promise); } nit: this never can be `null`. Remove the check

Target:
public ChannelFuture writeOneInbound(Object msg, ChannelPromise promise) { if (checkOpen(true)) { if (!config().isAutoRead()) { Queue<AbstractMap.SimpleEntry<Object, ChannelPromise>> tempInboundMessages = tempInboundMessages(); tempInboundMessages.add(new AbstractMap.SimpleEntry<Object, ChannelPromise>(msg, promise)); return promise; } else { pipeline().fireChannelRead(msg); } } return checkException(promise); }
Source:
private void encodeUtf8Component(CharSequence s) { for (int i = 0, len = s.length(); i < len; i++) { char c = s.charAt(i); if (!dontNeedEncoding(c)) { START if (i > 0) { END uriBuilder.append(s, 0, i); } encodeUtf8ComponentSlow(s, i); return; } } uriBuilder.append(s); } I would pack this entire branch in a differet method

Target:
private void encodeUtf8Component(CharSequence s) { for (int i = 0, len = s.length(); i < len; i++) { char c = s.charAt(i); if (!dontNeedEncoding(c)) { encodeUtf8Component(s, i, len); return; } } uriBuilder.append(s); }
Source:
final int drainTasks() { int numTasks = 0; for (;;) { Runnable runnable = taskQueue.poll(); if (runnable == null) { break; } // WAKEUP_TASKS should be just discarded as these are added internally. // The important bit is that we not have any user tasks left. START if (AbstractScheduledEventExecutor.WAKEUP_TASK != runnable) { END numTasks++; } } return numTasks; } nit: can just use `WAKEUP_TASK` here since `AbstractScheduledEventExecutor` is a superclass

Target:
final int drainTasks() { int numTasks = 0; for (;;) { Runnable runnable = taskQueue.poll(); if (runnable == null) { break; } // WAKEUP_TASK should be just discarded as these are added internally. // The important bit is that we not have any user tasks left. if (WAKEUP_TASK != runnable) { numTasks++; } } return numTasks; }
Source:
public ByteBufOutputStream(ByteBuf buffer) { ObjectUtil.checkNotNull(buffer, "buffer"); START this.buffer = buffer; END startIndex = buffer.writerIndex(); } nit: you can merge both lines above as `checkNotNull` will return the given argument

Target:
public ByteBufOutputStream(ByteBuf buffer) { this.buffer = ObjectUtil.checkNotNull(buffer, "buffer"); startIndex = buffer.writerIndex(); }
Source:
private EmptyByteBuf(ByteBufAllocator alloc, ByteOrder order) { ObjectUtil.checkNotNull(alloc, "alloc"); START this.alloc = alloc; END this.order = order; str = StringUtil.simpleClassName(this) + (order == ByteOrder.BIG_ENDIAN? "BE" : "LE"); } nit: you can merge both lines above as `checkNotNull` will return the given argument

Target:
private EmptyByteBuf(ByteBufAllocator alloc, ByteOrder order) { this.alloc = ObjectUtil.checkNotNull(alloc, "alloc"); this.order = order; str = StringUtil.simpleClassName(this) + (order == ByteOrder.BIG_ENDIAN? "BE" : "LE"); }
Source:
public SwappedByteBuf(ByteBuf buf) { ObjectUtil.checkNotNull(buf, "buf"); START this.buf = buf; END if (buf.order() == ByteOrder.BIG_ENDIAN) { order = ByteOrder.LITTLE_ENDIAN; } else { order = ByteOrder.BIG_ENDIAN; } } nit: you can merge both lines above as `checkNotNull` will return the given argument

Target:
public SwappedByteBuf(ByteBuf buf) { this.buf = ObjectUtil.checkNotNull(buf, "buf"); if (buf.order() == ByteOrder.BIG_ENDIAN) { order = ByteOrder.LITTLE_ENDIAN; } else { order = ByteOrder.BIG_ENDIAN; } }
Source:
public ByteBuf order(ByteOrder endianness) { ObjectUtil.checkNotNull(endianness, "endianness"); START if (endianness == order) { END return this; } return buf; } nit: you can merge both lines above as `checkNotNull` will return the given argument

Target:
public ByteBuf order(ByteOrder endianness) { if (ObjectUtil.checkNotNull(endianness, "endianness") == order) { return this; } return buf; }
Source:
protected AbstractCompositeByteBufTest(ByteOrder order) { ObjectUtil.checkNotNull(order, "order"); START this.order = order; END } nit: you can merge both lines above as `checkNotNull` will return the given argument

Target:
protected AbstractCompositeByteBufTest(ByteOrder order) { this.order = ObjectUtil.checkNotNull(order, "order"); }
Source:
public DefaultHttpContent(ByteBuf content) { ObjectUtil.checkNotNull(content, "content"); START this.content = content; END } nit: you can merge both lines above as `checkNotNull` will return the given argument

Target:
public DefaultHttpContent(ByteBuf content) { this.content = ObjectUtil.checkNotNull(content, "content"); }
Source:
public HttpMessage setProtocolVersion(HttpVersion version) { ObjectUtil.checkNotNull(version, "version"); START this.version = version; END return this; } nit: you can merge both lines above as `checkNotNull` will return the given argument

Target:
public HttpMessage setProtocolVersion(HttpVersion version) { this.version = ObjectUtil.checkNotNull(version, "version"); return this; }
Source:
public HttpResponse setStatus(HttpResponseStatus status) { ObjectUtil.checkNotNull(status, "status"); START this.status = status; END return this; } nit: you can merge both lines above as `checkNotNull` will return the given argument

Target:
public HttpResponse setStatus(HttpResponseStatus status) { this.status = ObjectUtil.checkNotNull(status, "status"); return this; }
Source:
public void setContentType(String contentType) { ObjectUtil.checkNotNull(contentType, "contentType"); START this.contentType = contentType; END } consider merging both lines

Target:
public void setContentType(String contentType) { this.contentType = ObjectUtil.checkNotNull(contentType, "contentType"); }
Source:
private CompositeByteBuf(ByteBufAllocator alloc, boolean direct, int maxNumComponents, int initSize) { super(AbstractByteBufAllocator.DEFAULT_MAX_CAPACITY); if (maxNumComponents < 1) { throw new IllegalArgumentException( "maxNumComponents: " + maxNumComponents + " (expected: >= 1)"); } START this.alloc = ObjectUtil.checkNotNull(alloc, "alloc"); END this.direct = direct; this.maxNumComponents = maxNumComponents; components = newCompArray(initSize, maxNumComponents); } @carryxyh lets move this check (and assignment) above the `maxNumComponents` check again (just like before).

Target:
private CompositeByteBuf(ByteBufAllocator alloc, boolean direct, int maxNumComponents, int initSize) { super(AbstractByteBufAllocator.DEFAULT_MAX_CAPACITY); this.alloc = ObjectUtil.checkNotNull(alloc, "alloc"); if (maxNumComponents < 1) { throw new IllegalArgumentException( "maxNumComponents: " + maxNumComponents + " (expected: >= 1)"); } this.direct = direct; this.maxNumComponents = maxNumComponents; components = newCompArray(initSize, maxNumComponents); }
Source:
public static void watch(Thread thread, Runnable task) { ObjectUtil.checkNotNull(thread, "thread"); if (!thread.isAlive()) { throw new IllegalArgumentException("thread must be alive."); } START schedule(thread, ObjectUtil.checkNotNull(task, "task"), true); END } move the mull check under the null check for thread to ensure we not change behaviour.

Target:
public static void watch(Thread thread, Runnable task) { ObjectUtil.checkNotNull(thread, "thread"); ObjectUtil.checkNotNull(task, "task"); if (!thread.isAlive()) { throw new IllegalArgumentException("thread must be alive."); } schedule(thread, task, true); }
Source:
public boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException { final Thread thread = this.thread; if (thread == null) { throw new IllegalStateException("thread was not started"); } START thread.join(ObjectUtil.checkNotNull(unit, "unit").toMillis(timeout)); END return !thread.isAlive(); } move null check back as first action in the method to not change behaviour

Target:
public boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException { ObjectUtil.checkNotNull(unit, "unit"); final Thread thread = this.thread; if (thread == null) { throw new IllegalStateException("thread was not started"); } thread.join(unit.toMillis(timeout)); return !thread.isAlive(); }
Source:
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { if (inEventLoop()) { throw new IllegalStateException("cannot await termination of the current thread"); } START threadLock.await(timeout, ObjectUtil.checkNotNull(unit, "unit")); END return isTerminated(); } move check back as first in the method to not change behaviour if null is passed as `unit` but we are in the `EventLoop` thread.

Target:
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { ObjectUtil.checkNotNull(unit, "unit"); if (inEventLoop()) { throw new IllegalStateException("cannot await termination of the current thread"); } threadLock.await(timeout, unit); return isTerminated(); }
Source:
public ChunkedFile(RandomAccessFile file, long offset, long length, int chunkSize) throws IOException { ObjectUtil.checkPositiveOrZero(offset, "offset"); ObjectUtil.checkPositiveOrZero(length, "length"); START this.file = ObjectUtil.checkNotNull(file, "file"); END this.chunkSize = ObjectUtil.checkPositive(chunkSize, "chunkSize"); this.offset = startOffset = offset; endOffset = offset + length; file.seek(offset); } move this assignment and check as first in the method to not change behaviour.

Target:
public ChunkedFile(RandomAccessFile file, long offset, long length, int chunkSize) throws IOException { ObjectUtil.checkNotNull(file, "file"); ObjectUtil.checkPositiveOrZero(offset, "offset"); ObjectUtil.checkPositiveOrZero(length, "length"); ObjectUtil.checkPositive(chunkSize, "chunkSize"); this.file = file; this.offset = startOffset = offset; this.endOffset = offset + length; this.chunkSize = chunkSize; file.seek(offset); }
Source:
public boolean clear(String hostname) { return resolveCache.clear( appendDot( START checkNotNull(hostname, "hostname"))); END } nit: maybe merge the lines as the formatting looks a bit strange.

Target:
public boolean clear(String hostname) { checkNotNull(hostname, "hostname"); return resolveCache.clear(appendDot(hostname)); }
Source:
public DefaultAddressedEnvelope(M message, A recipient, A sender) { if (recipient == null && sender == null) { throw new NullPointerException("recipient and sender"); } START this.message = ObjectUtil.checkNotNull(message, "message"); END this.sender = sender; this.recipient = recipient; } move this assignment and check as first in the method to not change behaviour

Target:
public DefaultAddressedEnvelope(M message, A recipient, A sender) { ObjectUtil.checkNotNull(message, "message"); if (recipient == null && sender == null) { throw new NullPointerException("recipient and sender"); } this.message = message; this.sender = sender; this.recipient = recipient; }
Source:
public SslContextBuilder trustManager(TrustManager trustManager) { trustCertCollection = null; try { this.trustManagerFactory = new TrustManagerFactoryWrapper(trustManager); } catch (Exception e) { START throw new Error(e.toString()); END } return this; } can we just throw an `IllegalStateException` here and wrap the original `Exception` ?

Target:
public SslContextBuilder trustManager(TrustManager trustManager) { this.trustManagerFactory = new TrustManagerFactoryWrapper(trustManager); trustCertCollection = null; return this; }
Source:
protected KeyManager[] engineGetKeyManagers() { START ObjectUtil.checkNotNull(km, "KeyManagerFactoryWrapper is created with null KeyManager value"); END return new KeyManager[] {km}; } remove this and do the check in the constructor to fail fast

Target:
protected KeyManager[] engineGetKeyManagers() { return new KeyManager[] {km}; }
Source:
KeyManagerFactoryWrapper(KeyManager km) { ObjectUtil.checkNotNull(km, "km"); START this.km = km; END } nit: you can merge both of the above line as `checkNotNull(...)` returns `km`.

Target:
KeyManagerFactoryWrapper(KeyManager km) { this.km = ObjectUtil.checkNotNull(km, "km"); }
Source:
TrustManagerFactoryWrapper(TrustManager tm) throws Exception { ObjectUtil.checkNotNull(tm, "tm"); START this.tm = tm; END } nit: you can merge both of the above line as `checkNotNull(...)` returns `tm`.

Target:
TrustManagerFactoryWrapper(TrustManager tm) { this.tm = ObjectUtil.checkNotNull(tm, "tm"); }
Source:
START WeakOrderQueue newWeakOrderQueue(Thread thread) { END return WeakOrderQueue.newQueue(this, thread); } private?

Target:
private WeakOrderQueue newWeakOrderQueue(Thread thread) { return WeakOrderQueue.newQueue(this, thread); }
Source:
void relink(Link link) { START if (this.link != link) { END reclaimSpace(LINK_CAPACITY); } this.link = link; } I don't think this check was there before, was it intentional? If so then the `this.link = link;` below could be moved inside the if block?

Target:
void relink(Link link) { reclaimSpace(LINK_CAPACITY); this.link = link; }
Source:
public StringEncoder(Charset charset) { if (charset == null) { throw new NullPointerException("charset"); } START this.encoder = CharsetUtil.encoder(charset); END } @johnou @carl-mastrangelo is right... it is `@Sharable` so this will not work.

Target:
public StringEncoder(Charset charset) { if (charset == null) { throw new NullPointerException("charset"); } this.charset = charset; }
Source:
public Attribute createAttribute(HttpRequest request, String name) { START Attribute attribute; END if (useDisk) { attribute = new DiskAttribute(name, charset); } else if (checkSize) { attribute = new MixedAttribute(name, minSize, charset); } else { attribute = new MemoryAttribute(name); } attribute.setMaxSize(maxSize); List<HttpData> list = getList(request); list.add(attribute); return attribute; } nit: make this final

Target:
public Attribute createAttribute(HttpRequest request, String name) { final Attribute attribute; if (useDisk) { attribute = new DiskAttribute(name, charset); } else if (checkSize) { attribute = new MixedAttribute(name, minSize, charset); } else { attribute = new MemoryAttribute(name); } attribute.setMaxSize(maxSize); List<HttpData> list = getList(request); list.add(attribute); return attribute; }