问:
Has test driven development (TDD) actually benefited a real world project?
I am not new to coding. I have been coding (seriously) for over 15 years now. I have always had some testing for my code. However, over the last few months I have been learning test driven design/development (TDD) using Ruby on Rails. So far, I'm not seeing the benefit.

I see some benefit to writing tests for some things, but very few. And while I like the idea of writing the test first, I find I spend substantially more time trying to debug my tests to get them to say what I really mean than I do debugging actual code. This is probably because the test code is often substantially more complicated than the code it tests. I hope this is just inexperience with the available tools (RSpec in this case).

I must say though, at this point, the level of frustration mixed with the disappointing lack of performance is beyond unacceptable. So far, the only value I'm seeing from TDD is a growing library of RSpec files that serve as templates for other projects/files. Which is not much more useful, maybe less useful, than the actual project code files.

In reading the available literature, I notice that TDD seems to be a massive time sink up front, but pays off in the end. I'm just wondering, are there any real world examples? Does this massive frustration ever pay off in the real world?

I really hope I did not miss this question somewhere else on here. I searched, but all the questions/answers are several years old at this point. It was a rare occasion when I found a developer who would say anything bad about TDD, which is why I have spent as much time on this as I have. However, I noticed that nobody seems to point to specific real-world examples. I did read one answer that said the guy debugging the code in 2011 would thank you for have a complete unit testing suite (I think that comment was made in 2008).

So, I'm just wondering, after all these years, do we finally have any examples showing the payoff is real? Has anybody actually inherited or gone back to code that was designed/developed with TDD and has a complete set of unit tests and actually felt a payoff? Or did you find that you were spending so much time trying to figure out what the test was testing (and why it was important) that you just tossed out the whole mess and dug into the code?

答:
The answer is yes. In my company we have been developing a C++ application for over 20 years.
Last year, we got into TDD in some new modules, and defect rates decreased significantly. We liked it so much that some of us are even adding tests to legacy code every time we change something there.

Moreover, a whole module was completed from start to finish, going through production, without ever demonstrating a bug (and it's a critical module, too). Its development thereby was faster than usual, because usually what would happen otherwise is that a module would be "completed", only to return 4-5 times from beta testing for bug fixes. It was a substantial improvement, and the developers were more pleased of the new process as well.

I haven't done a lot of Rails TDD, but I've done much in C++, C#, Java and Python. I can tell you that it definitely works.
My guess is that you're spending a lot of time thinking about test names because you're not confident enough. Write your test first, but let your creativity flow...

I've noticed that once you truly get the hang of TDD, you start caring a bit less on "How am I going to name this test... argh!", and you just flow with it, refactoring and adapting already-written tests to fit the current situation.

Time for a tip

Tip #1

So the tip I think should help you the most is to not worry so much. One of the prettiest things about TDD is that it gives you courage about changing things that are already written and working. And that includes the tests.

Tip #2

Start off new class tests by a simple "canCreate" test, just to set your mind in the right direction, as in "Ok, I'm working on this class now... right."

Then start adding more tests, but only one at a time, and make sure that each test you create, it is the next simplest case that comes to your mind at that point (think about it for no more than 30 seconds, and then timeout with the best you've got at that point).

And Remember

Don't worry about refactoring existing tests or even removing obsolete or redundant ones. Not many people realize this, but in TDD you actually get 2 safety nets for the price of 1. Your tests are a safety net for production code changes, but your production code is also a safety net for refactoring the tests. The relationship is mutual. It's actually a good case of tight coupling.

Give it another shot. And let me recommend watching Clean Code Casts, especially the ones about TDD.

OwnerDisplayName: James


问:
Is it okay to have people with multiple roles in a Scrum team?
I'm evaluating some Agile-style methodologies for possible introduction to my team.  With Scrum, is it allowable to have the same person perform multiple roles?  We have a small team of four developers and a web designer; we don't really have a lead (I fulfill this role), QA testers or business analysts, and all of our development tasks come from the CIO.  Automated testing is seen as a total waste of time, and everything focuses on speed and not quality.

What will happen is the CIO will come up with a development task (whether a feature or a bug) and give it to a developer (not to the whole team, to an individual, often in private or out of the blue) who is then expected to get it completed.  The CIO doesn't gather requirements beyond the initial idea (and this has bitten us before as we'll implement something only to find out that none of the end users can use the feature, because they weren't consulted or even informed about it before we developed it, and in a panic we'll be told to revert the change) but requires say in/approval of everything that we do.

First things first, is a Scrum style something to consider to introduce some standards and practices?  From reading, Scrum seems to rely on a bit more trust and communication and focuses more on project management than on development, which is something we are completely devoid of as we don't have any semblance of project management at present.

Second, if it can work is it unreasonable for someone, let's say myself, to act as both ScrumMaster and a developer?  Or for a developer to also be the Product Owner (although chances are this will be the CIO, who isn't a developer)?  I realize the Scrum Master and the Product Owner should be different people but at the same time I don't think we have anyone who has the qualities of a Product Owner (chances are it would turn into a "I need all these stories, I don't care how but get it done" type of deal and/or any freeze would be unfrozen on a whim).

It seems to me that I might need to pick and choose pieces of Scrum/XP/Lean to compensate for how things are done currently, as it's highly unlikely that the mentality can be changed; for instance Pair Programming would never fly (seen as a waste, you get half the tasks done if you need two people for everything), TDD would be a hard sell, but short cycles would be welcomed.

答:
Scrum, Kanban or any other Agile methodology is primarily a methodology focused on software development projects.  In other words, it is a project management practice by its very nature.

As much as you desperately want you and your team to be doing project work, you will find that Agile will just simply not work in your organization because of the fact that you really are not doing "project" work or devoting yourselves as a team to a "project commitment".

You may organize a mini project around a complex feature, but in reality you have no connection to business analysts or the end users so how can you verify that you are delivering on User Stories when you have no way of really knowing what it is the user wants?

Your only stakeholder is your boss, and he basically ensures that your team doesn't exist to serve the other stakeholders of the project, you exist as a team to serve him and his needs regardless how this affects the other stakeholders.

On top of all of that, he is giving individual tasks to individuals and probably reprioritizing things immediately as he decides that they should go.  You can't function in an Agile project methodology if individual project resources are going to reprioritized at a moments notice, or if the sprint will be put on hold.

It is not supposed to work like that

A sprint is a commitment by the entire team to deliver a subset of user stories by a specified date.  Once started, a sprint should be gone through to completion before any reprioritization or changes are to occur.  How is a project supposed to be managed when run in such a chaotic ad-hoc environment?

You don't work in an environment that is conducive to Agile project management methodologies.  You don't even work in an environment conducive to Waterfall methodologies.  You work in a monarchy and you are merely the kings pawns doing his bidding and putting out fires.

This is not the makings of a software development project team.

So in a very obscure way I am answering your question in saying that in your situation that it really doesn't matter if individuals are playing multiple roles.  You have much bigger problems on your hands.  You are asking how to get water stains out of carpet on a house without a roof.

ContentLicense: CC BY-SA 3.0


问:
Should I strictly follow every single HTML and CSS Standard?
A few years ago I considered myself somewhat of a web developer, knowing the basic 3 languages (HTML, CSS, JS) and lots of PHP. Moving on from simple text to actual websites was a pain because of the so called "standards" out there, which at the time were ridiculously complicated for me. It pretty much boiled down to this (minus the IE related stuff):

Standards are there to replace old ways of doing things in a simpler way. However when trying to actually implement some of the stuff (Entirely CSS based layout for example), it took me 10x longer to actually do it then if I did the simpler and still working solution. If it rendered the same, then why should I use the more complicated example that takes 10x longer and breaks once you change browsers? This sparked many long religious debates in ##php, ##css, and ##js in Freenode IRC and actually got me banned from ##css because I messed with their little world over there.

My question: Should I follow every single standard and coding conventions even if they take me 10x longer but get me the same result as the simple one?

For the poll tag, those of you who have websites of any size (huge or small), do you follow all the standards?

答:
Laziness is not an excuse for not following the standard. Sometimes, if the standard is stupid, that is a reason not to follow it. How do you know when the standard is stupid? When you have been making a good faith effort over an extended period to follow all the relevant standards in letter and in spirit and you've come to a reasonable and well-supported conclusion that the standard in some niche case is actually at fault, not you.

Most of the time, this will not be applicable though.

ContentLicense: CC BY-SA 2.5


问:
Do you ever read language specs?
While trying to answer questions on SO site (particularly C++ questions) I find that most of the times one person or the other includes a quote from the standard. I myself have hardly read the language spec. Even when I try to read it, I can't get my head around the language used in the specs. So, my question to become a good developer in a particular language is it essential to read its spec and know all its dusty corners which invoke undefined/implementation defined behavior? </p>

答:
As one of the guilty parties, I'll add my 2¢ worth. No, I don't think it's necessary. Unfortunately, in C++ it's closer to necessary than almost anybody would like -- i.e., as Bjarne put it, C++ is "expert friendly". You need to be aware of a lot more details than anybody would like to be able to use it well. While probably true to some degree in almost any case, this is much less true in many (most?) other languages.

The other side of it is that a lot of times people are asking about relatively subtle details of the language that, quite frankly, darned few people really know off the top of their head, so those of us who provide answers about them often have to look up the details to be sure we're right. I also find that quoting from the standard has a tendency to prevent a lot of arguments -- even when I do know an answer, it'll frequently be questioned (to at least some degree) if I just say: "here's how it is." If you quote the standard, far fewer people will argue, so it can save time and effort in the long run.

