问:
Recommended content for layers
As an expansion from my previous question about using separate projects for seperate layers - Good practice on Visual Studio Solutions

I now wish to know if I am putting the right functionality in the correct layers.

Background

I'm building a WPF application from scratch, that contains business logic and business objects. The database itself sits on another server on the web with access to it, restricted to web API calls using OAuth authentication.

I think the following content should be in these layers. The idea being, you go from layer 1 to layer 4, you are only depending on the layers below you. To prevent circular dependencies.

1. Presentation

WPF View (what the user will see)

WPF ViewModel (how the program responds to user interaction)

No WPF Model, as it will just be the business object

2. Application/Services

Repository (class used by ViewModel to load/save business objects)

Utility classes to assist in saving objects, by selecting the correct API calls.

3. Business layer

Business objects/Entities/DTO (whichever name is preferred)

Factories (Used by the repositories in the creation of business objects)

Other misc business class (i.e. storage of currently logged in user)

4. Infrastructure/Data Access

OAuth client (makes authenticated calls against the web server, used by repository classes)

答:
The four layers you mentioned match the names of the layering I've used when I recently architected two our our company solutions. I also strongly agree to @Konamiman reply, Data Access and Infrastructure shall be two separate layer. In our solutions Infrastucture is a cross-cutting layer which can be referenced by projects in any layer. In the infrastructure layer we keep the logging functionality, security and validation code.

I would also consider adding a layer below the Data Access Layer called Entities. Put all your business object there, add Interfaces of of the entities in the Data Access Layer and reference the Data Access Layer with the Entities project.

I'm used to using non-strict referencing as you described, an upper layer can reference any of the lower layers. In a strict referencing an upper layer should only reference the the closest lower layer.

Title: Recommended content for layers


问:
Mastering technology like LINQ, WCF really necessary or is OOPS enough?
I am a C# developer.

My observation of the IT industry as a C# developer is that the technology keeps changing or being updated by Microsoft like LINQ, WCF, and WPF etc.

OOP has been the fundamental for all kinds of developments that we see today in any language.

My question is,

Is it good if I am a decent programmer in OOPS but not mastering any specific technology?

As a WinForms developer, is it necessary to know C++ with C# for better job perspective?

答:
Object Oriented programming is a paradigm, not a technology. Different technologies follow this paradigm, like C#. There exist dozens of different paradigms, which basically are different approaches to solving problems.

LINQ inherits concepts of functional programming to make your life easier where pure OOP falls short. Learning this technology is a must if you are a C# developer.

WCF and WPF are part of the .NET framework to solve particular common scenarios. WCF can be used for networking, while WPF can be used to create visual applications. Obviously, if you aren't creating an application which does any form of communication with external applications, there is no need to learn/use WCF. Likewise for WPF, there is no use to learn it if you don't need any visuals. Alternatives exist for both WCF and WPF, but given they are frameworks supported by Microsoft they are often a good choice.

Even experimental alternatives to LINQ start to pop up, e.g. Push LINQ. These are far away from completion, and you are probably better off sticking to ordinary LINQ for the time being.

ContentLicense: CC BY-SA 3.0


答:
Resharper is the best tool Ive found to learn LINQ. I've so far not had the need to learn more than the refactorings suggested by Resharper.

As for WCF I'd recommed learning when/if you need to. Study webservices, SOAP and remoting instead. If you grasp the concept you can very quickly learn WCF when you need to.

Title: Mastering technology like LINQ, WCF really necessary or is OOPS enough?

Body:
I am a C# developer.

My observation of the IT industry as a C# developer is that the technology keeps changing or being updated by Microsoft like LINQ, WCF, and WPF etc.

OOP has been the fundamental for all kinds of developments that we see today in any language.

My question is,

Is it good if I am a decent programmer in OOPS but not mastering any specific technology?

As a WinForms developer, is it necessary to know C++ with C# for better job perspective?


问:
How to make sure I don't end up with the blame
I'm working on a contract at present where I'm essentially working as a subcontractor for a fairly big digital agency. The real end customer is a big corp.

So far, I have of course done an amazing job :)

The agency had a "spec" up front - basically a "sitemap" for the app. This was my "blueprint".

Inside the first week, I built a working prototype app complete with a new data service  - which met the sitemap perfectly. Milestone formally accepted - lots of +ive feedback from the agency.

In the second week I built and delivered a beautiful fully working CMS for the data (really, it's beautiful - I'm stunned). Milestone formally accepted - again lots of +ive feedback from the agency.

Then the problems started... basically I needed the assets and design pack to complete the app and the project, and what the agency delivered was rubbish - unfinished photoshop files completely skipping half of the app and with every page having undecided A/B options. There's nothing decided in this design pack, so we can't even start on the next project phase.

I flagged this with them a few times... they ignored me for a week, then came back with "what are you talking about? we finished the design pack weeks ago"... I then asked them if they'd looked at what they produced... they then looked at it and admitted it needed "some work". Since then it's been more delays and nothing delivered.

The situation now is that:

this project is now being delayed and delayed and delayed which is causing problems all over the place (with the customer, within the agency, within my schedule)

I get the sense that the problems/delays are actually being blamed on "that subcontractor"

my only contact in the project is one person in the agency - so no-one has any visibility of what the true situation is.

I can cope with the delays and the problems, and I'm pretty sure I don't want to work with this current contact ever again. However, I'd really quite like to work for other people in this same agency in the future - and (in my dreams) I also wouldn't mind getting some contact with the end customer too.

How can I avoid a "bum rap" on this project? Any ideas?

答:
It doesn't sound like your contact will be on your side, my feeling is going to the end customer with anything at this point would not be the correct course of action. The way I see it the only viable option is to gather what documentation you have of how things played out and keep it. If it comes to it you then have evidence to defend yourself with.

When and how you use that evidence is another question, you could possibly go over the head of  your contact in the agency and talk to his/her boss.


答: You need to check your contractual obligations in regards to delays are you financially responsible if they occur? make sure the shit doesn't fall on your head and you're ok!</p>

Title: How to make sure I don't end up with the blame

Body:
I'm working on a contract at present where I'm essentially working as a subcontractor for a fairly big digital agency. The real end customer is a big corp.

So far, I have of course done an amazing job :)

The agency had a "spec" up front - basically a "sitemap" for the app. This was my "blueprint".

Inside the first week, I built a working prototype app complete with a new data service  - which met the sitemap perfectly. Milestone formally accepted - lots of +ive feedback from the agency.

In the second week I built and delivered a beautiful fully working CMS for the data (really, it's beautiful - I'm stunned). Milestone formally accepted - again lots of +ive feedback from the agency.

Then the problems started... basically I needed the assets and design pack to complete the app and the project, and what the agency delivered was rubbish - unfinished photoshop files completely skipping half of the app and with every page having undecided A/B options. There's nothing decided in this design pack, so we can't even start on the next project phase.

I flagged this with them a few times... they ignored me for a week, then came back with "what are you talking about? we finished the design pack weeks ago"... I then asked them if they'd looked at what they produced... they then looked at it and admitted it needed "some work". Since then it's been more delays and nothing delivered.

The situation now is that:

this project is now being delayed and delayed and delayed which is causing problems all over the place (with the customer, within the agency, within my schedule)

I get the sense that the problems/delays are actually being blamed on "that subcontractor"

my only contact in the project is one person in the agency - so no-one has any visibility of what the true situation is.

I can cope with the delays and the problems, and I'm pretty sure I don't want to work with this current contact ever again. However, I'd really quite like to work for other people in this same agency in the future - and (in my dreams) I also wouldn't mind getting some contact with the end customer too.

How can I avoid a "bum rap" on this project? Any ideas?


问:
ELMAH - Where does it fit right...?
The question title may not be correct.

I have worked in a very big ASP.NET web application (without using MVC), there I used a simple error handling strategy :

Enclose every statement in try..catch block

Have a error label on each page at the very top

If any exception occurs then show the error description on the Error Label.

Now I am switching to a new project where MVC 3 framework is to be used, so I came across ELMAH. It is indeed a nice tool for error handling and logging. But as I read from many sites, it basically logs unhandled exceptions.

If I use the same strategy that every statement in try..catch block and then show the error message on the page at the top, then where does ELMAH sit, how will it log the exception? Which exception will it log if I am not putting a single statement outside try..catch block. So there is no scope for the unhandled exception.

答:
ELMAH is a module to be used with ASP.NET or ASP.NET/MVC.

I suggest always using it. It will log any unhandled exceptions - the ones you think you have handled, but haven't, or the ones where your normal logging fails.

You may believe there is no scope for unhandled exceptions - you are wrong.

Title: ELMAH - Where does it fit right...?


答:
I would suggest the following.

Write a lengthy email to the design company explaining exactly which assets are not done well, which A/B options are missing, and be as detailed as possible about those requirements.  Be nice, and just ask for those assets and psds with those fixes.

If they do not get back to you in the next day regarding those assets, send the same email to the final client and ask them if they can help you gain those assets.

When you send the emails, CC as many people as possible that are relevant.

This should make it clear to everyone that you are not at fault, and perhaps you might even get the final client to find a better agency to get you the designs you need and it might help you  build a relationship with that bigger larger corp.

If you only know of one single email address, then use some google skills to find other people at the company who you think might be relevant. LinkedIn is useful for that.  Alternatively, if you are close by, you can visit the office itself with the written request if you are feeling particularly pissed :)


问:
How to protect source code from remote developers?
My company is going to hire an external developer to create some new modules and fix some bugs in our PHP software.

We have never hired an external developer by the hour before. How can we protect the source code? We are not comfortable giving out source code and were thinking that everything remained under a surveillance enabled VPN which external developer would log in to.

