问:
Is anyone doing "real" TDD with Visual-C++, and if yes, how do they do it?
Test Driven Development implies writing the test before the code and following a certain cycle:

Write Test

Check Test (run)

Write Production Code

Check Test (run)

Clean up Production Code

Check test (run)

As far as I'm concerned, this is only possible if your development solution allows you to very quickly switch between the production and test code, and to execute the test for a certain production code part extremely quickly.

Now, while there exist lots of Unit Testing Frameworks for C++ (I'm using Bost.Test atm.) it does seem that there doesn't really exist any decent (for native C++) Visual Studio (Plugin) solution that makes the TDD cycle bearable regardless of framework used.

"Bearable" means that it's a one-click action to run a test for a certain cpp file without having to manually set up a separate testing project etc. "Bearable" also means that a simple test starts (linking!) and runs very quickly.

So, what tools (plugins) and techniques are out there that make the TDD cycle possible for native C++ development with Visual Studio?

Note: I'm fine with free or "commercial" tools.

Please: No framework recommendations. (Unless the framework has a dedicated Visual Studio plugin and you want to recommend the plugin.)

Edit Note: The answers so far have provided links on how to integrate a Unit Testing framework into Visual Studio. The resources more or less describe how to get the UT framework to compile and get your first Tests running. This is not what this question is about. I'm of the opinion that to really work productively, having the Unit Tests in a manually maintained(!), separate vcproj from your production classes will add so much overhead that TDD "isn't possible". As far as I am aware, you do not add extra "projects" to a Java or C# thing to enable Unit Tests and TDD, and for a good reason. This should be possible with C++ given the right tools, but it seems (this question is about) that there are very little tools for TDD/C++/VS.

Googling around, I've found one tool, VisualAssert, that seems to aim in the right direction. However, afaiks, it doesn't seem to be in widespread use (compared to CppUnit, Boost.Test etc.).

Edit: I would like to add a comment to the context for this question. I think it does a good summary of outlining (part of) the problem: (comment by Billy ONeal)

Visual Studio does not use "build scripts" that are reasonably
  editable by the user. One project produces one binary. Moreover, Java
  has the property that Java never builds a complete binary -- the
  binary you build is just a ZIP of the class files. Therefore it's
  possible to compile separately then JAR together manually (using e.g.
  7z). C++ and C# both actually link their binaries, so generally
  speaking you can't write a script like that. The closest you can get
  is to compile everything separately and then do two linkings (one for
  production, one for testing).

答:
Well, don't know if this helps, but there are some great videos about TDD from Brett L. Schuchert. Unfortunately, he does not show the combination "C++" and "VS", but

TDD with C# and VS:    http://vimeo.com/album/210446

TDD with C++ and Eclipse: http://vimeo.com/13240481

Perhaps you can work it out from those two.

EDIT: the C++ video is about using the CppUTest testing framwork with Eclipse, of course. When I posted it I thought it should be easily adopted for using in VS. So I googled a little and found this:

http://schuchert.wikispaces.com/tdd.cpp.NotesOnCppUTest

which gives you information how to use CppUTest in Visual Studio.


问:
Who owns this work?
I worked for a small company as a long term contractor making websites and other such things.  A client comes along, pays what he said was "A lot of money" for me to spend a week doing his website.  He paid it to the company.

I didn't see any of his money, I've since left that job because they owe me months of back pay and it looks like I'm not going to end up getting much of it. (Bad situation)

I want to consider the possibility now of exploring who owns any work I did that was unpaid, because if I need to, I can use it as leverage to help get my owed money.  The company is still using some work in-house that's unpaid which I'm a lot clearer about contesting rights to.

What's I'm struggling with is working out what to do about the clients website.  From his POV he paid for it, it's his.  From my POV I did it and didn't get paid for it so it's mine.  Who owns it?  If I do, I wouldn't want to strip it away from him, it seems really unfair, but I would like to use it as leverage if it comes to that.

答:
IANAL and you should speak to one but my reading of this:

Obviously a lot of it depends on the contracts between the three main parties and the country you're in but I suspect it's fairly straight forward (and probably not what you want to hear).

In terms of the relationship between you and the supplier (that is the company who employed you), you need to look at how you were employed and how the project ran.

If anyone else did any work on that site at all (including relationship management, analysis, copy writing, testing or whatever) then legally it may be that you did not create the site, you were part of a team creating the site at which point the ownership would rest with the umbrella under which the team were operating (the company). I'm guessing that this was the most likely situation.

You also talk about back pay rather than invoices so I'm assuming that you were contracted on a daily rate / hourly rate basis rather than working on a specified project basis. You're in the UK so IR35 might help as an indicator here - do you pay PAYE? If so then it's far more likely that you'd be seen as an employee and have no rights to the IP.

If my assumptions here are true, I don't see you have much of a claim.

Even if they're not it's not a given that the IP will have reverted to you. They have breached the terms of the contract but that doesn't necessarily void it, it just means that you have a claim against them.

The client on the other hand had an agreement with the supplier to supply a website - they paid for it and received it so would seem to have a pretty solid and reasonable expectation that they own the IP.

If you think that you do have a claim on it after that then you need to think about what you're actually going after the "client" for. They're not your client, you have no contract with them (express or implied) which means that you'd have to go after them based on infringing your IP.

That is likely to be far less straight forward - particularly as they have a reasonable case that they own the IP which is likely to mean the whole thing will likely cost more than you can ever recoup.

So all in all I suspect you're better hammering away at the company you were contracted to and leaving the client alone. It's not necessarily a case of do you have a claim, but where do you have the best claim, and that would seem to be for straight forward breach of contract.

That said, as an aside, have you thought about approaching the client and saying "BTW, I was the guy who actually did that work, would you prefer to contract direct with me in the future and save money?". That would potentially seem to be a win win.

ContentLicense: CC BY-SA 3.0

Title: Who owns this work?


问:
What should you leave behind for your successors?
Assume that you're a sole developer leaving a job. What kind of information/material, outside of the code itself, should you create and leave behind for your replacement?

An obvious answer is "whatever you would want at a new job" for sure, but it's been a while since I started a new job, and I forget what the most important things that I needed were back then.

I'm thinking:

accounts/passwords

location of equipment, backups, software CDs

What else?

答:
My email address, or perhaps even phone number.

In my experience it's difficult to get every detail written down, so the best thing is to be available (to a certain degree) if your successors need more information.

ContentLicense: CC BY-SA 2.5


问:
What is the best way to comment a deprecated class in Java?
I would like to know the best way to add a comment to identify a deprecated class in Java. Should I remove the previous comment added to the top of the class that helps another programmer to know what was that class for, or should I add it below the comment?</p>

答:
The recommended approach to deprecating a class, method, or field in Java is to use the @Deprecated annotation, which became available in Java 5, or the @deprecated JavaDoc tag, which has been around since Java 1.1. Oracle has a document about the specifics on how and when to deprecate APIs that appears to be relevant.

Should i remove the previous comment added to the top of the class that helps another programmer to know what was that class for or add it below the comment?

You should not edit or remove any existing comments, other than to add the JavaDoc tag or annotation. Deprecated code might still be in use in legacy systems, and developers of those systems need to have access to the documentation that the original developers did in some form.


问:
Why contribute to non-free open source projects?
As a owner of an open source project you'd want people to contribute and make it better, right?

But if you then decide to throw on a nice tasty licencing model for people to use the software [Corporate or otherwise], do you get rights to all the income? if so why would people bother contributing? They could be doing all the work while you, the owner, reap all the rewards?

This just seems wrong to me, maybe i'm misunderstanding it.

答: In projects that have dual licensing (like Qt or MySQL) the biggest incentive to contributing is getting changes your own local changes (bug fixes, and so on) accepted into upstream therefore reducing the need to create and maintain local forks.</p>


答:
The open source project you are contributing to may be important to you, as it is.

Let's take the example of Mono which is open source, but licensed to corporation:

Mainsoft, one of the most prolific contributor of the project uses the code for its own .NET to Java compiler. The company clearly don't care than the license owner, relicense their work to corporations. It's a win-win scheme.

Title: Why contribute to non-free open source projects?

Body:
As a owner of an open source project you'd want people to contribute and make it better, right?

But if you then decide to throw on a nice tasty licencing model for people to use the software [Corporate or otherwise], do you get rights to all the income? if so why would people bother contributing? They could be doing all the work while you, the owner, reap all the rewards?

This just seems wrong to me, maybe i'm misunderstanding it.


问:
What's the purpose of 'so that' clause in user story definition?
A user story can be defined in a sentence like:

```<code>As a <type of user> I want <some goal> so that <some reason>
</code>```

Just Google for 'user story formula' and first links all propose this formula.

My question is, what is the purpose of so that clause? Is it there for managers? Is it there so that project managers and stakeholders can understand the priority of the item better? Why is it there?

Note: I've worked with as a <type of user> I want <some goal> formula, and it works just well. I haven't noticed any problem in my work by implementing this format which is more brief.

答:
The purpose is to avoid unnecessary work by forcing the user/customer to supply a solid, tangible business benefit as a reason for the existence of this feature.

It is not unheard of that features get added just because someone thought they sounded cool, or because other software has it, so ours must have it, too. More often than not, those are at least completely unneccessary, if not actively harmful.

However, it is usually easy to spot those features, because the people proposing them generally will have trouble supplying a convincing business reason for them.

There is a technique called Popping The Why Stack, where you take the "so that" part, and ask "Why?", then you take that answer, and ask "Why?" again, recursively. If, after (let's say) three to five "Why"s, you have not arrived at either "because it'll make us money" or "because it'll save us money" (preferably with a precise description of exactly how that is going to happen), then the feature isn't worth implementing.

Some people believe this to be so important that they actually put it first in the story template:

In order to [...]

As a [...]

I want to [...]

There's a great example from a talk by some Thoughtworks people: one of their clients wanted the printed reports formatted in a very peculiar way. When the consultant asked "Why", they said that that way they were easier to type back in. So, instead of implementing the report formatting feature, they just transferred the reports over the network. Without the "so that" clause, they would still be printing theose papers out in one department, mailing them over to the other department and typing them back in.


问:
Is there a reason for initial overconfidence of scientists and engineers working on artificial intelligence in the 1960s?
I just started an AI & Data Mining class, and the book. AI Application Programming, starts off with an overview of the history of AI. The first chapter deals with the history of AI from the 1940s to present. One particular statement stuck out at me:

[In the 60s] AI engineers overpromised and underdelivered...

What was the reason for the overconfidence? Was it because of mathematical prediction models showing that a breakthrough was around the corner, or due to the ever-increasing hardware capability to take advantage of?

答:
AI has a long history of disappointments, but I think many critics often over-simplify what happened, such as with your quote "1960's engineers overpromised and underdelivered".

In the 60's, AI was the domain of a relative handful of researchers (the field wasn't really sufficiently developed yet to call it engineering), mostly at universities, and very few of them were accomplished programmers.

The sudden availability of computing machines in the 1950's had led to great expectations for automation, particularly in machine translation of natural language, playing chess, and similar problems.  You might find some actual predictions of success from those days, but the promises inevitably came BEFORE anyone tackled one of those problems in depth.  (Or, they wrongly assumed one success guaranteed another, such as expecting to be able to implement good chess playing after Samuel had so much success with checkers.)

Also, be wary of any claims of "they said", "they felt", "they thought", etc.; retrospective opinions (like this one!) are easy to throw around, while documented evidence of actual predictions by "experts" (those who actually tried solving a given problem) can be much harder to find.

Overpromising and undelivering has always been a symptom of software development, regardless of the specific field where the programming is applied.  A major difficulty with AI is that non-trivial problems are beyond the capabilities of most engineers.  For example, although Charles E. Grant's answer categorizes ELIZA and SHRDLU as "relatively simple", I'd say that's true only of ELIZA (which most first-year programming students could probably implement without much difficulty).  On the other hand, SHRDLU is a large, extremely sophisticated program that most programmers would have a very difficult time inventing, let along implementing.  Indeed, two teams of university students couldn't even get the source code fully running again, and SHRDLU-like abilities are still hard to find nowadays, over 40 years later.

Since AI is probably one of the least understood and most intractable problems where computers can be applied, overall I'd say progress in AI has generally been at par for the course.  There are still high expectations, and our hardware speed and capacities have increased tremendously since the 60's, but I'd say engineers' abilities and understanding of AI aren't improving all that much, so a holy grail like passing the Turing test is still probably a long way off, and overpromising and underdelivering will probably continue for some time.


答:
Well, I would say it's more or less the same thing that is happening with OWL right now. Look around, and try to draw parallels.

Sounds good on paper, seems to work well on toy problems, gets incredibly complicated on most real data.

Title: Is there a reason for initial overconfidence of scientists and engineers working on artificial intelligence in the 1960s?

Body:
I just started an AI & Data Mining class, and the book. AI Application Programming, starts off with an overview of the history of AI. The first chapter deals with the history of AI from the 1940s to present. One particular statement stuck out at me:

[In the 60s] AI engineers overpromised and underdelivered...

What was the reason for the overconfidence? Was it because of mathematical prediction models showing that a breakthrough was around the corner, or due to the ever-increasing hardware capability to take advantage of?


答:
More than just documentation, I'd like to know why certain decisions were made when they were made.  We're using SWIG currently on a project and one of the other developers wanted to know why we just didn't use Boost::Python.  The simple answer was that the customer did not allow the use of Boost at the time.  Now is a different story.

Such things will help them not only in understanding the project but also what limitations/constraints/challenges your implementation overcame.  It'll give them a starting point for future maintenance and feature augmentation.

Title: What should you leave behind for your successors?

Body:
Assume that you're a sole developer leaving a job. What kind of information/material, outside of the code itself, should you create and leave behind for your replacement?

An obvious answer is "whatever you would want at a new job" for sure, but it's been a while since I started a new job, and I forget what the most important things that I needed were back then.

I'm thinking:

accounts/passwords

location of equipment, backups, software CDs

What else?


答:
Googletest

How to integrate with vc++

You don't need a plugin, the test is just another target.  There aren't plugins to generate test with c++, evne if you could it would be testing pointless stuff like assignments

Title: Is anyone doing "real" TDD with Visual-C++, and if yes, how do they do it?

Body:
Test Driven Development implies writing the test before the code and following a certain cycle:

Write Test

Check Test (run)

Write Production Code

Check Test (run)

Clean up Production Code

Check test (run)

As far as I'm concerned, this is only possible if your development solution allows you to very quickly switch between the production and test code, and to execute the test for a certain production code part extremely quickly.

Now, while there exist lots of Unit Testing Frameworks for C++ (I'm using Bost.Test atm.) it does seem that there doesn't really exist any decent (for native C++) Visual Studio (Plugin) solution that makes the TDD cycle bearable regardless of framework used.

"Bearable" means that it's a one-click action to run a test for a certain cpp file without having to manually set up a separate testing project etc. "Bearable" also means that a simple test starts (linking!) and runs very quickly.

So, what tools (plugins) and techniques are out there that make the TDD cycle possible for native C++ development with Visual Studio?

Note: I'm fine with free or "commercial" tools.

Please: No framework recommendations. (Unless the framework has a dedicated Visual Studio plugin and you want to recommend the plugin.)

Edit Note: The answers so far have provided links on how to integrate a Unit Testing framework into Visual Studio. The resources more or less describe how to get the UT framework to compile and get your first Tests running. This is not what this question is about. I'm of the opinion that to really work productively, having the Unit Tests in a manually maintained(!), separate vcproj from your production classes will add so much overhead that TDD "isn't possible". As far as I am aware, you do not add extra "projects" to a Java or C# thing to enable Unit Tests and TDD, and for a good reason. This should be possible with C++ given the right tools, but it seems (this question is about) that there are very little tools for TDD/C++/VS.

Googling around, I've found one tool, VisualAssert, that seems to aim in the right direction. However, afaiks, it doesn't seem to be in widespread use (compared to CppUnit, Boost.Test etc.).

Edit: I would like to add a comment to the context for this question. I think it does a good summary of outlining (part of) the problem: (comment by Billy ONeal)

Visual Studio does not use "build scripts" that are reasonably
  editable by the user. One project produces one binary. Moreover, Java
  has the property that Java never builds a complete binary -- the
  binary you build is just a ZIP of the class files. Therefore it's
  possible to compile separately then JAR together manually (using e.g.
  7z). C++ and C# both actually link their binaries, so generally
  speaking you can't write a script like that. The closest you can get
  is to compile everything separately and then do two linkings (one for
  production, one for testing).


问:
Is there a name for the not given/null/empty-problem?
I work with code, where data is stored/exchanged in Hashtable/Dictionary/Associative-Array-like structures, like this

```<code>{
   'alpha': None,
   'bravo': '',
   # 'charlie' is not given
}
</code>```

there is not much standartization, which field is 'given', and when given, if it may be given as None/Null/Nil or an empty string. As a result, the code is littered with checks like if hasattr(obj, 'alpha') and default fallbacks.

Is there a name or slang term for this kind of (imho) anti-pattern?

UPDATE:

it seems, currently there is no name, so i'd like to hear suggestions. Currently we have these:

Incorporeal Horde (credits to psr)

答:
In JavaScript, this is referred to as undefined, which is a unique sentinel value, distinct from null.

You get undefined by either evaluating the global variable undefined, or a property of an object, that is not defined or by evaluating a statement, that doesn't return a value, such as calls to functions, that don't return anything, or a block or a variable declaration (although those two aren't valid expressions, so you will only encounter that in a JavaScript REPL).

When the undefined value is coerced to be an Object it becomes null, but it is not null.

Here's a little illustration:

```<code>var a = [1, 2, 3];//undefined
a[0];//1
a[4];//undefined

var o = { foo: "123" };//undefined
o.foo;//"123";
o.bar;//undefined

function bar() { return null; };//undefined
bar();//null
function foo() { /*just an empty block*/};//undefined
foo();//undefined

typeof undefined;//"undefined"
typeof null;//"object"
null == undefined;//true - that is because undefined is converted to an object for comparison and thus yields null
null === undefined;//false - because they are not the same
</code>```

I think it is reasonable to call undefined values (in contrast to values defined to be null) undefined, if that is your question. Using a unique sentinel value to communicate the absence of a defined value is a workable solution for dynamic languages, although it is often poorly understood.

Body:
In JavaScript, this is referred to as undefined, which is a unique sentinel value, distinct from null.

You get undefined by either evaluating the global variable undefined, or a property of an object, that is not defined or by evaluating a statement, that doesn't return a value, such as calls to functions, that don't return anything, or a block or a variable declaration (although those two aren't valid expressions, so you will only encounter that in a JavaScript REPL).

When the undefined value is coerced to be an Object it becomes null, but it is not null.

Here's a little illustration:

var a = [1, 2, 3];//undefined
a[0];//1
a[4];//undefined

var o = { foo: "123" };//undefined
o.foo;//"123";
o.bar;//undefined

function bar() { return null; };//undefined
bar();//null
function foo() { /*just an empty block*/};//undefined
foo();//undefined

typeof undefined;//"undefined"
typeof null;//"object"
null == undefined;//true - that is because undefined is converted to an object for comparison and thus yields null
null === undefined;//false - because they are not the same

I think it is reasonable to call undefined values (in contrast to values defined to be null) undefined, if that is your question. Using a unique sentinel value to communicate the absence of a defined value is a workable solution for dynamic languages, although it is often poorly understood.


问:
Understanding the Open Game License
I'm thinking about using the basic mechanics behind the D20 system royalty-free, however, I'm unsure if the OGL allows that. Any thoughts appreciated. And if I can't use the D20 system royalty-free, then any suggestions on other well tested systems appreciated as well.</p>

答:
You absolutely can. You need to have all software based on the d20 SRD follow the license such as clearly marking what is and is not Open Game Content and PI.

Here is software that is actively using the OGL : http://www.dundjinni.com/eula.htm

Title: Understanding the Open Game License


问:
C++ wrapper for "releasing" a singleton object
I have a class like this

```<code>    template <typename T, typename Policy>
    AutoObjectRelease {
public:
    AutoObjectRelease(T& obj):obj_(obj){}

    ~AutoObjectRelease(){ Policy::Release(obj_); }
private:
    T&  obj_;
}
</code>```

I wonder how one would you name this class, as it seems to me this could be quite a common pattern. I also wonder in which other situations you would use such a class. In my case I use the singleton object only sporadically and I wanted to make sure it doesn't remain loaded for the duration of the application. What are your thoughts on this ? Another idea would be to make the singleton object reference counted, but don't know exactly what would be the benefits for a singleton object - it might only complicate the implementation (need to make it thread safe also)

答:
It's called a smart pointer. Specifically, the unique version is in the next Standard as a unique_ptr, and the reference-counted version is in Boost, TR1 and C++11 as shared_ptr.

As for it's uses with Singletons, let me give you a hint: Don't use Singletons and you won't have many, many, many problems.

This is exactly a smart pointer, but with default deletion not provided.


答:
I think people in the 60's used their own human experience to divide problems into "hard problems" and "easy problems": Things like winning chess, solving logical riddles, solving mathematical equations seem hard to us humans. Things like understanding natural languages or finding the outlines of objects in an image seem easy, because our brain does all the work without conscious effort. When we try to explain how we do those things, we come up with simple explanations like "English sentences always have the structure subject-predicate-object where subject can be a simple term or a phrase...", or "I'm looking for edges and connect them to object boundaries". Today we know things aren't that simple, but only because all the simple (and many not-so-simple) solutions have been tried and didn't work.

Besides, this fallacy didn't start in the 60's: There's centuries of research on how to solve those "hard problems" (heuristics, game theory, decision theory, mathematics, logics, etc.) but I'm, not sure anyone ever bothered to research how natural languages might be parsed before the 1950's.

And even today, you can regularly find questions on stackoverflow, where people ask how they can parse English sentences, estimate the age of a person in an image, judge if an image is "safe for work" or if two images show the same thing. I don't think the people who ask these questions suffer from too much hubris or arrogance: These problems just seem so simple, it's unbelievable that there is no simple algorithm to solve them.


问:
Favoring Immutability in Database Design
One of the items in Joshua Bloch's Effective Java is the notion that classes should allow mutation of instances as little as possible, and preferably not at all.

Oftentimes, the data of an object is persisted to a database of some form. This has led me to thinking about the idea of immutability within a database, especially for those tables that represent a single entity within a larger system.

Something I have been experimenting with recently is the idea of trying to minimize the updates I do to table rows representing these objects, and trying to perform inserts instead as much as I can.

A concrete example of something I was experimenting with recently. If I know I might append a record with additional data later on, I'll create another table to represent that, sort of like the following two table definitions:

```<code>create table myObj (id integer, ...other_data... not null);
create table myObjSuppliment (id integer, myObjId integer, ...more_data... not null);
</code>```

It is hopefully obvious that these names are not verbatim, but just to demonstrate the idea.

Is this a reasonable approach to data persistence modeling? Is it worth trying to limit updates performed on a table, especially for filling in nulls for data that might not exist when the record is originally created? Are there times when an approach like this might cause severe pain later on?

答:
Disclaimer: I am pretty much a newby in DB :p

That being said, this approach of satellizing data has an immediate impact on performance:

Good less traffic on the primary table

Good smaller rows on the primary table

Bad requiring the satellite data means another look-up is necessary

Bad more space occupied if all objects exist in both tables

depending on your requirements, you may either welcome this, or not, but it is certainly a point to consider.


问:
How do you tackle really bizarre errors that keep you puzzled for more than 10 hours?
You know them, those errors that make NO sense. Where it seems like a gremlin just jumped deep inside your chips and messed up something. Do you take a walk, write stuff, call an uncle?</p>

答:
Take a bath.

Any Rodney McKay fans?

Seriously, though, if there's one commonality among all these answers, it's to take a break and do something else.

I like to think of it as relegating the problem to your subconscious. Even if we are otherwise unaware, our minds (seem to) continue to work on the problem, even when we're doing something else, such as taking a bath.


问:
Project management tool built into visual studio
My friend and I are working on a project together in visual studio, and we are using subversion for source control.  We have used php based project management tools before for task and bug tracking, but we find it inconvenient to go to work in visual studio for hours then have to go find the website and log in and report on what we already made commit notes for, especially since sometimes we are working off line and then have to remember to go back and update the trackers.

We are wondering if there is a project management tool (or set of tools) that is built into (slash an add-on) Visual Studio that will work with AnkhSvn allowing multiple people to maintain and track tasks.

答:
Trac works very well with Subversion and provides a wiki, ticketing, basic project management, and many community plugins. To achieve the integration between commits in SVN and Trac, you can use Subversion commit hooks to automatically cross-reference commit comments to tickets.

This means that by using AnkhSVN within Visual Studio (or TortoiseSVN outside VS), your commit comments will be copied to an open Trac ticket (in fact I would recommend that this be enforced by using a pre-commit hook) providing the essential link between source control and the ticket system. Using the correct syntax (e.g. "fixes" vs. "refs") you can also close tickets using your commit comments. General ticket/task maintenance still requires you to log in to your Trac website.


答:
I generally do one of the three:

Take a walk/bike ride...some that gets you away from the computer.

Play with my dog or cat

If you have a hobby, work on that for a while.

Any of the three do a good job of distracting oneself from the situation at hand.  I find the distractions let my subconscious brain chew on something for a while.  After an hour or so of this, bam, there's the solution :-).

Title: How do you tackle really bizarre errors that keep you puzzled for more than 10 hours?

Body: You know them, those errors that make NO sense. Where it seems like a gremlin just jumped deep inside your chips and messed up something. Do you take a walk, write stuff, call an uncle?</p>


答:
Step through it step by step, down into assembly. Who calls what, break-point on memory access. That usually catches the bug real fast.

If not, take a walk.


答:
This just seems wrong to me, maybe i'm misunderstanding it.

You are. Open Source is in itself a protected term. A project under Open Source license is using a license that has been approved by the OSI – and all those licenses imply, by definition, that the licensed product is free (as in free beer)1). There is no discussion about that.

CKEditor is an instance of double licensing. But their commercial license does not negate the fact that it’s also OSS, which makes it free for you, if you can abide by the remaining terms of that license. If you can’t, your only choice is to pick the non-free commercial usage license.

As a developer, if you contribute to an Open Source project, you are contributing to a free project. Sure, the maintainer may still make money from it, but so what? It’s still free to use and modify for everybody who wants to. As a “service in return”, if you will, the maintainer makes sure that updates are incorporated into the code, pushed to distributors and published.

1) First point of the Open Source Definition


答:
Edit:

The short answer:

Q: How do you tackle really bizarre errors that keep you puzzled for more than 10 hours?

A: Make sure they never happen: understand your design, know your code, learn how to use your debugger.

Explanation:

"Where it seems like a gremlin just jumped deep inside your chips and messed up something"

This should never happen. If it's your code, you should have a very good idea of what is causing the error before you attempt to fix it.

Futhermore, when you write your code you should already know where and why it's likely to fail.

Having said that - asking a peer, posting on SO, retracing and rolling back your steps and taking a break - all the suggestions mentioned above will help.

The other thing, is you must know your tools - your debugging toolkit. Logging messages at suspect points in your code, examining your call stack carefully, using conditional breakpoints and watches, etc etc. Debugging skills are not extras - they are part of programming.


问:
Do the young minds need to learn the pointer concepts?
Why did the C master Dennis Ritchie introduce pointers in C? And why did the other programming languages like VB.NET or Java or C# eliminate them? I have found some points in Google, and I want to listen your comments too. Why are they eliminating pointer concepts in modern languages?

People say C is the basic language and pointers is the concept that makes C powerful and outstanding and makes C still to compete with more modern languages. Then why did they eliminate pointers in more modern languages?

Do you think knowledge of pointers is still important for new programmers? People are using VB.NET or Java these days, which supports more highly advanced features than C (and does not use any pointer concepts) and many people as I see now (my friends) choose these languages ignoring C as they support advanced features. I tell them to start with C. They say it's a waste to learn the concepts of pointers when you're doing the advanced things in VB.NET or Java which are not possible in C.

What do you think?

Updated:

The comments I read on Google are:

The earlier computers were too slow and not optimized.

Using pointers makes it possible to access an address directly and this saves time instead of making a copy of it in function calls.

Security is significantly worse using pointers, and that's why Java and C# did not include them.

These and some more what I found. I still need some valuable answers. That would be greatly appreciated.

答:
Why did the C master Dennis Ritchie introduce pointers in C?

Because pointers are a very powerful mechanism that can be used in many ways.

And why did the other programming languages like VB.NET or Java or C# eliminate them?

Because pointers are a very dangerous mechanism that can be misused in many ways.

I think programmers should learn about pointers, but from an educational perspective, it is unwise to introduce them early. The reason is that they are used for so many different purposes, it's hard to tell as a beginner why you are using a pointer in a particular circumstance.

Here is an incomplete list what pointers are used for:

dynamic allocation (new T)

recursive data structures (struct T { T* next; /* ... */ };)

iterators over arrays (for (T* p = &a[0]; p != &a[0] + n; ++p) { ... })

shared access to objects (T* new_pointer = existing_pointer;)

subtype polymorphism (T* pointer_to_base = pointer_to_derived;)

legacy call by reference (mutate(&object);)

optional types (if (p) { /* ... */ })

Note that using a single mechanism for all of these concepts demonstrates both the power and elegance for the experienced programmer and the great confusion potential for someone new to programming.


问:
What is better for prototyping: a statically-typed language, or a dynamically-typed one?
When working out the design for a new system, is it better to start with a statically-typed language (like Haskell), or a dynamically-typed language (like Ruby)?

Arguments I can think of:

With a static language, you can quickly create a specification and scope for what the program will do.  With a dynamic language, you can quickly create a working demo to present to the customer for review.

With a dynamic language, you often avoid having to rearrange data structures and refactor code when you change your design.  With a static language, you can define types before implementation, keeping the code to maintain very small.

With a static language, you have to figure out in advance what your program will do.  With a dynamic language, you can start writing code, and let the design grow organically.  As Paul Graham says in Hackers and Painters:

A programming language is for thinking of programs, not for expressing
  programs you've already thought of.

With a static language, the compiler can help identify many types of bugs.  With a dynamic language, you can begin testing and finding bugs sooner.

Static and dynamic typing both have advantages and disadvantages as far as prototyping is concerned.  However, they both seem to me like equally valid approaches.  Based on your experiences, which one is ultimately better?

Notes

Prototyping in natural language

A third type of language to consider: natural language.  Instead of prototyping in code, one can prototype in writing.  The customer can then read your documentation and critique your design early on, but cannot toy around with a working demo.  If well-written, the documentation can make implementation in any language straightforward.  Caveats:

The documentation may be tedious to read through, and difficult to digest without being able to see it.  I speculate that a customer would rather experiment with something that works rather than read a wall of text (and images).

Prototyping an application in English rather than in type definitions is more verbose and less concrete.

Haskell types are descriptive

Note that types are particularly descriptive in Haskell, more so than in many static languages like C++ and Java.  For example, suppose I have a function with this type signature in Haskell:

```<code>foo :: forall a. [a] -> a
</code>```

A function that, for any type a, takes a list of items of type a and returns a value of type a.

Even without knowing the function's name, I know for a fact that:

It does not perform input/output or modify any values (well, unless it uses unsafePerformIO incorrectly), because Haskell is purely functional.

It cannot treat the items as, say, integers, because it has to support any type.

It has to use the input list (that, or throw an exception or go into an infinite loop).  Otherwise, where would it get a value of type a from?

Therefore, the only thing this function could possibly do (other than fail) is extract an item out of the input list and return it.  Although I still do not know which item it will use, [a] -> a tells me just about everything else.

答: Dynamic, especially if you know that the actual product would have to be in one of several popular static languages to be fast enough to solve the real problem in the wild.  Doing this will automatically protect you from making the mistake of using the prototype as the end product.</p>


答:
If it is a desktop program, how to build the entire system from scratch (may be several separate programs), how to create a package for distribution (what dependencies it has, e.g. versions of .NET), and how to deploy it to servers for download if that is applicable, or burn it to a CD or DVD.

If it is a web-based program, FTP and (if applicable) SSH access to the server, and what tools are used to locally create and test the code.

If it is an embedded system, complete instructions on building the binary image, what tools are used, how to download and flash the code into the product, how to set up the filesystem on the device, if any.


问:
C++ to friend or not to friend
I have an object oriented programming with c++ course this semester at college and we were learning about friend functions.

I instinctively dislike them for their ability to bypass the security that Encapsulation and Data hiding provide, I read a few articles on the internet and some people thought that it was a good idea with some legitimate uses.

What would an OOPs expert say about friend fucntions in C++? Should I just skim over it or should I learn more about it?

答:
Friend functions are best used for user-defined operator definitions.  They are useful in other situations, but if you find yourself specifying friend classes frequently then you may be on a design detour (just a good self-check to use while writing code).

Do be careful about the "security" statement in the original question.  Access modifiers are there to prevent you from writing bad code on accident, just like the compiler in a way.  Access modifiers limit the interface, and serve to communicate what functions are important to use the class (public and protected), and which ones were created as part of making the class prettier for the maintainers (private).  Modifiers do not constitute security in that there are many ways to get at private data.  For example, get a pointer to the class and its size, and go fishing.

Title: C++ to friend or not to friend


问:
Should a competent programmer be able to come up with his own shortest path algorithm?
I'm suffering a crisis of confidence in my ability as a computer programmer.

Yesterday I tried to come up with my own shortest path algorithm for a graph and after some hours I simply threw in the towel and learned Dijkstra's algorithm.

Is this the kind of thing a good programmer should be able to "reinvent" in a couple of hours or am I being unrealistic?

Oh well, at least I was able to reinvent bubble sort :D

答:
Yes, he/she should.

It might be the moral equivalent of bubble sort, but I do think a good programmer should be able to come up with at least something that works, however inefficient it might be.

Needless to say, if that particular problem would come up a good programmer would first look if there is a library to do that for him, or which published algorithms do that and are easy to implement.

Of course, many programming tasks are much less difficult and not everybody needs to be able to tackle such hard problems. But you'll want to have someone with a mind like that on your team, because you might have some complicated project specific problems where you can't rely on loads of previous scientific research.


答:
The idea of avoiding updates, and preferring inserts, is one of the thoughts behind building your data storage as an Event Source, an idea you will often find used together with CQRS. In an event source model, there is no update: an aggregate is represented as the sequence of its "transformation" (events), and as a result the storage is append-only.

This site contains interesting discussions on CQRS and event sourcing, if you are curious about it!

Title: Favoring Immutability in Database Design

Body:
One of the items in Joshua Bloch's Effective Java is the notion that classes should allow mutation of instances as little as possible, and preferably not at all.

Oftentimes, the data of an object is persisted to a database of some form. This has led me to thinking about the idea of immutability within a database, especially for those tables that represent a single entity within a larger system.

Something I have been experimenting with recently is the idea of trying to minimize the updates I do to table rows representing these objects, and trying to perform inserts instead as much as I can.

A concrete example of something I was experimenting with recently. If I know I might append a record with additional data later on, I'll create another table to represent that, sort of like the following two table definitions:

```<code>create table myObj (id integer, ...other_data... not null);
create table myObjSuppliment (id integer, myObjId integer, ...more_data... not null);
</code>```

It is hopefully obvious that these names are not verbatim, but just to demonstrate the idea.

Is this a reasonable approach to data persistence modeling? Is it worth trying to limit updates performed on a table, especially for filling in nulls for data that might not exist when the record is originally created? Are there times when an approach like this might cause severe pain later on?


答:
In addition to what have been said, providing a reason for the requirements allows you to judge the validity of the requirement. The user may want things for the wrong reason. Having the "so that" clarifies the reason hence allows the analyst to validate that the request is best satisfied in this way.

Example:

A-I want to be able to select employees from a list of all company employees

B-I want to be able to select employees from a list of all company employees so that I can delete the ones that have left the company 5 years ago.

(B) does not make sense even in a medium organization, but you can validate the user requirement and propose another way for the customer to fulfill the requirement.

Title: What's the purpose of 'so that' clause in user story definition?

Body:
A user story can be defined in a sentence like:

```<code>As a <type of user> I want <some goal> so that <some reason>
</code>```

Just Google for 'user story formula' and first links all propose this formula.

My question is, what is the purpose of so that clause? Is it there for managers? Is it there so that project managers and stakeholders can understand the priority of the item better? Why is it there?

Note: I've worked with as a <type of user> I want <some goal> formula, and it works just well. I haven't noticed any problem in my work by implementing this format which is more brief.


问:
Is it okay to use a language that isn't supported by your company for some tasks?
I work for a company that supports several languages: COBOL, VB6, C#, and Java. I use those languages for my primary work, but I often find myself coding some minor programs (e.g. scripts) in Python because I find it to be the best tool for that type of task.

For example: an analyst gives me a complex CSV file to populate some DB tables, so I use Python to parse it and create a DB script.

What's the problem?

The main problem I see is that a few parts of these quick and dirty scripts are slowly gaining importance and:

My company does not support Python

They're not version controlled (I back them up in another way)

My coworkers do not know Python

The analysts have even started to reference them in emails ("launch the script that exports..."), so they are needed more often than I initially thought.

I should add that these scripts are just utilities that are not part of the main project; they simply help to get trivial tasks done in less time. For my own small tasks they help a lot.

In short, if I were a lottery winner to be in a accident, my coworkers would need to keep the project alive without those scripts; they would spend more time fixing CSV errors by hand, for example.

Is this a common scenario? Am I doing something wrong? What should I do?

答:
My rule of the thumb is:

Anything that potentially impacts the work of others should be discussed with your peers and superiors ASAP.

But, if it's for you and you alone, as long as it doesn't do any damage to your firm's infrastructure or security, you are free to do as you wish to get the job done.

ContentLicense: CC BY-SA 4.0


问:
What is a *slightly* less extreme equivalent to being "fluent" in a language?
tl;dr: What is a less extreme (but still noticeable) alternative to the word "fluent", when saying e.g. "I am fluent in C++/Python/whatever?"

I think I can call myself "fluent" in C#, because I know the language and runtime very well, and I'm very familiar with the .NET framework's APIs and classes, etc.

I would like to claim the same thing for Python and C++.
But while I can program in Python (I did so for an entire summer, making a website with Django), for example, I would not call myself fluent because my code isn't always "Pythonic" (e.g. using map/filter vs. list comprehensions), and I'm not too intimate with some aspects of the language and standard library yet (e.g. the introspection API, etc.).

Is there a word or phrase I can use on e.g. a resume to describe what I know?

I can think of "very familiar with", but is there a better word/phrase I can use?

答: Would "proficient" be useful, if not that, "competent".  Both words suggesting a comfort with tasks given within a certain range.</p>


问:
How do people read big technical books?
I see that most of the good programmers have the habit of reading big books for learning about technology.

What does it really take to read technical books, apart from the real interest on the technology?

How can I improve my ability to read these books?

答:
I have lots of big fat technical books:

*) A good eReader is essential unless you want to set aside a LARGE area for dust bunnies to collect...  I like the Sony Reader line because of the way they handle notes, navigation and indexes - great for technical reading - but I don't work for Sony - 'to each, his own'.

*) I generally buy reference type books that are well indexed, and I rarely, if ever, READ them the way you read a novel. I read the preface and intro and scan the TOC and indexes, so that I know what's there when I need it.