Ultimately, I think knowing the standard (or the dark corners of the language) really well is less important to programming per se than to mentoring others about the language -- even cases where you just say "don't go there!" About the only programming to which it's important is writing code that actually works with the language (tokenizing, parsing, analyzing, etc.)

Title: Do you ever read language specs?


问:
About Intellectual-Property agreement with employer
In IP agreement IP is define as below

Intellectual Property (whether or not patentable and whether or not made during working
  hours) is defined as but not limited to: all product specifications, developments, inventions, works of authorship, derivative works, technologies, programs, systems, software, mobile applications and other mobile programming interfaces, designs, methodologies, encryptions, ideas, techniques, patents, formulas, processes, concepts, know-how and date made or conceived or reduced to practice or developed during employment period ,remain the property of XXXXXXX[COMPANY_NAME]XXXX or its affiliates.

This is the first time I have seen any IP agreement. Isn't it too stringent? or its standard practice across industry?

答:
A couple of points to add to the excellent answers already.

Ultimately this would be decided in court. By a jury of 'ordinary' people who just might not be software professionals. So while it would be obvious to them that, for example, a house painter producing watercolors at the weekend isn't in the same business as his employer - would they be able to distinguish between your network admin day job and your evenings writing iPhone apps?

Your current boss might be perfectly OK with you writing iPhone apps and they might think this is just silly legalese - but next year your company might be bought by Apple or $EVILCORP$ , what then?


问:
finding houses within a radius
During an interview I was asked given the following: A real estate application that lists all houses that are currently on the market (i.e., for sale) within a given distance (say for example the user wants to find all houses within 20 miles), how would you design your application (both data structure and alogirithm) to build this type of service?

Any ideas? How would you implement it? I told him I didn't know becaue I've never done any geo-related stuff before.

答:
This is probably obvious, but for many applications the poor man's slow solution may be fine.

Have a table in a relational database that stores latitude and longitude.  Query for all locations that have a latitude within 20 miles and a longitude within 20 miles.  This gives you a bounding rectangle the size of the smallest bounding rectangle that contains the radius you really want to search (and ignores curvature of the earth as well).

Then you take the set that's returned (by a query using indexes), and filter it down using an accurate calculation of distance.

So, not efficient performance, but very efficient in time to develop.  For many applications that might be a better choice.

Title: finding houses within a radius


答:
Whenever you are faced with a question like this and you simply do not have expertise in the problem domain it's good to do a couple things.

First acknowledge that you don't have specific expertise in this problem domain.

Second, explain how you would go about solving the problem.

Although I don't have specific experience when working with geographical search I am
  confident there are well documented algorithms and existing
  technologies to solve the problem. I would explore these to gain
  knowledge of common solutions that are available to me and make a
  choice about implementation based on the requirements of the project.

Third, Always reduce problems like this down to their basic components.  You know that locations on a map are 2-dimensionally distributed. You know that if you are given arbitrary x,y coordinates the distance to each coordinate from another coordinate is calculated by forming a triangle and solving for the unknown length.  You hopefully also know that if you are asked to find all coordinates within a bounding box, you can do this simply by calculating the extents of the box you want to find and using simple greater than, less than logic along both axis.

Last, I have never hired a developer that seemed to give up on questions.  If I ask a question and the person says "I don't know" and doesn't even attempt to think through it verbally it gives me the impression they won't contribute to brainstorming sessions - which is critical at organizations that are writing software.

Title: finding houses within a radius

Body:
During an interview I was asked given the following: A real estate application that lists all houses that are currently on the market (i.e., for sale) within a given distance (say for example the user wants to find all houses within 20 miles), how would you design your application (both data structure and alogirithm) to build this type of service?

Any ideas? How would you implement it? I told him I didn't know becaue I've never done any geo-related stuff before.


问:
User intentions analysis
I'm going to work on some project that would do a user-action recognition based on what he/she does in the system.

As far as I understand there are two main parts here:

Intercept the user actions (say http traffic in web/ui interaction in thick-client)
analysis of user intentions.

While the first part is rather technical and therefor easy to implement, the second one is AI related and can be academic.

So I was wondering whether someone knows some third-parties/academic projects that would implement the 'action-recognition' stuff?

答:
I might be far off, but to me that looks more like the recognition of critical paths in a decision tree, as it's pretty much how you could represent the interactions of a user with a system: a long chain of decisions, which are represented as concrete actions.

So I'd recommend to read on expert systems, graph theory, and predictions systems.

Then if you need to make predictions of more abstract actions, like the evaluation of search habits, that gets a bit more complex.

Title: User intentions analysis


问:
Indenting labels in C
I noticed that in the Vim automatically indents labels in a rather unintuitive way (IMHO).

```<code>int main(void) {
    goto end;

end:
    return 0
}
</code>```

Are there any style guidelines for labels?

For the faint-hearted, the goto's I am using are for error handling in a controlled and structured manner.

答: I've seen this used for the syntactically identical access specifiers in C++. It's a good thing- it makes the labels very visible, which they really should be.</p>

Title: Indenting labels in C


答: This is the standard way for labels to be indented. </p>

Title: Indenting labels in C

Body:
I noticed that in the Vim automatically indents labels in a rather unintuitive way (IMHO).

```<code>int main(void) {
    goto end;

end:
    return 0
}
</code>```

Are there any style guidelines for labels?

For the faint-hearted, the goto's I am using are for error handling in a controlled and structured manner.


问:
Generators in Javascript into the new ECMA standard
Generators are being introduced in the new version of the ECMA standards.
Could any one suggest the importance and the usage of generators in the present Javascript world?
Examples of generators in real world problems will be helpful.</p>

答:
Starters

I'd suggest to look at:

the ECMAScript Harmony Project's wiki page on Generators,

the Mozilla Developer Doc on Iterators and Generators,

the JavaScript Tips page of the jslibs project,

the Google Traceur Compiler's page on JavaScript Language Features,

SO questions for "javascript generator yield".

A simple example is given in the Mozilla Developer Doc introducing the new features of JavaScript 1.7:

```<code>function fib() {
  var i = 0, j = 1;
  while (true) {
    yield i;
    var t = i;
    i = j;
    j += t;
  }
}

var g = fib();
for (var i = 0; i < 10; i++) {
  console.log(g.next());
}
</code>```

Others are available in the documents listed above.

Real-World

For real world examples, you can for instance see:

Google's own Traceur-Compiler's tests for EndYieldGenerator, and SwitchGenerator,

or even the whole test battery for the yield keyword in Google's traceur-compiler,

or the AcidMonkey tests, for instance this Pi Generator.

Body:
Starters

I'd suggest to look at:

the ECMAScript Harmony Project's wiki page on Generators,

the Mozilla Developer Doc on Iterators and Generators,

the JavaScript Tips page of the jslibs project,

the Google Traceur Compiler's page on JavaScript Language Features,

SO questions for "javascript generator yield".

A simple example is given in the Mozilla Developer Doc introducing the new features of JavaScript 1.7:

function fib() {
  var i = 0, j = 1;
  while (true) {
    yield i;
    var t = i;
    i = j;
    j += t;
  }
}

var g = fib();
for (var i = 0; i < 10; i++) {
  console.log(g.next());
}

Others are available in the documents listed above.

Real-World

For real world examples, you can for instance see:

Google's own Traceur-Compiler's tests for EndYieldGenerator, and SwitchGenerator,

or even the whole test battery for the yield keyword in Google's traceur-compiler,

or the AcidMonkey tests, for instance this Pi Generator.


问:
Getting data from a webpage in a stable and efficient way
Recently I've learned that using a regex to parse the HTML of a website to get the data you need isn't the best course of action.

So my question is simple: What then, is the best / most efficient and a generally stable way to get this data?

I should note that:

There are no API's

There is no other source where I can get the data from (no databases, feeds and such)

There is no access to the source files. (Data from public websites)

Let's say the data is normal text, displayed in a table in a html page

I'm currently using python for my project but a language independent solution/tips would be nice.

As a side question: How would you go about it when the webpage is constructed by Ajax calls?

EDIT:

In the case of HTML parsing, I know that there is no actual stable way to get the data. As soon as the page changes, your parser is done for. What I mean with stable in this case is: an efficient way to parse the page, that always hands me the same results (for the same set of data obviously) provided that the page does not change.

答:
There is no stable or better way to do this, HTML web pages was not made to be manipulated by computers. It is for human users, but if you need to do it I suggest that will use a browser and some javascript. At my work I was involved with a project that need to extract some information from a third party site. The application was developed as a Chrome extension. The application logic is written using javascript that is injected on the site after the Page load is complete. The data that is extracted is sent to a database through a http server. It is not the best approach, but it works.
Ps: The Site owner has authorized us to do such thing. </p>


问:
FxCop / Code Analysis with VS2010 Ultimate
I've getting some information about this, but I still can find a proper answer, I was asked recently in my company for this : "run a fxcop analysis on that code and tell me the results".

Ok, I have VS2010 Ultimate which has code analysis, but before making any comment, I browse it on the internet cause I want to implement the best choice...

So, let's say I'm gonna use the same rules on both analyzers:

Should I recommend using one above the other?

Should I say "hey, thats kinda old, let's use code analysis!"

