Konstantin
Konstantin

Reputation: 3055

Java style: Multiple variable assignment

Take the following:

if (filter instanceof FileNameExtensionFilter) {
    fnef = (FileNameExtensionFilter) filter;
    String[] extensions = fnef.getExtensions();
    if (extensions.length > 1) {
        fnef = filter = new FileNameExtensionFilter(fnef.getDescription(), extensions[0]);
    }
}

where filter is a FileFilter object and fnef an instance variable of the type FileNameExtensionFilter.

Would you consider it good coding practice to assign a value to multiple variables on the same line? Or would it be better to write line 6 from the example as follows:

fnef = new FileNameExtensionFilter(fnef.getDescription(), extensions[0]);
filter = fnef;

I personally prefer the latter, though I'd like to hear what you think.

Upvotes: 0

Views: 4284

Answers (2)

Diego Borda
Diego Borda

Reputation: 173

I would rather use separate lines to avoid confusions when using non-immutable objects like FileNameExtensionFilter. For example it's not the same to say:

MyObject var1 = new MyObject();
MyObject var2 = new MyObject();

Than

MyObject var1, var2;
var1 = var2 = new MyObject();

In the first case the variables are different objects with the same values but in the second case they are the same variable. Multiple variable assignment is risky so I do consider it bad practice. It's still a matter of taste.

Upvotes: 0

Rob Wagner
Rob Wagner

Reputation: 4421

This is a pretty subjective question.

I think this is more clear:

fnef = new FileNameExtensionFilter(fnef.getDescription(), extensions[0]);
filter = fnef;

But any experienced developer will understand this:

fnef = filter = new FileNameExtensionFilter(fnef.getDescription(), extensions[0]);

Upvotes: 3

Related Questions