Has anyone solved this problem before? If so, how?

Edit: We want the developer to see/modify the code but under surveillance and on our machine remotely. Does anybody have a similar setup?

Edit 2: NDA is just a formality. IMO, even people who are in favor of NDAs know that it'll do nothing to protect their property.

Edit 3: Let me clarify that we aren't worried about the developer copying an algorithm or a solution from the code. Code is coming out of his brain, so naturally he is the creator and he can create that again. But our code is built over several years with tens of developers working on it. Let's say I hire an incompetent programmer by mistake, who steals our years of work and then sells it to the competitor. That can make us lose our cutting edge. I know this is rare, but such a threat has to be taken under consideration if you're in business. I'll make points of my comments so its easy for everyone to communicate:

Why NDA sucks? Take this scenario, if anyone is capable of suggesting a solution to this scenario I will consider the NDA effective. Ok, here goes:
We hire 2 external developers, one of them sells our code as it is to someone else after a year. You are no longer in touch with any of the developers, how are you supposed to find out who ripped you off? NDA does provide a purpose, but you can't rely completely on that. At least we cannot.

I did not meant to offend anyone while I was posting this question, even though unintentionally I did. But again to people answering/commenting like 'I will never ever work with you' or that Men-in-black-gadget thingy: It's not about you, it's a thread about how feasible a given technical solution would be. And if anyone in this community has worked under such an environment.

About 'Trust', of course we won't hire anyone we do not trust. But is that it? Can't someone be deceitful at first? We all trusted a lot of politicians to run our country, did they not fail us ever? So, I'm saying 'trust' is a complete other layer of protection like NDA, and my question was not directed to it. My question is rather directed towards technical measures we can take to avoid such a thing from happening.

答:
Use source control. There is nothing a remote developer can do that will not be reversible.

Apart from that, depending on what you mean by "protect", you should have the right contract with him, including NDA.

On another note - why hire an external developer in the first place, if you are not going to trust him?

Update:

Now that you have clarified that by "protect" you mean "not allow to get the sensitive code", my points above about NDAs and trust remain unchanged.

When it comes to source control, if you have several repositories where you have different levels of code (boilerplate - not sensitive, infrastructure - not sensitive, business logic - very sensitive etc...), you can select which repository to give access to this developer. Of course, this depends on whether you can segregate like this and still have a working application (for this to work, some repositories may require having binary dependencies checked-in - these would be compile artefacts from the sensitive repositories). The feasibility of this depends on what you want the developer to work on.

Even with the scheme described above, you need to consider decompilation and reverse engineering of code (this is always possible with a determined enough attacker) so obfuscation of code/binaries may be another thing you need to consider (again, this is not perfect - with enough know how and determination, the best obfuscators can be defeated).

In essence, my point is that if you want to protect a sensitive code base, you should only give access to the sensitive portions to people you trust.


答: Make a contract with the external developer that he's not allowed to give out the source code to outsiders nor keep it after his hire has ended. If he violates the contract, then it's a legal case. You surely can't protect source code from the developers' eyes though!</p>

Title: How to protect source code from remote developers?

Body:
My company is going to hire an external developer to create some new modules and fix some bugs in our PHP software.

We have never hired an external developer by the hour before. How can we protect the source code? We are not comfortable giving out source code and were thinking that everything remained under a surveillance enabled VPN which external developer would log in to.

Has anyone solved this problem before? If so, how?

Edit: We want the developer to see/modify the code but under surveillance and on our machine remotely. Does anybody have a similar setup?

Edit 2: NDA is just a formality. IMO, even people who are in favor of NDAs know that it'll do nothing to protect their property.

Edit 3: Let me clarify that we aren't worried about the developer copying an algorithm or a solution from the code. Code is coming out of his brain, so naturally he is the creator and he can create that again. But our code is built over several years with tens of developers working on it. Let's say I hire an incompetent programmer by mistake, who steals our years of work and then sells it to the competitor. That can make us lose our cutting edge. I know this is rare, but such a threat has to be taken under consideration if you're in business. I'll make points of my comments so its easy for everyone to communicate:

Why NDA sucks? Take this scenario, if anyone is capable of suggesting a solution to this scenario I will consider the NDA effective. Ok, here goes:
We hire 2 external developers, one of them sells our code as it is to someone else after a year. You are no longer in touch with any of the developers, how are you supposed to find out who ripped you off? NDA does provide a purpose, but you can't rely completely on that. At least we cannot.

I did not meant to offend anyone while I was posting this question, even though unintentionally I did. But again to people answering/commenting like 'I will never ever work with you' or that Men-in-black-gadget thingy: It's not about you, it's a thread about how feasible a given technical solution would be. And if anyone in this community has worked under such an environment.

About 'Trust', of course we won't hire anyone we do not trust. But is that it? Can't someone be deceitful at first? We all trusted a lot of politicians to run our country, did they not fail us ever? So, I'm saying 'trust' is a complete other layer of protection like NDA, and my question was not directed to it. My question is rather directed towards technical measures we can take to avoid such a thing from happening.


问:
Should a programmer fix someone else's failed build?
One programmer committed some work to the SVN repository, then went home. After he left, the Hudson automatic build failed. Another programmer saw this, and after looking through the code changes, detected that the problem was the absence of one library. He added this library to SVN and the next build completed successfully.

Did the second programmer do the right thing or should he have just waited until the first programmer fixed the issue?

答:
First, 'went home' is an anachronism. Programmers don't go home anymore -- they are just either online or offline. You could ping and wait.

More seriously, there are actually two parts to the question. 'looking through the code changes' is fine; rest may not be the right thing to do. What if his judgement of a missing library was wrong?


答:
As usual "it depends". Really it mainly depends on whether you need these tools to get your particular jobs done. However you should know what these particular technologies allow you to achieve otherwise you could end up reinventing the wheel to get a particular job done or creating non-standard parts to get the job done.

For example, if you don't know LINQ you could achieve the same result by using loops to query a dataset etc. but this would probably not have as good performance and take 10 lines of code where as LINQ would take 2.

I don't know every .net related tech going, e.g. I don't know WWF (Workflow) at all because its never been needed, but I do know what it is used for!

TL;DR you should know what tools are used for even if you don't know how to use that tool.


答:
It sounds like there has been a communication breakdown between you and your customer.

I get the sense that the problems/delays are actually being blamed on
  "that subcontractor"

Getting the sense ? If no one has come to you with an issue stop imagining them.

Speaking from experience as a freelancer, its your role to find the solution and work constructively with your client. Its no good blaming them, you should enable them to give them what you require.

A second approach regarding the specific problems

unfinished photoshop files completely skipping half of the app and
  with every page having undecided A/B options

Finish them yourself and take control of the work, making sure you implement solutions in in an easy to change manner.


问:
How do you run a sprint retrospective to maximize participation and honesty? And what about follow up on action items?
I've seen it done as a free-for-all where the scrum master just asks everyone to throw out comments. Or a time-boxed session where "anonymous" comments are posted on the walls bucketed by category. My current team is constrained by being spread out, so it has be done online/over the phone. What is everyone's best experience with soliciting constructive feedback? And how do you follow through on action items for improvement?</p>

答:
Generally about the retrospective, I highly recommend this book : http://pragprog.com/book/dlret/agile-retrospectives

It is a short and very practical book. It explains all sorts of games, exercise and techniques to gather feedback in the different context your retrospective might be, the kind of team you have, and the current situation of your project.
It helps a lot keeping a good dynamic in this kind of meeting, balancing the positive and negative feedback and analyzing properly all that info you have gathered.

I would also recommend The back of the napkin.

More specifically about your question, we dont know much about your environment, but keeping the chickens (authority) out of the retrospective can remove the 'fear' of sharing.

Another thing that has proven to work is to start the meeting with a simple 'check-in question'. Everyone express his feeling about the iteration in 1/2 word, no more, no question asks (yet). That breaks the ice and get everyone started on sharing/talking.

If people are not comfortable sharing in front of everyone, maybe make pairs of people sharing to eachother, and then everyone reports their findings/ideas?


答:
You should never allow outsourced or I would argue temporary contractors access to any code that is highly proprietary, extremely sensitive, or code that contains valuable algorithms or other business secrets.

Even having them sign an NDA or a Non-Compete is likely useless as they commonly do not hold up in court.

This mad orgy of offshoring all development possible is a pox on the industry and self defeating strategy.  Offshoring or outsourcing makes sense with menial, tedious, or well solved and understood development problems.  It was never meant to save money on the unique work and bread and butter.

When you lay your companies most proprietary and industry specific code to bare for the world to see then you are literally inviting future competitors to rise and challenge you.

With that being said, do a close evaluation of your code base and decide what code you would not like them to see and see how easy it would be to restrict their access to this through source control.  If there is nothing to troublesome or worrying about your code then the application likely has very little substaintial value to steal.

Many companies like to think their codebase is special and highly proprietary when in reality it is little more than a simple CRUD app.  In which case you might be more concerned with exposing all of your business requirements and possibly your data model, where the most business knowledge would be stored.  This can be mitigated by focusing on giving them access to presentation code and restricting access to data access code.


答:
This happens a lot on contract jobs, especially when there's a disconnect between the actual end client and IT/IS management. From the sound of things, yes, you probably are being setup as the fall guy for a project failure. I've been there more than once myself.

The first thing to do is find out why the project is at risk if you can. Sometimes the answer might be surprising and it might not blowback on you.

For example, I found out, on two separate occasions, management wanted the project to fail. One was due to internal political reasons (one manager sabotaging another) and the other was to put on a show for regulatory compliance since a project "failure" would delay implementation and penalties while lobbyists worked their magic in the halls of government.