Should I get the same results on different computers? (for what I undersand, fxcop gives you some "points" and for what I've read, sometimes it gives you diff points on diff computers, I don't know about this with code analysis

Thanks, any help would be appreciated

答: FxCop is mostly a "style" analyzer (it finds things documented in the Framework Design Guidelines).  It does not substitute for a full-blown static code analysis tool like the one in VS2010 Ultimate.


问:
If immutable objects are good, why do people keep creating mutable objects?
If immutable objects¹ are good, simple and offer benefits in concurrent programming why do programmers keep creating mutable objects²?

I have four years of experience in Java programming and as I see it, the first thing people do after creating a class is generate getters and setters in the IDE (thus making it mutable). Is there a lack of awareness or can we get away with using mutable objects in most scenarios?

¹ Immutable object is an object whose state cannot be modified after it is created.

² Mutable object is an object which can be modified after it is created.

答: I think one major contributing factor has been ignored: Java Beans rely heavily on a specific style of mutating objects, and (especially considering the source) quite a few people seem to take that as a (or even the) canonical example of how all Java should be written.


问:
How to deal with ad-hoc mindsets?
I joined a dev team of six two month ago. People are nice, all is good. But more and more I observe an ad-hoc mindset. Stuff gets quick fixed, at the cost of future usability, there is little testing and two people happily admitted, that they like to carry the knowledge around in their head, rather than to write it down.

How to deal with this? I'd like to lead by example, but time is limited - I like architecting and actually implementing the stuff. But I'm afraid the ad-hoc mindset infects me and rather than striving for clearness and simplicity in design and code - which isn't simple to establish - I get pulled down the drain of an endless spiral of hacks on hacks - which no outsider can uncouple - just for schedule's and management's sake.

答:
You already know part of the answer: you need to lead by example. You also need to become comfortable with the fact that your "leadership" might be ignored, that your colleagues will continue to do things the way they've always done them -- either because it makes the boss happy or because they themselves value expediency over long-term maintainability.

In the end, you need to let your results speak for themselves. Did you miss a deadline by three days but save the QA team at least that many scheduled days of testing because you test-drove your development and it largely works as designed? That's a win.

In the end, however, if you don't have at least some degree of management buy-in for that sort of trade-off, you're simply in the wrong environment, and need to find one more conducive to good practices. Bad practices are habit forming, so the sooner you can either find a way to stand your ground, or change to a working environment with better practices, the better.

Title: How to deal with ad-hoc mindsets?


答:
It has been the usage to unindent labels in all languages I've used (included ASM and fixed form FORTRAN where it was mandatory). The only variation I've seen is that the unindent may be the half of the usual indent.  In your case, that would have been:

```<code>int main(void) {
    goto end;

  end:
    return 0
}
</code>```

(case label in switches in C and C++ are often indented in the same way, but that's not as universal)

Title: Indenting labels in C

Body:
It has been the usage to unindent labels in all languages I've used (included ASM and fixed form FORTRAN where it was mandatory). The only variation I've seen is that the unindent may be the half of the usual indent.  In your case, that would have been:

int main(void) {
    goto end;

  end:
    return 0
}

(case label in switches in C and C++ are often indented in the same way, but that's not as universal)


问:
Flash messages in ASP.NET MVC without sessions
I'm developing a web application for Windows Azure using ASP.NET MVC 4. I would like to enforce one restriction in the architecture: do not use Session.

To achieve availability on Azure, and since there is no sticky sessions, I would need to store the session data in some central service, probably either SQL Azure or the Caching Service.

I would rather avoid sessions on the SQL database to avoid the increased latency, and the caching service on Azure is very expensive for the ammount of memory offered.

On the other hand, I would like to have the ability to easily pass Flash-style messages among redirects. TempData is the recommended way to do this, but by default it uses the session object.

So I would like to know:

Is there an alternative way to use TempData that doesn't require sessions or shared data between servers? Cookies perhaps?

Is there a better alternative I'm overlooking?

答:
I worked with Azure for almost 2 years, I had dreams of building my own caching service using an Azure worker role and something like memcached. I never got around to it but it still sounds like fun, and I think it would meet your needs.

Steve Marx (former azure evangelist) wrote about it on his blog a while back...

http://blog.smarx.com/posts/memcached-in-windows-azure


答: Scrum could be a good solution for your problem of the CIO assigning work to a developer ad hoc, but only if the CIO will buy in to the process.  I suspect that your CIO is not going to like being taken out direct assignment.  But if you can get the CIO to buy in to the idea of him writing user stories and then prioritizing them, he could find it a very effective way to manage.  But it will start with you convincing your CIO to stick to the process.  </p>

Title: Is it okay to have people with multiple roles in a Scrum team?

Body:
I'm evaluating some Agile-style methodologies for possible introduction to my team.  With Scrum, is it allowable to have the same person perform multiple roles?  We have a small team of four developers and a web designer; we don't really have a lead (I fulfill this role), QA testers or business analysts, and all of our development tasks come from the CIO.  Automated testing is seen as a total waste of time, and everything focuses on speed and not quality.

What will happen is the CIO will come up with a development task (whether a feature or a bug) and give it to a developer (not to the whole team, to an individual, often in private or out of the blue) who is then expected to get it completed.  The CIO doesn't gather requirements beyond the initial idea (and this has bitten us before as we'll implement something only to find out that none of the end users can use the feature, because they weren't consulted or even informed about it before we developed it, and in a panic we'll be told to revert the change) but requires say in/approval of everything that we do.

First things first, is a Scrum style something to consider to introduce some standards and practices?  From reading, Scrum seems to rely on a bit more trust and communication and focuses more on project management than on development, which is something we are completely devoid of as we don't have any semblance of project management at present.

Second, if it can work is it unreasonable for someone, let's say myself, to act as both ScrumMaster and a developer?  Or for a developer to also be the Product Owner (although chances are this will be the CIO, who isn't a developer)?  I realize the Scrum Master and the Product Owner should be different people but at the same time I don't think we have anyone who has the qualities of a Product Owner (chances are it would turn into a "I need all these stories, I don't care how but get it done" type of deal and/or any freeze would be unfrozen on a whim).

It seems to me that I might need to pick and choose pieces of Scrum/XP/Lean to compensate for how things are done currently, as it's highly unlikely that the mentality can be changed; for instance Pair Programming would never fly (seen as a waste, you get half the tasks done if you need two people for everything), TDD would be a hard sell, but short cycles would be welcomed.


答:
Nothing?

I mean, business time constraints exist. Yours might be a scenario where time to market is more valuable than future ease of use.

If you are a rank and file programmer, then setting standards and concerning yourself with product architecture is not really your job (especially 2 months in). You should strive to improve the product however you can (including culture change), but not at the expense of alienating your team and/or boss. Being the new guy who thinks he knows better is a quick and easy way to do that.

I would ask why you're doing all of these quick hack fixes? Is it due to previous quick hack fixes? It's easy enough then to point out that if things were done 'right' in the first place...

In the end, bad programming practices lead to concrete pain. If people think they won't, all you need to do is wait.

Title: How to deal with ad-hoc mindsets?

Body:
I joined a dev team of six two month ago. People are nice, all is good. But more and more I observe an ad-hoc mindset. Stuff gets quick fixed, at the cost of future usability, there is little testing and two people happily admitted, that they like to carry the knowledge around in their head, rather than to write it down.

How to deal with this? I'd like to lead by example, but time is limited - I like architecting and actually implementing the stuff. But I'm afraid the ad-hoc mindset infects me and rather than striving for clearness and simplicity in design and code - which isn't simple to establish - I get pulled down the drain of an endless spiral of hacks on hacks - which no outsider can uncouple - just for schedule's and management's sake.


答:
There's no right or wrong, it just depends what you prefer. There's a reason why some people prefer languages that favor one paradigm over another, and one data model over another. It just depends on your preference, and on what you want to achieve (and being able to easily use both approaches without alienating die-hard fans of one side or another is a holy grail some languages are seeking after).

I think the best and quickest way to answer your question is for you to head over Pros and Cons of Immutability vs Mutability.

Title: If immutable objects are good, why do people keep creating mutable objects?

Body:
If immutable objects¹ are good, simple and offer benefits in concurrent programming why do programmers keep creating mutable objects²?

I have four years of experience in Java programming and as I see it, the first thing people do after creating a class is generate getters and setters in the IDE (thus making it mutable). Is there a lack of awareness or can we get away with using mutable objects in most scenarios?

¹ Immutable object is an object whose state cannot be modified after it is created.

² Mutable object is an object which can be modified after it is created.


问:
Is programming or computer science in general, all about algorithms?
As a grad student, I find it more and more common for prestigious companies (like Google, Facebook, Microsoft,...) to put algorithm questions in their test and interviews. A few startups I applied to also asked about algorithms. I wonder if algorithms fluency is the most important thing for software developer in those companies?

If the answer being yes, what are the best method or resources for one to learn & practice about algorithms effectively? I can't seem to get interested in solving seemingly too complicated problems found in most textbook or websites. Though easily understand basic algorithms (like quicksort, bubblesort,...), I find it immensely difficult to remember and reuse them later.

Thanks.

P/S: If you ask me what I like, it's building good softwares to solve users' problems innovatively. I suppose that does not necessarily mean the software has to be very complicated.

答: If I had to pick one thing in computer science as being the most important part of it, I would pick abstractions, not algorithms.


答:
Scrum is something to consider, sure.  However, there is something to be said for getting all those involved on the same page and accepting a few changes to the structure along with getting at least a few sprints to work out various initial issues in using this methodology.

The Product Owner should be outside of the development team as there would otherwise be a bad conflict of interest presented here.  The Scrum Master may be a developer though as there isn't as bad of a conflict in this case.


问:
Open source projects and MDD?
Model-driven development seems to have a lot of buzz in certain software engineering circles, but I've never encountered an open source MDD projects "in the wild".

Are any open source projects using model-driven development? (I don't just mean that there's some UML documentation, but that the primary artifacts that the developers manipulate are the models, rather than the code).

答:
I don't know of many projects using a completely MDD-oriented approach, but I've often come across projects that use generated sources and artifacts from models of various kind.

I've found a few interesting links on this in the past:

Here's a wikipedia list of projects based on Eclipse EMF (so, not necessarily consumer products using it, but still interesting),

an IBM Developer Series tutorial on Eclipse EMF,

a very interesting software called CodeWorker that uses Generative Programming as its core concept (to a certain extent, this allows you to work purely on models).

You may also want to read Why aren't we all doing MDD yet?

Title: Open source projects and MDD?


答:
Once. I read the Java Spec. The only reason I read it was I was competing nationally in Java Programming for FBLA (Future Business Leaders of America) and thought it would give me an edge.

It was helpful, but the ROI (return on investment) was too low for me to do it again.

Title: Do you ever read language specs?

Body: While trying to answer questions on SO site (particularly C++ questions) I find that most of the times one person or the other includes a quote from the standard. I myself have hardly read the language spec. Even when I try to read it, I can't get my head around the language used in the specs. So, my question to become a good developer in a particular language is it essential to read its spec and know all its dusty corners which invoke undefined/implementation defined behavior? </p>


问:
Is there any functional difference between immutable value types and immutable reference types?
Value types are types which do not have an identity. When one variable is modified, other instances are not.

Using Javascript syntax as an example, here is how a value type works.

```<code>var foo = { a: 42 };
var bar = foo;
bar.a = 0;
// foo.a is still 42
</code>```

Reference types are types which do have an identity. When one variable is modified, other instances are as well.

Here is how a reference type works.

```<code>var foo = { a: 42 };
var bar = foo;
bar.a = 0;
// foo.a is now 0
</code>```

Note how the example uses mutatable objects to show the difference. If the objects were immutable, you couldn't do that, so that kind of testing for value/reference types doesn't work.

Is there any functional difference between immutable value types and immutable reference types? Is there any algorithm that can tell the difference between a reference type and a value type if they are immutable? Reflection is cheating.

I'm wondering this mostly out of curiosity.

答:
You are defining value types and reference in a language agnostic way, but doing so only by example in terms of changing of data members.  Logically, making the types immutable makes you lose the only difference guaranteed by your definition (and the answer might be "no").

However, once we start looking at particular programming languages, then yes: there are more differences.

Consider the following C# example.

```<code>void increment()
{
    lock (synchro)
    {
        total++;
    }
}

private int total = 0;
private SomeType synchro;
</code>```

If SomeType is a reference type, this counter will be thread safe.  If SomeType is a value type, then, due to boxing, each thread is locking a copy of synchro and increments may be lost under concurrency.

Of course, there are no genuine immutable types in .NET in the most abstract sense, as the monitors involved are implemented using hidden fields (akin to the C++ mutable keyword that can declare mutable members in otherwise immutable types).  But on Stack Overflow, everyone will understand your question to refer to anything that their platform calls "immutable".

OwnerDisplayName: Kendall Frey

Body:
You are defining value types and reference in a language agnostic way, but doing so only by example in terms of changing of data members.  Logically, making the types immutable makes you lose the only difference guaranteed by your definition (and the answer might be "no").

However, once we start looking at particular programming languages, then yes: there are more differences.

Consider the following C# example.

void increment()
{
    lock (synchro)
    {
        total++;
    }
}

private int total = 0;
private SomeType synchro;

If SomeType is a reference type, this counter will be thread safe.  If SomeType is a value type, then, due to boxing, each thread is locking a copy of synchro and increments may be lost under concurrency.

Of course, there are no genuine immutable types in .NET in the most abstract sense, as the monitors involved are implemented using hidden fields (akin to the C++ mutable keyword that can declare mutable members in otherwise immutable types).  But on Stack Overflow, everyone will understand your question to refer to anything that their platform calls "immutable".

OwnerDisplayName: Jirka Hanika


问:
Good design for class with similar constructors
I was reading this question and thought that good points were made, but most of the solutions involved renaming one of the methods. I am refactoring some poorly written code and I've run into this situation:

```<code>public class Entity {

  public Entity(String uniqueIdentifier, boolean isSerialNumber) {
    if (isSerialNumber) {
      this.serialNumber = uniqueIdentifier;
      //Lookup other data
    } else {
      this.primaryKey = uniqueIdentifier;
      // Lookup other data with different query
    }
  }

}
</code>```

The obvious design flaw is that someone needed two different ways to create the object, but couldn't overload the constructor since both identifiers were of the same type (String). Thus they added a flag to differentiate.

So, my question is this: when this situation arises, what are good designs for differentiating between these two ways of instantiating an object?

My First Thoughts

You could create two different static methods to create your object. The method names could be different. This is weak because static methods don't get inherited.

You could create different objects to force the types to be different (i.e., make a PrimaryKey class and a SerialNumber class). I like this because it seems to be a better design, but it also is a pain to refactor if serialNumber is a String everywhere else.

答:
I like the second option you've given. It's type safe, and to me, more intuitive.

I'm not sure if the code here is C# or Java, but if it's C#, you could take your second option and add an implicit conversion to string to help with the other places where serialNumber might be used as a string.

```<code>public class SerialNumber
{
    private string serialNumber = null;

    public SerialNumber(string serialNumber)
    {
        this.serialNumber = serialNumber;
    }

    public static implicit operator string(SerialNumber sn)
    {
        return sn.serialNumber;
    }
}
</code>```

Of course, implicit operators have been frowned upon in the past, so you'd have to weigh the pros and cons.

Body:
I like the second option you've given. It's type safe, and to me, more intuitive.

I'm not sure if the code here is C# or Java, but if it's C#, you could take your second option and add an implicit conversion to string to help with the other places where serialNumber might be used as a string.

public class SerialNumber
{
    private string serialNumber = null;

    public SerialNumber(string serialNumber)
    {
        this.serialNumber = serialNumber;
    }

    public static implicit operator string(SerialNumber sn)
    {
        return sn.serialNumber;
    }
}

Of course, implicit operators have been frowned upon in the past, so you'd have to weigh the pros and cons.


答: Number 2 is easily the best solution. It allows you to do validation and provides an actual distinction in the type system for distinct types.</p>

Title: Good design for class with similar constructors

Body:
I was reading this question and thought that good points were made, but most of the solutions involved renaming one of the methods. I am refactoring some poorly written code and I've run into this situation:

```<code>public class Entity {

  public Entity(String uniqueIdentifier, boolean isSerialNumber) {
    if (isSerialNumber) {
      this.serialNumber = uniqueIdentifier;
      //Lookup other data
    } else {
      this.primaryKey = uniqueIdentifier;
      // Lookup other data with different query
    }
  }

}
</code>```

The obvious design flaw is that someone needed two different ways to create the object, but couldn't overload the constructor since both identifiers were of the same type (String). Thus they added a flag to differentiate.

So, my question is this: when this situation arises, what are good designs for differentiating between these two ways of instantiating an object?

My First Thoughts

You could create two different static methods to create your object. The method names could be different. This is weak because static methods don't get inherited.

You could create different objects to force the types to be different (i.e., make a PrimaryKey class and a SerialNumber class). I like this because it seems to be a better design, but it also is a pain to refactor if serialNumber is a String everywhere else.


答:
Well, here are my 2 cents:

If there is no AJAX involved, or it can be cleared easily, 'fix' the HTML to XHTML (using HTMLTidy for example), then use XPath instead of regular expressions to extract the information.

In a well-structured web page, the logically separated entities of information are in different
s, or whatever other tag, which means you would be able to easily find the right information with a simple XPath expression. This is great also because you can test it in, say, Chrome's console, or Firefox' developer console and verify it works before writing even one line of other code.

This approach also has very high signal-to-noise ratio, since usually expressions to select the relevant information will be one-liners. They are also way easier to read than regular expressions and are designed for that purpose.

If there is AJAX and serious JavaScript-ing involved in the page, embed a browser component in the application and use its DOM to trigger events you need, and XPath to extract information. There are plenty good embeddable browser components out there, most of which use real-world browsers under the hood, which is a good thing, since a web-page might be incorrect (X)HTML, but still render good on all major browsers (actually, most of the pages eventually get this way).

Title: Getting data from a webpage in a stable and efficient way

Body:
Recently I've learned that using a regex to parse the HTML of a website to get the data you need isn't the best course of action.

So my question is simple: What then, is the best / most efficient and a generally stable way to get this data?

I should note that:

There are no API's

There is no other source where I can get the data from (no databases, feeds and such)

There is no access to the source files. (Data from public websites)

Let's say the data is normal text, displayed in a table in a html page

I'm currently using python for my project but a language independent solution/tips would be nice.

As a side question: How would you go about it when the webpage is constructed by Ajax calls?

EDIT:

In the case of HTML parsing, I know that there is no actual stable way to get the data. As soon as the page changes, your parser is done for. What I mean with stable in this case is: an efficient way to parse the page, that always hands me the same results (for the same set of data obviously) provided that the page does not change.

Body:
Well, here are my 2 cents:

If there is no AJAX involved, or it can be cleared easily, 'fix' the HTML to XHTML (using HTMLTidy for example), then use XPath instead of regular expressions to extract the information.

In a well-structured web page, the logically separated entities of information are in different <div>s, or whatever other tag, which means you would be able to easily find the right information with a simple XPath expression. This is great also because you can test it in, say, Chrome's console, or Firefox' developer console and verify it works before writing even one line of other code.

This approach also has very high signal-to-noise ratio, since usually expressions to select the relevant information will be one-liners. They are also way easier to read than regular expressions and are designed for that purpose.

If there is AJAX and serious JavaScript-ing involved in the page, embed a browser component in the application and use its DOM to trigger events you need, and XPath to extract information. There are plenty good embeddable browser components out there, most of which use real-world browsers under the hood, which is a good thing, since a web-page might be incorrect (X)HTML, but still render good on all major browsers (actually, most of the pages eventually get this way).


答:
Yes, equality still differs:

```<code>a: value type = 4;
b: value type = 4;

c: reference type = 4;
d: reference type = 4;

a == b; // true;
c == d; // false;
</code>```

C# cheats for things like strings by consolodating references that are equivalent, but this isn't strictly necessary for immutable reference types.

Body:
Value types are types which do not have an identity. When one variable is modified, other instances are not.

Using Javascript syntax as an example, here is how a value type works.

```<code>var foo = { a: 42 };
var bar = foo;
bar.a = 0;
// foo.a is still 42
</code>```

Reference types are types which do have an identity. When one variable is modified, other instances are as well.

Here is how a reference type works.

```<code>var foo = { a: 42 };
var bar = foo;
bar.a = 0;
// foo.a is now 0
</code>```

Note how the example uses mutatable objects to show the difference. If the objects were immutable, you couldn't do that, so that kind of testing for value/reference types doesn't work.

Is there any functional difference between immutable value types and immutable reference types? Is there any algorithm that can tell the difference between a reference type and a value type if they are immutable? Reflection is cheating.

I'm wondering this mostly out of curiosity.

Body:
Yes, equality still differs:

a: value type = 4;
b: value type = 4;

c: reference type = 4;
d: reference type = 4;

a == b; // true;
c == d; // false;

C# cheats for things like strings by consolodating references that are equivalent, but this isn't strictly necessary for immutable reference types.


答:
Value vs reference type is not a language-agnostic term. A language such as C++ and C does not hold a distinction- it is an arbitrary imposition of some languages. However, I'm gonna try and roll with it anyway.

A simple example is sizeof(T). All reference types have the size of a pointer (possibly plus the size of another pointer, depending on what your memory management system is). Value types, however, do not. In addition, you can measure performance characteristics to determine whether you are dealing with a value or a reference type. In addition, it's not particularly safe to refer to value types in some contexts.

Reference types can do some things that immutable value types cannot- for example, references to them can rebound to another instance.

```<code>class X {
    const int imm;
    X() : imm(0) {}
};
class Y {
    const int* imm;
    Y() : imm(new int(0));
};
X x;
Y y;
y.imm = new int(5); // Whoops! The reference itself is not immutable.
</code>```

Fundamentally, it must always be known whether a type is a value or a reference, else you cannot generate the correct code to access it.

Title: Is there any functional difference between immutable value types and immutable reference types?

Body:
Value vs reference type is not a language-agnostic term. A language such as C++ and C does not hold a distinction- it is an arbitrary imposition of some languages. However, I'm gonna try and roll with it anyway.

A simple example is sizeof(T). All reference types have the size of a pointer (possibly plus the size of another pointer, depending on what your memory management system is). Value types, however, do not. In addition, you can measure performance characteristics to determine whether you are dealing with a value or a reference type. In addition, it's not particularly safe to refer to value types in some contexts.

Reference types can do some things that immutable value types cannot- for example, references to them can rebound to another instance.

class X {
    const int imm;
    X() : imm(0) {}
};
class Y {
    const int* imm;
    Y() : imm(new int(0));
};
X x;
Y y;
y.imm = new int(5); // Whoops! The reference itself is not immutable.

Fundamentally, it must always be known whether a type is a value or a reference, else you cannot generate the correct code to access it.


答:
One thing you can do is subclass Entity and define specific constructors for each. I would wage a bet that there's other code that could be moved into the subclasses from the parent one. If not right now, then probably in the future. In either case, you still have all the common functionality in Entity.

public class SerialEntity extends Entity{
    public SerialEntity(String serialNumber){
        this.serialNumber = serialNumber;
    }
}

public class PKEntity extends Entity{
    public PKEntity(String primaryKey){
        this.primaryKey= primaryKey;
    }
}
```

<p>Perhaps at the same time make <code>Entity</code> abstract? But that's slightly out of scope here.</p>

<p>However, if the <em>only</em> thing different about <code>Entity</code> is the identifier, then create an <code>EntityIdentifier</code> interface with implementations for each type of identifier. This way <code>Entity</code> only needs one constructor with a single argument.</p>

<pre class="lang-java prettyprint-override"><code>public class SerialIdentifier implements EntityIdentifier{
    private final String serialNumber;

    public SerialIdentifier(String serialNumber){
        this.serialNumber = serialNumber;
    }

    @Override
    public String getKey(){
        return serialNumber;
    }
}

public class Entity{
    public Entity(EntityIdentifier id){
        this.id = id;
    }
}
</code>```

(This assumes you only ever need serialNumber xor primaryKey, though.)

I think the identifier approach is complementary to creating specific types for the values themselves. That is, if your application really needs a SeraialNumber type, but doesn't need a "pimary key" type, then you can easily refactor the SerialIdentifier above to work with the new type. This also decouples SerialNumber from being an identifier type, if such decoupling is necessary. The beauty of this is that you wouldn't have to worry about the rest of the Entity class because it already operates against the EntityIdentifier interface and is independent of what the "id" actually is.

Body:
One thing you can do is subclass Entity and define specific constructors for each. I would wage a bet that there's other code that could be moved into the subclasses from the parent one. If not right now, then probably in the future. In either case, you still have all the common functionality in Entity.

public class SerialEntity extends Entity{
    public SerialEntity(String serialNumber){
        this.serialNumber = serialNumber;
    }
}

public class PKEntity extends Entity{
    public PKEntity(String primaryKey){
        this.primaryKey= primaryKey;
    }
}

Perhaps at the same time make Entity abstract? But that's slightly out of scope here.

However, if the only thing different about Entity is the identifier, then create an EntityIdentifier interface with implementations for each type of identifier. This way Entity only needs one constructor with a single argument.

public class SerialIdentifier implements EntityIdentifier{
    private final String serialNumber;

    public SerialIdentifier(String serialNumber){
        this.serialNumber = serialNumber;
    }

    @Override
    public String getKey(){
        return serialNumber;
    }
}

public class Entity{
    public Entity(EntityIdentifier id){
        this.id = id;
    }
}

(This assumes you only ever need serialNumber xor primaryKey, though.)

I think the identifier approach is complementary to creating specific types for the values themselves. That is, if your application really needs a SeraialNumber type, but doesn't need a "pimary key" type, then you can easily refactor the SerialIdentifier above to work with the new type. This also decouples SerialNumber from being an identifier type, if such decoupling is necessary. The beauty of this is that you wouldn't have to worry about the rest of the Entity class because it already operates against the EntityIdentifier interface and is independent of what the "id" actually is.


答:
Personally, my solution to this would be to factor the constructor to take no parameters and use setter injection.  After all, if half the time serial number can be uninitialized and half the time primary key can be uninitialized, it's obvious that neither one is essential to the functioning of the class.  Since that's the case, forget the awkward primitive gymnastics and leave it to clients to specify what data they have.

This may reveal a requirement that one or the other be set, but that would seem to lead to factoring two classes out of the target class rather than represent some kind of C-style union structure.


问:
Quantitfying a cost for a software project
Disclaimer: I didn't know exactly where to put this question. If you feel that this question is not suitable for Programmers @ StackExchange, feel free to migrate it.

Background: Broadening my last question, there is a request for tender for a software system that's open and I have decided to take it on. I am a software developer & engineer by profession and, in this tender process, I have to put on the pricing for my bid. I have been provided a documentation consisting of functional and non-functional requirements only.

I have to put a project manager's cap on and think of all aspects, e.g. cost for implementation for the project, resources needed, etc.

My question is: Is there a project framework that I can follow that breaks the project cycle into steps and corresponding cost aspect or how would I go about best calculating/approximating the cost for the project?

答:
You are being asked to turn requirements into hours, and then hours into $'s. There is no magic wand for doing this. All your competitors will be trying to make the same calculations. The more experience you have the better your estimates will be.

Each requirement will take time to design, code and test; plus time for all the other parts of the project.

There is no easy way to turn lines of requirements into lines of code, and then into hours.

The risks are that the customer may chew up weeks of time approving small changes, or in a 30 minute meeting cause the entire project to be trashed (I heard that language X is the wave of the future, just rename the files...). Depending on the structure of the contract all the money risk is on you. Underbid and you will win, but go broke in the end. Overbid, and you will not get the contract.


答:
My view is that the labels should be unindented - and this is what I do when I write C.

The labels are not executable, they are closer to function declarations than anything else (in that they mark a new point of execution) and you don't indent function declarations, do you?

But in the end it is a matter of taste. I think it's easy to spot the labels and their purpose if they are unindented.

Title: Indenting labels in C


答:
First rule of estimating is you will lose money on fixed price projects always.

Second rule of estimating is you will never be able to provide a comprehensive estimate within a margin of error that will be acceptable to a customer because they will always argue that you mis-interpreted a requirement, which will cost you money.

Software has soft requirements, fluid expectations by the customer, and un-predictable risks.

This is why Agile Methodologies become so popular for building software.

They allow for you to plan for the change and risk and budget it in.

They allow for your customer to be in charge of priority and direction.

They allow the customer to have transparent view of what is costing what, for good and bad. The customer gains trust and rapport rapidly if you deliver on time the first few iterations, and feels like it is a team effort, not you charging them money.

Protect you by setting short term expectations that the customer can expect to see and the team can meet.

There are many other benefits, if you research some of the methodologies.

Title: Quantitfying a cost for a software project

Body:
Disclaimer: I didn't know exactly where to put this question. If you feel that this question is not suitable for Programmers @ StackExchange, feel free to migrate it.

Background: Broadening my last question, there is a request for tender for a software system that's open and I have decided to take it on. I am a software developer & engineer by profession and, in this tender process, I have to put on the pricing for my bid. I have been provided a documentation consisting of functional and non-functional requirements only.

I have to put a project manager's cap on and think of all aspects, e.g. cost for implementation for the project, resources needed, etc.

My question is: Is there a project framework that I can follow that breaks the project cycle into steps and corresponding cost aspect or how would I go about best calculating/approximating the cost for the project?


问:
.NET Dependency Management Systems
I have some .NET projects that are starting to get large enough to merit looking into Dependency Management solutions, so we don't have to copy binaries from one project to another. Here's what I've found so far:

NPanday is based on a port of Maven. I can't tell how recently it was worked on, but the last release was in May 2011.

NuGet seems to be under active development, and it appears to have support directly from Microsoft. Some people complained that it "only addresses dependency resolution," but I don't know what else it should address, or whether it has added more features since that point. It does appear to have recently added the ability to import binaries as part of the build process so we don't have to commit them to our repositories.

Refix appears to still be in Beta, after having received no attention since Sept 2011.

Would somebody with recent experience using any of these dependency management tools (or any others that work well) share your experience? Is NuGet mature enough to use it for dependency management? If not, what does it lack?

答:
I have just downloaded a latest version of NuGet to see what changed since the last time. Please correct me if I'm wrong (I'm really considering migrating my stuff to nuget):