*) I avoid big fat books on narrow specialized topics - IMO these generally turn out to be a waste, because by the time you finish the book, the technology is outdated, or you've moved on to another project, or they spend a lot of time on things that any experienced programmer will discover themselves buy just DOING IT.

Title: How do people read big technical books?


问:
Nightly builds for one-man projects
I'm working on a C++ wrapper for libpcap and I'd like to get more into version control as I'm not experienced with this (the only reason I used it was to put code on GitHub :)).

Does it make sense to schedule nightly builds for a one-man project? What advantages are there in doing this?

答:
Probably not.

The advantages of automated nightly builds only start to play when the team becomes so large that no individual team member can keep the entire project in their head anymore. When this happens, nightly builds ensure you always know whether you'd be able to ship if you had to, at any given time - but if you're going solo, you probably know anyway. It's still a good idea to have automated tests and a script that executes a full build (from clean checkout to shippable package) and run it every now and then: whenever you've completed a feature, refactored or rewritten some code, or did anything that could somehow break things.

Using source control, however, is an absolute must. Start using it, and you'll wonder how you ever managed to live without it.

Title: Nightly builds for one-man projects


答: If anything, I would suggest setting up a continuous integration server like Hudson or Jenkins and have it build and execute your tests after a check-in, as opposed to nightly. This has the benefits of giving you feedback on the current health of the project on a regular basis as you work on it, without wasting time and resources building when no changes have been made.</p>

