Should I fully declare throw-away objects?
If I need to do something like this:
var connection = new Connection(host);
connection.Execute(Commands.Delete);
Is there anything wrong in doing this:
(new Connection(host)).Execute(Commands.Delete);
The first example may be more readable, but the second works better if I need to do this multiple times:
(new 开发者_开发技巧Connection(anotherHost)).Execute(Commands.Create);
(new Connection(someOtherHost)).Execute(Commands.Update);
(new Connection(host)).Execute(Commands.Delete);
Does your Connection
class implement IDisposable
? Then:
using (var connection = new Connection(host))
{
connection.Execute(Commands.Delete);
}
First thing I am a Java person and I havent used C# But based on your code and knowing similarity with java what I can say is -
If your Connection class maintains a state information then its meaningful to create new object every time. But if it is stateless then its pretty inefficient to create multiple objects. You can create one and re-use the same.
i.e. If you cannot set the 'host' to a connection once created, then both approaches you mentioned should not make any difference.
The more verbose you are, the easier of a time you will have debugging.
The effect on your code readability really depends on how much you're trying to wrap into one line - if you've got a single idea that just takes a lot of different words to express, putting it in one line isn't a big deal in my opinion. But if you're trying to cram multiple ideas into one line you'll lose clarity.
For instance. We'll start with a simple idea that just takes some space to express:
transactionTime = generationTime + retrievalTime + processingTime + loggingTime
And here we have a more complex idea that we happen to express in one line:
logTransactionData(processTransaction(retrieveTransaction(generateTransactionQuery())))
I think that the first example is easier to understand at a glance than the second, even though they're about the same in character length.
So in general: consider how likely it is you'll need to debug the line, as well as your idea-complexity-to-line ratio.
Yes, you're initializing a new object, using it, and loosing it! you cannot reuse it again and it's gonna be there somewhere, until GC collects it! So, there's no harm in storing new initialized objects in a variable, and declaring them in another line makes your code more readable.
精彩评论