NuGet packages still don't specify a "platform" as a package dependency. I have just installed "Ninject" and it referenced .NET 4.0 version in a subfolder "packages". I suppose it was a best guess as my project is in 4.0, but that is quite dangerous to suppose. I don't understand which platform will be selected by packages' dependency either.

"Package Restore" feature transforms my solution adding a custom pre-build step. I don't like something modifying my solution files, but that't not a problem. I don't understand how often it checks for the new versions (I'd like to set a frequency for private repositories to be quite often).

I may be totally wrong here, however it looks like nuget doesn't automatically upgrade project's dependency when a package version gets upgraded. Package Restore will create a new subfolder for a new package version, however I have to manually choose that folder from Visual Studio deleting the reference beforehand.

Some packages (like jQuery) will run an embedded PowerShell script on startup. I really don't like any custom execution and PS dependency which is not always there on windows and totally missing in Mono non-windows builds. By the way, as I mentioned MSBuild previously, even this dependency may be not realistic to satisfy for some C++ builds (otherwise I will miss Package Restore feature?).

The last one may be not that important, however it takes some reasonable amount of time to Restore Dependencies when I have quite a lot of them.

Title: .NET Dependency Management Systems


问:
Design help with parallel process
I am re-factoring some code and an having an issue with retrieving data from two parallel processes.