Title: Nightly builds for one-man projects

Body:
I'm working on a C++ wrapper for libpcap and I'd like to get more into version control as I'm not experienced with this (the only reason I used it was to put code on GitHub :)).

Does it make sense to schedule nightly builds for a one-man project? What advantages are there in doing this?


答:
You've got it a little bit from the wrong angle.

The important idea is that you need reproducible builds!

Given any deployment you need to be able to later reproduce the exact build process that generated that deployment, so you can debug it and fix it.  Here it is important to use source control so you can retrieve those sources.  To be absolutely certain that the sources are the same, you should use a robot to check out the sources from your source controle and then build your program.  This has the added benefit of catching any dependencies not in source control.

If that process takes a long time to do (e.g. because you have a lot of tests in place) then it is nice to have the latest version available to everyone interested in the morning, i.e. you do a build at night.  If you do not have that need, then nightlies are probably not necessary (but you'll want the robot though!).

Also learn your source control well including how it is usually used by others.  This will give you tricks and ideas that will save you a lot of trouble in the long run.

Title: Nightly builds for one-man projects


答:
If you are referring to a natural spoken language, one step down from fluent would be "conversant", such as "Fluent in French, conversant in Spanish."

For programming languages, I usually write something like: "Very experienced in C and C++, familiar with Python and C#". But I agree with Irwin that "proficient" seems to be one step below "fluent", so maybe it goes: fluent --> proficient --> familiar.

Title: What is a *slightly* less extreme equivalent to being "fluent" in a language?

Body:
tl;dr: What is a less extreme (but still noticeable) alternative to the word "fluent", when saying e.g. "I am fluent in C++/Python/whatever?"

I think I can call myself "fluent" in C#, because I know the language and runtime very well, and I'm very familiar with the .NET framework's APIs and classes, etc.

I would like to claim the same thing for Python and C++.
But while I can program in Python (I did so for an entire summer, making a website with Django), for example, I would not call myself fluent because my code isn't always "Pythonic" (e.g. using map/filter vs. list comprehensions), and I'm not too intimate with some aspects of the language and standard library yet (e.g. the introspection API, etc.).

Is there a word or phrase I can use on e.g. a resume to describe what I know?

I can think of "very familiar with", but is there a better word/phrase I can use?


问:
Is there a term for the error-handling anti-pattern of discarding all available info and just returning failure?
From time to time (unfortunately way too often) I have to fix code such as this:

```<code>// C++ code
bool anyOldFunction(Param p) {
  try {
  ...
  if(some_condition_here) {
    handleErrorX();
    return false;
  } else if(other_condition) {
    return false; // (*stackexchange question comment*) Apparently no additional error action taken here
  }
  ...
  return true;
  } catch(...) {
    // (*old comment*) Catch all possible error (FroobleFub and BrabbleBub can happen)
    return false;
  }
}
</code>```

So, the original implementer actually had some inkling what exceptions could be thrown (although the list may not be exhaustive) but had no idea how to do some decent handling and just discarded any info he might have gotten out of the exception objects, leaving the calling code / the calling context non-the-wiser.

Is there a name for this anti-pattern? (If anti-pattern it is indeed.)

答:
direct answer to your question: I most commonly hear it referred to as swallowing or eating the error.

Indirect answer: It is not always an undesirable pattern.  Sometimes this pattern is desirable when you absolutely do not want the error detail leaving the tier/class/function/whatever you are currently in.  Data access was (is still in some instances) famous for including sensitive info in exception detail.  It is was fairly common in several past jobs to see exception blocks like that so that internal details were not exposed just by someone making a resource unavailable.  I sometimes heard people call this safe exceptions or secure failure.

The other place where I still see that pattern is where the exception detail just isn't important.  For example, when interacting with an external library that does not have a good way to check preconditions or lock a changing variable for example sometimes you just have to make the call and if it exceptions you know the value isn't available.  If you have another way to continue it is more efficient to consume the error as low as possible and pass a flag than to unwind the stack at every level with a whole mess of catch blocks.

You could certainly change it (and all it's calling methods to include extra catch blocks & not to rely of the return flag), but unless you have something meaningful that you can do with the exception detail at the next higher level and there is no risk of showing all the possible exceptions and stack business all you are doing is creating more places you have to code slow catch blocks.


问:
What has been learned about making variance part of the type?
In Java, the variance of parameterized types is indicated depending on how it's used:

```<code><A extends B,B> void store(ArrayList<B> list, A elem) {
    list.add(elem);
}
</code>```

Whereas in Scala it is indicated in the class declaration with a + or -.

What I want to know is, now that Scala has been around awhile, what has been people's experience with making variance a property of the type? Is it generally flexible enough for what you want to do? Are there aspects you would have done differently, knowing what you know now?

答:
There is a lot of misunderstanding in the question:

First, there is no such thing as "variance of parametric types". Types (as List[Int]) are, by themselves, fixed, and therefore not variant (co-/contra-variant). What can be co(ntra)variant, are type constructors, eg. List, which are not themselves types.

Therefore, the line

```<code><A extends B,B> void store(ArrayList<B> list, A elem)
</code>```

cannot "indicate variance of types", since it does not define any type constructor. It is a simple example of (bounded) parametric polymorphism.

We have several types of polymorphism in programming languages. The one most natural to OOP languages like Java is subtype polymorphism, which is characterized by the fact that from X <: Y and t : Y, it follows that t : Y (IOW if a term/variable/parameter/whatever has type X which is a subtype of Y, it has also type Y and is usable in any place a real Y would be).

Another type of polymorphism is parametric polymorphism, which means that some types are actually type variables, which represent a placeholder for any type and are instantiated to real types during typechecking. Bounded parametric polymorphism means the tpe variables can be constrained to be a subtype or supertype of other type. Generics offer parametric polymorphism in Java.

Now, how do these two play together? It seems natural that a file of employees can be read as a file of citizen, since every employee is naturally a citizen (which is captured in the program by the subtype relation). This means ReadableFile[Employee] <: ReadableFile[Citizen]. However, the rules for determining subtypes don't support this conclusion - both types are totally unrelated.

This is where variance comes to play. If we define some type constructors (in this case ReadableFile) to be co(contra-)variant, we can use inference rules like "if X <: Y and T is covariant, then T[X] <: T[Y]". In effect, this rule supports the conclusion above.

Parametric type constructors in Java are always invariant.

As you have already noted, we can sometimes get away without variant type constructors and still achieve the same effect. In function parameters,

```<code>def foo(x : TCovar[Reader]) : Unit
</code>```

with covariant TCovar is functionally equivalent to

```<code>def foo[A <: Reader](x : T[A]) : Unit
</code>```

This doesn't anyhow mean that T in the second definition is covariant.

However, in function return type and variable types, this trick doesn't generally help. Even in that case, we can get the same effect as variant type constructors with the help of existential types. So

```<code>val foo : TCovar[Reader]
</code>```

becomes

```<code>val foo : T[X] forSome { type X <: Reader }
</code>```

You can see this in action in this example. As you can see in the definition of v4 and v5, covariant type constructors can make the program much simpler. This simplification applies to the function parameter declarations, too, which is why functional programming languages with subtype polymorphism use variant type constructors (at least for their function types).

However, for a type constructor to be covariant, it needs to satisfy some rules. These rules cause that Java's List<T> and other interfaces are actually invariant, because they provide both reading and writing of the container data (which is typical for imperative programming). Scala's functional data structures don't work that way, so they can be covariant. It is demonstrated in the example, too - NCov can't be covariant, because it provides read and write access to its inner data. I believe this is the main reason covariant type constructors don't exist in Java, which is the answer to your question.

Sorry for mixing Java and Scala in this post. I hope the examples are so easy to understand that it doesn't matter.

Body:
There is a lot of misunderstanding in the question:

First, there is no such thing as "variance of parametric types". Types (as List[Int]) are, by themselves, fixed, and therefore not variant (co-/contra-variant). What can be co(ntra)variant, are type constructors, eg. List, which are not themselves types.

Therefore, the line

<A extends B,B> void store(ArrayList<B> list, A elem)

cannot "indicate variance of types", since it does not define any type constructor. It is a simple example of (bounded) parametric polymorphism.

We have several types of polymorphism in programming languages. The one most natural to OOP languages like Java is subtype polymorphism, which is characterized by the fact that from X <: Y and t : Y, it follows that t : Y (IOW if a term/variable/parameter/whatever has type X which is a subtype of Y, it has also type Y and is usable in any place a real Y would be).

Another type of polymorphism is parametric polymorphism, which means that some types are actually type variables, which represent a placeholder for any type and are instantiated to real types during typechecking. Bounded parametric polymorphism means the tpe variables can be constrained to be a subtype or supertype of other type. Generics offer parametric polymorphism in Java.

Now, how do these two play together? It seems natural that a file of employees can be read as a file of citizen, since every employee is naturally a citizen (which is captured in the program by the subtype relation). This means ReadableFile[Employee] <: ReadableFile[Citizen]. However, the rules for determining subtypes don't support this conclusion - both types are totally unrelated.

This is where variance comes to play. If we define some type constructors (in this case ReadableFile) to be co(contra-)variant, we can use inference rules like "if X <: Y and T is covariant, then T[X] <: T[Y]". In effect, this rule supports the conclusion above.

Parametric type constructors in Java are always invariant.

As you have already noted, we can sometimes get away without variant type constructors and still achieve the same effect. In function parameters,

def foo(x : TCovar[Reader]) : Unit

with covariant TCovar is functionally equivalent to

def foo[A <: Reader](x : T[A]) : Unit

This doesn't anyhow mean that T in the second definition is covariant.

However, in function return type and variable types, this trick doesn't generally help. Even in that case, we can get the same effect as variant type constructors with the help of existential types. So

val foo : TCovar[Reader]

becomes

val foo : T[X] forSome { type X <: Reader }

You can see this in action in this example. As you can see in the definition of v4 and v5, covariant type constructors can make the program much simpler. This simplification applies to the function parameter declarations, too, which is why functional programming languages with subtype polymorphism use variant type constructors (at least for their function types).

However, for a type constructor to be covariant, it needs to satisfy some rules. These rules cause that Java's List<T> and other interfaces are actually invariant, because they provide both reading and writing of the container data (which is typical for imperative programming). Scala's functional data structures don't work that way, so they can be covariant. It is demonstrated in the example, too - NCov can't be covariant, because it provides read and write access to its inner data. I believe this is the main reason covariant type constructors don't exist in Java, which is the answer to your question.

Sorry for mixing Java and Scala in this post. I hope the examples are so easy to understand that it doesn't matter.


问:
Product Owner and automated tests
One of the claims of BDD-style development is that it bridges the gap between Product Owner and developers: the Product Owner writes a story, which can be converted in an equivalent automated test "frame" that should eventually pass.

What I would like to hear is how to keep bridging the gap after that: once there are automated tests in place, how do you help the Product Owner review them? Or is it enough for the Product Owner to know that the test passes, without looking at the test code itself?

In short, how intimate should the Product Owner be with the actual tests implemented, and how do you keep him/her productively involved with the tests beyond the initial story writing?

The reason behind this question is double. First, between the paper story and the implementation details, some assumptions may sneak in, and having the author of the story review the test can be invaluable. On the other hand, the implementation introduces quite a bit of noise, too, and requires the PO to become fairly technical (read code, run tests). Is the test implementation a "developer's detail", or is it fair to request the PO to become a bit of a developer in this area?

Then, in most case, the PO can actually validate the test without the automated test, by simply using the application. However, some stories are "headless" and can only be verified via code, so unless the PO knows how to read and run tests, he/she will never be able to state that he verified the story complete.

答:
What I would like to hear is how to keep bridging the gap after that: once there are automated tests in place, how do you help the Product Owner review them? Or is it enough for the Product Owner to know that the test passes, without looking at the test code itself?

The Product Owner (or whoever is wearing the Product Owner hat at the time) is acting in a non-technical capacity. They are simply representing the customer and users of the product. They care nothing about how the process works, they are just responsible for developing, prioritizing, and accepting stories.

If your Product Owner is also a developer (which is possible - that paring is not one of the ones that is advised against), then perhaps the best task for them would be to serve as the developer of the test cases. If they aren't a developer, work with them to see what they want. Someone with no development experience wouldn't get value out of seeing the implementation of the test cases.

First, between the paper story and the implementation details, some assumptions may sneak in, and having the author of the story review the test can be invaluable. On the other hand, the implementation introduces quite a bit of noise, too, and requires the PO to become fairly technical (read code, run tests). Is the test implementation a "developer's detail", or is it fair to request the PO to become a bit of a developer in this area?

This is the difference between verification (your automated tests) and validation (acceptance tests and other tests/reviews conducted by the Product Owner).

The fact that you have test cases to verify the user story is good. However, it's up to the Product Owner to actually validate the implementation. Saying that your test passes is only good enough to say "we have implemented the story as we understand it", not enough to say "the implementation of this story meets the needs of the customer and the users". The Product Owner should perform additional acceptance testing on the application to validate the story and its implementation.

However, some stories are "headless" and can only be verified via code, so unless the PO knows how to read and run tests, he/she will never be able to state that he verified the story complete.

I'm just going to be straight on this one - those aren't good user stories. The whole point of a user story is to explain how the user will interact with a system. You might develop internal stories to break down a user story, and those might be "headless". But you'll know that you have completed those based on your passing internal tests and the larger user story passing acceptance testing.

Title: Product Owner and automated tests


问:
Is there a reason for initial overconfidence of scientists and engineers working on artificial intelligence in the 1960s?
I just started an AI & Data Mining class, and the book. AI Application Programming, starts off with an overview of the history of AI. The first chapter deals with the history of AI from the 1940s to present. One particular statement stuck out at me:

[In the 60s] AI engineers overpromised and underdelivered...

What was the reason for the overconfidence? Was it because of mathematical prediction models showing that a breakthrough was around the corner, or due to the ever-increasing hardware capability to take advantage of?

答:
In addition to the good answers given, two observations:

Some quotes of the day seem to imply that many of the researchers were thinking that the trivial solutions could be scaled up once faster computers were designed.  For some kind of learning systems this was very true, but for the kind of thing I think the OP is referring to it really didn't get any better at scale.

Researchers at the time had a very low estimate of the complexity of the human mind (focus on ideas like Turing test, the idea that people only use a small percentage of their brain ever, etc).  AI at the level of a simple animal has been achieved by some measures as things scaled up, but the jump to a human level AI was a lot bigger than expected.  This has lead some researchers to try learning baby systems and other growth/evolution based simulations as an attempt to bridge that gap.


问:
What should you leave behind for your successors?
Assume that you're a sole developer leaving a job. What kind of information/material, outside of the code itself, should you create and leave behind for your replacement?

An obvious answer is "whatever you would want at a new job" for sure, but it's been a while since I started a new job, and I forget what the most important things that I needed were back then.

I'm thinking:

accounts/passwords

location of equipment, backups, software CDs

What else?

答:
A strong cup of coffee and an apology note.

Is what I wish I was left.

Documentation. How hard is it to write a few comments? Build notes, deployment notes, moving the system notes. What to do when you restart and everything is gone.

Papers. Write up why it's being done this way so I don't have to wonder why you aren't doing it another way. How does the backup system work, how does the server respond to loads, testing, test cases, use cases.

Notes. "When using the database, don't ever say SELECT * FROM clients. We aren't sure why but it dumps the database".


问:
When should development branches be created?
We are moving our project's team from using a single Main/Trunk branch, to multiple Development/Work branches that should be regularly merged into Main. We're basing our new process on this article and the TFS Branching Guide (we are using TFS and Visual Studio 2010).

There are currently between 1 and 5 people working on the project at any one time. Main must be stable at all times because we want the option to release whenever we need. We don't have fixed sprints - at least not yet - and at the moment release every 1-2 weeks.

Right at this point in time each person is fixing bugs across the application. In a couple of weeks we will be starting development on a new large component for the app.

One sticking point we are finding is when development branches should be created. We will be implementing multiple user stories in parallel depending on the skill set of the developer. We've thought about creating a branch for each developer but that doesn't make sense because there will always be some need for collaboration on a piece of work. We can't get by with a single development branch because we will want to merge to Main while other work is completed.

Does anyone have some guidance on this?

答:
We can't get by with a single development branch because we will want
  to merge to Main while other work is completed.

It sounds like you already know that multiple development branches must be created. Two probable scenarios come to mind:

Each of the five developers are working on independent parts of the project (bug-fixing) - Make sure that an individual branch is created for each developer. This places the onus and responsibility onto each developer to make sure their set of changes does not conflict with anyone else's work. It is highly likely that one of your five developer will make a mistake. If/When that's the case, it doesn't make any sense for everyone else to be held up.

Multiple feature developments - Regardless of the number of developers working on a particular feature/bug, these should be separated. An example of this being beneficial is that all code commits are part of the feature(s) being developed - there's no second-guessing involved.


问:
Do programmers possess the means of production?
I was listening to The Servile State by Hilare Belloc this morning and pondering whether or not I possessed the means of production, as did the peasant of the Middle Ages; as did not his descendants after the oligarchs of England forced him into servitude.

The means of production was the arable land that the serf was seated on, which, even though not legally his, was illegal to evict him from.

So, as programmers, with the hitherto unknown supply of free tools and resources, have we reclaimed as a class of workers, unlike any others, the means of production? Given the chance, a midrange PC and a stable internet connection, could we not each of us be wholly self-sufficient and not just wage-earners?

答:
There is nothing unique about programmers. If you want to use classical Marxist terminology they are petite bourgeoisie. From the Encyclopedia of Marxism:

Petit-Bourgeoisie, lit., “little city-folk” – the small business
  people, sometimes extended to include the professional middle-class
  and better-off farmers.

Some of the more successful entrepenurial programmers enter the haute-bourgeoisie.


问:
JavaScript's prompt, confirm and alert considered "old-fashioned"
Lately I've been developing a web-based management system for a gym. Their previous app was developed in Visual Basic. For the new app, all the front-end scripting uses jQuery, the server is running PHP & MySQL... you know, the typical el-cheapo linux based stack.

Anyways, I was wondering why JavaScript's prompt, confirm and alert message dialogs are so underused nowadays. There a lot of jQuery plugins for modal windows and alert messages that try to mimic something that the language already offers and every browser is forced to support properly.

Using hand-made or plugin-based solutions is ok for complex forms and special needs, but if you just need to ask for a single value or confirm the deletion of a record, why would you add such overhead to your web app? Furthermore, iOS and Android offer nicely adapted message dialogs when you use prompt, confirm and alert.

答:
You are only adding overhead if you don't need the fancy dialogs elsewhere, which you probably do. At that point it doesn't make much difference whether the functionality is included as part of the browser or as part of the framework you are using, and you may as well keep all your popups looking consistent.

While you can do a lot with javascript and no frameworks, I remember what it was like developing in javascript before the frameworks were available, and I wouldn't want to go back to it.


问:
Want to know performance issues of Class types & access modifiers
Someone suggested me to mark classes as SEALED that are not being inherited anywhere. I was using default style and was not concerned with the type of class. At present I don't have a benchmark tool to study the performance gains but read somewhere that Sealed Classes give performance benefits.

Is this performance issue applicable to other class types like: Abstract, Static, New etc. and also with access modifiers like public, protected, internal, protected-internal and virtual?

If it does make difference in performance, what type of optimization is done internally?

答:
Yes, using sealed classes, in addition to significant design benefits, can offer some performance benefits.

The design benefits (which you say you aren't interested in, but I'll include here for a complete answer) are that one can avoid the Brittle base class problem.  Which, briefly, means a future change to a base class can cause problems if things aren't marked sealed.

As stated in the link you posted: "Sealing the virtual methods makes them candidates for inlining and other compiler optimizations" and "virtual members...are more expensive to call due to a virtual table lookup".

The .NET framework makes every attempt to optimize virtual dispatch, so by no means are virtual function calls 'expensive', but they are somewhat slower than a direct function call, or better yet an inlined function.  This extra overhead is only significant if the function you are calling is extremely short (e.g. doesn't iterate over data), and if the function call is within a loop.

If you want detailed information on approximately how much slower a virtual function call is, consider this link.

As for the other keywords:

static functions are not overridable, so they are the same performance as sealed.  All the rest will not make a difference in the performance of your class.  However, as the link states, field and method design choices can (e.g. volatile fields are slower).


答:
Because browsers don't handle them very well. As you may have noticed they are usually modal dialogs and not only prevent users from moving and resizing their browsers they also prevent other tabs from being accessed, which is very annoying.

For dialogs like confirm and alter I still think the browser should be enforcing the behaviour, and for the latest Firefox browser you can see they've fixed the problem I mentioned above. They use in page alerts that are scoped to the current page.

Therefore I suggest that you override the alert behaviour so that all browsers can handle (at least alerts) more elegantly.

A few summarised reasons:

This is the standard API and developers can figure out what you’re trying to do.

It’s more user friendly, and looks better.

Platform support, mobile sites might need the native API.

Title: JavaScript's prompt, confirm and alert considered "old-fashioned"

Body:
Lately I've been developing a web-based management system for a gym. Their previous app was developed in Visual Basic. For the new app, all the front-end scripting uses jQuery, the server is running PHP & MySQL... you know, the typical el-cheapo linux based stack.

Anyways, I was wondering why JavaScript's prompt, confirm and alert message dialogs are so underused nowadays. There a lot of jQuery plugins for modal windows and alert messages that try to mimic something that the language already offers and every browser is forced to support properly.

Using hand-made or plugin-based solutions is ok for complex forms and special needs, but if you just need to ask for a single value or confirm the deletion of a record, why would you add such overhead to your web app? Furthermore, iOS and Android offer nicely adapted message dialogs when you use prompt, confirm and alert.


问:
Term for domain specific business object?
This question might be a little vague.

I have seen an acronym referring to a business object in a software system. It's usually mentioned when discussing such design patterns as Java EE's DAO pattern.

答: Possibly a Data Transfer Object (DTO) or a Plain Old Java Object (POJO). Some more context would be useful as there are many, many such acronyms.</p>


答:
1. UX: message boxes are mostly evil

Alert boxes are bad in all cases from the UX point of view. In desktop apps. In web apps as alerts or inline JavaScript messages. Everywhere.

You can read About Face 3 by Alan Cooper¹ if you want to know why; it explains very well how does this interrupt the workflow and annoys the user, and how nearly every alert box which exists in current software is deeply wrong. On page 542, "The dialog that cried “Wolf!”" explains that alert boxes are dismissed routinely, so their model is completely broken. On page 543 of the book are listed three major design principles:

Do, don't ask.

Make all actions reversible.

Provide modeless feedback to help users avoid mistakes.

Then, the authors tell us how to replace the alert boxes by the correct design approach.

Prompt messages are slightly different. And still, they break the user experience of your app. If you want the user to enter something, consider using a textbox or a textarea, decorating it with JavaScript when need. Don't be lazy, provide a rich interface in an era of RIA and AJAX-enabled apps; in all cases, if JavaScript is disabled, your prompt will not be displayed.

In web pages, both alert boxes and prompts are mostly annoying. Some examples:

Some forums let you create lists by prompting infinitely for the list items. It means that while creating the list, you cannot use the page itself, including copy-paste. You also have a single tiny field. What about long text? What about bold and italics?

"If you continue, the photo will be removed definitively from your profile. Are you sure?". Of course I am sure! Would I click "Remove photo from my profile" otherwise? Why your web app supposing I'm so stupid? Actually, Google applications as GMail show the correct approach. You can remove, delete, destroy whatever you want, and when you do so, the app displays a small "Undo" link.

"Do you want to take our greatest survey?". Well, actually I was there to visit your website, but since you bother me with your annoying messages, I would rather go somewhere else.

"The right click is disabled on this website in order to protect copyrighted photos". Well, actually I right-clicked to change the language of spell checker before sending my comment. Sure, I'll send it without checking the spelling.

Conclusion: from user experience point of view, the applications use message boxes wrongly most of the time.

But wait! Many low-quality websites replace annoying alert boxes by annoying JQuery messages with a semi-transparent background which covers all the page. So the drawbacks remain.

Well, there are another reasons not to use message boxes in web applications :

2. Design: alert boxes have their own design

You can't design an alert box at all. You can't change its color, its size, its font. This makes it even more annoying for the user: you were working with a web app, and your workflow is broken by a message which seems to come from nowhere and does not even match the visual aspect of the app. Not counting that the language of the buttons also match the OS/browser language, not the web application one.

For designers, JavaScript messages are much more powerful than the alert boxes.

They are also much more extensive. You can add bold and italic, you can choose your own buttons (what about: "We apologize but the password you entered is invalid. [Reset my password] [Try another one] [Cancel]"?)².

3. JavaScript: application flow stops

When displaying an alert box, JavaScript stops executing until the user clicks. On a website, it might be ok. With a web app, it often becomes a problem.

4. Sandbox: don't force the user to reboot his computer

Remember the crappy websites which show you an infinite number of message boxes? The only way for the users without enough technical background to be able to continue working was in fact to reboot their computer. This brings us to a problem: alert boxes are out of the scope of the website or web application. You are not authorized to prevent the user from accessing other tabs of the browser³.

The same problem forced the browsers to solve it in different ways. Firefox, for example, permits the access to other tabs when displaying an alert on your tab. Chrome, on the other hand, allows you to check that you don't want to get any alert boxes from a page any-longer, but still blocks the access to other tabs.

While Firefox approach is perfectly valid, Chrome's one can be criticized (since it still blocks every tab), and causes a problem: what if the user was severely annoyed by several message boxes issued by your app and checked the case, and then, you tried to show something really important? Right, the user will never see it.

The fact remains the same, most users will be annoyed by alert boxes, so they are still not very user friendly, and may severely block a user with no enough technical background. Inline, JavaScript messages may block the page, but not the browser itself. Since web app model is a sort of sandboxing, where you can't for example access the user keyboard or reboot the computer or read files from hard disk or go full-screen or use two monitors, alert boxes with their blocking effect break severely this sandboxing model.

Last but not least, what if the user was on another tab when your application decided to show the alert box? What if the user was doing something important, and does not want to interact with your app right now?

¹ About Face 3, The Essentials of Interaction Design, Alan Cooper, Robert Reimann and David Cronin, ISBN 978-0-470-08411-3; Chapter 25: Errors, Alerts, and Confirmations.

² This is just an example. Please, don't do it in your web applications, since it's really a poor design choice.

³ If you want a comparison with the world of desktop apps, an inline JavaScript message is like a message box of a desktop application. An alert box in a browser, on the other hand, is like a window appearing from nowhere, set as topmost, on a full-screen opaque background which blocks you from accessing any other desktop application. Any app which will decide to do it once on my computer will be removed immediately, and forever.


答: The #1 rule for documentation is not what it does but why.  What's the backstory on the programs that run, and what they do?


答:
Not any more than writers who sell their books to publishers. Intellectual property is the means by which rent-seeking capitalists extract profit from the labor of programmers, writers, et al.

And then ideas themselves are turned into property via the patent system. One only needs to watch Stallman discuss how many lawsuits he faced when developing Emacs.

These ugly property regimes can be seen as the rash that formed on the cold hands of capital after high-paying jobs didn't require expensive (i.e., capital-intensive) machinery.

Title: Do programmers possess the means of production?

Body:
I was listening to The Servile State by Hilare Belloc this morning and pondering whether or not I possessed the means of production, as did the peasant of the Middle Ages; as did not his descendants after the oligarchs of England forced him into servitude.

The means of production was the arable land that the serf was seated on, which, even though not legally his, was illegal to evict him from.

So, as programmers, with the hitherto unknown supply of free tools and resources, have we reclaimed as a class of workers, unlike any others, the means of production? Given the chance, a midrange PC and a stable internet connection, could we not each of us be wholly self-sufficient and not just wage-earners?


答:
I'm not fond of arbitrary branches i.e. Fred's bugfixes or Harry's bugfixes.  I'm much more comfortable with one (independent) feature one branch which allows multiple developers to operate on one feature; but for the feature to be merged only when it's complete.

So, right now you only need the "bugfix" branch but once you start development you should create a branch for every significant feature.  That way when they are done they can be merged in & released without being dependent on other buggier functionality.

Not sure how good TFS is at merging but I'm sure you'll know in a few months :)

Title: When should development branches be created?

Body:
We are moving our project's team from using a single Main/Trunk branch, to multiple Development/Work branches that should be regularly merged into Main. We're basing our new process on this article and the TFS Branching Guide (we are using TFS and Visual Studio 2010).

There are currently between 1 and 5 people working on the project at any one time. Main must be stable at all times because we want the option to release whenever we need. We don't have fixed sprints - at least not yet - and at the moment release every 1-2 weeks.

Right at this point in time each person is fixing bugs across the application. In a couple of weeks we will be starting development on a new large component for the app.

One sticking point we are finding is when development branches should be created. We will be implementing multiple user stories in parallel depending on the skill set of the developer. We've thought about creating a branch for each developer but that doesn't make sense because there will always be some need for collaboration on a piece of work. We can't get by with a single development branch because we will want to merge to Main while other work is completed.

Does anyone have some guidance on this?


答: I'd say automated builds are, if anything, more important on a one-man team. You can lie to yourself, but the CI server is much stricter master. She does not lie.</p>

Title: Nightly builds for one-man projects


答:
Implied work branches with DVCS

We use Mercurial so there is the implied work branch on the developers dev box.  Commit are always done to the local workspace.  When a releasable piece of work is completed it is pushed up to the primary repo server where it is automatically built and tested.

We almost never create explicit branches, but then again our sprints are never more than 1 week long and are cards take no more than 1-2 days to complete.

Also, you can mitigate merge pain by threading in work from other parts of code or other projects so people aren't having to do difficult merges all the time.


答:
Advantages

The earlier you set up a Continuous Integration process the easier it is.

Exposes errors earlier in the development process which is always cheaper.

Provides a framework for other good habits like automated tests, automated packaging, automated tagging and versioning, etc.

Leads you to better design (relocatable, correctly parameterized, config driven)

Disadvantages

Time to setup the system (should be about 1-2 days for a simple setup)

Cost of maintaining the server

Cost of maintaining the service

Cost of better design (relocatable, correctly parameterized, config driven,e tc)

You don't have the luxury of being sloppy in your code with CIs.  If you hard-code paths, users, etc, the CI build is likely to break, especially if you have an automated test suite.

Title: Nightly builds for one-man projects


答:
Working a Feature and Sign off

At my work when a developer picks up a new piece of work the first thing they do is identify who the "Owner".  They then go to them have a quick discussion on their understanding of the problem and what the intended solution will be.

Once the developer has finished the implementation they then go back to the "Owner" for sign off.  Sign off involves the developer showing the implementation in a working system (their dev system) with reasonable data.  If the "Owner" is satisfied they sign off and the implementation is complete.  If the "Owner" is not satisfied the developer identifies what changes needs to occur.  He then implements those and tries for sign off again.

Title: Product Owner and automated tests

Body:
One of the claims of BDD-style development is that it bridges the gap between Product Owner and developers: the Product Owner writes a story, which can be converted in an equivalent automated test "frame" that should eventually pass.

What I would like to hear is how to keep bridging the gap after that: once there are automated tests in place, how do you help the Product Owner review them? Or is it enough for the Product Owner to know that the test passes, without looking at the test code itself?

In short, how intimate should the Product Owner be with the actual tests implemented, and how do you keep him/her productively involved with the tests beyond the initial story writing?

The reason behind this question is double. First, between the paper story and the implementation details, some assumptions may sneak in, and having the author of the story review the test can be invaluable. On the other hand, the implementation introduces quite a bit of noise, too, and requires the PO to become fairly technical (read code, run tests). Is the test implementation a "developer's detail", or is it fair to request the PO to become a bit of a developer in this area?

Then, in most case, the PO can actually validate the test without the automated test, by simply using the application. However, some stories are "headless" and can only be verified via code, so unless the PO knows how to read and run tests, he/she will never be able to state that he verified the story complete.


问:
Automatic programming: write code that writes code
After reading the book The Pragmatic Programmer, one of the arguments I found most interesting was "write code that writes code".

I tried searching over the net for some more explanations or articles about it, and while I found some good articles on the subject, I still haven't found any specific code implementation or good examples.

I feel it's still not a so common argument, something that lacks documentation or it's not embraced by so many people, and I would like to know more about it.

What do you think about the subject? Is it something that will really increase your productivity? What are some good resources on the subject, among books, blogs, slideshows, etc?

Some code examples would be greatly appreciated to allow me to better understand its implementation.

Here's the wiki page on the subject with various relevant programming techniques, like Meta Programming, Generative Programming and Code Generation.

答:
Here's a concrete example from my past.

I was working at a site that had around 50MB of Delphi source code using the BDE for data access.  They wanted to switch to using Direct Oracle Access to allow an Oracle upgrade past the highest version supported by the BDE (8i if I recall correctly).

So, instead of getting a team of coders to work through every form and data module changing every component manually I wrote a PERL script that:-

Parsed the DFM (form file) and identified all of the TQuery, TTable, TStoredProcedure & TDatabase objects - storing the items in a list.

Parsed the PAS (code) and identified the usage of the objects - were the TQueries doing updates or selects?  Also, it identified any objects created in code rather than dropped onto a form in the IDE.

Rewrote the DFM & PAS changing the object types appropriately (e.g. TTable -> TOracleDataSet with the SQL property set to "select * from " etc) and the method calls.  Also, extra method calls were added if appropriate to close, open & set parameters.

In short, 3 weeks work tweaking the script to work on different applications written by different teams with different coding styles instead of the original estimate of 5+ developers working for 6 months.

And the reason I even thought of using that approach was through reading The Pragmatic Programmer