HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaMinor

Data flow anomaly: how to do it correct?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
flowanomalycorrecthowdata

Problem

I am modifying Volley for Android a bit and Findbugs complains about the data flow and I am a bit lost. First the code:

String userAgent;
try {
    String packageName = getPackageName();
    PackageInfo info = getPackageManager().getPackageInfo(packageName, 0);
    userAgent = packageName + "/" + info.versionCode; // DD
} catch (PackageManager.NameNotFoundException e) {
    userAgent = "volley/0";
}

HttpStack stack;
if (Build.VERSION.SDK_INT >= 9) {
    stack = new HurlStack();
} else {
    stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
}


So I thought that findbugs would differ between definition and declaration of a variable which should make the DD gone.

I also tried to predefine the userAgent with the content from the catch but an empty catch is bad practice as well. Also findbugs just complains with the data flow anomalies just on different places...

So what would be a good solid way to prevent the findbugs reports?

Solution

It would be bad practice to silently swallow an exception. However, I think the following code would be acceptable:

String userAgent = "volley/0";  // Default value
try {
    String packageName = getPackageName();
    PackageInfo info = getPackageManager().getPackageInfo(packageName, 0);
    userAgent = packageName + "/" + info.versionCode;
} catch (PackageManager.NameNotFoundException justUseDefaultUserAgent) {
}


For the second snippet, I would use a ternary conditional to emphasize the goal of assigning stack a value no matter what.

HttpStack stack = (Build.VERSION.SDK_INT >= 9) ? new HurlStack() :
    new HttpClientStack(AndroidHttpClient.newInstance(userAgent));

Code Snippets

String userAgent = "volley/0";  // Default value
try {
    String packageName = getPackageName();
    PackageInfo info = getPackageManager().getPackageInfo(packageName, 0);
    userAgent = packageName + "/" + info.versionCode;
} catch (PackageManager.NameNotFoundException justUseDefaultUserAgent) {
}
HttpStack stack = (Build.VERSION.SDK_INT >= 9) ? new HurlStack() :
    new HttpClientStack(AndroidHttpClient.newInstance(userAgent));

Context

StackExchange Code Review Q#38742, answer score: 2

Revisions (0)

No revisions yet.