I have an application that sends packets back and forth via different mediums (ex: RS232, TCP/IP, etc). The jist if of this question is that there are two parallel processes going on.

I hope the picture below displays what is going on better than I can word it:

SetupRS232() class creates a new instance of the SerialPort by:

```<code>SerialPort serialPort = new SerialPort();
</code>```

My question is, what is the best way that the Communicator() class, which sends out the packet via the respective medium, get access to the SerialPort object from the SetupRS232 class? I can do it with a Singleton but have heard that they are generally not the best design to go by.

I am trying to follow SRP but I do feel like I am doing something wrong here. Communicator() will need to go out of it's way to get access to SetupRS232() to get access to the SerialPort class. I actually haven't found a way to even get access to it.

Would designing each medium class, for example, SetupRS232(), SetupTCPIP, as a singleton be the best way to approach this problem?

答: The difference between a singleton and an object that's only created once is that a singleton enforces it. In your case, I don't think you really need to enforce it. All you really need is a place for your setup classes to register the SerialPort instances, and a way for your Communicator to access that registry. This way the setup classes and the Communicator are safely decoupled from each other. Then you'll just have to be careful that the "registry" is thread-safe and that interaction with it is well-defined.</p>

Title: Design help with parallel process


答:
I'll try to help solve your problem more than answer your question.

