Possible Duplicate:
Is it b开发者_运维问答etter to create a new object and return it or create the new object in the return statement?
Hi guys,
Can someone explain if the first method is worse than second one?
public byte[] getBytesForSource() throws IOException {
Preconditions.checkNotNull(this.fSource, "Raw source does not exist.");
byte[] baFile = Files.toByteArray(this.fConvertedSource);
return baFile;
}
vs
public byte[] getBytesForSource() throws IOException {
Preconditions.checkNotNull(this.fSource, "Raw source does not exist.");
return Files.toByteArray(this.fConvertedSource);
}
I understand that the first one instantiates an array of bytes and return it but however, the second one also returns an array of bytes...
So why the second one is better?
They are identical. The second one is just a bit concise.
Sometimes introducing intermediate variables to break up lengthy chain calls can improve readability but that's definitely true in your case.
Simply because the second one is more concise. They are functionally equivalent.
They're functionally equivalent, but each has its own advantages:
- The second is more concise, and personally is what I'd normally go with
- The first is easier to debug, as you get to see / examine / modify the byte array after you call the method, but before you hit the return statement.
I suspect in many debuggers there may be a way of seeing "the value which is about to be returned" but not being someone who spends a lot of time in the debugger, I've never actually seen that :(
Of course an alternative is to debug into Files.toByteArray
.
I'm not sure there is anything wrong with either of them. They do the same thing. The only advantage I see is that the second one is slightly less code, which won't make much difference except to someone reading it.
If you think that all things being equal, fewer lines and fewer variables are better, then the second is better.
If the existence of the variable baFile
makes the code more readable to you, then it's better.
To me, it doesn't, so I prefer the second.
What makes you think that the second one is better? Is this a "give me a defense against my teacher marking something wrong" question?
The only difference is: In 1: you create a byte array in which you put the bytes from the file. You return the array. In 2: You return exactly the same, but without creating a byte array in between. Instea of first putting the bytes in an array, you return them straight away.
The only reason why the second is better is that it's faster, and it takes less code.
They are the same thing. They both return a pointer to a byte array. The first one just assigns a locally scoped variable which would only need if you're going to read/write to/from the array before returning it. All that you will lose is the time that it takes to make the assignment, though most compilers should just automatically change the compiled code to the second version since you're doing nothing with baFile.
精彩评论