auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void setBounds(int x, int y, int width, int height) { Dimension previousSize = getSize(); super.setBounds(x, y, width, height); // Update the size of the layout renderer. This is done here instead of a component listener because // this runs before the paintComponent saving an extra paint cycle. Dimension currentSize = getSize(); synchronized (myGraphicsLayoutRendererLock) { if (myGraphicsLayoutRenderer != null && !currentSize.equals(previousSize)) { // Because we use GraphicsLayoutRender in vertical scroll mode, the height passed it's only a minimum. If the actual rendering results // in a bigger size, the GraphicsLayoutRenderer.getPreferredSize() call will return the correct size. myGraphicsLayoutRenderer.setSize(width, (myCurrentWidth < width) ? 1 : height); myCurrentWidth = width; } } }

Target:
cant we just always pass 1, or -1, so it calculates the right size?
Source:
ArrayList<FieldValue> getFields(String name) { ArrayList<FieldValue> result = new ArrayList<FieldValue>(); for (FieldValue value : getValues()) { if (value.getField().getName().equals(name)) { result.add(value); } } return result; }

Target:
List
Source:
public JComponent getPreferredFocusedComponent() { String name = myNameField.getText(); if (name.length() == 0 || name.equals(ResourceHelper.prependResourcePrefix(myModule, null))) { return myNameField; } else if (myValueField.isVisible()) { return myValueField; } else if (myModuleCombo.isVisible()) { return myModuleCombo; } else { return myFileNameCombo; } }

Target:
name.isEmpty
Source:
public void enableDefault() { if (getDefaultApi() == null) { return; } List<? extends CloudTestingType> appSupportedDomain = getAppSupportedDomain(); if (appSupportedDomain.contains(defaultApi)) { enable(defaultApi); } else if (appSupportedDomain.size() > 0) { enable(appSupportedDomain.get(0)); } }

Target:
!isEmpty and throughout the CL
Source:
private static void show(JComponent... components) { for (JComponent component : components) { component.setVisible(true); component.getParent().invalidate(); component.getParent().getParent().invalidate(); } }

Target:
Just curious, do we still have to invalidate our direct parent if we invalidate our grandparent?
Source:
public List<String> getApplicableMethodNames() { List<String> values = new ArrayList<String>(2); // Detect calls to potentially insecure SSLCertificateSocketFactory methods values.add("createSocket"); //$NON-NLS-1$ values.add("getInsecure"); //$NON-NLS-1$ return values; }

Target:
Nit - just return Arrays.asList("createSockets", "getInsecure") instead?
Source:
public final void engineInit(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException { if (!(spec instanceof ApplicationConfigParameters)) { throw new InvalidAlgorithmParameterException("Unsupported spec: " + spec + ". Only " + ApplicationConfigParameters.class.getName() + " supported"); } mApplicationConfig = ((ApplicationConfigParameters) spec).config; }

Target:
What's the reason for marking all methods final? If you don't want this whole class to be subclassed, just mark the whole class final instead.
Source:
public JMultiCastOperation(@Nonnull SourceInfo info, @Nonnull JExpression expr, @Nonnull JType... castTypes) { super(info, expr); this.castTypes = Arrays.asList(castTypes); assert this.castTypes.size() >= 1; }

Target:
- nit !isEmpty()
Source:
public Collection<JType> getTypes() { return castTypes; }

Target:
Idem
Source:
public int getTop(final ViewGroup ancestor, View view){ if (view==ancestor){ return 0; } else { int top = view.getTop(); if (ViewGroup.class.isAssignableFrom(view.getParent().getClass())){ top += getTop(ancestor, (ViewGroup) view.getParent()); } else { Log.i("DataInteraction","giving up calculating the top"); } return top; } }

Target:
spaces
Source:
public void test_SerializationBug_26387905() throws Exception { Locale l = Locale.US; ObjectInputStream oinput = null; try { oinput = new ObjectInputStream(getClass().getResource("/serialization/org/apache/harmony/tests/java/util/Locale_Bug_26387905.ser") .openStream()); l = (Locale) oinput.readObject(); } finally { try { if (null != oinput) { oinput.close(); } } catch (Exception e) { // ignore } } }

Target:
please use try with resources. try (ObjectInputStream oinput = ...) { }
Source:
protected void onFinishInflate() { mLockPatternUtils = new LockPatternUtils(mContext); mSecurityMessageDisplay = (KeyguardMessageArea) KeyguardMessageArea.findSecurityMessageDisplay(this); mEcaView = findViewById(R.id.keyguard_selector_fade_container); EmergencyButton button = (EmergencyButton) findViewById(R.id.emergency_call_button); if (button != null) { button.setCallback(this); } }

Target:
Instead of breaking the abstraction here, introduce isEmpty on SecurityMessageDisplay.
Source:
public void snapChildInstantly(final View view) { final View targetView = mCallback.getChildContentView(view); final boolean canAnimViewBeDismissed = mCallback.canChildBeDismissed(targetView); setTranslation(targetView, 0); updateSwipeProgressFromOffset(targetView, canAnimViewBeDismissed); }

Target:
private
Source:
public void testRemoveIfUnsupportedOperation() { Collection<Integer> c = Arrays.asList(1, 2, 3, 4); try { c.removeIf(truth); fail(); } catch (UnsupportedOperationException expected) { } try { c.removeIf(falsity); } catch (Exception e) { fail(); } }

Target:
unnecessary try { catch } . have your test "throw Exception" and just write this as c.removeIf. The advantage of doing that is the test runner will give you a full stack of what happened.
Source:
public void testLongFloorDivMod() { testFloorDivModL(123L, 456L); testFloorDivModL(456L, 123L); testFloorDivModL(369L, 123L); testFloorDivModL(1L, 0L); testFloorDivModL(Long.MAX_VALUE, 1L); testFloorDivModL(Long.MAX_VALUE, -1L); testFloorDivModL(Long.MIN_VALUE, -1L); testFloorDivModL(Long.MIN_VALUE, -1L); }

Target:
1L
Source:
protected void fillRtTestInfos() { rtTestInfos.add(TEST001); }

Target:
Remove.
Source:
private void writeToFile(String fileName, byte[] bytes) { try (FileOutputStream fos = getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE)) { fos.write(bytes); } catch (IOException e) { throw new RuntimeException("Couldn't write to " + fileName, e); } }

Target:
remove this... openFileInput(fileName) should be sufficient and using an Application context is often an anti-pattern
Source:
public void dispose() { mDestroyed.set(true); // It is possible that there is another thread waiting for the response // to requestIccSimAuthentication() in getIccSimChallengeResponse(). // A pseudo error response is made here to avoid the deadlock. auth_rsp = new IccIoResult(0x6F, 0, (byte[]) null); synchronized (mLock) { mLock.notifyAll(); } mParentApp = null; mFh = null; mCi = null; mContext = null; }

Target:
Change this to null instead and add auth_rsp != null check in getIccSimChallengeResponse(). That function can return null if auth_rsp is null.
Source:
private void markLoaded(@Nonnull Scope range, @Nonnull JDefinedClassOrInterface loaded) { loadStatus |= range.getMask(); if (loadStatus == Scope.ALL) { // Open a synchronize block just to prevent reordering synchronized (this) { loaded.removeLoader(); } } }

Target:
Are you sure this will prevent reordering, markLoaded is always called when the lock is already taken. I also believe that if it does prevent it, doing nothing on reader side will still be a problem since it is not synchronized in any way.
Source:
public void testSMSSendingExploit() throws Exception { int inboxSizeBeforeExploit = getSMSInboxSize(); TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE); if(!telephonyManager.isSmsCapable()) { return; } SmsManager manager = SmsManager.getDefault(); manager.sendTextMessage("25578", null, "STOP", null, null); SystemClock.sleep(250); int inboxSizeAfterExploit = getSMSInboxSize(); assertTrue("Device is vulnerable to bug #22314646!! For more information " + "please refer - https://android.googlesource.com/platform/frameworks/" + "opt/telephony/+/ce058be%5E!/", inboxSizeBeforeExploit == inboxSizeAfterExploit); }

Target:
Can you move this line after check logic below? Calling getSMSInboxSize() caused an exception if there is no telephony.
Source:
public int hashCode() { return name.hashCode() ^ parameterTypes.hashCode(); }

Target:
final, here and elsewhere
Source:
private void setUsbConfig(String config) { if (DEBUG) Slog.d(TAG, "setUsbConfig(" + config + ")"); // set the new configuration // we always set it due to b/23631400, where adbd was getting killed // and not restarted due to property timeouts on some devices SystemProperties.set(USB_CONFIG_PROPERTY, config); return; }

Target:
Please remove the return statement.
Source:
public void enter() { super.enter(); if (!mBluetoothRouteManager.isInbandRingingEnabled()) { setSpeakerphoneOn(false); } CallAudioState newState = new CallAudioState(mIsMuted, ROUTE_BLUETOOTH, mAvailableRoutes); setSystemAudioState(newState); updateInternalCallAudioState(); }

Target:
I think it was there as a copy-paste error. It should probably be removed.
Source:
private String getMethodNameAndParameters(String methodSignature) { Pattern pattern = Pattern.compile("[\\w\\$]+\\([^)]*\\)"); Matcher methodPatternMatcher = pattern.matcher(methodSignature); if (methodPatternMatcher.find()) { return methodPatternMatcher.group(); } else { throw new IllegalArgumentException(); } }

Target:
static
Source:
public void endVisit(UnaryExpression x, BlockScope b) { int operator = ((x.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT); // We don't take the constant result from ECJ if it involves a unary + and a non-literal. if (operator == OperatorIds.PLUS && !(x.expression instanceof Literal)) { foundUnaryPos = true; // We have an (+ (expression)) Constant outer = x.constant; Constant inner = x.expression.constant; // Since the + operator is no-op, the inner and the outer constant should be exactly the // same. If not, the current version of ECJ has the mentioned bug. boolean hasEcjUnaryPosBug = !outer.equals(inner); // We are going to assume there is a bug in ECJ and work around it. If this fails, // we know that the bug has been fixed. assert hasEcjUnaryPosBug; } }

Target:
I guess that we can rename foundUnaryPos to hasEcjUnaryPosBug and write something like: hasEcjUnaryPosBug |= !outer.equals(inner); Unless the check is not really accurate?
Source:
public void setUp() throws Exception { super.setUp(); fakeFtpServer = new FakeFtpServer(); fakeFtpServer.setServerControlPort(0 /* allocate port number automatically */); fakeFtpServer.addUserAccount(new UserAccount(USER, PASSWORD, USER_HOME_DIR)); fileSystem = new UnixFakeFileSystem(); fakeFtpServer.setFileSystem(fileSystem); fileSystem.add(new DirectoryEntry(USER_HOME_DIR)); fakeFtpServer.start(); fileContents = "abcdef 1234567890".getBytes(UTF_8); }

Target:
This can be a static constant called "ARBITRARY_BYTES" or something if you think it's valuable to have it pulled out (I think I'd just inline it, personally).
Source:
public static void skipContent(@Nonnull JayceInternalReaderImpl in) throws IOException { throw new UnsupportedOperationException(); }

Target:
Remove ?
Source:
public static void skipContent(@Nonnull JayceInternalReaderImpl in) throws IOException { }

Target:
Remove ?
Source:
public void iccOpenLogicalChannel(String AID, byte p2, Message response) { RILRequest rr = RILRequest.obtain(RIL_REQUEST_SIM_OPEN_CHANNEL, response); rr.mParcel.writeByte(p2); rr.mParcel.writeString(AID); if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest)); send(rr); }

Target:
don't we normally pass args in arg order (ie do this after writing AID)?
Source:
public final boolean hasSourceInfo() throws InvalidTokenException { if (!hasSourceInfoBeenRequested) { Class<? extends NNode> nodeClass = getNNodeClass(); hasSourceInfo = HasSourceInfo.class.isAssignableFrom(nodeClass); hasSourceInfoBeenRequested = true; } return hasSourceInfo; }

Target:
Definitively, JayceFormatException is not the right thing here. But, not related to this CL. I have a question. Is NUMBER_VALUE has a SourceInfo? If no, I think it is a good thing that the method return false, right?
Source:
int wifiFeatureMaskFromStaCapabilities(int capabilities) { int features = WifiManager.WIFI_FEATURE_INFRA; // Always set this if we have a STA interface for (int i = 0; i < sFeatureCapabilityTranslation.length; i++) { if ((capabilities & sFeatureCapabilityTranslation[i][1]) != 0) { features |= sFeatureCapabilityTranslation[i][0]; } } return features; }

Target:
Remove this and use the STA iface type below to set this.
Source:
public void setLineWidth(float width) { if (width < 0) { throw new AssertionError(); } mLineWidth = width; }

Target:
why does this not use Utils.assertTrue ?
Source:
public void test2GhzQualifiedNo5GhzAvailable() { // Do not perform selection on 2GHz if current network is good and no 5GHz available testStayOrSwitch(mThresholdQualifiedRssi2G + 1, false, mThresholdQualifiedRssi2G + 10, false, false); }

Target:
Delete this, take one step closer to the edge.
Source:
public void test2GhzNotQualifiedOther2GhzAvailable() { // Run Selection on 2Ghz networks when not qualified even if no 5GHz available testStayOrSwitch(mThresholdQualifiedRssi2G - 1, false, mThresholdQualifiedRssi2G + 1, false, true); }

Target:
delete
Source:
public void tearDown() throws Exception { super.tearDown(); mIccRecords.dispose(); }

Target:
Why is this removed?
Source:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (!Utils.isMonkeyRunning()) { updatePreferences(); } }

Target:
It is not fixing the root cause. Please change the updatePreferences() call to check null on each field before accessing.
Source:
private static void processFailLoadAndGc() throws TestFailed { try { BrokenDexLoader loader; loader = new BrokenDexLoader(ClassLoader.getSystemClassLoader()); loader.findBrokenClass(); System.out.println("ERROR: Inaccessible was accessible"); } catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof NullPointerException) { System.out.println("Got expected ITE/NPE"); } else { System.out.println("Got unexpected ITE"); ite.printStackTrace(); } } }

Target:
This is still printing to System.err but that's mostly OK as the test is already failing in this code path anyway.
Source:
private int priority(int eventId) { switch (eventId) { case MetricsEvent.NOTIFICATION_NETWORK_SIGN_IN: return 4; case MetricsEvent.NOTIFICATION_NETWORK_NO_INTERNET: return 3; case MetricsEvent.NOTIFICATION_NETWORK_SWITCH: return 2; case MetricsEvent.NOTIFICATION_NETWORK_LOST_INTERNET: return 1; default: return 0; } }

Target:
static probably works here
Source:
public final boolean isProfileOwnerAction(String action) { return (action != null) ? action.equals(ACTION_PROVISION_MANAGED_PROFILE) || action.equals(ACTION_PROVISION_MANAGED_USER) : false; }

Target:
Instead of checking for action!= null, i'd suggest to simply change the order of equals, e.g. return ACTION_PROVISION_MANAGED_PROFILE.equals(action) || ACTION_PROVISION_MANAGED_USER.equals(action);
Source:
protected Mutation generateMutation(MutatableCode mutatableCode) { generateCachedNewInstanceInsns(mutatableCode); int newInstanceIdx = rng.nextInt(newInstanceCachedInsns.size() - 1); int newInstanceTypeIdx = rng.nextInt(mutatableCode.program.getTotalPoolIndicesByKind(PoolIndexKind.Type)); AssociatedMutation mutation = new AssociatedMutation(); mutation.setup(this.getClass(), mutatableCode); mutation.newInstanceToChangeIdx = newInstanceIdx; mutation.newInstanceTypeIdx = newInstanceTypeIdx; return mutation; }

Target:
why -1? the nextInt is 0..N with N exclusive
Source:
protected boolean canMutate(MutatableCode mutatableCode) { for (MInsn mInsn : mutatableCode.getInstructions()) { return (mInsn.insn.info.opcode == Opcode.NEW_INSTANCE); } Log.debug("No New Instance in method, skipping..."); return false; }

Target:
uh, this is not right? can you spot the error?
Source:
public IpSecTransform.Builder setEncryption( @TransformDirection int direction, IpSecAlgorithm algo) { if (mConfig.getAuthenticatedEncryption(direction) != null) { throw new IllegalArgumentException( "Encryption is unsupported while " + "Authenticated Encryption algorithm is specified"); } mConfig.setEncryption(direction, algo); return this; }

Target:
Looks like these checks duplicate the ones in IpSecConfig. Can we remove either these or those? Since IpSecConfig is not public, we probably don't need the check there.
Source:
public void testCreateInvalidConfigAeadWithAuth() throws Exception { IpSecConfig ipSecConfig = new IpSecConfig(); addDefaultSpisAndRemoteAddrToIpSecConfig(ipSecConfig); for (int direction : DIRECTIONS) { ipSecConfig.setAuthentication(direction, AUTH_ALGO); try { ipSecConfig.setAuthenticatedEncryption(direction, AEAD_ALGO); } catch (IllegalArgumentException expected) { /* Expected exception; do nothing */ } } try { mIpSecService.createTransportModeTransform(ipSecConfig, new Binder()); fail( "IpSecService should have thrown an error on authentication being" + " enabled with authenticated encryption"); } catch (IllegalArgumentException expected) { /* Expected exception; do nothing */ } }

Target:
If an exception is expected, should we fail if the exception is not thrown?
Source:
public void test_pipe2_errno() throws Exception { try { // flag=1 is not a valiud value for pip2, will EINVAL Libcore.os.pipe2(1); fail(); } catch(ErrnoException expected) }

Target:
needs a newline before the }, see section 4.1.3 of the style guide. (The one-line style makes it harder to see where blocks begin/end, so it is not allowed).
Source:
private void updateRemoteVideoSurfaceDimensions() { if (mVideoCallScreen == null) { LogUtil.e("VideoCallPresenter.updateRemoteVideoSurfaceDimensions", "mVideoCallScreen is null"); return; } Activity activity = mVideoCallScreen.getVideoCallScreenFragment().getActivity(); if (activity != null) { Point screenSize = new Point(); activity.getWindowManager().getDefaultDisplay().getSize(screenSize); getRemoteVideoSurfaceTexture().setSurfaceDimensions(screenSize); } }

Target:
Remove this check? It will throw NullPointerException if it's null, which should never happen.
Source:
public void testOpenUdpEncapsulationSocketCallsSetSocketOwner() throws Exception { int localport = findUnusedPort(); IpSecUdpEncapResponse udpEncapResp = mIpSecService.openUdpEncapsulationSocket(localport, new Binder()); verify(mMockNetd).ipSecSetSocketOwner(anyObject(), eq(Os.getuid())); mIpSecService.closeUdpEncapsulationSocket(udpEncapResp.resourceId); }

Target:
Optional: since it is irrelevant to this test, you can omit findUnusedPort() and just use 0.
Source:
public Entity toEntity() { Entity branchEntity = new Entity(this.key); return branchEntity; }

Target:
return ?
Source:
private static int readInt(File f) throws FileNotFoundException { Scanner s = new Scanner(f); try { return s.nextInt(); } finally { s.close(); } }

Target:
I think you can write this as: try (Scanner s = new Scanner(f)) { return s.nextInt(); } (and similar for FileOutputStream below)
Source:
private void onUserStart(int userId) { synchronized (mVpns) { Vpn userVpn = mVpns.get(userId); if (userVpn != null) { loge("Starting user already has a VPN"); return; } userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId); mVpns.put(userId, userVpn); } if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) { updateLockdownVpn(); } }

Target:
Here too it looks like whether the tracker is enabled or not might change between the check and the call. Also LockdownVpnTracker.isEnabled() here might be replaced with mLockdownEnabled I thik
Source:
synchronized boolean sendReport(BluetoothDevice device, int id, byte[] data) { if (DBG) { Log.d(TAG, "sendReport(): device=" + device + " id=" + id + " caller=" + Binder.getCallingUid()); } return checkDevice(device) && checkCallingUid() && mHidDeviceNativeInterface.sendReport(id, data); }

Target:
In the common case, this will not be useful information. What about logging the CallingUid in checkCallingUid() if it doesn't match mCallingUid? Are there any cases where we wouldn't want to know if the wrong Uid is being used?
Source:
public static InterfaceParams getByName(String name) { final NetworkInterface netif = getNetworkInterfaceByName(name); if (netif == null) return null; // Not all interfaces have MAC addresses, e.g. rmnet_data0. final MacAddress macAddr = getMacAddress(netif); try { return new InterfaceParams(name, netif.getIndex(), macAddr, netif.getMTU()); } catch (IllegalArgumentException|NullPointerException|SocketException e) { return null; } }

Target:
Out of curiosity, where can this NPE come from? netif is known not to be null at this point.
Source:
private boolean isRunningInVR() { final Context context = InstrumentationRegistry.getTargetContext(); if ((context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_VR_HEADSET) { return true; } return false; }

Target:
nit: return (context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_VR_HEADSET
Source:
public void onRegistered(int imsRadioTech) { if (DBG) { log("onRegistered ::"); } synchronized (mRegistrationListeners) { mRegistrationListeners.forEach(l -> l.onRegistered(imsRadioTech)); } }

Target:
this can just go on one line.
Source:
private boolean supportsConditionProviders() { ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); return !am.isLowRamDevice() || mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH); }

Target:
this line shouldn't be there on this branch (sorry, forgot to mention)
Source:
private boolean satisfiedByNetCapabilities(NetworkCapabilities nc, boolean onlyImmutable) { long requestedCapabilities = mNetworkCapabilities; long requestedUnwantedCapabilities = mUnwantedNetworkCapabilities; long providedCapabilities = nc.mNetworkCapabilities; if (onlyImmutable) { requestedCapabilities &= ~MUTABLE_CAPABILITIES; requestedUnwantedCapabilities &= ~MUTABLE_CAPABILITIES; providedCapabilities &= ~MUTABLE_CAPABILITIES; } return ((providedCapabilities & requestedCapabilities) == requestedCapabilities) && ((requestedUnwantedCapabilities & providedCapabilities) == 0); }

Target:
I don't think this line does anything. Rationale: you only use providedCapabilities by ANDing it to requestedCapabilities and requestedUnwantedCapabilities. These both have MUTABLE_CAPABILITIES masked out. So the result of the ANDs will be guaranteed to have MUTABLE_CAPABILITIES masked out even if this line is not present. Remove?
Source:
public void setCapabilities(@NetCapability int[] capabilities) { mNetworkCapabilities = BitUtils.packBits(capabilities); // Remove given capabilities from unwanted list mUnwantedNetworkCapabilities &= ~(mNetworkCapabilities & mUnwantedNetworkCapabilities); }

Target:
Why the double & ? Don't you just want mUnwantedNetworkCapabilities &= ~mNetworkCapabilities ? I mean, A & ~(B & A) = A & (~B | ~A) = (A & ~B) | (A & ~A) = A & ~B ...or am I missing something ?
Source:
public void onProfileServiceStateChanged(ProfileService profile, int state) { if (state != BluetoothAdapter.STATE_ON && state != BluetoothAdapter.STATE_OFF) { Log.e(TAG, "onProfileServiceStateChanged: Unhandled " + BluetoothAdapter.nameForState( state)); return; } Message m = mHandler.obtainMessage(MESSAGE_PROFILE_SERVICE_STATE_CHANGED); m.obj = profile; m.arg1 = state; mHandler.sendMessage(m); }

Target:
I think we should crash here by throwing IllegalArgumentException.
Source:
void stopProfileServices() { Class[] supportedProfileServices = Config.getSupportedProfiles(); if (mRunningProfiles.size() > 0) { setAllProfileServiceStates(supportedProfileServices, BluetoothAdapter.STATE_OFF); } debugLog("stopProfileServices() - No profiles services to stop or already stopped."); }

Target:
The meaning of this log message changes after removing the return statements.
Source:
private void handleScreenTurnedOn() { final int count = mCallbacks.size(); for (int i = 0; i < count; i++) { KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); if (cb != null) { cb.onScreenTurnedOn(); } } updateIrisListeningState(); }

Target:
Why is this necessary? This should probably use the generic updateBiometicListeningState(). I think you're doing this to turn on the iris scanner? If so, you should leave it authenticating state, like we do for fingerprint, and send another signal to go into high power mode to complete authentication. This is what we do in fingerprint.
Source:
private void handleScreenTurnedOff() { mHardwareFingerprintUnavailableRetryCount = 0; mHardwareIrisUnavailableRetryCount = 0; final int count = mCallbacks.size(); for (int i = 0; i < count; i++) { KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get(); if (cb != null) { cb.onScreenTurnedOff(); } } updateBiometricsListeningState(); }

Target:
Same question.
Source:
private int parseIdFromInsertedUri(Uri uri) throws NumberFormatException { int id = -1; if (uri != null) { id = Integer.parseInt(uri.getLastPathSegment()); } return id; }

Target:
Can be reduced to a single line: return (uri != null ? Integer.parseInt(uri.getLastPathSegment()) : -1)
Source:
public void removeAddress(LinkAddress address) throws IOException { try { mService.removeAddressFromTunnelInterface(mResourceId, address); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } }

Target:
Actually it would probably be better to throw something IOException than to throw a runtime exception. General guidance is a checked exception is for failures outside the programmer's control, and unchecked exceptions for programming errors. Doesn't need to be in this CL.
Source:
public void ipSecConnectSocket(Integer socketFd, String addr, Integer port) { FileDescriptor fd = new FileDescriptor(); fd.setInt$(socketFd.intValue()); try { InetAddress remoteAddr = NetworkUtils.numericToInetAddress(addr); Os.connect(fd, remoteAddr, port.intValue()); } catch (SocketException | ErrnoException e) { Log.e("IpSec: Failed to connect socket " + e.toString()); } }

Target:
this needs to at least return boolean success/failure
Source:
private void startListenForPhoneState() { if (!mListening) { int subId = SubscriptionManager.getDefaultSubscriptionId(); if (SubscriptionManager.isValidSubscriptionId(subId)) { mPhoneStateListener = new HeadsetPhoneStateListener(subId, mHeadsetService.getStateMachinesThreadLooper()); mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_SERVICE_STATE | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS); mTelephonyManager.setRadioIndicationUpdateMode( TelephonyManager.INDICATION_FILTER_FULL_NETWORK_STATE | TelephonyManager.INDICATION_FILTER_SIGNAL_STRENGTH, TelephonyManager.INDICATION_UPDATE_MODE_IGNORE_SCREEN_OFF); mListening = true; } else { Log.w(TAG, "startListenForPhoneState, invalid subscription ID " + subId); } } }

Target:
I think you probably don't need this. This is just for turning off insignificant network updates (e.g. cell tower info) when the screen is off.
Source:
protected void setUserUnlocked(int userId) { Log.i(TAG, "User unlocked, initializing the service"); if (!SystemProperties.getBoolean(AVRCP_ENABLE_PROPERTY, false)) { Log.w(TAG, "Skipping initialization of the new AVRCP Target Player List"); sInstance = null; return; } mMediaPlayerList.init(new ListCallback()); }

Target:
This can happen on a conditional basis to avoid crash.
Source:
private File getApnConfFile() { // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system". File confFile = new File(Environment.getRootDirectory(), PARTNER_APNS_PATH); File oemConfFile = new File(Environment.getOemDirectory(), OEM_APNS_PATH); File vendorConfFile = new File(Environment.getVendorDirectory(), PARTNER_APNS_PATH); File updatedConfFile = new File(Environment.getDataDirectory(), OTA_UPDATED_APNS_PATH); confFile = pickSecondIfExists(confFile, vendorConfFile); confFile = pickSecondIfExists(confFile, oemConfFile); confFile = pickSecondIfExists(confFile, updatedConfFile); return confFile; }

Target:
you re-added this? maybe it should be a separate CL?
Source:
private void checkSerialVersionUID(long expectedSUID, Class<?> clazz) { assertEquals(expectedSUID, ObjectStreamClass.lookup(clazz).getSerialVersionUID()); }

Target:
static, and move to the bottom because it's an obviously named helper method.
Source:
public boolean isBootCompleted() throws DeviceNotAvailableException { return getProp(SYSPROP_SYS_BOOT_COMPLETED) == "1" && getProp(SYSPROP_DEV_BOOTCOMPLETE) == "1"; }

Target:
use .equals()
Source:
public boolean isTimeDetectionEnabled() { try { return Settings.Global.getInt(mContentResolver, Settings.Global.AUTO_TIME) > 0; } catch (Settings.SettingNotFoundException snfe) { return true; } }

Target:
Technically these booleans are defined as != 0.
Source:
private void startInvocation(IConfiguration config, IInvocationContext context, ITestInvocationListener listener) { if (mInvocationStarted) { return; } logStartInvocation(context, config); listener.invocationStarted(context); mInvocationStarted = true; }

Target:
Is this to avoid the method being called more than once? If it is not an expected behavior, shouldn't we raise an exception?
Source:
public Collection<IRemoteTest> split(int shardCountHint) { if (shardCountHint <= 1 || mIsSharded) { return null; } Collection<IRemoteTest> tests = new ArrayList<>(); for (int i = 0; i < shardCountHint; i++) { tests.add(getTestShard(shardCountHint, i)); } return tests; }

Target:
Add a log message here.
Source:
public Collection<IRemoteTest> split(int shardCountHint) { if (shardCountHint <= 1 || mIsSharded) { return null; } Collection<IRemoteTest> tests = new ArrayList<>(); for (int i = 0; i < shardCountHint; i++) { tests.add(getTestShard(shardCountHint, i)); } mIsSharded = true; return tests; }

Target:
Why do you need this var? Isn't this method idempotent? In general, it is better to avoid making object stateful.
Source:
public int computeCellInfoMinInterval() { // The screen is on and we're either on cellular or charging. Screen on + Charging is // a likely vehicular scenario, even if there is a nomadic AP. if (mIsScreenOn && (!mIsWifiConnected || mIsCharging)) { // TODO: should this be an automatic value or a fixed periodic value return CELL_INFO_INTERVAL_SHORT_MS; } // if the screen is off, or the screen is on and connected to wifi and not charging return CELL_INFO_INTERVAL_LONG_MS; }

Target:
Could you maybe split this into two in blocks? if (mIsScreenOn && !mIsWifiConnected) { // Screen on + no wifi means the device is on the go return CELL_INFO_INTERVAL_SHORT_MS; } else if (mIsScreenOn && mIsCharging) { // Screen on + charging means the device is probably in a car or at home return CELL_INFO_INTERVAL_SHORT_MS; } else { return CELL_INFO_INTERVAL_LONG_MS; }
Source:
public boolean showMuteOverlayOnVideoCall() { if (carrierConfig == null) { return false; } return carrierConfig.getBoolean(CarrierConfigManager.KEY_VIDEO_CALL_MUTE_OVERLAY_VISIBLE_BOOL); }

Target:
The carrierConfig sets showMuteOverlay to true by default: https://android-review.googlesource.com/c/platform/frameworks/base/+/731570/2/telephony/java/android/telephony/CarrierConfigManager.java I'm not sure whether this should be true/false. Any suggestions/thoughts on this?
Source:
private void updateMutePreviewOverlayVisibility() { boolean showMuteOverlay = getMuteOverlayConfig(); // Normally the mute overlay shows on the bottom right of the preview bubble. In green screen // mode the preview is fullscreen so there's no where to anchor it. // However, it should be hidden if carrier config of mute overlay is disabled. mutePreviewOverlay.setVisibility( showMuteOverlay && muteButton.isChecked() && !isInGreenScreenMode ? View.VISIBLE : View.GONE); }

Target:
Any reasons for creating a local parameter instead of using the method directly when setVisibility?
Source:
public boolean showMuteOverlayOnVideoCall() { if (carrierConfig == null) { return true; } return carrierConfig.getBoolean(CarrierConfigManager.KEY_VIDEO_CALL_MUTE_OVERLAY_VISIBLE_BOOL); }

Target:
This defaults to false. Since the key is new it will be missing on older platforms. Use getBoolean(String, boolean) instead.
Source:
protected DynamicRouteDescriptor() { }

Target:
package private? @SuppressWarnings("WeakerAccess") /* synthetic access */
Source:
public void onPause() { super.onPause(); SubscriptionManager.from(getActivity()).removeOnSubscriptionsChangedListener( mOnSubscriptionsChangeListener); }

Target:
Call this at the end of the method
Source:
private String getApplicationLabel(ComponentName componentName) { final PackageManager pm = getPackageManager(); ApplicationInfo info = null; try { info = pm.getApplicationInfo(componentName.getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, "Application info not found for packageName " + componentName .getPackageName()); } if (info == null) { return componentName.getPackageName(); } else { return info.loadLabel(pm).toString(); } }

Target:
Should be able to just do: ApplicationInfo info = pm.getApplicationInfo(packageName, 0); return pm.getApplicationLabel(info);
Source:
public boolean isDefaultCallScreeningApp(ComponentName componentName) { try { if (isServiceConnected()) { getTelecomService().isDefaultCallScreeningApp(componentName); } } catch (RemoteException e) { Log.e(TAG, "RemoteException calling ITelecomService#isDefaultCallScreeningApp.", e); } return false; }

Target:
why always return false?
Source:
public void checkInterrupted() { Thread thread = Thread.currentThread(); String message; if (isInterruptable() && (message = mInterruptMessage.get(thread)) != null) { thread.interrupt(); throw new RunInterruptedException(message); } }

Target:
Why do we need to interrupt the current thread? Wouldn't throwing RunInterruptedException be enough?
Source:
public void testScrollBarViewShowAllWhenLimitedSpace() { setLayoutRestrictions(/*allowScrollThumb=*/true, /*allowAlphaJump=*/true, /*bias=*/false); onView(withId(androidx.car.test.R.id.page_up)).check(matches(isDisplayed())); onView(withId(androidx.car.test.R.id.scrollbar_thumb)).check(matches(isDisplayed())); onView(withId(androidx.car.test.R.id.alpha_jump)).check(matches(isDisplayed())); }

Target:
Enough
Source:
AlphaJumpTestAdapter() { for (int i = 0; i < sSize; i++) { mStrings[i] = "Dummy" + i; } }

Target:
Use mStrings.length here
Source:
public void testSetBrightness() { final int mode = Settings.System.getInt(mContext.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_AUTOMATIC); if(mode==1) { mDevicePolicyManager.setSystemSetting(ADMIN_RECEIVER_COMPONENT, Settings.System.SCREEN_BRIGHTNESS_MODE, "0"); testSetBrightnessWithValue(TEST_BRIGHTNESS_1); testSetBrightnessWithValue(TEST_BRIGHTNESS_2); mDevicePolicyManager.setSystemSetting(ADMIN_RECEIVER_COMPONENT, Settings.System.SCREEN_BRIGHTNESS_MODE, "1"); } else { testSetBrightnessWithValue(TEST_BRIGHTNESS_1); testSetBrightnessWithValue(TEST_BRIGHTNESS_2); } }

Target:
if (mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC) { mDevicePolicyManager.setSystemSetting(ADMIN_RECEIVER_COMPONENT, Settings.System.SCREEN_BRIGHTNESS_MODE, "0"); } testSetBrightnessWithValue(TEST_BRIGHTNESS_1); testSetBrightnessWithValue(TEST_BRIGHTNESS_2); mDevicePolicyManager.setSystemSetting(ADMIN_RECEIVER_COMPONENT, Settings.System.SCREEN_BRIGHTNESS_MODE, mode == SCREEN_BRIGHTNESS_MODE_AUTOMATIC? "1" : "0");
Source:
public void testAuthorizedAPDUAID40() { if (PropertyUtil.getFirstApiLevel() < Build.VERSION_CODES.P) { return; } for (byte[] apdu : AUTHORIZED_APDU_AID_40) { testTransmitAPDU(AID_40, apdu); } }

Target:
Done
Source:
protected void accumulateConsecutiveDnsTimeoutCount(int code) { final DnsResult result = new DnsResult(code); // Keep only the last mSize events in the mDnsEvents. Remove the oldest one if its size // become larger than mSize. final int index = mResultIndices.add(); if (index >= 0 && index < mSize) { mDnsEvents[index] = result; } if (result.isTimeout()) { mConsecutiveTimeoutCount++; } else { // Keep the event in mDnsEvents without clearing it so that there are logs to do the // simulation and analysis. mConsecutiveTimeoutCount = 0; } }

Target:
I suggest you simply say mDnsEvents[mResultIndices.add()];, as the RingBufferIndices class is defined to never return anything out of these bounds. It's contractual.
Source:
public void setVpnProxy(@Nullable ProxyInfo proxyInfo) { synchronized (mProxyLock) { if (proxyInfo == null) { mVPNProxy = null; return; } if (!TextUtils.isEmpty(proxyInfo.getHost()) && proxyInfo.getPort() != 0) { // vpn proxy with empty blacklist mVPNProxy = proxyInfo; } } }

Target:
So if there is a host, but the port is 0, we simply don't change the previous value ? That sounds counter-intuitive. Honestly I think this should simply read synchronized (mProxyLock) { mVPNProxy = proxyInfo; }
Source:
public void setUp() { mAppStartupHelper = new AppStartupHelper(); // Make sure the apps are starting from the clean state. HelperTestUtility.clearApp(String.format(KILL_TEST_APP_CMD_TEMPLATE, CALENDAR_PKG_NAME)); HelperTestUtility.clearApp(String.format(KILL_TEST_APP_CMD_TEMPLATE, SETTINGS_PKG_NAME)); HelperTestUtility.clearApp(String.format(KILL_TEST_APP_CMD_TEMPLATE, SETTINGS_PKG_NAME)); // Make sure display is on and unlocked. HelperTestUtility.wakeUpAndUnlock(); }

Target:
Can you remove this?
Source:
private void addRepeatedAnnotationHandlers( Builder<String, AnnotationHandler> builder, String annotationName, String containerAnnotationName, AnnotationHandler handler) { builder.put(annotationName, handler); builder.put(containerAnnotationName, new RepeatedAnnotationHandler(annotationName, handler)); }

Target:
line too long
Source:
public void testGetFirstRowItemCount_singleItemFullSpan() throws Throwable { int itemCount = 1; setUpPagedListView(itemCount); RecyclerView recyclerView = mPagedListView.getRecyclerView(); mActivityRule.runOnUiThread(() -> { ((GridLayoutManager) recyclerView.getLayoutManager()).setSpanSizeLookup( new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { return SPAN_COUNT; } }); }); // Wait for the UI to lay itself out. InstrumentationRegistry.getInstrumentation().waitForIdleSync(); assertEquals(itemCount, GridLayoutManagerUtils.getFirstRowItemCount(recyclerView)); }

Target:
Could you somehow fold this into the setupPagedListView method? Maybe define a new method that sets the SpanSizeLookup. The reasoning is that we already wait for idle after the setupPagedListView() method. And then we'll wait again for this. Makes the test slower.
Source:
public static void setLogger(Logger logger) { sLogger = logger; }

Target:
Synchronize this too.
Source:
public void testRunTimedCmd_WithOutputRedirect() throws IOException { File outputRedirect = FileUtil.createTempFile("output_redirect", ".txt"); try { CommandResult result = RunUtil.getDefault() .runTimedCmd( SHORT_TIMEOUT_MS, new FileOutputStream(outputRedirect), /* stderr= */ null, "echo", "TEST_OUTPUT"); assertTrue(CommandStatus.SUCCESS.equals(result.getStatus())); assertEquals("TEST_OUTPUT\n", FileUtil.readStringFromFile(outputRedirect)); } finally { FileUtil.deleteFile(outputRedirect); } }

Target:
nit: close the stream
Source:
public void setSwitchScale(float scale) { mSwitchScale = scale; requestLayout(); }

Target:
I think it's ok not to expose this as a public method yet. We can have a default scaling for the switches that doesn't change.
Source:
private void initCellularData() { CellularData data = new CellularData(); data.ratType = DataStallEventProto.RADIO_TECHNOLOGY_UNKNOWN; data.networkMccmnc = ""; data.simMccmnc = ""; data.signalStrength = UNKNOWN_SIGNAL_STRENGTH; cellularInfo = MessageNano.toByteArray(data); }

Target:
I think you could return a byte[] here to have cellularInfo final
Source:
private boolean areNetworksValid(QualifiedNetworks networks) { if (networks.qualifiedNetworks == null) { return true; } for (int network : networks.qualifiedNetworks) { if (!ACCESS_NETWORK_TRANSPORT_TYPE_MAP.containsKey(network)) { return false; } } return true; }

Target:
static ?
Source:
public void start() { if (mRunning) return; mRunning = true; new Thread() { @Override public void run() { while (mRunning) { listen(); } } }.start(); }

Target:
nit: Can this be a lambda?
Source:
public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) { enforceNetworkStackPackagePermission(); mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, new Pair<>(mNai, networkMonitor))); }

Target:
Why do we need these permission checks? I was assuming that since the callback is coming from the object that the system is explicitly bound to, that would be enough proof that the sender is authorized to perform the action. If we do need them here, then do we need them on all the other callbacks as well?
Source:
private boolean doesCellInfoCorrespondToKnownMccMnc(CellInfo ci, Set<String> knownMccMncs) { String mccMnc = ci.getCellIdentity().getMccString() + ci.getCellIdentity().getMncString(); return knownMccMncs.contains(mccMnc); }

Target:
nit static?
Source:
public Map<String, Set<TestInfo>> getTestCollection() { return mTestCollection; }

Target:
this doesn't look like it needs to be public
Source:
public boolean isDefaultOrEmptyAccessibilityDelegateCompat() { return (this.getClass().equals(AccessibilityDelegateCompat.class) && mOriginalDelegate.getClass().equals(AccessibilityDelegate.class)) || mOriginalDelegate == null; }

Target:
Does platform set an accessibilityDelegate by default?
Source:
static boolean isTransformSelectedFrom(Transform[] selected, Transform[] selectFrom) { // If the selected proposal has multiple transforms with the same type, the responder MUST // choose a single one. if ((selected.length > 1) || (selected.length == 0) != (selectFrom.length == 0)) { return false; } if (selected.length == 0) return true; Transform chosenTransform = selected[0]; return Arrays.asList(selectFrom).contains(chosenTransform); }

Target:
Nit: Can probably just inline this if it's the only place it's used
Source:
public void setUp() throws InitializationError { initMocks(this); mRunner = spy(new LongevityClassRunner(SampleTest.class)); }

Target:
It's not great to rely on this without knowing what it relies on. In particular, you replace it with failing test elsewhere, but it's not immediately obvious that this is running the "sample" test once I got to the bottom of the file.
Source:
public void registerDialogWatchers() { registerWatcher( AppIsNotRespondingWatcher.class.getSimpleName(), new AppIsNotRespondingWatcher(InstrumentationRegistry.getInstrumentation())); }

Target:
nit: you also could leave these private without modifying the API, JFYI. Not sure if it's necessary at all. If not, I think it's worth making that change.
Source:
public static void setDefaultNightMode(@NightMode int mode) { switch (mode) { case MODE_NIGHT_NO: case MODE_NIGHT_YES: case MODE_NIGHT_FOLLOW_SYSTEM: case MODE_NIGHT_AUTO_TIME: case MODE_NIGHT_AUTO_BATTERY: if (sDefaultNightMode != mode) { sDefaultNightMode = mode; synchronized (sActiveDelegatesLock) { applyDayNightToActiveDelegates(); } } break; default: Log.d(TAG, "setDefaultNightMode() called with an unknown mode"); break; } }

Target:
Push synchronization block into method.
Source:
public LinkAddress getDestinationLinkAddress() { if (mDestination == null) return null; return new LinkAddress(mDestination.getAddress(), mDestination.getPrefixLength()); }

Target:
Ditto, I think destination can never be null.
Source:
void release() { if (mSurface == null && mSurfaceTexture == null) { return; } Resource resource; synchronized (mLock) { resource = mResourceMap.get(mSurfaceTexture); } if (resource != null) { releaseResourceWhenDetached(resource); } mSurfaceTexture = null; mSurface = null; if (!mSurfaceToReleaseList.isEmpty()) { for (Surface surface : mSurfaceToReleaseList) { surface.release(); } mSurfaceToReleaseList.clear(); } }

Target:
The if-check for empty list can be removed. The for-loop and clear call also work for empty list.
Source:
public static void switchToExistingOrCreateUserType(ITestDevice device) throws DeviceNotAvailableException, UserSwitchFailedException { try { UserUtil.switchToUserType(device, mUserToSwitchTo); } catch (UserUtil.SecondaryUserNotFoundException attemptCreate) { CLog.d("No secondary users exist, creating one."); UserUtil.createAndSwitchToSecondaryUser(device); } }

Target:
this should remain private, right?
Source:
public List<CaptureConfig> onPresetSession() { return new ArrayList<>(); }

Target:
Is there a reason this is a list instead of just a CaptureConfig? From a usage perspective, it only makes sense to issue a single config.
Source:
public void onlineUseCase() { Assume.assumeTrue(mCameraId != null); mCamera.open(); mCamera.addOnlineUseCase(Collections.<UseCase>singletonList(mFakeUseCase)); verify(mMockOnImageAvailableListener, never()).onImageAvailable(any(ImageReader.class)); mCamera.release(); }

Target:
Rather than put this in every test, you can just put it once in the setup() method.
Source:
private void validateTsPayloads(List<IkePayload> reqPayloads, List<IkePayload> respPayloads) throws TsUnacceptableException { for (int tsType : new int[] { IkePayload.PAYLOAD_TYPE_TS_INITIATOR, IkePayload.PAYLOAD_TYPE_TS_RESPONDER }) { IkeTsPayload reqPayload = IkePayload.getPayloadForTypeInProvidedList( tsType, IkeTsPayload.class, reqPayloads); IkeTsPayload respPayload = IkePayload.getPayloadForTypeInProvidedList( tsType, IkeTsPayload.class, respPayloads); if (!reqPayload.contains(respPayload)) { throw new TsUnacceptableException(); } } }

Target:
Nit: Suggest move to a separate line, just so it's more readable.
Source:
private boolean hasActualVideo() { if (mVideoTrackCount > 0) { return true; } VideoSize videoSize = mPlayer.getVideoSize(); if (videoSize.getHeight() > 0 && videoSize.getWidth() > 0) { Log.w(TAG, "video track count is zero, but it renders video. size: " + videoSize.getWidth() + "/" + videoSize.getHeight()); return true; } return false; }

Target:
How about just videoSize?
Source:
public CustomTabsSession newSession(@Nullable final CustomTabsCallback callback) { return newSessionInternal(callback, null); }

Target:
@Nullable?
Source:
public NetworkStats getNetworkStatsDetail() { mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG); try { return mStatsFactory.readNetworkStatsDetail(UID_ALL, null, TAG_ALL); } catch (IOException e) { throw new IllegalStateException(e); } }

Target:
nit: can be replaced with readNetworkStatsDetail()
Source:
void waitForLoadCompletion() { waitForCriteria(LOAD_TIMEOUT, () -> { return isLoaded(); }); clearLoad(); }

Target:
simplify to () -> isLoaded()? Can it just be this::isLoaded? I'm not sure what the interchangeability of bound method references and lambdas is like.
Source:
private ChildSessionStateMachine buildChildSession(ChildSessionOptions childOptions) { boolean isNatDetected = mIsLocalBehindNat || mIsRemoteBehindNat; ChildSessionStateMachine childSession = ChildSessionStateMachineFactory.makeChildSessionStateMachine( "ChildSessionStateMachine", getHandler().getLooper(), mContext, childOptions, new ChildSessionSmCallback(), mLocalAddress, mRemoteAddress, (isNatDetected ? mIkeSessionOptions.getUdpEncapsulationSocket() : null), mIkePrf, mCurrentIkeSaRecord.getSkD()); return childSession; }

Target:
Do we need to pass this in if it's always the same?
Source:
protected String getLocalAddressString(SSLSocket socket) { InetAddress addr = socket.getLocalAddress(); return String.format( (addr instanceof Inet6Address ? "[%s]:%d" : "%s:%d"), addr.getHostAddress(), socket.getLocalPort()); }

Target:
final
Source:
private void prepareDnsTlsMeasurement(String hostname, InetAddress target) { // Since we iterate LinkProperties.getDnsServers() before PrivateDnsCfg.ips, if the entry // of |target| is found in the DnsTlsChecks map, then 1) the entry must have been created // when we iterated LinkProperties.getDnsServers() 2) we are iterating PrivateDnsCfg.ips // now. Thus, overwrite the entry in order to set SNI. if (!mDnsTlsChecks.containsKey(target) || !TextUtils.isEmpty(hostname)) { Measurement measurement = new Measurement(); measurement.thread = new Thread(new DnsTlsCheck(hostname, target, measurement)); mDnsTlsChecks.put(target, measurement); } }

Target:
Style : we prefer to write our code in a return-fast style. if (mDnsTlsChecks.containsKey(target) && TextUtils.isEmpty(hostname)) return; Note that in this case it's much clearer with the reversed check that it's really a bizarre thing to test. You want to overwrite, except if the hostname is empty ? Why ?