When you understand the reason why, then you can plan your next step. It may be to find a new job or to make a lateral move. For now, just quietly do the work you've been assigned and don't make any unnecessary waves. However, you should strongly defend yourself if you see anyone lying about you or trying to sabotage you.


答:
This is SUCH a common problem but the reality of being the contractor or vendor.

My advice to you is not to worry too much about blame.  The worst that could happen is that you still get paid at the end of the project and you don't use them for a testimonial. Blame gets you nowhere in business and is more of a political action than a business action.  Good business people ignore it, and focus on the problem and the best way to approach it with limited information.

Be professional, courteous and go above and beyond what you were called to do.  If the design pack is incomplete then make every attempt to fill in the gaps and present this to the client for approval.  Typically it works to word it such as,

I noticed that X didn't account for the Y situation in the design pack.  I thought it might be a good idea to try something like this.  Let me know what you think.

Finally, make sure that you maintain a complete record of all correspondence with the clients, including email and meeting minutes.  Avoid informal phone conversations unless you can record them.  Having this information at your disposal can help defend you if somebody is looking to make you the fallout boy.

Good luck.


问:
Why would I learn C++11, having known C and C++?
I am a programmer in C and C++, although I don't stick to either language and write a mixture of the two. Sometimes having code in classes, possibly with operator overloading, or templates and the oh so great STL is obviously a better way. Sometimes use of a simple C function pointer is much much more readable and clear. So I find beauty and practicality in both languages. I don't want to get into the discussion of "If you mix them and compile with a C++ compiler, it's not a mix anymore, it's all C++" I think we all understand what I mean by mixing them. Also, I don't want to talk about C vs C++, this question is all about C++11.

C++11 introduces what I think are significant changes to how C++ works, but it has introduced many special cases, exceptions and irregularities that change how different features behave in different circumstances, placing restrictions on multiple inheritance, identifiers that act as keywords, extensions of string literals, lambda function variable capturing, etc.

I know that at some point in the future, when you say C++ everyone would assume C++11. Much like when you say C nowadays, you most probably mean C99. That makes me consider learning C++11. After all, if I want to continue writing code in C++, I may at some point need to start using those features simply because my colleagues have.

Take C for example. After so many years, there are still many people learning and writing code in C. Why? Because the language is good. What good means is that, it follows many of the rules to create a good programming language. So besides being powerful (which easy or hard, almost all programming languages are), C is regular and has few exceptions, if any. C++11 however, I don't think so. I'm not sure that the changes introduced in C++11 are making the language better.

So the question is: Why would I learn C++11?

答:
Actually the OP have some points, as of the most of the answers. But they are "distant" in vision. C++ (including C subset) has a long history where a number of features had been added across the time, some of them used more or less frequently and -through teir useage and mistakes- perfectioned into others and others.

Sometimes it happens that, after introducing a new feature, an old one is anymore needed, or feels in contradiction with it. A "clean" language should be self-consistent as it is, and not anymore needed features should be removed.