There are many systems for estimating software costs in advance.  Why isn't there only one?  Because there isn't one that actually works.  A comment mentioned COCOMO-II, which I believe claims to be accurate within a factor of 7 times either way! (that's from memory, I can't find a reference, so take it with a grain of salt).

You won't be able to give a client an estimate with a multiply/divide factor of 7.

So, what do people really do?

Bid conservatively and usually lose the contract.

Bid aggressively and lose money most of the time.

Talk the client into not doing fixed-price bidding.

Bid aggressively then make up the money later.

Item 4 bears explanation.  The most common tactics are:

Do nothing not in the requirements.  For example, code quality is rarely a requirement.  Training is frequently not a requirement. To be fully complete, a spec would be a working program, so vital things not in the spec can almost always be found.

If asked to do anything not in the requirements then that gets billed hourly, usually at a high rate.

Usually bugs have to be fixed.  So every bug gets classified as "by design".

This is why many fixed price projects are an unending battle between the parties.  How bad it gets tends to be based on how much money the contractor is losing, how greedy the contractor is, how greedy the customer is, and how far behind estimate the project is.

If the process goes well (which can happen, even if I'm not making it sound that way), items in the spec that are difficult to implement can be traded for items that were forgotten, the ultimate price (initial fixed price spec plus all the stuff nobody thought of) is fair, and everyone is happy.

If the process goes badly, what is actually implemented is based on what is on the original spec plus the result of political battles over money, and somebody loses money (probably everybody).

In managing a project, if you won't bend on price, time, or features, but you can't control quality, guess what usually suffers?  The fixed price bidding process eliminates at the start the possibility of bending on price or features, and is generally strongly against bending on time.  You sound like you would like to be fair and do a good job, but understand it's a tough model to work under.


答:
I think the pattern you are looking for is an Adapter

You can implement an ICommunicator interface to effect an Adapter pattern so that your Communicator process does not need to know what kind of transport mechanism it is using

creating the ports and sockets et al would be the responsibility of a configuration object/process, not the Communicator

that is, if i understood your question correctly!

Title: Design help with parallel process

Body:
I am re-factoring some code and an having an issue with retrieving data from two parallel processes.

I have an application that sends packets back and forth via different mediums (ex: RS232, TCP/IP, etc). The jist if of this question is that there are two parallel processes going on.

I hope the picture below displays what is going on better than I can word it:

SetupRS232() class creates a new instance of the SerialPort by:

```<code>SerialPort serialPort = new SerialPort();
</code>```

My question is, what is the best way that the Communicator() class, which sends out the packet via the respective medium, get access to the SerialPort object from the SetupRS232 class? I can do it with a Singleton but have heard that they are generally not the best design to go by.

I am trying to follow SRP but I do feel like I am doing something wrong here. Communicator() will need to go out of it's way to get access to SetupRS232() to get access to the SerialPort class. I actually haven't found a way to even get access to it.

Would designing each medium class, for example, SetupRS232(), SetupTCPIP, as a singleton be the best way to approach this problem?


答:
Take the requirements and break them down into the smallest possible tasks.  Estimate how long to do each task.  The smaller the task, the more accurate the estimate.  Then factor in things like bathroom breaks, lunch breaks, sick time (yours, wifes, kids, dog etc) and anything else that will keep you from working.

Use the task list as your statement of work.  Anything not on the list, you charge extra for.

I personally add 30-50% onto the first estimate as insurance.


问:
Is defining every method/state per object in a series of UML diagrams representative of MDA in general?
I am currently working on a project where we use a framework that combines code generation and ORM together with UML to develop software. Methods are added to UML classes and are generated into partial classes where "stuff happens". For example, an UML class "Content" could have the method DeleteFromFileSystem(void). Which could be implemented like this:

```<code>public partial class Content
{
    public void DeleteFromFileSystem()
    {
        File.Delete(...);
    }
}
</code>```

All methods are designed like this. Everything happens in these gargantuan logic-bomb domain classes.

Is this how MDA or DDD or similar usually is done? For now my impression of MDA/DDD (which this has been called by higherups) is that it severely stunts my productivity (everything must be done The Way) and that it hinders maintenance work since all logic are roped, entrenched, interspersed into the mentioned gargantuan bombs.

Please refrain from interpreting this as a rant - I am merely curious if this is typical MDA or some sort of extreme MDA

UPDATE

Concerning the example above, in my opinion Content shouldn't handle deleting itself as such. What if we change from local storage to Amazon S3, in that case we would have to reimplement this functionality scattered over multiple places instead of one single interface which we can provide a second implementation for.

答: DDD does not require you to have a class handle it's own storage, in fact DDD has the concept of a repository to handle storage.  What you're higher ups are doing is having you implement Active Record, and tieing the implementation to the class, rather then hiding it from the class.</p>


答:
Lots of people had good answers so I want to point out something you touched on that was very observant and extremely true and hasn't been mentioned elsewhere here.

Automatically creating setters and getters is a horrible, horrible idea, yet it's the first way procedural-minded people try to force OO into their mindset.  Setters and getters, along with properties should only be created when you find you need them and not everyby default

In fact although you need getters pretty regularly, the only way setters or writable properties should ever exist in your code is through a builder pattern where they are locked down after the object has been completely instantiated.

Many classes are mutable after creation which is fine, it just shouldn't have it's properties directly manipulated--instead it should be asked to manipulate it's properties through method calls with actual business logic in them (Yes, a setter is pretty much the same thing as directly manipulating the property)

Now this doesn't really apply to "Scripting" style code/languages either but to code you create for someone else and expect others to read repeatedly over the years.  I've had to start making that distinction lately because I enjoy messing with Groovy so much and there is a huge difference in targets.


问:
Why most use Cygwin and not Uwin?
Most academic researchers I know target just *nix, and rely on Cygwin to make their applications available on Windows. I have tried many of these projects and always found them too unstable for serious use when running on Cygwin.

Uwin looks like a promising alternative to Cygwin. I haven't tried it yet, but I found several comments that it is faster and more stable. However, I haven't seen any use of Uwin to support running *nix apps on Windows.

What are the social and/or technical reasons behind Uwin's lack of popularity?

答: According to http://slashdot.org/story/01/02/06/2030205/David-Korn-Tells-All (question 11), UWIN was not originally open source (though that appears to have changed in the 11 years since that interview was published). Not being open source would have been a significant barrier to widespread adoption, especially considering a functionally equivalent open source option (Cygwin) was available at the time.</p>

Title: Why most use Cygwin and not Uwin?


问:
Is it bad etiquette to ask a potential employer how they score on the Joel Test?
Developer interviews are different than most other places, because not only do you worry about the people you work with, benefits, job description, etc., you also have EXTRA to worry about after getting the job.  Writing two application with exact requirements can be vastly different if you're working in a loud vs quiet environment, using VS2003/.NET 2.0 vs VS210/.NET 4.0., using SVN vs VSS.

Is it ok to give the potential employer the straight-up Joel Test?  I try to ask as many questions to get the type of environment I will be working in, which is extremely important from my perspective, but what's the best way to cut to the chase and just ask the tough questions (like they ask you during the same interview).

NOTE: By the "Joel Test" I mean a specific list of things that are deal breakers that are important to you (not necessarily Joel), but you may not have time to get out using the traditional casual "conversational" way of asking them, so you decide to either email or schedule another meeting, or ask other people, etc.

答: I've never worked at a place that scored higher than a 4 on the Joel test. When I go, I have a small packet I bring with me which includes another copy of my resume (I've come across recruiters putting my name on top of someone else's resume) as well as a bunch of questions, some of which were the joel test shuffled around. No one ever mentioned that they recognized the questions.</p>


答:
Every enterprise Java system that I've worked on in my career uses either Hibernate or the Java Persistence API (JPA). Hibernate and JPA essentially dictate that your system uses mutable objects, because the whole premise of them is that they detect and save changes to your data objects. For many projects the ease of development that Hibernate brings is more compelling than the benefits of immutable objects.

Obviously mutable objects have been around for much longer than Hibernate, so Hibernate is probably not the original 'cause' of the popularity of mutable objects. Maybe the popularity of mutable objects allowed Hibernate to flourish.

But today if many junior programmers cut their teeth on enterprise systems using Hibernate or another ORM then presumably they'll pick up the habit of using mutable objects. Frameworks like Hibernate may be entrenching the popularity of mutable objects.


问:
How do you keep released binaries under version control?
How do you keep released binaries under version control?
This allows to track which stuffs are changed between each release.
I mean to separate the released binaries from source repository.
The released binaries are either built from Continuous Integration software or manually compiled.</p>

答:
Use an artifact repository for binaries, not a version control system. A specific version of a released binary is not supposed to change over time, hence version control does not make sense since the file(s) wouldn't change.

See for example Maven repositories as a repository to archive/publish/offer releases and other binaries (e.g. such as documentation)


问:
What does it mean to do a "null check" in C or C++?
I have been learning C++ and I am having a hard time understanding null. In particular, the tutorials I have read mention doing a "null check", but I am not sure what that means or why it's necessary.

What exactly is null?

What does it mean to "check for null"?

Do I always need to check for null?

Any code examples would be much appreciated.

答:
In C and C++, pointers are inherently unsafe, that is, when you dereference a pointer, it is your own responsibility to make sure it points somewhere valid; this is part of what "manual memory management" is about (as opposed to the automatic memory management schemes implemented in languages like Java, PHP, or the .NET runtime, which won't allow you to create invalid references without considerable effort).

A common solution that catches many errors is to set all pointers that don't point to anything as NULL (or, in correct C++, 0), and checking for that before accessing the pointer. Specifically, it is common practice to initialize all pointers to NULL (unless you already have something to point them at when you declare them), and set them to NULL when you delete or free() them (unless they go out of scope immediately after that). Example (in C, but also valid C++):

```<code>void fill_foo(int* foo) {
    *foo = 23; // this will crash and burn if foo is NULL
}
</code>```

A better version:

```<code>void fill_foo(int* foo) {
    if (!foo) { // this is the NULL check
        printf("This is wrong\n");
        return;
    }
    *foo = 23;
}
</code>```

Without the null check, passing a NULL pointer into this function will cause a segfault, and there is nothing you can do - the OS will simply kill your process and maybe core-dump or pop up a crash report dialog. With the null check in place, you can perform proper error handling and recover gracefully - correct the problem yourself, abort the current operation, write a log entry, notify the user, whatever is appropriate.

Body:
In C and C++, pointers are inherently unsafe, that is, when you dereference a pointer, it is your own responsibility to make sure it points somewhere valid; this is part of what "manual memory management" is about (as opposed to the automatic memory management schemes implemented in languages like Java, PHP, or the .NET runtime, which won't allow you to create invalid references without considerable effort).

A common solution that catches many errors is to set all pointers that don't point to anything as NULL (or, in correct C++, 0), and checking for that before accessing the pointer. Specifically, it is common practice to initialize all pointers to NULL (unless you already have something to point them at when you declare them), and set them to NULL when you delete or free() them (unless they go out of scope immediately after that). Example (in C, but also valid C++):

void fill_foo(int* foo) {
    *foo = 23; // this will crash and burn if foo is NULL
}

A better version:

void fill_foo(int* foo) {
    if (!foo) { // this is the NULL check
        printf("This is wrong\n");
        return;
    }
    *foo = 23;
}

Without the null check, passing a NULL pointer into this function will cause a segfault, and there is nothing you can do - the OS will simply kill your process and maybe core-dump or pop up a crash report dialog. With the null check in place, you can perform proper error handling and recover gracefully - correct the problem yourself, abort the current operation, write a log entry, notify the user, whatever is appropriate.


答:
Two options:

a) Don't. Just make sure you have reproducable deterministic builds, that is, building the same source control revision with the same configuration always produces the exact same binary.

b) Designate a directory somewhere as the authoritative source for published builds. Make uploading the binaries part of the deployment / shipping procedure,and make sure the published-build directory is covered by your backup plan. You don't need any version control here; builds are write-once, if you need to change anything, you make a new build.

Either way, binaries and other build output don't belong under source control, for numerous reasons.

Body:
How do you keep released binaries under version control?
This allows to track which stuffs are changed between each release.
I mean to separate the released binaries from source repository.
The released binaries are either built from Continuous Integration software or manually compiled.</p>


答:
I don't keep release binaries under version control. Instead I publish them to a well defined location so that other tools and inspect and use them. I do a lot of work in Java, so that means I publish Jars to local Maven repositories. However, I don't use these tools to track what has changed per release. After all, they are binaries and there's not really much to track other than file count.

In order to track changes between releases, I would tag or label releases in my version control system with the version number of the release.  But this is really only to track the source files, not the binaries. The binaries are artifacts of the build and do not need to be under version control.

Title: How do you keep released binaries under version control?


问:
scalablity of Scala over Java
I read an article that says Scala handles concurrency better than Java.

http://www.theserverside.com/feature/Solving-the-Scalability-Paradox-with-Scala-Clojure-and-Groovy

...the scalability limitation is confined specifically to the Java programming language itself, but it is not a limitation of the Java platform as a whole...

The scalability issues with Java aren't a new revelation. In fact, plenty of work has been done to address these very issues, with two of the most successful projects being the programming languages named Scala and Clojure...

...Scala is finding ways around the problematic thread and locking paradigm of the Java language...

How is this possible? Doesn't Scala use Java's core libraries which brings all the threading and locking issues from Java to Scala?

答:
Well, of course it does. And Java reuses all the infrastructure provided by the JVM, which was written in C, and it ultimately runs in machine code!

The point of enabling developers to let their applications scale is not to provide more raw power. Assembler already has all the power that your hardware allows, and no language can provide more. In fact, the entire point of higher-order languages is to restrict what programmers can do in them them. That sounds horrible, but the bottleneck in writing great, correct, efficient code is not the computation model. It is the brains of the people who have to understand the programs written for the machine. Experience has shown that we are not smart enough to understand the theoretically optimal solution of a complex computation problem; we would probably not even recognize it if we saw it.

In the concrete example, the article presumably means that Scala provides higher-level libraries and concepts that make it easier for developers to understand their problems from the perspective of concurrency, and so the end result is better and more scalable than coding directly in Java (or C, or Assembler) would have been. That doesn't contradict the fact that Scala runs entirely on top of a Java virtual machine. The JVM is a beautiful invention that allows all kinds of neat stuff to be written more easily than would be possible without it - including frameworks and libraries that make even more complex things easy. Amazing, isn't it?

Title: scalablity of Scala over Java


问:
On mobile is there a reason why processes are often short lived and must persist their state explicitly?
Most mobile platforms (such as Android, iOS, Windows phone 7 and I believe the new WinRT) can kill inactive application processes under memory pressure. To prevent this from affecting the user experience applications are expected to save and restore their state as their process is killed and restarted.

Having application processes killed in this way makes the developers job harder.

On various occasions I've seen a mobile app that would:

Return to the welcome screen each time I switch back to it.

Crash when I switch back to it (possibly accessing some state that no longer exists after the process was killed)

Misbehave when I switch back to it (sometimes requiring a restart or tasks killer to fix)

Otherwise misbehave in some hard to reproduce way (e.g. android service killed and restarted at the wrong time)

I don't really understand why these mobile operating systems are designed to kill tasks in this way especially since it makes application development more difficult and error prone.

Desktop operating systems don't kill processes like that. They swap out unused pages of memory to mass storage. Is there a reason why the same approach isn't used on mobile? Mobile hardware is only a few years behind PC hardware in term of performance.

I'm sure there are very good reasons why mobile operating systems are designed this way. If you can point me to a paper or blog post that explain these reasons or can give me some insight I'd very much appreciate it.

答:
For most users the primary function of a smart phone is as a phone, followed by receiving text messages, and receiving e-mails. The designers of a smart phone OS must ensure that no application can interfere with these primary functions.

The other constraint of mobile is battery life, any app which "spins" in the background it will consume current and shorten battery life. The designers of a smart phone OS must ensure that any applications not being currently used are put to sleep so battery life can be extended.


答:
Battery life - many applications running in the background will drain your battery really fast.

Available memory

Processor

Small screen

Did I mention Battery life? :)

