多次比较,存储结果

本文关键字:存储 结果 比较 | 更新日期: 2023-09-27 17:54:45

当我正在构建一个类来管理在Android中显示AlertDialog的有点乏味和重复的过程时,我偶然发现了这个:

我是否应该将比较的结果存储到变量中,并使用它而不是进行n次比较?

在我的例子中,我进行了两次相同的比较(比较将始终返回相同的结果,因为在这些比较之间,我没有改变任何可能改变结果的东西)。

这是我所拥有的:

public static AlertDialog BuildDialog( Activity activity, String header, String body, View view, DialogButton negative, DialogButton positive, DialogButton neutral ) {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( activity );
    alertDialogBuilder.SetTitle( header );
    alertDialogBuilder.SetMessage( body );
    if( view != null ) {
        alertDialogBuilder.SetView( view );
    }
    if( positive == null && negative == null && neutral == null ) {
        alertDialogBuilder.SetNeutralButton( "OK", (EventHandler<DialogClickEventArgs>) null );
    } else {
        if( negative != null ) {
            alertDialogBuilder.SetNegativeButton( negative.Text, negative.Action );
        }
        if( neutral != null ) {
            alertDialogBuilder.SetNeutralButton( neutral.Text, neutral.Action );
        }
        if( positive != null ) {
            alertDialogBuilder.SetPositiveButton( positive.Text, positive.Action );
        }
    }
    return alertDialogBuilder.Create();
}

现在是这样的:

public static AlertDialog BuildDialog( Activity activity, String header, String body, View view, DialogButton negative, DialogButton positive, DialogButton neutral ) {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( activity );
    alertDialogBuilder.SetTitle( header );
    alertDialogBuilder.SetMessage( body );
    Boolean
        hasView = view != null,
        hasNeutral = neutral != null,
        hasPositive = positive != null,
        hasNegative = negative != null;
    if( hasView ) {
        alertDialogBuilder.SetView( view );
    }
    if( !hasNeutral && !hasPositive && !hasNegative ) {
        alertDialogBuilder.SetNeutralButton( "OK", (EventHandler<DialogClickEventArgs>) null );
    } else {
        if( hasNegative ) {
            alertDialogBuilder.SetNegativeButton( negative.Text, negative.Action );
        }
        if( hasNeutral ) {
            alertDialogBuilder.SetNeutralButton( neutral.Text, neutral.Action );
        }
        if( hasPositive ) {
            alertDialogBuilder.SetPositiveButton( positive.Text, positive.Action );
        }
    }
    return alertDialogBuilder.Create();
}

虽然在这个特定的情况下不应该有明显的影响,哪一个执行更好,哪一个阅读更好?

多次比较,存储结果

. net中的Null比较非常便宜,所以做这样的事情的唯一原因是可读性,而不是执行速度。这尤其适用于复杂的条件,例如

bool nonNegative = hasPositive || hasNeutral;
...
if (nonNegative) ...

使代码更紧凑,更易于阅读。