2

Android ソース コードでこのメソッドを見たことがあります。

 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
                }
            }
        }
    }

なぜこのようなものではないのですか

 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;
    }

新しい値を返す代わりに引数を変更する利点は何ですか

4

1 に答える 1

2

新しいインスタンスを返す代わりに引数を変更する利点は、インスタンス化の制御を呼び出し元のコードに委ねることです。つまり、既存のインスタンスを再利用できるようになります。

「引数の変更」アプローチを使用すると、そのようないくつかのメソッドを使用してオブジェクトを初期化できます。例えば

LocaleConfiguration localeConfiguration = new LocaleConfiguration();
readConfiguration(Launcher.this, localeConfiguration);
readSomeOtherConfiguration(Launcher.this, localeConfiguration);
return localeConfiguration;

おそらく、パラメーターとして渡されたものと同じインスタンスを返すことで同じことを行うことができますが、個人的にはそれは問題を引き起こしていると思います.

もう 1 つの考えられる理由は、インスタンス化のコストが高い場合、古いオブジェクトをリサイクルしたい場合です。ただし、これは提示されたコードには当てはまらないようです。これは最適化であるため、絶対に必要な場合にのみこれを行うことを考えてください!

個人的には、特別な理由がない限り、「新しいインスタンスを返す」アプローチを取る傾向があります。私はそれがより簡単で、呼び出しコードの微妙なエラーの可能性を減らすと思います.

于 2013-02-06T09:50:19.333 に答える