Here is an article about this feature on the Windows Phone Platform. It starts by explaining the reason why this it is a "necessary evil":
Mobile Matters - Windows Phone 7 Tombstoning

A good mobile platform should acknowledge the hardware constraints that mobility imposes on the device. Compared to desktops, mobile devices have less memory, less processing power, limited screen real-estate and limited battery life. Add up these constraints and you should conclude that, on a non-dedicated device where many applications will run, applications will eventually be closed or shut down to make resources available to other applications...

Title: On mobile is there a reason why processes are often short lived and must persist their state explicitly?

Body:
Most mobile platforms (such as Android, iOS, Windows phone 7 and I believe the new WinRT) can kill inactive application processes under memory pressure. To prevent this from affecting the user experience applications are expected to save and restore their state as their process is killed and restarted.

Having application processes killed in this way makes the developers job harder.

On various occasions I've seen a mobile app that would:

Return to the welcome screen each time I switch back to it.

Crash when I switch back to it (possibly accessing some state that no longer exists after the process was killed)

Misbehave when I switch back to it (sometimes requiring a restart or tasks killer to fix)

Otherwise misbehave in some hard to reproduce way (e.g. android service killed and restarted at the wrong time)

I don't really understand why these mobile operating systems are designed to kill tasks in this way especially since it makes application development more difficult and error prone.

