开发者

Which code is preferable? [closed]

开发者 https://www.devze.com 2023-04-05 18:14 出处:网络
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references,or expertise, but this question will likely solicit debate, a
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. 开发者_C百科 Closed 11 years ago.

A:

new Thread(new ThreadStart(ListenForResponse)) { IsBackground = true }.Start();

B:

ThreadStart threadStart = new ThreadStart(ListenForResponse);

Thread listeningThread = new Thread(threadStart);

listeningThread.IsBackground = true;

listeningThread.Start();

As far as I can tell they are functionally equivalent. I'm just wondering which is preferred. Which would you rather see in a project?


I prefer this:

Thread listeningThread = new Thread(new ThreadStart(ListenForResponse))
{
    IsBackground = true
}

listeningThread.Start();

This question is quite subjective, though.

If you are setting more parameters on the various objects, the one-liner version starts to get hard to read.

On the other hand, writing everything out explicitly for the simple case can be wordy and clutter the meaning of what's going on.

Also, a personal pet peeve is putting a function call waaay at the end of the line, where it is hard to see, as in your first example. Even if you want to use that syntax, I would prefer to see the .Start() on its own line.


I personally prefer the selection B. It is a lot more readable. Each step is logically laid out, you can understand what is happening by simply stepping through it.

My opinion of A is that its showoff code. You do this to show how short you can make an operation, but its re-usability is pretty low and requires you understand the structure of the call a little better.

My opinion: Assume your code will be used by someone else and assume they need all the help they can get. Choose the most readable solution that does not sacrifice efficiency.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号