But adding doesn't destroy anything. Removing (or changing) breaks existing code that it is still in production, so whatever feature you add, you must take care to don't break existing code (in particular, don't break it silently, making it doing different things as intended).

Do you have to learn all of that?
Yes, because all features are -in the good or bad, sooner or later- used.
Whether this is a good thing for language "quality" (admitting there is an objective measure for it) is another story: how long should backward compatibility retained? hard to find an answer, when someone say 3 years and some other say 50.

The alternative to keep C++ more "regular" is... break it more often, with a scratch restart. But it will be no C++ anymore.

There are attempts to do that as well (think to D, for example: much much more orthogonal as C++ (even 11) actually is), but how popular are them? On of the reasons of their difficult in having momentum is the incompatibility with many existing code that still has to run.

C++11, to me, is clearly a compromise between new needs and backward compatibility. That resulted in a certain "messiness" of its specs and implementation. Until the cost of that "messiness" is less than the cost of incompatibility... you have to leave with that compromise.

If you cannot anymore tolerate it, ... better to consider another younger language. C++ simply cannot be simplified in that sense. Not at this age.

OwnerDisplayName: anon


问:
Where did the notion of "one return only" come from?
I often talk to programmers who say "Don't put multiple return statements in the same  method." When I ask them to tell me the reasons why, all I get is "The coding standard says so." or "It's confusing." When they show me solutions with a single return statement, the code looks uglier to me. For example:

if (condition)
   return 42;
else
   return 97;
```

<p>"<em>This is ugly, you have to use a local variable!</em>"</p>

<pre class="lang-c prettyprint-override"><code>int result;
if (condition)
   result = 42;
else
   result = 97;
return result;
</code>```

How does this 50% code bloat make the program any easier to understand? Personally, I find it harder, because the state space has just increased by another variable that could easily have been prevented.

Of course, normally I would just write:

return (condition) ? 42 : 97;
```

But many programmers eschew the conditional operator and prefer the long form.

Where did this notion of "one return only" come from? Is there a historical reason why this convention came about?

答:
"Single Entry, Single Exit" originated with the Structured Programming revolution of the early 1970s, which was kicked off by Edsger W. Dijkstra's letter to the Editor, GOTO Statement Considered Harmful.  The concepts behind structured programming were laid out in detail in the classic book Structured Programming by Ole Johan-Dahl, Edsger W. Dijkstra, and Charles Anthony Richard Hoare.

"GOTO Statement Considered Harmful" is required reading, even today.  "Structured Programming" is dated, but still very, very rewarding, and should be at the top of any developer's "Must Read" list, far above anything from e.g. Steve McConnell.  (Dahl's section lays out the basics of classes in Simula 67, which are the technical foundation for classes in C++ and all of object-oriented programming.)

ContentLicense: CC BY-SA 4.0


答: Even if you decide to ignore the new C++11 features, you'll still benefit from them because the C++ Standard Library will use them. For instance, in C++ 98 having a variable of type vector<string> was potentialy a performance disaster because of the number of copies needed to be made when the vector grows. With C++11 move constructor, it is a non-issue. In fact, I wish C++11 brought us more new features, not less  - especially in the Standard Library.

Title: Why would I learn C++11, having known C and C++?

Body:
I am a programmer in C and C++, although I don't stick to either language and write a mixture of the two. Sometimes having code in classes, possibly with operator overloading, or templates and the oh so great STL is obviously a better way. Sometimes use of a simple C function pointer is much much more readable and clear. So I find beauty and practicality in both languages. I don't want to get into the discussion of "If you mix them and compile with a C++ compiler, it's not a mix anymore, it's all C++" I think we all understand what I mean by mixing them. Also, I don't want to talk about C vs C++, this question is all about C++11.

C++11 introduces what I think are significant changes to how C++ works, but it has introduced many special cases, exceptions and irregularities that change how different features behave in different circumstances, placing restrictions on multiple inheritance, identifiers that act as keywords, extensions of string literals, lambda function variable capturing, etc.

I know that at some point in the future, when you say C++ everyone would assume C++11. Much like when you say C nowadays, you most probably mean C99. That makes me consider learning C++11. After all, if I want to continue writing code in C++, I may at some point need to start using those features simply because my colleagues have.

Take C for example. After so many years, there are still many people learning and writing code in C. Why? Because the language is good. What good means is that, it follows many of the rules to create a good programming language. So besides being powerful (which easy or hard, almost all programming languages are), C is regular and has few exceptions, if any. C++11 however, I don't think so. I'm not sure that the changes introduced in C++11 are making the language better.

So the question is: Why would I learn C++11?


问:
What are the dangers of setting an unlimited database transaction life timeout?
We have a process that may last between a few seconds and a few minutes. As such, we may update just a few records or thousands of them. The process can be committed only when everything has been done correctly.

Recently we have begun having problems when attempting to commit transaction as they were marked as "rollbackOnly". I've discovered that in fact the transaction had been marked "rollbackOnly" because it had timed out a bit earlier (not clear to see in the log files as our application server is Websphere and its transaction manager just gives a one-line warning), and as such it could not be committed. Of course it makes sense that you cannot commit a transaction that has timed out.

The problem is in fact that we never set the transaction timeout in transaction definitions, and that in that case the value of the timeout is the one set at the application server level (see Websphere's transaction settings, the paragraph on "Total transaction lifetime timeout"). That value is 2 minutes and sometimes we exceed it.

Now, that explains the setting (and in case somebody encounters a "rollbackOnly" transaction, I've provided here a possible explanation).

I'm tempted to increase the timeout, but I've also seen in the documentation that the timeout can be set to 0, meaning there is no timeout.

As such, my question is: what are the dangers of setting an unlimited transaction life timeout ?

Note that I'm aware of programmatic/database solutions to my problem like for example working on temporary tables, and reversing data from temporary tables to the real tables when we know everything has been done right (using PL/SQL for example). I'm just curious about the transaction timeout thing.

答:
The problem is you may lock resources for a long time.  Even if your row locks don't get escalated to table locks, you run the risk of locking groups of records in both the tables and any associated indexes, which can prevent other processes from accessing them.  And if your program hangs or gets killed without closing the connection, those tables could be locked for hours.

You could try raising the timeout to (say) five minutes and see if that helps, but I'd be really wary about disabling it completely.


问:
Should a method comment include both a summary and return description when they're often so similar?
I'm a proponent of properly documented code, and I'm well aware of the possible downsides of it. That is outside of the scope of this question.

I like to follow the rule of adding XML comments for every public member, considering how much I like IntelliSense in Visual Studio.

There is one form of redundancy however, which even an excessive commenter like me is bothered by. As an example take List.Exists().

```<code>/// <summary>
///     Determines whether the List<T> contains elements
///     that match the conditions defined by the specified predicate.
/// </summary>
/// <returns>
///     true if the List<T> contains one or more elements that match the
///     conditions defined by the specified predicate; otherwise, false.
/// </returns>
public bool Exists( Predicate<T> match )
{
    ...
}
</code>```

Summary and returns are basically saying the same thing. I often end up writing the summary more from a returns perspective, dropping the returns documentation altogether.

Returns true when the List contains elements that match the
  conditions defined by the specified predicate, false otherwise.

Additionally, the returns documentation doesn't show up in IntelliSense, so I rather write any immediately relevant information in summary.

Why would you ever need to document returns separately from summary?

Any information on why Microsoft adopted this standard?

答:
Why would you ever need to document returns separately from summary?

I think if the summary part is really long and descriptive, it might be useful to have a separate, brief returns part at the end.

I usually write just the  part in my own code, wording it the way you did saying "Returns _".

I put in any remarks that a caller should know that aren't obvious from the method name and parameters (and their names).  Hopefully though, the method name and parameters make it obvious enough that the comment can be very brief.

Body:
Why would you ever need to document returns separately from summary?

I think if the summary part is really long and descriptive, it might be useful to have a separate, brief returns part at the end.

I usually write just the <summary> part in my own code, wording it the way you did saying "Returns _".

I put in any remarks that a caller should know that aren't obvious from the method name and parameters (and their names).  Hopefully though, the method name and parameters make it obvious enough that the comment can be very brief.


问:
How to quickly search through a very large list of strings / records on a database
I have the following problem: I have a database containing more than 2 million records.
Each record has a string field X and I want to display a list of records for which field X contains a certain string. Each record is about 500 bytes in size.

To make it more concrete: in the GUI of my application I have a text field where I can enter a string. Above the text field I have a table displaying the (first N, e.g. 100) records that match the string in the text field. When I type or delete one character in the text field, the table content must be updated on the fly.

I wonder if there is an efficient way of doing this using appropriate index structures and / or caching. As explained above, I only want to display the first N items that match the query. Therefore, for N small enough, it should not be a big issue loading the matching items from the database. Besides, caching items in main memory can make retrieval faster.

I think the main problem is how to find the matching items quickly, given the pattern string. Can I rely on some DBMS facilities, or do I have to build some in-memory index myself? Any ideas?

EDIT

I have run a first experiment. I have split the records into different text files (at most 200 records per file) and put the files in different directories (I used the content of one data field to determine the directory tree). I end up with about 50000 files in about 40000 directories. I have then run Lucene to index the files. Searching for a string with the Lucene demo program is pretty fast. Splitting and indexing took a few minutes: this is totally acceptable for me because it is a static data set that I want to query.

The next step is to integrate Lucene in the main program and use the hits returned by Lucene to load the relevant records into main memory.

答: The technology you are looking for is full-text indexing. Most RDBMS have some sort of built-in capabilities which could work here, or you could use something like Lucene if you wanted to get fancier and/or just run it in memory.</p>


答:
My usage:

describes what the method does (to get the <returns>).

<returns> describes the return value.

Links to MSDN: . <returns>

Title: Should a method comment include both a summary and return description when they're often so similar?

Body:
I'm a proponent of properly documented code, and I'm well aware of the possible downsides of it. That is outside of the scope of this question.

I like to follow the rule of adding XML comments for every public member, considering how much I like IntelliSense in Visual Studio.

There is one form of redundancy however, which even an excessive commenter like me is bothered by. As an example take List.Exists().

```<code>/// <summary>
///     Determines whether the List<T> contains elements
///     that match the conditions defined by the specified predicate.
/// </summary>
/// <returns>
///     true if the List<T> contains one or more elements that match the
///     conditions defined by the specified predicate; otherwise, false.
/// </returns>
public bool Exists( Predicate<T> match )
{
    ...
}
</code>```

Summary and returns are basically saying the same thing. I often end up writing the summary more from a returns perspective, dropping the returns documentation altogether.

Returns true when the List contains elements that match the
  conditions defined by the specified predicate, false otherwise.

Additionally, the returns documentation doesn't show up in IntelliSense, so I rather write any immediately relevant information in summary.

Why would you ever need to document returns separately from summary?

Any information on why Microsoft adopted this standard?

Body:
My usage:

<summary>describes what the method does (to get the <returns>).

<returns> describes the return value.

Links to MSDN: <summary>. <returns>


答:
I would like add on top of Wyatt Barnett's answer that a RDBMS solution with full-text indexing on the appropriate column will work, but if you want to utilize a local cache of previously fetched records then you need to a plan to utilize these cached records to your advantage.

One option is to collect the unique identifiers of these records that you EXPLICITLY do not want to retrieve from the query and include them, possibly in a NOT IN or a NOT EXISTS.

Word of caution though, using NOT IN or NOT EXISTS tends not to be cheap and MAY negatively influence your query performance or query plan depending on what database engine you are utilizing.  Run an explain plan on your final query to ensure that all of your indexes on the affected columns are being utilized.

It also doesn't hurt to do a performance comparison between the two approaches to see which is faster.  You may be surprised to find out that maintaining a local cache and filtering those from your query explicitly may have worse performance than a finely tuned query that fetches all records.

Title: How to quickly search through a very large list of strings / records on a database

Body:
I have the following problem: I have a database containing more than 2 million records.
Each record has a string field X and I want to display a list of records for which field X contains a certain string. Each record is about 500 bytes in size.

To make it more concrete: in the GUI of my application I have a text field where I can enter a string. Above the text field I have a table displaying the (first N, e.g. 100) records that match the string in the text field. When I type or delete one character in the text field, the table content must be updated on the fly.

I wonder if there is an efficient way of doing this using appropriate index structures and / or caching. As explained above, I only want to display the first N items that match the query. Therefore, for N small enough, it should not be a big issue loading the matching items from the database. Besides, caching items in main memory can make retrieval faster.

I think the main problem is how to find the matching items quickly, given the pattern string. Can I rely on some DBMS facilities, or do I have to build some in-memory index myself? Any ideas?

EDIT

I have run a first experiment. I have split the records into different text files (at most 200 records per file) and put the files in different directories (I used the content of one data field to determine the directory tree). I end up with about 50000 files in about 40000 directories. I have then run Lucene to index the files. Searching for a string with the Lucene demo program is pretty fast. Splitting and indexing took a few minutes: this is totally acceptable for me because it is a static data set that I want to query.

The next step is to integrate Lucene in the main program and use the hits returned by Lucene to load the relevant records into main memory.


答:
Simply put: You don't.

Professional developers take this kind of thing seriously. They are well aware of the importance of the code, and the consequences of stealing bits and pieces of it. If they are caught, it is a stain on their reputation as a professional, and could affect their livelihood in a meaningful manner.

Others have suggested an NDA, and while it is not a technological means of "protecting the code", it is often all that is needed. Functionally, there is no difference between internal and external programmers. You have to cede some amount of trust to all of them.


答:
On the one hand, single return statements make logging easier, as well as forms of debugging that rely on logging. I remember plenty of times I had to reduce the function into single return just to print out the return value at a single point.

  int function() {
     if (bidi) { print("return 1"); return 1; }
     for (int i = 0; i < n; i++) {
       if (vidi) { print("return 2"); return 2;}
     }
     print("return 3");
     return 3;
  }
```

On the other hand, you could refactor this into function() that calls _function() and logs the result.

Title: Where did the notion of "one return only" come from?

Body:
I often talk to programmers who say "Don't put multiple return statements in the same  method." When I ask them to tell me the reasons why, all I get is "The coding standard says so." or "It's confusing." When they show me solutions with a single return statement, the code looks uglier to me. For example:

if (condition)
   return 42;
else
   return 97;
```

<p>"<em>This is ugly, you have to use a local variable!</em>"</p>

<pre class="lang-c prettyprint-override"><code>int result;
if (condition)
   result = 42;
else
   result = 97;
return result;
</code>```

How does this 50% code bloat make the program any easier to understand? Personally, I find it harder, because the state space has just increased by another variable that could easily have been prevented.

Of course, normally I would just write:

return (condition) ? 42 : 97;
```

But many programmers eschew the conditional operator and prefer the long form.

Where did this notion of "one return only" come from? Is there a historical reason why this convention came about?

Body:
On the one hand, single return statements make logging easier, as well as forms of debugging that rely on logging. I remember plenty of times I had to reduce the function into single return just to print out the return value at a single point.

  int function() {
     if (bidi) { print("return 1"); return 1; }
     for (int i = 0; i < n; i++) {
       if (vidi) { print("return 2"); return 2;}
     }
     print("return 3");
     return 3;
  }

On the other hand, you could refactor this into function() that calls _function() and logs the result.


答:
There are two ways of working with people:

Control:

monitor all their actions

dictate their processes

restrict their freedoms

keep them exchangeable

make a clear distinction between them and you

Collaboration

respect their freedom

trust them

build a long term relationship that both sides benefit from

work as a team

You go choose. But IMHO you shouldn't expect people, whom you openly treat as if they were potential criminals, to treat you fair in response. So here is a crazy idea:

be forthcoming and fair

actively engage in creating mutual trust and loyalty

don't be greedy and pay on time

If you make people feel, that they are in a satisfying, productive and lucrative business relationship, they will stick to you. And that is exactly the same for contractors and employees. Nothing can stop your employees from quitting and taking the source code with them, except an incentive to stay.

So make your work pleasant and worth working on, rather than wasting resources on freakish control.


问:
Simulating double-click, how long should I wait between clicks?
I'm simulating a double click programmatically and I want to have a slight pause between both clicks in order to better simulate a real user.

I know the interval should be less than GetDoubleClickTime but am not sure what would be a good time to choose. Does anyone know of any data on how fast a typical person performs a double-click?

I was thinking in the direction GetDoubleClickTime()/3 but of course the magic number seems a bit iffy.

答:
Fire up an audio recording program in a quiet space and double click your mouse a few times. The time distance between the two peaks is how long it takes. If you're feeling really intense, you can calculate the statistical deviation among many clicks.

Me? I'd go with your thought of GetDoubleClickTime()/3. I think you're over-analyzing a double click.


答:
Does anyone know of any data on how fast a typical person performs a double-click? - doubleclick interval is an adjustable OS user setting.

Our user might not have configured his machine typically.

I don't know what's the issue with GetDoubleClickTime() / 3. Even if there was some research proving that an average person doubleclicks 2.56768 time faster than the required minimum speed - 2.56768 is still a magic number of sorts...

Title: Simulating double-click, how long should I wait between clicks?

Body:
I'm simulating a double click programmatically and I want to have a slight pause between both clicks in order to better simulate a real user.

I know the interval should be less than GetDoubleClickTime but am not sure what would be a good time to choose. Does anyone know of any data on how fast a typical person performs a double-click?

I was thinking in the direction GetDoubleClickTime()/3 but of course the magic number seems a bit iffy.


答:
You can infer one from another, but those two sections remain separate, because it helps to focus on the one which interests the person when reviewing/using the code.

Taking your example, I would rather write:

```<code>/// <summary>
/// Determines whether the List<T> contains elements that match the conditions
/// defined by the specified predicate.
/// </summary>
/// <returns>
/// A value indicating whether at least one element matched the predicate.
/// </returns>
public bool Exists(Predicate<T> match)
{
    ...
}
</code>```

If I'm reviewing this code and I want to know what the method does, I read the summary, and that's all what I care about.

Now, let's imagine I'm using your method and the return value I receive is strange, given the input. Now, I don't really want to know what the method does, but I do want to know something more about the return value. Here, <returns/> section helps, and I don't need to read the summary.

Again, in this example, you can infer the summary from <returns/>, and infer the expected return value from the summary. But taking the same argument to the extreme, there is no need to document your method at all in this case: the name of the method, put inside List<T>, with Predicate<T> match as a sole argument is quite explicit itself.

Remember, the source code is written once but read plenty of times. If you can reduce excise for the further readers of your code, while spending ten seconds writing an additional sentence in the XML documentation, do it.

Body:
You can infer one from another, but those two sections remain separate, because it helps to focus on the one which interests the person when reviewing/using the code.

Taking your example, I would rather write:

/// <summary>
/// Determines whether the List<T> contains elements that match the conditions
/// defined by the specified predicate.
/// </summary>
/// <returns>
/// A value indicating whether at least one element matched the predicate.
/// </returns>
public bool Exists(Predicate<T> match)
{
    ...
}

If I'm reviewing this code and I want to know what the method does, I read the summary, and that's all what I care about.

Now, let's imagine I'm using your method and the return value I receive is strange, given the input. Now, I don't really want to know what the method does, but I do want to know something more about the return value. Here, <returns/> section helps, and I don't need to read the summary.

Again, in this example, you can infer the summary from <returns/>, and infer the expected return value from the summary. But taking the same argument to the extreme, there is no need to document your method at all in this case: the name of the method, put inside List<T>, with Predicate<T> match as a sole argument is quite explicit itself.

Remember, the source code is written once but read plenty of times. If you can reduce excise for the further readers of your code, while spending ten seconds writing an additional sentence in the XML documentation, do it.


问:
How to you "sell" support as an career option
We find it relatively easy to hire developers to work on various projects.

The problem arises when the project is finished but still needs to be supported.

We really battle to get people to join the support team. It's seen as dead-end, career-limiting, boring, second-class etc.

Currently, we get round this by getting the project team to assign some of their team to the support team for a while. Part of the assignment is to do a "brain dump" of the project so that the support team understands it. This works as long as the assignment is only for a fixed period.

Trying to hire people to work in support full-time is a problem. There are few applications and the calibre is not particularly high.

(The financial reality though is that support can be very lucrative for a company and once you get a reputation, you get approached by other companies to do their support even though you weren't involved in the original development.)

答:
Don't

To me the best option here is not to separate the developers into support and non-support in the first place.  IMHO there are three main reasons:

people that write things that are hard to support do not learn until they have to support these things.

people doing only support will usually take the path of least resistance in correcting an error even if it hampers future work.

the theoretical time savings in staying on schedule in the new development by having the separate support developers is always more than consumed by having to provide instruction or repeat work.

Within the dev team you can have people that have maintenance tasks or take an approach of letting the maintenance tasks be the training grounds for the newer team members, but if you try to sell it as the long term goal of the position you will only attract people that will give you heartburn or people that will soon be on their way out.

There always needs to be a clear path to getting out of a 100% support dev role, and/or a certain percentage of new development work to keep good people interested.

You do not want to attract the sort of people that are happy in that role indefinitely and you are never going to convince otherwise good devs to take that role and keep it long term unless you are offering the kind of pay that would never have them considering a career move.

ContentLicense: CC BY-SA 2.5


问:
Is using nested try-catch blocks an anti-pattern?
Is this an antipattern? It is an acceptable practice?</p>

```<code>    try {
        //do something
    } catch (Exception e) {
        try {
            //do something in the same line, but being less ambitious
        } catch (Exception ex) {
            try {
                //Do the minimum acceptable
            } catch (Exception e1) {
                //More try catches?
            }
        }
    }
</code>```

答: I don't think it's automatically an anti-pattern, but I'd avoid it if I can find an easier and cleaner way to do the same thing. If the programming language you're working in has a finally construct, that might help clean this up, in some cases.


答:
This is sometimes unavoidable, especially if your recovery code might throw an exception.

Not pretty, but sometimes there are no alternatives.

Title: Is using nested try-catch blocks an anti-pattern?

Body:
Is this an antipattern? It is an acceptable practice?</p>

```<code>    try {
        //do something
    } catch (Exception e) {
        try {
            //do something in the same line, but being less ambitious
        } catch (Exception ex) {
            try {
                //Do the minimum acceptable
            } catch (Exception e1) {
                //More try catches?
            }
        }
    }
</code>```


答:
The logic is fine - it can make perfect sense in some situations to try a fallback approach, which could itself experience exceptional events.... hence this pattern is pretty much unavoidable.

However I would suggest the following to make the code better:

Refactor the inner try...catch blocks out into separate functions, e.g. attemptFallbackMethod and attemptMinimalRecovery.

Be more specific about the particular exception types that are being caught. Do you really expect any Exception subclass and if so do you really want to handle them all the same way?

Consider whether a finally block might make more sense - this is usually the case for anything that feels like "resource cleanup code"


答:
"Single Entry, Single Exit" was written when most programming was done in assembly language, FORTRAN, or COBOL.  It has been widely misinterpreted, because modern languages do not support the practices Dijkstra was warning against.

"Single Entry" meant "do not create alternate entry points for functions".  In assembly language, of course, it is possible to enter a function at any instruction.  FORTRAN supported multiple entries to functions with the ENTRY statement:

```<code>      SUBROUTINE S(X, Y)
      R = SQRT(X*X + Y*Y)
C ALTERNATE ENTRY USED WHEN R IS ALREADY KNOWN
      ENTRY S2(R)
      ...
      RETURN
      END

C USAGE
      CALL S(3,4)
C ALTERNATE USAGE
      CALL S2(5)
</code>```

"Single Exit" meant that a function should only return to one place: the statement immediately following the call.  It did not mean that a function should only return from one place.  When Structured Programming was written, it was common practice for a function to indicate an error by returning to an alternate location.  FORTRAN supported this via "alternate return":

```<code>C SUBROUTINE WITH ALTERNATE RETURN.  THE '*' IS A PLACE HOLDER FOR THE ERROR RETURN
      SUBROUTINE QSOLVE(A, B, C, X1, X2, *)
      DISCR = B*B - 4*A*C
C NO SOLUTIONS, RETURN TO ERROR HANDLING LOCATION
      IF DISCR .LT. 0 RETURN 1
      SD = SQRT(DISCR)
      DENOM = 2*A
      X1 = (-B + SD) / DENOM
      X2 = (-B - SD) / DENOM
      RETURN
      END

C USE OF ALTERNATE RETURN
      CALL QSOLVE(1, 0, 1, X1, X2, *99)
C SOLUTION FOUND
      ...
C QSOLVE RETURNS HERE IF NO SOLUTIONS
99    PRINT 'NO SOLUTIONS'
</code>```

Both these techniques were highly error prone.  Use of alternate entries often left some variable uninitialized.  Use of alternate returns had all the problems of a GOTO statement, with the additional complication that the branch condition was not adjacent to the branch, but somewhere in the subroutine.

Thanks to Alexey Romanov for finding the original paper. See http://www.cs.utexas.edu/users/EWD/ewd02xx/EWD249.PDF, page 28 (printed page number is 24). Not limited to functions.

Body:
"Single Entry, Single Exit" was written when most programming was done in assembly language, FORTRAN, or COBOL.  It has been widely misinterpreted, because modern languages do not support the practices Dijkstra was warning against.

"Single Entry" meant "do not create alternate entry points for functions".  In assembly language, of course, it is possible to enter a function at any instruction.  FORTRAN supported multiple entries to functions with the ENTRY statement:

      SUBROUTINE S(X, Y)
      R = SQRT(X*X + Y*Y)
C ALTERNATE ENTRY USED WHEN R IS ALREADY KNOWN
      ENTRY S2(R)
      ...
      RETURN
      END

C USAGE
      CALL S(3,4)
C ALTERNATE USAGE
      CALL S2(5)

"Single Exit" meant that a function should only return to one place: the statement immediately following the call.  It did not mean that a function should only return from one place.  When Structured Programming was written, it was common practice for a function to indicate an error by returning to an alternate location.  FORTRAN supported this via "alternate return":

C SUBROUTINE WITH ALTERNATE RETURN.  THE '*' IS A PLACE HOLDER FOR THE ERROR RETURN
      SUBROUTINE QSOLVE(A, B, C, X1, X2, *)
      DISCR = B*B - 4*A*C
C NO SOLUTIONS, RETURN TO ERROR HANDLING LOCATION
      IF DISCR .LT. 0 RETURN 1
      SD = SQRT(DISCR)
      DENOM = 2*A
      X1 = (-B + SD) / DENOM
      X2 = (-B - SD) / DENOM
      RETURN
      END

C USE OF ALTERNATE RETURN
      CALL QSOLVE(1, 0, 1, X1, X2, *99)
C SOLUTION FOUND
      ...
C QSOLVE RETURNS HERE IF NO SOLUTIONS
99    PRINT 'NO SOLUTIONS'

Both these techniques were highly error prone.  Use of alternate entries often left some variable uninitialized.  Use of alternate returns had all the problems of a GOTO statement, with the additional complication that the branch condition was not adjacent to the branch, but somewhere in the subroutine.

Thanks to Alexey Romanov for finding the original paper. See http://www.cs.utexas.edu/users/EWD/ewd02xx/EWD249.PDF, page 28 (printed page number is 24). Not limited to functions.


答:
I actually think it's an antipattern.

In some cases you might want multiple try-catches, but only if you DONT KNOW what kind of error you are looking, eg:

```<code>public class Test
{
    public static void Test()
    {
        try
        {
           DoOp1();
        }
        catch(Exception ex)
        {
            // treat
        }

        try
        {
           DoOp2();
        }
        catch(Exception ex)
        {
            // treat
        }

        try
        {
           DoOp3();
        }
        catch(Exception ex)
        {
            // treat
        }
    }

    public static void Test()
    {
        try
        {
            DoOp1();
            DoOp2();
            DoOp3();
        }
        catch (DoOp1Exception ex1)
        {
        }
        catch (DoOp2Exception ex2)
        {
        }
        catch (DoOp3Exception ex3)
        {
        }
    }
}
</code>```

If you don't know what you're looking for you HAVE to use the first manner, which is IMHO, ugly and not functional. I guess the latter is much better.

So, if you know what KIND of error you are looking for, be specific. No need for nested or multiple try-catches inside the same method.

Body:
I actually think it's an antipattern.

In some cases you might want multiple try-catches, but only if you DONT KNOW what kind of error you are looking, eg:

public class Test
{
    public static void Test()
    {
        try
        {
           DoOp1();
        }
        catch(Exception ex)
        {
            // treat
        }

        try
        {
           DoOp2();
        }
        catch(Exception ex)
        {
            // treat
        }

        try
        {
           DoOp3();
        }
        catch(Exception ex)
        {
            // treat
        }
    }

    public static void Test()
    {
        try
        {
            DoOp1();
            DoOp2();
            DoOp3();
        }
        catch (DoOp1Exception ex1)
        {
        }
        catch (DoOp2Exception ex2)
        {
        }
        catch (DoOp3Exception ex3)
        {
        }
    }
}

If you don't know what you're looking for you HAVE to use the first manner, which is IMHO, ugly and not functional. I guess the latter is much better.

So, if you know what KIND of error you are looking for, be specific. No need for nested or multiple try-catches inside the same method.


答:
This is a side point, but I think it is important. If you application in an on-line application with live users using it, I find it strange that you have transactions that need to update thousands of records while you have users logged on.

Either your database design can be modified or you should consider running a batch process on the background maybe. I suggest you consider this first before changing the database settings.

The danger of changing the setting is as you have mentioned; users can click a mouse or hit enter and wait for long time without response. This is not OK in many cases.

Title: What are the dangers of setting an unlimited database transaction life timeout?

Body:
We have a process that may last between a few seconds and a few minutes. As such, we may update just a few records or thousands of them. The process can be committed only when everything has been done correctly.

Recently we have begun having problems when attempting to commit transaction as they were marked as "rollbackOnly". I've discovered that in fact the transaction had been marked "rollbackOnly" because it had timed out a bit earlier (not clear to see in the log files as our application server is Websphere and its transaction manager just gives a one-line warning), and as such it could not be committed. Of course it makes sense that you cannot commit a transaction that has timed out.

The problem is in fact that we never set the transaction timeout in transaction definitions, and that in that case the value of the timeout is the one set at the application server level (see Websphere's transaction settings, the paragraph on "Total transaction lifetime timeout"). That value is 2 minutes and sometimes we exceed it.

Now, that explains the setting (and in case somebody encounters a "rollbackOnly" transaction, I've provided here a possible explanation).

I'm tempted to increase the timeout, but I've also seen in the documentation that the timeout can be set to 0, meaning there is no timeout.

As such, my question is: what are the dangers of setting an unlimited transaction life timeout ?

Note that I'm aware of programmatic/database solutions to my problem like for example working on temporary tables, and reversing data from temporary tables to the real tables when we know everything has been done right (using PL/SQL for example). I'm just curious about the transaction timeout thing.


答:
Instead of putting your data inside the DB, you can keep them as a set of documents (text files) separately and keep the link (path/url etc.) in the DB.

This is essential because, SQL query by design will be very slow both in sub-string search as well as retrieval.

Now, your problem is formulated as, having to search the text files which contains the set of strings. There are two possibilities here.

Sub-string match
If your text blobs is a single sting or word (without any white space) and you need to search arbitrary sub-string within it. In such cases you need to parse every file to find best possible files that matches. One uses algorithms like Boyer Moor algorithm. See this and this for details. This is also equivalent to grep - because grep uses similar stuff inside. But you may still make at least 100+ grep (worst case 2 million) before returning.

Indexed search.
Here you are assuming that text contains set of words and search is limited to fixed word lengths. In this case, document is indexed over all the possible occurrences of words. This is often called "Full Text search". There are number of algorithms to do this and number of open source projects that can be used directly. Many of them, also support wild card search, approximate search etc. as below :

a. Apache Lucene : http://lucene.apache.org/java/docs/index.html

b. OpenFTS : http://openfts.sourceforge.net/

c. Sphinx http://sphinxsearch.com/

Most likely if you need "fixed words" as queries, the approach two will be very fast and effective.


问:
Why do people still say Java is slow?
For a long time in SO and in other places Java has the reputation of being slow. From jokes to many comments in questions and answers, people still believe Java is slow based solely on experience with it in the 90s.

This is my issue: we have disproved (most) of the reasons that people believe Java is slow. Outside of small things, Java is pretty fast.

So why is it that people still refuse to believe Java is fast now? Is it part of their mindset that anything thats not C/C++ is slow? Is it because people don't check over time? Is it because people are just biased?

答:
Another point for "slowness" of Java is the 64bit runtime.

I've heard some people complain that Java is very slow for them on 64bit computers. <s>As it turns out, 64bit Java runtime uses server JVM which compiles whole program before starting.</s>

HERE is explanation why 64bit  VM starts slower.

For example on Windows:

```<code>C:\> java -version
java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b06)
Java HotSpot(TM) 64-Bit Server VM (build 17.0-b16, mixed mode)
</code>```

Title: Why do people still say Java is slow?

Body:
Another point for "slowness" of Java is the 64bit runtime.

I've heard some people complain that Java is very slow for them on 64bit computers. <s>As it turns out, 64bit Java runtime uses server JVM which compiles whole program before starting.</s>

HERE is explanation why 64bit  VM starts slower.

For example on Windows:

C:\> java -version
java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b06)
Java HotSpot(TM) 64-Bit Server VM (build 17.0-b16, mixed mode)


答:
Support is a difficult job, no body likes to listen to people complain all day. Finding good people can take time but once you have then you need to keep them by

Pay good money, even well above industry rates to keep good people

Provide good working environment, little things like work supplied lunch and drinks help

Don't cram all your support staff into a small, noisy room

Title: How to you "sell" support as an career option

Body:
We find it relatively easy to hire developers to work on various projects.

The problem arises when the project is finished but still needs to be supported.

We really battle to get people to join the support team. It's seen as dead-end, career-limiting, boring, second-class etc.

Currently, we get round this by getting the project team to assign some of their team to the support team for a while. Part of the assignment is to do a "brain dump" of the project so that the support team understands it. This works as long as the assignment is only for a fixed period.

Trying to hire people to work in support full-time is a problem. There are few applications and the calibre is not particularly high.

(The financial reality though is that support can be very lucrative for a company and once you get a reputation, you get approached by other companies to do their support even though you weren't involved in the original development.)


问:
Avoiding new operator in JavaScript -- the better way
Warning: This is a long post.

Let's keep it simple. I want to avoid having to prefix the new operator every time I call a constructor in JavaScript. This is because I tend to forget it, and my code screws up badly.

The simple way around this is this...

```<code>function Make(x) {
  if ( !(this instanceof arguments.callee) )
  return new arguments.callee(x);

  // do your stuff...
}
</code>```

But, I need this to accept variable no. of arguments, like this...

```<code>m1 = Make();
m2 = Make(1,2,3);
m3 = Make('apple', 'banana');
</code>```

The first immediate solution seems to be the 'apply' method like this...

```<code>function Make() {
  if ( !(this instanceof arguments.callee) )
    return new arguments.callee.apply(null, arguments);

  // do your stuff
}
</code>```

This is WRONG however -- the new object is passed to the apply method and NOT to our constructor arguments.callee.

Now, I've come up with three solutions. My simple question is: which one seems best. Or, if you have a better method, tell it.

First – use eval() to dynamically create JavaScript code that calls the constructor.

```<code>function Make(/* ... */) {
  if ( !(this instanceof arguments.callee) ) {
    // collect all the arguments
    var arr = [];
    for ( var i = 0; arguments[i]; i++ )
      arr.push( 'arguments[' + i + ']' );

    // create code
    var code = 'new arguments.callee(' + arr.join(',') + ');';

    // call it
    return eval( code );
  }

  // do your stuff with variable arguments...
}
</code>```

Second – Every object has __proto__ property which is a 'secret' link to its prototype object. Fortunately this property is writable.

```<code>function Make(/* ... */) {
  var obj = {};

  // do your stuff on 'obj' just like you'd do on 'this'
  // use the variable arguments here

  // now do the __proto__ magic
  // by 'mutating' obj to make it a different object

  obj.__proto__ = arguments.callee.prototype;

  // must return obj
  return obj;
}
</code>```

Third – This is something similar to second solution.

```<code>function Make(/* ... */) {
  // we'll set '_construct' outside
  var obj = new arguments.callee._construct();

  // now do your stuff on 'obj' just like you'd do on 'this'
  // use the variable arguments here

  // you have to return obj
  return obj;
}