Desktop operating systems don't kill processes like that. They swap out unused pages of memory to mass storage. Is there a reason why the same approach isn't used on mobile? Mobile hardware is only a few years behind PC hardware in term of performance.

I'm sure there are very good reasons why mobile operating systems are designed this way. If you can point me to a paper or blog post that explain these reasons or can give me some insight I'd very much appreciate it.


答:
It's a matter of library support.  Java uses the low level Thread construct to represent concurrency (this is like the assembly language of the concurrency world). There are lots of libraries and techniques you can use to build scalable solutions on top of these such as using the support provided by the java.util.concurrent package and following Brian's Goetz's techniques in his Java Concurrency in Practice book. Scala helped introduce things like the Akka framework (also usable by Java now) which bake in some of these better practices and library support. That's not to say that Java the language couldn't catch up (parallel collections etc), as Kilian states, it all runs on the JVM and therefore the JMM.

Also, Java's objects are also mutable by default and it requires some non trivial knowledge to make them effectively immutable. Scala reputedly makes it easier to create immutable objects

Title: scalablity of Scala over Java

Body:
I read an article that says Scala handles concurrency better than Java.

http://www.theserverside.com/feature/Solving-the-Scalability-Paradox-with-Scala-Clojure-and-Groovy

...the scalability limitation is confined specifically to the Java programming language itself, but it is not a limitation of the Java platform as a whole...

The scalability issues with Java aren't a new revelation. In fact, plenty of work has been done to address these very issues, with two of the most successful projects being the programming languages named Scala and Clojure...

...Scala is finding ways around the problematic thread and locking paradigm of the Java language...

How is this possible? Doesn't Scala use Java's core libraries which brings all the threading and locking issues from Java to Scala?


问:
Are there any situations where having a "data model" in which all your entities are instances of a Map<String, Object>
Are there any situations where having a "data model" in which all of the entities are instances of a Map<String, Object> would make any sense?

How do you explain to someone why having such a "data model" is not such a good idea? It seems like it's an absurd approach to me, could I be missing something?

答:
Well few examples I found are:

in Apache Camel documentation for CSV data format

Map<String, Object> body = new HashMap<String, Object>(); //...

in Atlassian Java cookbook, Converting a Map to JSON

Map<String, Object> data = new HashMap<String, Object>(); //...

in Spring JDBC API, queryForMap API docs

Map<String,Object> queryForMap(String sql, Object... args) //...

The way I see it, it boils down to a pretty simple question.

1234 - what type is it? is it... Integer? or String, or Long, or maybe, Double?

When there is a context one can learn about semantics of the data, above question is easy to answer. But what if there is no such context? this seem to be pretty common case in data passing frameworks.

Imagine writing a library that passes data from various sources to different consumers. One source can pass 1234 as String, another as Integer - you just have no reason to prefer one over another. As for the consumers, they "know" what type they expect from particular source, but why would they "tell" you?

If you slavishly follow the never an Object dogma, you might be tempted to arbitrarily cast everything to some type you just happen to prefer, like say String. The problem is though, this will make your library harder for clients to understand, not easier - they will break their mind trying to figure why did you use that type and what could be consequences.

Why String? I plan to plug data source that passes Double, what will happen? Will you convert? or will you break? Also, my consumer expects Double, does that mean I have to convert back? by the way how do you convert - does locale matter? Oh and another thing, in my other module I plan to use data source that passes Long and consumer that expects Long, too - could there be problems with that?

I did not use CSV, JDBC, JSON libraries mentioned in examples below, but in one of my past projects there has been Map<String, Object> used in a proprietary data passing framework and have to admit, as its client I've got nothing to complain against.

One interesting thing I noticed about that proprietary framework is that they did not intrude their untyped Objects into my client code. They exposed data through some API layer that presented it to me using the types I needed.

Actually I only learned about Map<String, Object> through one auxiliary "escape hatch" method in their API. I don't remember if method javadocs explicitly mentioned that it is for debugging purposes, but that was my understanding of why it's there.

If I mis-configure data source so that it passes String where I expect Integer, I would prefer to test the Object that is being passed under the hood instead of staring at cryptic ClassCastException. For that, I'd use "escape hatch" API.

Summing up, (1) I can imagine a library where using untyped Object makes better sense than pulling arbitrary type out of thin air and (2) at client code, I'd be be OK with that library as long as (2a) library API presents data with needed type and (2b) there is a convenient way to debug stuff when things go wrong.


问:
questions on a particular algorithm
Upon searching for a fast primr algorithm, I stumbled upon this:

```<code>public static boolean isP(long n) {
    if (n==2 || n==3) return true;
    if ((n&0x1)==0 || n%3==0 || n<2) return false;
    long root=(long)Math.sqrt(n)+1L;
    // we check just numbers of the form 6*k+1 and 6*k-1
    for (long k=6;k<=root;k+=6) {
        if (n%(k-1)==0) return false;
        if (n%(k+1)==0) return false;
    }
    return true;
}
</code>```

My questions are:

Why is long being used everywhere instead of int? Because with a long type the argument could be much larger than Integer.MAX thus making the method more flexible?

In the second 'if', is n&0x1 the same as n%2? If so why didn't the author just use n%2? To me it's more readable.

The line that sets the 'root' variable, why add the 1L?

What is the run-time complexity? Is it O(sqrt(n/6)) or O(sqrt(n)/6)? Or would we just say O(n)?

答:
Yes, there is no other reason I can see why they would choose long over int.

It is the same, but it's one of the clever things developers (especially with an embedded-C background) do to shave off a few CPU cycles between applying a mask over a long and applying modulo. The developer probably thought that the jitted bytecode going to the CPU will carry the trick, thus making his algorithm 0.000...00005% faster (note that the trick is not even in the loop) at the expense of having people wtf all the time.

Either readability, or the developer thought that since + is evaluated right-to-left, forcing the rightmost constant to be long (1L) - given that the result is long - may be faster. The generated bytecode will likely push 1 to the stack (as long with 1L or as int with 1), evaluate the sqrt, pop-cast-push the sqrt, and then do a ladd (long addition). It's unlikely there is a real gain, especially since, again, you're not in the loop, and since usually the jitter is smart.

The big-O complexity is O(sqrt(n)) or O(n^(1/2)) - a multiplicative constant over n is irrelevant in theory. Saying O(n) is not wrong (big-O is an upper boundary), but it's not really useful either, because O(sqrt(n)) is a much better estimator (you try to estimate the upper bound as close to running time as possible, to a constant).

edit: saying it's O(n) is indeed wrong, given the definition of big-O.

Title: questions on a particular algorithm