Reputation: 15303
I have seen this method in android source code.
protected LocaleConfiguration doInBackground(Void... unused) {
LocaleConfiguration localeConfiguration = new LocaleConfiguration();
readConfiguration(Launcher.this, localeConfiguration);
return localeConfiguration;
}
private static void readConfiguration(Context context, LocaleConfiguration configuration) {
DataInputStream in = null;
try {
in = new DataInputStream(context.openFileInput(PREFERENCES));
configuration.locale = in.readUTF();
configuration.mcc = in.readInt();
configuration.mnc = in.readInt();
} catch (FileNotFoundException e) {
// Ignore
} catch (IOException e) {
// Ignore
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// Ignore
}
}
}
}
why not something like this
private static LocaleConfiguration readConfiguration(Context context) {
LocaleConfiguration configuration = new LocaleConfiguration();
DataInputStream in = null;
try {
in = new DataInputStream(context.openFileInput(PREFERENCES));
configuration.locale = in.readUTF();
configuration.mcc = in.readInt();
configuration.mnc = in.readInt();
} catch (FileNotFoundException e) {
// Ignore
} catch (IOException e) {
// Ignore
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// Ignore
}
}
}
return configuration;
}
what is the advantage of modifying argument instead of returning new value
Upvotes: 2
Views: 94
Reputation: 4374
The advantage of modifying an argument instead of returning a new instance is that you put control of instantiation in the hands of the calling code - i.e. you allow it to re-use an existing instance.
The 'modifying argument' approach allows you to initialise an object using several such methods. e.g.
LocaleConfiguration localeConfiguration = new LocaleConfiguration();
readConfiguration(Launcher.this, localeConfiguration);
readSomeOtherConfiguration(Launcher.this, localeConfiguration);
return localeConfiguration;
Arguably you could do the same thing by returning the same instance as was passed in as a parameter, but I personally think that's asking for trouble.
Another possible reason might be if the cost of instantiation was high, you might want to recycle an old object. This doesn't appear to be the case with the code you present though, and it's an optimisation so only think about doing this if absolutely necessary!
Personally I would tend to take the 'return a new instance' approach unless there's a specific reason not to. I think it's simpler and decreases the likelihood of subtle errors in the calling code.
Upvotes: 2