// now first set the _construct property to an empty function
Make._construct = function() {};

// and then mutate the prototype of _construct
Make._construct.prototype = Make.prototype;
</code>```

eval solution seems clumsy and comes with all the problems of "evil eval".

__proto__ solution is non-standard and the "Great Browser of mIsERY" doesn't honor it.

The third solution seems overly complicated.

But with all the above three solutions, we can do something like this, that we can't otherwise...

```<code>m1 = Make();
m2 = Make(1,2,3);
m3 = Make('apple', 'banana');

m1 instanceof Make; // true
m2 instanceof Make; // true
m3 instanceof Make; // true

Make.prototype.fire = function() {
  // ...
};

m1.fire();
m2.fire();
m3.fire();
</code>```

So effectively the above solutions give us "true" constructors that accept variable no. of arguments and don't require new. What's your take on this.

-- UPDATE --

Some have said "just throw an error". My response is: we are doing a heavy app with 10+ constructors and I think it'd be far more wieldy if every constructor could "smartly" handle that mistake without throwing error messages on the console.

答:
Firstly arguments.callee is deprecated in ES5 strict so we don't use it. The real solution is rather simple.

You don't use new at all.

```<code>var Make = function () {
  if (Object.getPrototypeOf(this) !== Make.prototype) {
    var o = Object.create(Make.prototype);
    o.constructor.apply(o, arguments);
    return o;
  }
  ...
}
</code>```

That's a right pain in the ass right?

Try enhance

```<code>var Make = enhance(function () {
  ...
});

