Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

java - for-loop with included initialization syntactically and semantically correct?

I wonder if the following code snippet is an elegant and efficient replacement that really is 100% semantically identical. Especially, is the decalation and initialization inside the for a good idea:

for ( BroadcastReceiver br : new BroadcastReceiver[] {receiverA, receiverB, receiverC} )
    if ( br != null ) {
        try {
            unregisterReceiver( br );
        } catch ( Exception ignored ) {}
    }

Instead of:

    if ( receiverA != null ) {
        try {
            unregisterReceiver( receiverA );
        } catch ( Exception e ) {}
    }
    if ( receiverB != null ) {
        try {
            unregisterReceiver( receiverB );
        } catch ( Exception e ) {}
    }
    if ( receiverC != null ) {
        try {
            unregisterReceiver( receiverC );
        } catch ( Exception e ) {}
    }

(I know that an extra array is created and the for-overhead is also necessary but at the same time I save the code repetitions and the question for the reader if all these repetition really are identical)

question from:https://stackoverflow.com/questions/65869621/for-loop-with-included-initialization-syntactically-and-semantically-correct

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The first code snippet indeed looks better than the duplicated statements.

You could also implement a separate helper method with vararg and then invoke it with arbitrary number of arguments:

public void unregisterReceivers(BroadcastReceiver ... receivers) {
    for (BroadcastReceiver br : receivers)
        if (br != null) {
            try {
                unregisterReceiver(br);
            } catch (Exception ignored) {
                // at least log exception that some receiver failed to unregister
            }
        }
    }
}

unregisterReceivers(receiverA, receiverB, receiverC);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...