var enhance = function (constr) {
  return function () {
    if (Object.getPrototypeOf(this) !== constr.prototype) {
      var o = Object.create(constr.prototype);
      constr.apply(o, arguments);
      return o;
    }
    return constr.apply(this, arguments);
  }
}
</code>```

Now of course this requires ES5, but everyone uses the ES5-shim right?

You may also be interested in alternative js OO patterns

As an aside you can replace option two with

```<code>var Make = function () {
  var that = Object.create(Make.prototype);
  // use that

  return that;
}
</code>```

In case you want your own ES5 Object.create shim then it's really easy

```<code>Object.create = function (proto) {
  var dummy = function () {};
  dummy.prototype = proto;
  return new dummy;
};
</code>```

Body:
Firstly arguments.callee is deprecated in ES5 strict so we don't use it. The real solution is rather simple.

You don't use new at all.

var Make = function () {
  if (Object.getPrototypeOf(this) !== Make.prototype) {
    var o = Object.create(Make.prototype);
    o.constructor.apply(o, arguments);
    return o;
  }
  ...
}

That's a right pain in the ass right?

Try enhance

var Make = enhance(function () {
  ...
});

var enhance = function (constr) {
  return function () {
    if (Object.getPrototypeOf(this) !== constr.prototype) {
      var o = Object.create(constr.prototype);
      constr.apply(o, arguments);
      return o;
    }
    return constr.apply(this, arguments);
  }
}

Now of course this requires ES5, but everyone uses the ES5-shim right?

You may also be interested in alternative js OO patterns

As an aside you can replace option two with

var Make = function () {
  var that = Object.create(Make.prototype);
  // use that

  return that;
}

In case you want your own ES5 Object.create shim then it's really easy

Object.create = function (proto) {
  var dummy = function () {};
  dummy.prototype = proto;
  return new dummy;
};


答:
Easiest solution is to just remember new and throw an error to make it obvious you forgot.

```<code>if (Object.getPrototypeOf(this) !== Make.prototype) {
    throw new Error('Remember to call "new"!');
}
</code>```

Whatever you do, don't use eval. I would shy away from using non-standard properties like __proto__ specifically because they are non-standard and their functionality may change.

Title: Avoiding new operator in JavaScript -- the better way

Body:
Warning: This is a long post.

Let's keep it simple. I want to avoid having to prefix the new operator every time I call a constructor in JavaScript. This is because I tend to forget it, and my code screws up badly.

The simple way around this is this...

```<code>function Make(x) {
  if ( !(this instanceof arguments.callee) )
  return new arguments.callee(x);

  // do your stuff...
}
</code>```

But, I need this to accept variable no. of arguments, like this...

```<code>m1 = Make();
m2 = Make(1,2,3);
m3 = Make('apple', 'banana');
</code>```

The first immediate solution seems to be the 'apply' method like this...

```<code>function Make() {
  if ( !(this instanceof arguments.callee) )
    return new arguments.callee.apply(null, arguments);

  // do your stuff
}
</code>```

This is WRONG however -- the new object is passed to the apply method and NOT to our constructor arguments.callee.

Now, I've come up with three solutions. My simple question is: which one seems best. Or, if you have a better method, tell it.

First – use eval() to dynamically create JavaScript code that calls the constructor.

```<code>function Make(/* ... */) {
  if ( !(this instanceof arguments.callee) ) {
    // collect all the arguments
    var arr = [];
    for ( var i = 0; arguments[i]; i++ )
      arr.push( 'arguments[' + i + ']' );

    // create code
    var code = 'new arguments.callee(' + arr.join(',') + ');';

    // call it
    return eval( code );
  }

  // do your stuff with variable arguments...
}
</code>```

Second – Every object has __proto__ property which is a 'secret' link to its prototype object. Fortunately this property is writable.

```<code>function Make(/* ... */) {
  var obj = {};

  // do your stuff on 'obj' just like you'd do on 'this'
  // use the variable arguments here

  // now do the __proto__ magic
  // by 'mutating' obj to make it a different object

  obj.__proto__ = arguments.callee.prototype;

  // must return obj
  return obj;
}
</code>```

Third – This is something similar to second solution.

```<code>function Make(/* ... */) {
  // we'll set '_construct' outside
  var obj = new arguments.callee._construct();

  // now do your stuff on 'obj' just like you'd do on 'this'
  // use the variable arguments here

  // you have to return obj
  return obj;
}

// now first set the _construct property to an empty function
Make._construct = function() {};

// and then mutate the prototype of _construct
Make._construct.prototype = Make.prototype;
</code>```

eval solution seems clumsy and comes with all the problems of "evil eval".

__proto__ solution is non-standard and the "Great Browser of mIsERY" doesn't honor it.

The third solution seems overly complicated.

But with all the above three solutions, we can do something like this, that we can't otherwise...

```<code>m1 = Make();
m2 = Make(1,2,3);
m3 = Make('apple', 'banana');

m1 instanceof Make; // true
m2 instanceof Make; // true
m3 instanceof Make; // true

Make.prototype.fire = function() {
  // ...
};

m1.fire();
m2.fire();
m3.fire();
</code>```

So effectively the above solutions give us "true" constructors that accept variable no. of arguments and don't require new. What's your take on this.

-- UPDATE --

Some have said "just throw an error". My response is: we are doing a heavy app with 10+ constructors and I think it'd be far more wieldy if every constructor could "smartly" handle that mistake without throwing error messages on the console.

Body:
Easiest solution is to just remember new and throw an error to make it obvious you forgot.

if (Object.getPrototypeOf(this) !== Make.prototype) {
    throw new Error('Remember to call "new"!');
}

Whatever you do, don't use eval. I would shy away from using non-standard properties like __proto__ specifically because they are non-standard and their functionality may change.


答:
Let's keep it simple. I want to avoid having to prefix the new
  operator every time I call a constructor in JavaScript. This is
  because I tend to forget it, and my code screws up badly.

The obvious answer would be don't forget the new keyword.

You're changing the structure and meaning of the language.

Which, in my opinion, and for the sake of the future maintainers of your code, is a horrible idea.


问:
Sharing Authentication Across Subdomains using cookies
I know that in general cookies themselves are not considered robust enough to store authentication information.

What I am wondering is if there is an existing design pattern or framework for sharing authentication across subdomains without having to use something more complex like OpenID.

Ideally, the process would be that the user visits abc.example.org, logs in, and continues on to xyz.example.org where they are automatically recognized (ideally, the reverse should also be possible -- a login via xyz means automatic login at abc). The snag is that abc.example.org and xyz.example.org are both on different servers and different web application frameworks, although they can both use a shared database.

The web application platforms include PHP, ColdFusion, and Python (Django), although I'm also interested in this from a more general perspective (i.e. language agnostic).

答:
You can store cookies on the example.org domain and use the value there to log in. With specific info linking the user to the cookie (plus other stuff to make sure it is the same user) in the shared DB.

Or implement your own OpenID with forwarding to auth.example.org which authenticates the user and logs them in (the shared DB can also be used as a side channel to exchange data securely between abc.example.org and auth.example.org).


答:
I don't think its an antipattern, just widely misused.

Most nested try catch's are indeed avoidable and ugly as hell, but there are times you can't help it.

```<code>try {
    transaction.commit();
} catch {
    logerror();
    try {
        transaction.rollback();
    } catch {
        seriousLogging();
    }
}
</code>```

Also, you'll need an extra bool somewhere to signify the failed rollback...

Body:
I don't think its an antipattern, just widely misused.

Most nested try catch's are indeed avoidable and ugly as hell, but there are times you can't help it.

try {
    transaction.commit();
} catch {
    logerror();
    try {
        transaction.rollback();
    } catch {
        seriousLogging();
    }
}

Also, you'll need an extra bool somewhere to signify the failed rollback...


答:
Consider the fact that multiple return statements are equivalent to having GOTO's to a single return statement. This is the same case with break statements. As thus, some, like me, consider them GOTO's for all intents and purposes.

However, I don't consider these types of GOTO's harmful and will not hesitate to use an actual GOTO in my code if I find a good reason for it.

My general rule is that GOTO's are for flow control only. They should never be used for any looping, and you should never GOTO 'upwards' or 'backwards'. (which is how breaks/returns work)

As others have mentioned, the following is a must read
GOTO Statement Considered Harmful

However, keep in mind that this was written in 1970 when GOTO's were way overused. Not every GOTO is harmful and I would not discourage their use as long as you don't use them instead of normal constructs, but rather in the odd case that using normal constructs would be highly inconvenient.

I find that using them in error cases where you need to escape an area because of a failure that should never occur in normal cases useful at times. But you should also consider putting this code into a separate function so that you can just return early instead of using a GOTO... but sometimes that's also inconvenient.


答:
You could do something really fancy, like:

```<code>(GetDoubleClickTime() * 2 / 3) + (rand(0, (GetDoubleClickTime() / 2)) - (GetDoubleClickTime() / 4))
</code>```

But I kinda agree with Jeff.  Since catching double clicks is an OS task; and it just comes back to your program as "the user double clicked at (x, y)" I think you might be over-working this a bit.

The simplest way to simulate clicks is to call the handler directly.

Body:
You could do something really fancy, like:

(GetDoubleClickTime() * 2 / 3) + (rand(0, (GetDoubleClickTime() / 2)) - (GetDoubleClickTime() / 4))

But I kinda agree with Jeff.  Since catching double clicks is an OS task; and it just comes back to your program as "the user double clicked at (x, y)" I think you might be over-working this a bit.

The simplest way to simulate clicks is to call the handler directly.


问:
Learning the Theory Behind Programming
I'm interested in books that would introduce / explain the theory behind programming and programming languages. My logic is that by truly understanding the theory behind programming it will only take a few weeks to pick up new languages and implement some simple software.

As far as the type of books I'm looking for they would be similar to SICP.

I've done some research on this site and also on stack overflow. I know there are some large threads about books which discuss software architecture but I'm looking for information specific to programming. I have an okay understanding of Python which I've received from an into CS class on programming but I need to advance my knowledge.

Thanks

答:
I took a course called Programming Language Concepts, which had two facets. The first was an overview of a number of different programming paradigms - functional, logic, object-oriented - which were taught using Scheme and Standard ML, Prolog, and Ruby when I took the course. The second facet of the course was about syntax, semantics, compilation, interpretation, and language features.

The textbook we used, which I thought was very well done, was Programming Language Pragmatics by Michael Scott. This book covers both sides of the course very well. You can't use it to learn a language well, but it discusses topics including parsing, interpretation and compilation, grammars, scope, binding, data representation, control flow, garbage collection, and quite a bit more. It does these through discussions of Perl, C++, Java, C#, Prolog, Ruby, and a few other languages.

If you are more interested in learning new paradigms and languages without so much of the theory behind languages, another option is The Pragmatic Programmers' Seven Languages in Seven Weeks. This book covers Ruby, Io, Prolog, Scala, Erlang, Clojure, and Haskell, with sample projects and tutorials.

Title: Learning the Theory Behind Programming


问:
Why are people so strongly opposed to #region tags in methods?
I hear a lot about keeping methods short and I've heard a lot of programmers say that using #region tags within a method is a sure sign that it is too long and should be refactored into multiple methods. However, it seems to me that there are many cases where separating code with #region tags within a method is the superior solution to refactoring into multiple methods.

Suppose we have a method whose computation can be separated into three rather distinct phases.  Furthermore, each of these stages is only relevant to the computation for this method, and so extracting them into new methods gains us no code reuse. What, then, are the benefits of extracting each phase into it's own method? As far as I can tell, all we gain is some readability and a separate variable scope for each phase (which will help prevent modifications of a particular phase from accidentally breaking another phase).

However, both of these can be achieved without extracting each phase into its own method. Region tags allow us to collapse the code into a form which is just as readable (with the added benefit that we no longer have to leave our place in this file should we decide to expand and examine the code), and simply wrapping each phase in {} creates its own scope to work with.

The benefit to doing it this way is that we don't pollute the class level scope with three methods which are actually only relevant to the inner workings of a fourth method. Immediately refactoring a long method into a series of short methods seems to me to be the code-reuse equivalent to premature optimization; you are introducing extra complexity in order to address a problem which in many cases never arises. You can always extract one of the phases into its own method later should the opportunity for code reuse arise.

Thoughts?

答:
I think that the example you give in your argument is less about YAGNI (You ain't gonna need it) and more about writing proper quality code that is easily maintainable.

In the earliest programming courses we learn that if a method is 700 LOC long, it is probably too big and certainly would be a giant pain to try and debug.

Secondly if I write methods A, B and C that are only used within method D, then I can more easily unit test A B and C independently of D, allowing for more robust unit tests in all 4 methods.


问:
Mastering technology like LINQ, WCF really necessary or is OOPS enough?
I am a C# developer.

My observation of the IT industry as a C# developer is that the technology keeps changing or being updated by Microsoft like LINQ, WCF, and WPF etc.

OOP has been the fundamental for all kinds of developments that we see today in any language.

My question is,

Is it good if I am a decent programmer in OOPS but not mastering any specific technology?

As a WinForms developer, is it necessary to know C++ with C# for better job perspective?

答:
LINQ is far from necessary, but once you start using it you'll never want to go back.

Even if you've never done any functional programming, the functional aspects of LINQ will lead you into a new way of reasoning about problems and an expressive new way to represent your ideas in code.

Even if you've never used databases to store data, the fact that you can use LINQ on any data structure which implements IQueryable, means that you can learn to use LINQ with standard Collections now and when you later need to add XML, ADO or SQL, you know much of what you need already.

For me, LINQ to Objects was an elegant addition to C# and I'd love to find something equivalent for Java.


问:
Explicitly defining variable data types vs. using the keyword 'var'?
In C#, am I encouraged to use the all-purpose var keyword for every variable declaration? If yes, do I have to mention those special characters for literal values within the variable declaration like the M for decimal in the following statement:

```<code>var myDecimal = 14.5M;
</code>```

If it makes a difference, I'm trying to do some web development with C#.

答: The var keyword only requests the compiler to deduce the type of the var type variable automatically. Hence, if you want to store a decimal type variable in a var variable, you need to use the m. Likewise if you are storing a string you need to enclose it in quotes.</p>


答:
Suppose we have a method whose computation can be separated into three rather distinct phases. Furthermore, each of these stages is only relevant to the computation for this method, and so extracting them into new methods gains us no code reuse. What, then, are the benefits of extracting each phase into it's own method? As far as I can tell, all we gain is some readability and a separate variable scope for each phase (which will help prevent modifications of a particular phase from accidentally breaking another phase).

Those are two benefits.  But the important one, to me anyway, is debuggability.  If you have to trace through that code, it's a lot simpler to be able to Step Over two of the three sections and only trace into the one that you care about.  Refactoring into smaller methods allows this; region tags do not.

Title: Why are people so strongly opposed to #region tags in methods?

Body:
I hear a lot about keeping methods short and I've heard a lot of programmers say that using #region tags within a method is a sure sign that it is too long and should be refactored into multiple methods. However, it seems to me that there are many cases where separating code with #region tags within a method is the superior solution to refactoring into multiple methods.

Suppose we have a method whose computation can be separated into three rather distinct phases.  Furthermore, each of these stages is only relevant to the computation for this method, and so extracting them into new methods gains us no code reuse. What, then, are the benefits of extracting each phase into it's own method? As far as I can tell, all we gain is some readability and a separate variable scope for each phase (which will help prevent modifications of a particular phase from accidentally breaking another phase).

However, both of these can be achieved without extracting each phase into its own method. Region tags allow us to collapse the code into a form which is just as readable (with the added benefit that we no longer have to leave our place in this file should we decide to expand and examine the code), and simply wrapping each phase in {} creates its own scope to work with.

The benefit to doing it this way is that we don't pollute the class level scope with three methods which are actually only relevant to the inner workings of a fourth method. Immediately refactoring a long method into a series of short methods seems to me to be the code-reuse equivalent to premature optimization; you are introducing extra complexity in order to address a problem which in many cases never arises. You can always extract one of the phases into its own method later should the opportunity for code reuse arise.

Thoughts?