答:
Well, there's a couple of ways you can modify open source software without releasing it.

If you wrote it and are the one who applied the license then you can do whatever you want.  It is fully possible to release code under the GPL and have your own, internal proprietary version.

If you are using and modifying the software for internal purposes, and not releasing the binaries, then under most licenses (even GPL) you don't have to release source.

If you are in the process of developing, but have not released to the public, you don't have to release source.

Some open source licenses do not require release of the source.  (For instance, BSD or apache style licenses.)

If you are in one of these situations, and don't have to release source, then anything in the unreleased source can be a trade secret.  Once you release of course that stops being the case.

My understanding is that even with the GPL you can certainly limit who you ship binaries to, which in turn limits who you have to release source to.  So, for instance, if you say "you can't have the binaries unless you sign this NDA", then I don't think you have to give the source to anyone who has not signed the NDA.

In general, my understanding is that the GPL doesn't require giving source to anyone at all, just anyone with access to the binaries.

I am not a lawyer, so obviously consult a real one if it is an issue.


问:
Is version history really sacred or is it better to rebase?
I've always agreed with Mercurial's mantra 1, however, now that Mercurial comes bundled with the rebase extension and it is a popular practice in git, I'm wondering if it could really be regarded as a "bad practice", or at least bad enough to avoid using. In any case, I'm aware of rebasing being dangerous after pushing.

OTOH, I see the point of trying to package 5 commits in a single one to make it look niftier (specially at in a production branch), however, personally I think would be better to be able to see partial commits to a feature where some experimentation is done, even if it is not as nifty, but seeing something like "Tried to do it way X but it is not as optimal as Y after all, doing it Z taking Y as base" would IMHO have good value to those studying the codebase and follow the developers train of thought.

My very opinionated (as in dumb, visceral, biased) point of view is that programmers like rebase to hide mistakes... and I don't think this is good for the project at all.

So my question is: have you really found valuable to have such "organic commits" (i.e. untampered history) in practice?, or conversely, do you prefer to run into nifty well-packed commits and disregard the programmers' experimentation process?; whichever one you chose, why does that work for you? (having other team members to keep history, or alternatively, rebasing it).

1 per Google DVCS analysis, in Mercurial "History is Sacred".

答: IMHO, experiments usually belong to shelves or temporary branches, not baselines. If you follow this, there shouldn't be an issue, as all commits will be logically sound and add some value.</p>

ContentLicense: CC BY-SA 3.0


答: Not all mistakes are of the kind that you need to hide- for example, I once accidentally committed a binary file to my repo. Tampering with history is only bad when the fault is not exclusively in the history itself, like files committed which shouldn't be.</p>

Title: Is version history really sacred or is it better to rebase?

Body:
I've always agreed with Mercurial's mantra 1, however, now that Mercurial comes bundled with the rebase extension and it is a popular practice in git, I'm wondering if it could really be regarded as a "bad practice", or at least bad enough to avoid using. In any case, I'm aware of rebasing being dangerous after pushing.

OTOH, I see the point of trying to package 5 commits in a single one to make it look niftier (specially at in a production branch), however, personally I think would be better to be able to see partial commits to a feature where some experimentation is done, even if it is not as nifty, but seeing something like "Tried to do it way X but it is not as optimal as Y after all, doing it Z taking Y as base" would IMHO have good value to those studying the codebase and follow the developers train of thought.

My very opinionated (as in dumb, visceral, biased) point of view is that programmers like rebase to hide mistakes... and I don't think this is good for the project at all.

So my question is: have you really found valuable to have such "organic commits" (i.e. untampered history) in practice?, or conversely, do you prefer to run into nifty well-packed commits and disregard the programmers' experimentation process?; whichever one you chose, why does that work for you? (having other team members to keep history, or alternatively, rebasing it).

1 per Google DVCS analysis, in Mercurial "History is Sacred".


问:
JQuery / JSON + .Net Service Layer - to WCF or Not to WCF?
I Recently had a discussion with a colleague of mine about the pros / cons of WCF. He mentioned about how much code is generated to support WCF, and also the overhead required. It was mentioned that a simple jQuery /Ajax post to a .aspx page (or a handler for that matter) that returns JSON would work more efficiently and takes much less code to implement. I am also aware of the new WCF Web API and feel that technology may solve the "bloated"-ness required in attaining a proxy etc... by just outputting JSON.

So when developing a relational DB (MSSQL) storage model, with a fairly complex Business Layer (C#) and Data Access Layer (EntityFW)..  what's a good technology for creating a "service layer" which will spit out View Models represented in JSON, with a CQRS(Command Query..) approach in mind.. The app would use the service layer to support it's required UI, as well as provide an available subset of services (outputting JSON data) for service subscribers..

In other words an admin panel to support the admin UI, and service endpoints that return JSON to access the configurations made from the administration UI.

What are some potential technologies to use as the transport / communication layer. I'd like to use a pure RESTful approach, but am not against doing some URL rewriting with IIS.

Obviously some of the available technologies are:
WCF

WCF Web API (should this even be separate?)

Straight request / response (query string to .aspx / handler)

Would using MVC .Net solve this entire problem? maybe their single page app approach?

any suggestions / feedback from developing this type of application?

Thanks,

答:
Your colleague needs to understand what WCF is. Once everything is setup correctly, WCF can be very powerful. We built a RESTful service recently on top of WCF and we very happy with the result.

Here is the Microsoft's definition of WCF:

Windows Communication Foundation (WCF) is Microsoft’s unified programming model for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and interoperate with existing investments.

Few things WCF does better than a standard ASP.NET page (or service):

Service development

In an ASP.NET you must wire everything yourself. With WCF you add few attributes such as [ServiceContact] and [OperationContract]. Once you did that you can associate an address and a binding with a service type.

They include BasicHttpBinding (supporting the WS-BasicProfile 1.1 and Basic Security Profile 1.0), WSHttpBinding, WSDualHttpBinding, WSFederationBinding, NetTcpBinding, NetNamedPipeBinding, NetMsmqBinding, MsmqIntegrationBinding & NetPeerTcpBinding. All you have to do is to change the configuration. WCF does the rest.

Hosting

Your ASP.NET page or webservice is typically hosted in a website in IIS. WCF allows you to host your service in ISS but also as a standalone application or any compatible host. Again, without having to change anything but the configuration.

Message representation

WCF provides you with much richer feature including how you add header in the messages.

```<code><service name="Service ">
 <endpoint
  address="EchoService"
  binding="basicHttpBinding"
  contract="IEchoService ">
  <headers>
  <dsig:X509Certificate
   xmlns:dsig="http://www.w3.org/2000/09/xmldsig#">
   ...
  </dsig:X509Certificate>
  </headers>
 </endpoint>
</code>```

... and a lot more

WCF will also help you with:

Data Representation

Service Description

Exception Handling

State Management

Globalization

and of course, one of it's main feature, Security.

I think the best you can do right now is test yourself. You can be amazed or disgusted. But in any case, you'll know if WCF is for you or not.

Further reading: Comparing ASP.NET Web Services to WCF Based on Development

Body:
Your colleague needs to understand what WCF is. Once everything is setup correctly, WCF can be very powerful. We built a RESTful service recently on top of WCF and we very happy with the result.

Here is the Microsoft's definition of WCF:

Windows Communication Foundation (WCF) is Microsoft’s unified programming model for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and interoperate with existing investments.

Few things WCF does better than a standard ASP.NET page (or service):

Service development

In an ASP.NET you must wire everything yourself. With WCF you add few attributes such as [ServiceContact] and [OperationContract]. Once you did that you can associate an address and a binding with a service type.

They include BasicHttpBinding (supporting the WS-BasicProfile 1.1 and Basic Security Profile 1.0), WSHttpBinding, WSDualHttpBinding, WSFederationBinding, NetTcpBinding, NetNamedPipeBinding, NetMsmqBinding, MsmqIntegrationBinding & NetPeerTcpBinding. All you have to do is to change the configuration. WCF does the rest.

Hosting

Your ASP.NET page or webservice is typically hosted in a website in IIS. WCF allows you to host your service in ISS but also as a standalone application or any compatible host. Again, without having to change anything but the configuration.

Message representation

WCF provides you with much richer feature including how you add header in the messages.

<service name="Service ">
 <endpoint
  address="EchoService"
  binding="basicHttpBinding"
  contract="IEchoService ">
  <headers>
  <dsig:X509Certificate
   xmlns:dsig="http://www.w3.org/2000/09/xmldsig#">
   ...
  </dsig:X509Certificate>
  </headers>
 </endpoint>

... and a lot more

WCF will also help you with:

Data Representation

Service Description

Exception Handling

State Management

Globalization

and of course, one of it's main feature, Security.

I think the best you can do right now is test yourself. You can be amazed or disgusted. But in any case, you'll know if WCF is for you or not.

Further reading: Comparing ASP.NET Web Services to WCF Based on Development


问:
Is C++ not suitable for OOP?
I read somewhere in one of the answers to a question here (can't remember which) that C++ is not suitable for object-oriented programming. There was some mentioning that you could make use of its feature or something like that, but not in a purely OOP sense (I actually didn't really understand what the person meant).

Is there some truth in this; if so, why?

答: There is a reason Graham Lee had the most upvotes here.  To reiterate, it appears that a C++ class is not really an object in the sense that it does not perform message passing.  I think this is what trips people up a great deal when they are learning C++ or oop.  People are told object oriented is 'this' and then told that C++ does it differently.  Well C++ never did OOP differently.  If you think this way you'll never appreciate C++ classes for what they are meant for and that is that they are merely an improvement upon the procedural paradigm by incorporating abstraction, and dynamic behavior.  So C++ classes are fundementally procedural, they just improve upon the procedural paradigm, or rather they are a more advanced version of a C struct.  </p>

ContentLicense: CC BY-SA 2.5

Title: Is C++ not suitable for OOP?


问:
Which class to start TDD of card game application? What's the next 5-7 tests?
I have started to write card game applications.
Some model classes:

CardSuit, CardValue, Card

Deck, IDeckCreator, RegularDeckCreator, DoubleDeckCreator

Board

Hand

and some game classes:

Turn, TurnHandler

IPlayer, ComputerPlayer, HumanPlayer

IAttackStrategy, SimpleAttachStrategy, IDefenceStrategy, SimpleDefenceStrategy

GameData, Game

are already written. My idea is to create engine, where two computer players could play game and then later I could add UI part.

Already for some time I'm reading about Test Driven Development (TDD) and I have idea to start writing application from scratch, as currently I have tendency to write not needed code, which seems usable in future. Also code doesn't have any tests and it is hard to add them now.

Seems that TDD could improve all these issue - minimum of needed code, good test coverage and also could help to come to right application design.

But I have one issue - I can't decide from where to start TDD? Should I start from bottom - Card related classes or somewhere on top - Game, TurnHandler, ... ?

With which class you would start? And what would be the next 5 to 7 tests? (use the card game you know the best)

I would like to start TDD with your help and then continue on my own!

答:
I would start with the lowest-level objects, those objects that you may need to write few tests for anyway because they mostly return properties like Suit and Color.

Once you have the basic objects, you can start adding tests for behavioral methods, and for methods that cause those basic objects to interact with one another.


答:
Fitting tests into already existing application can be rather difficult and you might end up restructuring your code significantly. You might restructure it so much that the restructuring might feel as if you're 'starting from scratch' anyway.

Since it seems that you're just 'having fun' you might benefit more, at least from the design perspective, by starting from scratch.

I think that you should definitely test your models. Start with the 'smallest' models, like the Card objects for example. Your tests will verify these work. You can then move onto the Hand models. Then the Board.

In this way you build a hierarchy of tests that start with simple behaviors then build up to more complex behaviors.

For example, say you have a method named getHandValue that calculates a hand value based on the value of the cards in the hand. Well, you probably want to test the getCardValue method before testing the hand method because the hand method uses the card method anyway.

Also, you can use mock objects to get rid of unnecessary setup work.

For example, say you have a 'board' with a method getBoardValue. Let's say that this method uses all the hands currently in play to calculate its value. Instead of creating a hand and then creating cards to add to the hand you can simply create a mock hand object that returns a predetermined value. Now you don't have to do all this setup and remember what cards you added to the hands.

Some things are harder to test and that's where design decisions come into play.

Also, don't test the interfaces directly ( just in case you thought about it ). Only test the implementations since it's the implementations that actually do the work.

Title: Which class to start TDD of card game application? What's the next 5-7 tests?

Body:
I have started to write card game applications.
Some model classes:

CardSuit, CardValue, Card

Deck, IDeckCreator, RegularDeckCreator, DoubleDeckCreator

Board

Hand

and some game classes:

Turn, TurnHandler

IPlayer, ComputerPlayer, HumanPlayer

IAttackStrategy, SimpleAttachStrategy, IDefenceStrategy, SimpleDefenceStrategy

GameData, Game

are already written. My idea is to create engine, where two computer players could play game and then later I could add UI part.

Already for some time I'm reading about Test Driven Development (TDD) and I have idea to start writing application from scratch, as currently I have tendency to write not needed code, which seems usable in future. Also code doesn't have any tests and it is hard to add them now.

Seems that TDD could improve all these issue - minimum of needed code, good test coverage and also could help to come to right application design.

But I have one issue - I can't decide from where to start TDD? Should I start from bottom - Card related classes or somewhere on top - Game, TurnHandler, ... ?

With which class you would start? And what would be the next 5 to 7 tests? (use the card game you know the best)

I would like to start TDD with your help and then continue on my own!


答:
How about the below.  The {} is the hints for the next step and after that I would get into specific attributes too.

A pack of cards exists {Pack}

The pack has 52 cards {Card and Pack - number of cards}

The cards have 4 suits {Card attribute}

Each suit has A,2-10,J,Q,K {Card attribute}

A game is selected. {Game instance}

Players are selected {Player instances}

Cards are shuffled. {Shuffle method(s)}

Cards are dealt. {Deal method(s)}

Each person plays. {Play method(s)}

One person wins. {Part of Play method, maybe call to Win method}

End Game. {EndGame method}


答:
If you truly want to embrace test-driven development, then you can start by forgetting that you've written any code. (Don't throw it away, just set it aside in your mind.) Then ask yourself which test you would write if you hadn't written any code yet. What is that you would want to assert first? Answer that question then start the TDD cycle:

Write a failing test.

Change your code to make it succeed.

Repeat.

It doesn't really matter where you start, as long as it makes sense to you. It seems like you already have a solid understanding of how you want the application to be designed. That's great, so don't be afraid to write crappy tests. Over time you'll get the hang of it and can improve them.

Remember the tests are there to keep you (and others) from negatively altering your code. They are a "contract" you're defining so that you not only have an executable test, but a reference to how you anticipated your code would work. So start by writing tests that describe to you what your code should be doing. If you're still not sure how something will work, play with ideas (by writing tests) until it makes sense.


答:
Technically you cannot do TDD on already existing code. In TDD, tests are the basis for your design, here, the design is already made and then you want to refactor.

My recommendation is:

Write the tests based on the already implemented design (look for test-cases on each method) so you get code coverage

Make sure all your tests pass

Start doing some refactoring and/or new implementations, whenever you are about to implement a new feature or make a design change (adding methods, changing an algoritm, make additional checks, etc.) first write a test that fails

Change your code to pass the failing test

Go to 3

The class doesn't matter, the question is: how do you get into the process?


问:
How do you achieve a numeric versioning scheme with Git?
My organization is considering moving from SVN to Git. One argument against moving is as follows:

How do we do versioning?

We have an SDK distribution based on the NetBeans Platform. As the SVN revisions are simple numbers we can use them to extend the version numbers of our plugins and SDK builds. How do we handle this when we move to Git?

Possible solutions:

Using the build number from Hudson (Problem: you have to check Hudson to correlate that to an actual Git version)

Manually upping the version for nightly and stable (Problem: Learning curve, human error)

If someone else has encountered a similar problem and solved it, we'd love to hear how.

答:
This has come up on a few projects for me.  The best solution I've had so far is to generate a version number like this:

x.y.<number of commits>.r<git-hash>

Typically, it's generated by our build system using a combination of some static file or tag to get the major revision numbers, git rev-list HEAD | wc -l (which was faster than using git log), and git rev-parse HEAD.  The reasoning was follows:

We needed the ability to have high-level versioning happen explicitly (i.e. x.y)

When parallel development was happening, we needed to NEVER generate the same version number.

We wanted to easily track down where a version came from.

When parallel lines were merged, we wanted the new version to resolve higher than either of the branches.

Number 2 is invisible to most people, but is really important, and really difficult with distributed source control.  SVN helps with this by giving you a single revision number.  It turns out that a commit count is as close as you can get, while magically solving #4 as well.  In the presence of branches, this is still not unique, in which case we add the hash, which neatly solves #3 as well.

Most of this was to accommodate deploying via Python's pip.  This guaranteed that pip install would maybe be a bit odd during parallel development (i.e. packages from people on different branches would intermingle, but in a deterministic fashion), but that after merges, everything sorted out.  Barring the presence of an exposed rebase or amend, this worked quite nicely for the above requirements.

In case you're wondering, we chose to put the r in front of the hash due to some weirdness with how Python packaging handles letters in version numbers (i.e. a-e are less than 0, which would make "1.3.10.a1234" < "1.3.10" < "1.3.10.1234").


问:
Is there a decent way to maintain development of wordpress sites using the same base?
We've been churning out wordpress sites for a while, and we'd like to keep a base repository that can be used when starting a new project, as well as updating existing sites with changes to the wordpress base.

Am I wrong in assuming this would be a good thing? We take care of updating the sites, so having a common base would make this easier.

I've been looking at solutions using git, such as forking a base repository and using it to pull changes to the wordpress base, but committing the site to it's own repository. Or maybe, if it's possible, storing the base as a git submodule, but this would require storing themes and plugins outside of that.

Is there any common way to go about this kind of website development?

答:
You are not wrong in assuming it is a good thing; it makes a lot of sense if your business is spinning up WordPress sites for clients, and those base installations include your company's own set of custom themes, plugins, or other modifications to the actual WordPress base.

Mark Jaquith, lead WordPress dev, does something along those lines himself, with his WordPress-Skeleton repo on GitHub, where he says to feel free to "use it to jump-start your WordPress site repos, or fork it and customize it to your own liking!"


答:
In my view, it's not so much a definitional issue as a usability issue.

Objects are an abstraction intended to make it easier to read, write, and reason about complex programs. For a practical programmer, whether a language meets all the criteria of a particular formal definition of "object-oriented" (there seem to be several competing ones!) isn't really as important as whether the tools it offers are suitable for thinking about your program in terms of said objects -- i.e., actually reaping the supposed productivity benefits of OOP.

In C++, objects are a terribly leaky abstractions, often forcing programmers to wrangle with nasty issues related to how those objects are structured in memory -- issues that are more reminiscent of coding in straight C than other OOP languages. For example, C++ Frequently Questioned Answers offers this criticism (among others):

It is very beneficial for a practitioner to gain familiarity with OO
  systems other than C++, and with OO definitions other than the
  "encapsulation, inheritance, polymorphism" trinity interpreted in
  special ways allowing C++ to be considered "OO". For example, a claim
  that an environment lacking boundary checking or garbage collection is
  not an OO environment sounds outrageous to people accustomed to C++.
  But from many perspectives, it makes a lot of sense. If anyone can
  overwrite an object, where's the "encapsulation"? If disposing an
  object can lead to dangling references or memory leaks, how is the
  system "object-oriented"? What about the ability to tell what kind of
  object is located at a given place and time? You say the software
  works with objects - where are they? And if one can't find out, how is
  one supposed to debug the software?

C++ is object-oriented, but unpleasantly and incompletely: its users have to devote a lot of effort to making sure their data actually behaves like "real" objects rather than errant bits. That said, lots of code has been written in C++ over its lifespan, most of it making use of classes and dynamic dispatch, so it's self-evidently something that you can use for practical OOP.

Title: Is C++ not suitable for OOP?

Body:
I read somewhere in one of the answers to a question here (can't remember which) that C++ is not suitable for object-oriented programming. There was some mentioning that you could make use of its feature or something like that, but not in a purely OOP sense (I actually didn't really understand what the person meant).

Is there some truth in this; if so, why?


问:
Is it advisable to ask employees to create 'work' GitHub accounts?
I've moved all our company Git repositories to GitHub and now I want to add employees to the projects. Since most employees already have personal GitHub accounts, I'm wondering whether I should ask them to create a work GitHub account. The reason that I'm thinking of doing this is to decrease the chances of unauthorized access to our code base since their personal accounts may be well publicized through their personal activity on the site, increasing chances of targeted attacks. Furthermore, if their personal account is ever compromised it won't mean the whole company code is accessible to the hijacker. Since this will bring the burden of maintaining two accounts for the employees I'm wondering whether it is the correct approach and whether it even makes sense. I would love to hear your opinions on this.

Update
Thanks for all the useful insights. I won't set an answer as accepted because of the subjective nature of the question/answers and since I took the best points from several different answers.

I have decided to go forward this way: I will remind employees that work-related GitHub e-mail notifications will have to be sent to their work e-mail accounts for practical reasons. Therefore it would make more sense to create work GitHub accounts. If they are willing to use their personal GitHub accounts and connect it to their work e-mail accounts then that's fine. In any case, employees will have to agree in written form to a number  of conditions tied to using GitHub. These are related to account security: choosing a secure password using a secure random password generator that is not used with any other account, not accessing GitHub through computers not owned or administered by them, etc. At the end of the day employees will have to decide themselves whether a work account makes more sense for them or not.

答:
I'd vote "No". It's quite a bit of hassle for your developers and gives you security through obscurity: if someone's actively targeting your developers there's plenty of other attack vectors for someone to get your code.

Plus, as a startup unless you have a lot of magical secret-sauce-type algorithms at play someone getting your code would be embarrassing, and terrible, and obnoxious, but shouldn't result in a significant competitive advantage (who could legally use your code?) or cause you to go out of business.

Such a low order probability vs. developer productivity? I'd take developer productivity, but that's my calculus. :)


答:
If there was a benefit, it would merely be painful. But nothing sucks worse than painful and pointless. Just have the single personal account. Two reasons:

Github has incredibly good access control in their organizations. If an employee leaves, you can instantly remove their access. If they had a company account, you'd have to reclaim the account somehow to get the stated benefits. In practice, you'd probably just remove the account access, same as if they had a personal account.

Having more than one account is painful. Logging in and logging out between accounts hurts, and adding comments, following, and all the social stuff when you use different accounts.

References: I make a CI server that has GitHub integration, so I have about a lot of test accounts, and I've talked to customers with all sorts of weird configurations, including separate work accounts and personal accounts. It always leads to trouble.

Title: Is it advisable to ask employees to create 'work' GitHub accounts?

Body:
I've moved all our company Git repositories to GitHub and now I want to add employees to the projects. Since most employees already have personal GitHub accounts, I'm wondering whether I should ask them to create a work GitHub account. The reason that I'm thinking of doing this is to decrease the chances of unauthorized access to our code base since their personal accounts may be well publicized through their personal activity on the site, increasing chances of targeted attacks. Furthermore, if their personal account is ever compromised it won't mean the whole company code is accessible to the hijacker. Since this will bring the burden of maintaining two accounts for the employees I'm wondering whether it is the correct approach and whether it even makes sense. I would love to hear your opinions on this.

Update
Thanks for all the useful insights. I won't set an answer as accepted because of the subjective nature of the question/answers and since I took the best points from several different answers.

I have decided to go forward this way: I will remind employees that work-related GitHub e-mail notifications will have to be sent to their work e-mail accounts for practical reasons. Therefore it would make more sense to create work GitHub accounts. If they are willing to use their personal GitHub accounts and connect it to their work e-mail accounts then that's fine. In any case, employees will have to agree in written form to a number  of conditions tied to using GitHub. These are related to account security: choosing a secure password using a secure random password generator that is not used with any other account, not accessing GitHub through computers not owned or administered by them, etc. At the end of the day employees will have to decide themselves whether a work account makes more sense for them or not.


答:
Code review is a lot easier when there's one big cohesive change as opposed to a lot of small dependent ones.

When I work on a new feature, I like to commit lots of little changes in my branch. When I'm ready to submit the patch, I collapse those little commits into one big commit that represents all of the new code required for that feature. This is where rebase comes in handy.

On the other hand, rebase is ill-advised if the commits have nothing to do with each other. Multiple feature additions should be separate commits (and ideally come from separate branches).


问:
Are Intel compilers really better than the Microsoft ones?
Years ago, I was surprised when I discovered that Intel sells Visual Studio compatible compilers. I tried it in particular for C/C++ as well as fantastic diagnostic tools. But the code was simply not that computationally intensive to notice the difference. The only impression was: did Intel really do it for me just now, wow, amazing tools with nanoseconds resolution, unbelievable. But the trial ended and the team never seriously considered a purchase.

From your experience, if license cost does not matter, which vendor is the winner?

It is not a broad or vague question or attemt to spark a holy war. This sort of question is about two very visible tools. Nobody likes when tools have any mysteries or surprises. And choices between best and best are always the pain. I also understand the grass is always greener argument. I want to hear all "what ifs" stories.

What if Intel just locally optimizes it for the chip stepping of the month, and not every hardware target will actually work as well as Microsoft compiled? What if AMD hardware is the target and everything will slow down for no reason? Or on the other hand, what if Intel's hardware has so many unnoticable opportunities, that Microsoft compiler writers are too slow to adopt and never implement it in the compiler? What if both are the same exactly, actually a single codebase just wrapped into two different boxes and licensed to both vendors by some third-party shop?

And so on. But someone knows some answers.

答:
In an embedded application I once worked on, a trial of an Intel compiler showed it would save us having to spin new hardware with higher performance. The cost of the new hardware was around $10/unit, projected sales of 1 Million units, Add development cost and project delays. Option 2 was a profile/micro optimize an already reasonably well profiled/optimized code base - unknown results, unknown time.

What do you think the boss said when we asked for the funds to buy the compiler.......

However - this was a very lucky and rarer edge case - the 10% faster code output from the Intel compiler pushed us back onto the correct side of performance. If we were already on the right side, or were 10% over, it would not have made a difference.  Had we had the engineers we probably could have optimized the code and saved the hardware spin and not needed the Intel compiler, But the risk was high and the Intel compiler worked out cheaper than the engineering time.

On balance I would say it is a form of micro optimization - don't do it till you know you need to, and then, only after you have profiled and found the actual cause of the problems. It is a a particularly good choice of you profile shows you are slow 'everywhere' and have no identified bottle necks.


问:
Using PDO for Data Management
This question is more a design oriented question than a code specific question. I am new to PHP and I am planning to use PDO as a data access layer. Say for instance I have a class called CITY. Now if I need to create an instance of this class, what is the best technique.

Should have a singleton DB access class which is used to write and read data from the db layer.

OR should I delegate it to the individual class object. For example if I invoke city.save() (city is a class), then the city class will handle the saving of that city object's data into the database.

Excuse my ignorance but i have a java background and therefore trying to understand what is the best design principle for data management when using php.

答:
Java

Welcome to a, in my opinion, less confusing and less redundant language. A lot of what you know from Java can be transferred to PHP, the theories and design patterns will all be the same, as it is for most, if not all, languages.

"Should have a singleton DB access class which is used to write and read data from the db layer."

Probably the most "secure" method. I've not done it myself, mostly because I've not had the chance to play around with PDO or MYSQL yet, but I have read quite a bit on it and this seems to be the preferred method. It is common practice to limit instantiation of DB classes to control its flow, and a singleton class would be perfect for this.

Here is the pertinent part from a decent article on the subject. This is the second page from the third part of a multipart series. If you are interested in the rest it should be linked in the "See Also" box. While this is relatively old, it should still be pertinent as I don't think the theory has changed. I hope this helps!

OwnerDisplayName: edorahg

Title: Using PDO for Data Management

OwnerDisplayName: showerhead


问:
Almost Realtime Data and Web application
I have a computer that is recording 100 different data points into an OPC server.

I've written a simple OPC client that can read all of this data.

I have a front-end website on a different network that I would like to consume this data. I could easily set the OPC client to send the data to a SQL server and the website could read from it, but that would be a lot of writes.

If I wanted the data to be updated every 10 seconds I'd be writing to the database every 10 seconds. (I could probably just serialize the 100 points to get 1 write / 10 seconds but that would also limit my ability to search the data later). This solution wouldn't scale very well. If I had 100 of these computers the situation would quickly grow out of hand.

Obviously I am well out of my league here and I have no experience with working with a large amount of data like this.

What are my options and what should I research?

答:
While its a good idea to look ahead for possible obstacles an application may face down the road, you shouldnt be fixing problems that you dont know you'll have.

My advice is to proceed without over complicating things.  Send the data to the sql server, and query it as you would normally.  Make sure your classes are abstract enough that future changes to the storage system wont require major coding changes across all levels of the application.  If and when you notice the server is having problems keeping up, then start looking at options to change how data is written and retrieved.  Because the reality is a properly tuned database server can handle a significant load, 24x7, without missing a beat.


答:
We use the intel compiler for every performance critial project of our codebase. The great thing about it is, it makes optimizing code really maintainable. Instead of manually adding __mm calls everywhere, and telling the compiler to prefetch data, all of which will be sub optimal in the next release again, you just rearrange your code some and gain an insane speedup.

Often, the optimized code is easier to follow than the hand optimized, it's faster than the hand optimized, and when a new instruction set are release, the compiler will use that instruction set. It's fantastic.

The same also goes for the arm compiler (from arm, not intel), if your releasing on arm, does a great job in vectorizing for you.

Title: Are Intel compilers really better than the Microsoft ones?

Body:
Years ago, I was surprised when I discovered that Intel sells Visual Studio compatible compilers. I tried it in particular for C/C++ as well as fantastic diagnostic tools. But the code was simply not that computationally intensive to notice the difference. The only impression was: did Intel really do it for me just now, wow, amazing tools with nanoseconds resolution, unbelievable. But the trial ended and the team never seriously considered a purchase.

From your experience, if license cost does not matter, which vendor is the winner?

It is not a broad or vague question or attemt to spark a holy war. This sort of question is about two very visible tools. Nobody likes when tools have any mysteries or surprises. And choices between best and best are always the pain. I also understand the grass is always greener argument. I want to hear all "what ifs" stories.

What if Intel just locally optimizes it for the chip stepping of the month, and not every hardware target will actually work as well as Microsoft compiled? What if AMD hardware is the target and everything will slow down for no reason? Or on the other hand, what if Intel's hardware has so many unnoticable opportunities, that Microsoft compiler writers are too slow to adopt and never implement it in the compiler? What if both are the same exactly, actually a single codebase just wrapped into two different boxes and licensed to both vendors by some third-party shop?

And so on. But someone knows some answers.


答:
Alan Kay's perfectly valid objection to C++ was that it was a macro language on top of C.

The notion of "message passing" is simply the idea that instances of classes are held in memory and that they expose methods which can be called.  Message passing is *simulated" in C++ using vtables holding pointers to functions.

To say that message passing does not exist in C++ is inaccurate, what's more accurate to say is that message passing is an integral part of other languages likes smalltalk and Java because the language is not preprocessing a foreign construct and grafting it on C directly.

This is a highly semantic language design argument which I suspect is a little beyond the experience level of the questioner.

That being said there are a thousand reasons to hate C++, and very few reasons to love it.

Rather than looking for the perfect hammer and the perfect nail, find the perfect house to build and then find the right tools...that takes experience.

Its also important to remember that in systems programming what Alan Kay fears is not "pure OOP" is actually a strength of C++.  To each his own...

Title: Is C++ not suitable for OOP?


答:
Given the amount of data you've proposed, putting all 100 data points into a single record seems like a reasonable approach.

That said, most systems of this type use a binary file format to store the real-time data, and then post-process it later for analysis. Systems of this type can process real-time data in the megabits per second range.

Have a look at this White Paper:

http://www.microsoft.com/casestudies/ServeFileResource.aspx?4000003362

It explains how McClaren Systems uses the FILESTREAM type in SQL Server 2008 to manage high-throughput telemetry from Formula One race cars.

Title: Almost Realtime Data and Web application

Body:
I have a computer that is recording 100 different data points into an OPC server.

I've written a simple OPC client that can read all of this data.

I have a front-end website on a different network that I would like to consume this data. I could easily set the OPC client to send the data to a SQL server and the website could read from it, but that would be a lot of writes.

If I wanted the data to be updated every 10 seconds I'd be writing to the database every 10 seconds. (I could probably just serialize the 100 points to get 1 write / 10 seconds but that would also limit my ability to search the data later). This solution wouldn't scale very well. If I had 100 of these computers the situation would quickly grow out of hand.

Obviously I am well out of my league here and I have no experience with working with a large amount of data like this.

What are my options and what should I research?


答:
I hesitate to offer this up as an answer, since it's not exactly objective. But my personal experience is that every time I have been involved in a project that used WCF, we regretted it.

If you are implementing something that genuinely makes use of WCF's flexibility (e.g. a SOA that needs to be accessed via HTTP/SOAP over the web and also via TCP over an intranet), then by all means, go with WCF. But if you're doing something which can be implemented in another way - and something as simple as handlers to return JSON responses to AJAX queries certainly can - I would not choose WCF. There is just way too much complexity in there that you will not have any need for, but will all provide opportunities for problems.

Title: JQuery / JSON + .Net Service Layer - to WCF or Not to WCF?

Body:
I Recently had a discussion with a colleague of mine about the pros / cons of WCF. He mentioned about how much code is generated to support WCF, and also the overhead required. It was mentioned that a simple jQuery /Ajax post to a .aspx page (or a handler for that matter) that returns JSON would work more efficiently and takes much less code to implement. I am also aware of the new WCF Web API and feel that technology may solve the "bloated"-ness required in attaining a proxy etc... by just outputting JSON.

So when developing a relational DB (MSSQL) storage model, with a fairly complex Business Layer (C#) and Data Access Layer (EntityFW)..  what's a good technology for creating a "service layer" which will spit out View Models represented in JSON, with a CQRS(Command Query..) approach in mind.. The app would use the service layer to support it's required UI, as well as provide an available subset of services (outputting JSON data) for service subscribers..

In other words an admin panel to support the admin UI, and service endpoints that return JSON to access the configurations made from the administration UI.

What are some potential technologies to use as the transport / communication layer. I'd like to use a pure RESTful approach, but am not against doing some URL rewriting with IIS.

Obviously some of the available technologies are:
WCF

WCF Web API (should this even be separate?)

Straight request / response (query string to .aspx / handler)

Would using MVC .Net solve this entire problem? maybe their single page app approach?

any suggestions / feedback from developing this type of application?

Thanks,


答:
In answer to the 1st part of your question, I agree with your colleague's assessment that outputting JSON would be much more efficient & simple to do. (KISS principle)

Before you go ahead with WCF though, I highly recommend that you consider the excellent Service Stack - an opensource .NET & Mono REST web services framework.

The performance is excellent (as evidenced by the supporting benchmarks) and the developer experience (for me personally) is much better than working with WCF.


答: People are yet to trust the cloud based source servers. Github boasts lot of new age web companies signed up with them but the real fact is that, most people has their own servers for maintaining the source code. In my experience, most of them uses either Clear-case or SVN. Git is is yet to be adapted in an enterprise environment. Even the corporate mail servers aren't really appreciated outside the company's premises.</p>


问:
Is C# becoming harder to read?
As C# has progressed, many language features have been added. It has come to the point where it's becoming unreadable for me.

As an example, consider the following code snip from Caliburn.Micro code here:

```<code>            container = CompositionHost.Initialize(
                   new AggregateCatalog(
                      AssemblySource.Instance.
                             Select(x => new AssemblyCatalog(x))
                               .OfType<ComposablePartCatalog>()
                )
            );
</code>```

Now, this is just a small example.

I have a number of questions:

Is this a common or known problem?

Is the C# community finding the same?

Is this an issue with the language, or is it the style used by the developer?

Are there any simple solutions to better understand others code and avoid writing code in this way?

答:
When LINQ was added, it popularized a style of coding involving lots of Fluent-style method chaining, and passing of lambdas as parameters.

This style is very powerful once you're comfortable with it. However it can be abused to make fairly unreadable code. I don't think your example is too bad, although the indentation is kind of random (and that's a common feature of this style of code, Visual Studio doesn't auto-indent it very consistently).

At my workplace, we discussed this coding style when reviewing our coding standards earlier this year, and we decided to encourage developers to break up code like that: specifically, not to create and initialize anonymous objects inside a function call. So your code would become:

```<code>var assemblyCatalog = AssemblySource.Instance
    .Select(x => new AssemblyCatalog(x))
    .OfType<ComposablePartCatalog>();
var aggregateCatalog = new AggregateCatalog(assemblyCatalog);
container = CompositionHost.Initialize(aggregateCatalog);
</code>```

Title: Is C# becoming harder to read?

Body:
When LINQ was added, it popularized a style of coding involving lots of Fluent-style method chaining, and passing of lambdas as parameters.

This style is very powerful once you're comfortable with it. However it can be abused to make fairly unreadable code. I don't think your example is too bad, although the indentation is kind of random (and that's a common feature of this style of code, Visual Studio doesn't auto-indent it very consistently).

At my workplace, we discussed this coding style when reviewing our coding standards earlier this year, and we decided to encourage developers to break up code like that: specifically, not to create and initialize anonymous objects inside a function call. So your code would become:

var assemblyCatalog = AssemblySource.Instance
    .Select(x => new AssemblyCatalog(x))
    .OfType<ComposablePartCatalog>();
var aggregateCatalog = new AggregateCatalog(assemblyCatalog);
container = CompositionHost.Initialize(aggregateCatalog);


答:
No. C# is giving us more options to write code more succinctly. This can be used or abused. If used properly, it makes the code easier to read. If used improperly it can make the code harder to read. But bad programmers have always had a skill in writing hard to read code.

Lets take two examples, both based on examples found on StackOverflow regarding the same problem, finding types with a specific attribute:

C# 2.0:

```<code>static IEnumerable<Type> GetTypesWithAttribute<TAttribute>(bool inherit)
                              where TAttribute: System.Attribute
{
    foreach(Assembly assembly in AppDomain.Current.GetAssemblies())
    {
        foreach(Type type in assembly.GetTypes())
        {
            if (type.IsDefined(typeof(TAttribute),inherit))
                yield return type;
        }
    }
}
</code>```

C# 4.0:

```<code>IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit)
                              where TAttribute: System.Attribute
{
    return from assembly in AppDomain.CurrentDomain.GetAssemblies()
           from type in assembly.GetTypes()
           where type.IsDefined(typeof(TAttribute),inherit)
           select type;
}
</code>```

IMHO, the new syntax makes it a lot easier to read.

Title: Is C# becoming harder to read?

Body:
As C# has progressed, many language features have been added. It has come to the point where it's becoming unreadable for me.

As an example, consider the following code snip from Caliburn.Micro code here:

```<code>            container = CompositionHost.Initialize(
                   new AggregateCatalog(
                      AssemblySource.Instance.
                             Select(x => new AssemblyCatalog(x))
                               .OfType<ComposablePartCatalog>()
                )
            );
</code>```

Now, this is just a small example.

I have a number of questions:

Is this a common or known problem?

Is the C# community finding the same?

Is this an issue with the language, or is it the style used by the developer?

Are there any simple solutions to better understand others code and avoid writing code in this way?

Body:
No. C# is giving us more options to write code more succinctly. This can be used or abused. If used properly, it makes the code easier to read. If used improperly it can make the code harder to read. But bad programmers have always had a skill in writing hard to read code.

Lets take two examples, both based on examples found on StackOverflow regarding the same problem, finding types with a specific attribute:

C# 2.0:

static IEnumerable<Type> GetTypesWithAttribute<TAttribute>(bool inherit)
                              where TAttribute: System.Attribute
{
    foreach(Assembly assembly in AppDomain.Current.GetAssemblies())
    {
        foreach(Type type in assembly.GetTypes())
        {
            if (type.IsDefined(typeof(TAttribute),inherit))
                yield return type;
        }
    }
}

C# 4.0:

IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit)
                              where TAttribute: System.Attribute
{
    return from assembly in AppDomain.CurrentDomain.GetAssemblies()
           from type in assembly.GetTypes()
           where type.IsDefined(typeof(TAttribute),inherit)
           select type;
}

IMHO, the new syntax makes it a lot easier to read.


答:
Quick note on where the language is should clear it up: C# is a general purpose programming language; unlike C (like C++) it strives for high abstraction; unlike Lisp dialects it aims for practical expressiveness, and, unlike Java, it is more aggressively driven - Microsoft is quick to respond to demand.

That is why it's turning into a mixture of LINQ, lambdas and weird new keywords - it's adapting to new problem domains quickly, and this is indeed a slippery slope towards a language so complex that very few can use it correctly (like C++). It's not a problem with C# itself, it's a problem with any language with these ambitious goals.

The community is aware of this and, more importantly, the guys behind C# are acutely aware of this (the few blog entries and podcasts on what was behind the new additions in C# 5.0 show how bad these guys want to keep things simple). Microsoft is trying to take some of the load off their flagship such that it doesn't become a tarpit: the introduction of the DLR, a bright spotlight over new languages (F#).

Moreover, course material on C# (including MS certifications) recommends different (but consistent) styles of use for C# depending on the problem - choose your weapon and stick to it: Fluent-style LINQ on some problems, lambdas with TPL on others, plain-old for most.

Title: Is C# becoming harder to read?


问:
Basis of definitions
Let us suppose we have a set of functions which characterise something: in the OO world methods characterising a type. In mathematics these are propositions and we have two kinds: axioms and lemmas. Axioms are assumptions, lemmas are easily derived from them. In C++ axioms are pure virtual functions.

Here's the problem: there's more than one way to axiomatise a system. Given a set of propositions or methods, a subset of the propositions which is necessary and sufficient to derive all the others is called a basis.

So too, for methods or functions, we have a desired set which must be defined, and typically every one has one or more definitions in terms of the others, and we require the programmer to provide instance definitions which are sufficient to allow all the others to be defined, and, if there is an overspecification, then it is consistent.

Let me give an example (in Felix, Haskell code would be similar):

```<code>class Eq[t] {
  virtual fun ==(x:t,y:t):bool => eq(x,y);
  virtual fun eq(x:t, y:t)=> x == y;
  virtual fun != (x:t,y:t):bool => not (x == y);
  axiom reflex(x:t): x == x;
  axiom sym(x:t, y:t): (x == y) == (y == x);
  axiom trans(x:t, y:t, z:t): implies(x == y and y == z, x == z);
}
</code>```

Here it is clear: the programmer must define either == or eq or both. If both are defined, the definitions must be equivalent. Failing to define one doesn't cause a compiler error, it causes an infinite loop at run time. Defining both inequivalently doesn't cause an error either, it is just inconsistent. Note the axioms specified constrain the semantics of any definition. Given a definition of == either directly or via a definition of eq, then != is defined automatically, although the programmer might replace the default with something more efficient, clearly such an overspecification has to be consistent.

Please note, == could also be defined in terms of !=, but we didn't do that.

A characterisation of a partial or total order is more complex. It is much more demanding since there is a combinatorial explosion of possible bases.

There is an reason to desire overspecification: performance. There also another reason: choice and convenience.

So here, there are several questions: one is how to check semantics are obeyed and I am not looking for an answer here (way too hard!). The other question is:

How can we specify, and check, that an instance provides at least a basis?

And a much harder question: how can we provide several default definitions which depend on the basis chosen?

答:
In C++ axioms are pure virtual functions.

Not really. Pure virtual functions are only about run-time polymorphism- this has nothing to do with axioms.

What you can do (which is commonly done) is define new operators through the CRTP which are defined in terms of some subset of existing ones- commonly done with relational and arithmetic operators. However, C++ currently contains no Standard mechanism for axioms. It was considered but rejected along with Concepts, afaik. And as something you can't even describe, it's surely impossible to check- in the general case, this would involve solving the Halting Problem.

Title: Basis of definitions


问:
Is it possible to know what programming language a web-site uses?
For example, stackexchange.com, without asking the site owner or Google their information about developing the website, is this possible to know what language is used in the back end?

Seems, the website don't have .extension bar, for example .php that can indicated which is developed in PHP, but without the extension, how can I know that?

答:
In short:  It is possible to hide what language you are using on the back-end.  Trivial example: consider a "Hello World" page; it'd be extremely difficult to figure out what framework / language was being used on the back-end (assuming the basic stuff like session cookies are manually set or not in use).

However, the point of frameworks is to save you having to re-implement functionality, and to make you work in a standardised way.  Almost all frameworks have their specific little tell-tales which will give them away, if you look close enough.  As others have pointed out, it is possible to try to hide these, by using configuration or re-implementing various standard features.  Nevertheless, I'd argue that for large sites, it'd be extremely difficult to completely hide everything, and even if you accomplished that, you'd be using very little of your framework.

In summary, I'd say it's almost always possible to get a very good idea of what's being used underneath (with some careful examination and prodding).  Hiding the framework used is possible, but quickly becomes infeasible for large sites.

The previous answers have some good examples of various tell-tales that frameworks and languages have.  I'd like to add that various view engines have specific whitespace-related behaviour which can be used to identify them.  The Razor engine used in MVC3+ has some fairly specific quirks which could be used to identify it, or at least, narrow down the list of suspects (again, you can side-step it, but then, are you using it?).


答:
Nothing should be sacred, but make sure you have good reasons for what you're doing. Rebasing is extremely powerful when used properly, but as with any powerful tool it can be confusing and cause problems if used carelessly.

Personally I find it very useful to rebase a local feature branch against trunk (or main development branch) before running the final tests and merging the feature into the main branch. That way I get to deal with any merge conflicts etc before actually merging.


问:
Can modifications to open source project be considered trade secret?
While working for an employer if one modifies, rewrites, contributes or alters open source software in what cases can it ever be considered a trade secret?

A trade secret, FWIW, is defined by wikipedia as:

A trade secret is a formula, practice, process, design, instrument,
  pattern, or compilation of information which is not generally known or
  reasonably ascertainable, by which a business can obtain an economic
  advantage over competitors or customers. In some jurisdictions, such
  secrets are referred to as "confidential information", but should not
  be referred to as "classified information", due to the nature of the
  word in the USA.

答:
It very much depends on the Open Source license. E.g. the Reciprocal Public License 1.5 is an OSL-approved license. It explicitly requires that your modifications must be made public "when you Deploy in any form -- either internally or to an outside party." (emphasis mine).

Well-known Open Source licenses such as the GPL and BSD are studied extensively and there's a reasonable consensus on what's legally allowed and required. If you're depending on more obscure licenses (open or closed), you'll need a lawyer to consider your particular situation.


答:
You risk going off the rails in at least two ways:

C++'s pure virtual functions are nothing like axioms. An axiom is a defined assumption. A pure virtual function is the the absence or expectation of a definition. A set of axioms is required to create a mathematical system; a C++ class need not contain a single virtual function, pure or otherwise.

You're using two distinct notions of derivation. Lemmas are derived through the application of axioms. You can't claim that an expression is a lemma unless you can show that it is the result of axioms and nothing else. The set of axioms completely determines the set of possible lemmas. In OOP terminology, one class or method may be derived from another, but it's a different relationship than that of lemmas to axioms in that the creator of the class or method is free to add or remove parts.

So here, there are several questions: one is how to check semantics
  are obeyed and I am not looking for an answer here (way too hard!).

There's a great deal of research on the topic of proving the correctness of programs. You might be interested in reading about formal verification. Two other topics that might interest you are inference systems and formal grammars.

How can we specify, and check, that an instance provides at least a basis?

Are you talking about code specifically, or any "set of functions which characterize something"? And what do you mean by "instance"? Those concerns and the ones above notwithstanding, one approach is:

Enumerate all the definitions in the system.

For each definition d, decide whether d depends solely on other definitions in the system and nothing else. If so, remove d from the system.

Whatever remains in the system is by definition the "basis," i.e. the set of definitions that are necessary to create the original system.

Title: Basis of definitions

Body:
Let us suppose we have a set of functions which characterise something: in the OO world methods characterising a type. In mathematics these are propositions and we have two kinds: axioms and lemmas. Axioms are assumptions, lemmas are easily derived from them. In C++ axioms are pure virtual functions.

Here's the problem: there's more than one way to axiomatise a system. Given a set of propositions or methods, a subset of the propositions which is necessary and sufficient to derive all the others is called a basis.

So too, for methods or functions, we have a desired set which must be defined, and typically every one has one or more definitions in terms of the others, and we require the programmer to provide instance definitions which are sufficient to allow all the others to be defined, and, if there is an overspecification, then it is consistent.

Let me give an example (in Felix, Haskell code would be similar):

```<code>class Eq[t] {
  virtual fun ==(x:t,y:t):bool => eq(x,y);
  virtual fun eq(x:t, y:t)=> x == y;
  virtual fun != (x:t,y:t):bool => not (x == y);
  axiom reflex(x:t): x == x;
  axiom sym(x:t, y:t): (x == y) == (y == x);
  axiom trans(x:t, y:t, z:t): implies(x == y and y == z, x == z);
}
</code>```

Here it is clear: the programmer must define either == or eq or both. If both are defined, the definitions must be equivalent. Failing to define one doesn't cause a compiler error, it causes an infinite loop at run time. Defining both inequivalently doesn't cause an error either, it is just inconsistent. Note the axioms specified constrain the semantics of any definition. Given a definition of == either directly or via a definition of eq, then != is defined automatically, although the programmer might replace the default with something more efficient, clearly such an overspecification has to be consistent.

Please note, == could also be defined in terms of !=, but we didn't do that.

A characterisation of a partial or total order is more complex. It is much more demanding since there is a combinatorial explosion of possible bases.

There is an reason to desire overspecification: performance. There also another reason: choice and convenience.

So here, there are several questions: one is how to check semantics are obeyed and I am not looking for an answer here (way too hard!). The other question is:

How can we specify, and check, that an instance provides at least a basis?

And a much harder question: how can we provide several default definitions which depend on the basis chosen?


问:
introducing automated testing without steep learning curve
We're a group of 4 developers on a ajax/mysql/php web application. 2 of us end up focusing most of our efforts on testing the application, as it is time-consuming, instead of actually coding. When I say testing, I mean opening screens and testing links, making sure nothing is broken and the data is correct.

I understand there are test frameworks out there which can automate this kind of testing for you, but I am not familiar with any of them (neither is anyone on the team), or the fancy jargon (is it test-driven? behavior-driven? acceptance testing?)

So, we're looking to slowly incorporate automated testing. We're all programmers, so it doesn't have to be super-simple. But we don't want something that will take a week to learn... And it has to match our php/ajax platform...

The Question: Which testing framework will allow us to jump in right away without spending a lot of time learning the syntax and/or a new programming language.

答:
Just write computer programs to automate the work you are doing by hand. You are looking towards the system/acceptance/integration side of the spectrum rather than the unit testing side by the sound of things. Leverage libraries which automate the browser such as Selenium.

http://wiki.openqa.org/display/SEL/Home

Structure your code in the xUnit style which is pretty well documented online (basically a set of true/false assertions and some other conventions about setting up / tearing down the system under test).

http://en.wikipedia.org/wiki/XUnit

Think about how / when to run the tests. You could have each developer run them after checking in. Even better also have a CI server like Jenkins automatically deploy your code and run the tests on each checkin, and email your team if the tests fail.

https://wiki.jenkins-ci.org/display/JENKINS/Use+Jenkins


问:
How do you keep code with continuations/callbacks readable?
Summary: Are there some well-established best-practice patterns that I can follow to keep my code readable in spite of using asynchronous code and callbacks?

I'm using a JavaScript library that does a lot of stuff asynchronously and heavily relies on callbacks. It seems that writing a simple "load A, load B, ..." method becomes quite complicated and hard to follow using this pattern.

Let me give a (contrived) example. Let's say I want to load a bunch of images (asynchronously) from a remote web server. In C#/async, I'd write something like this:

```<code>disableStartButton();

foreach (myData in myRepository) {
    var result = await LoadImageAsync("http://my/server/GetImage?" + myData.Id);
    if (result.Success) {
        myData.Image = result.Data;
    } else {
        write("error loading Image " + myData.Id);
        return;
    }
}

write("success");
enableStartButton();
</code>```

The code layout follows the "flow of events": First, the start button is disabled, then the images are loaded (await ensures that the UI stays responsive) and then the start button is enabled again.

In JavaScript, using callbacks, I came up with this:

```<code>disableStartButton();

var count = myRepository.length;

function loadImage(i) {
    if (i >= count) {
        write("success");
        enableStartButton();
        return;
    }

    myData = myRepository[i];
    LoadImageAsync("http://my/server/GetImage?" + myData.Id,
        function(success, data) {
            if (success) {
                myData.Image = data;
            } else {
                write("error loading image " + myData.Id);
                return;
            }
            loadImage(i+1);
        }
    );
}

loadImage(0);
</code>```

I think the drawbacks are obvious: I had to rework the loop into a recursive call, the code that's supposed to be executed in the end is somewhere in the middle of the function, the code starting the download (loadImage(0)) is at the very bottom, and it's generally much harder to read and follow. It's ugly and I don't like it.

I'm sure that I'm not the first one to encounter this problem, so my question is: Are there some well-established best-practice patterns that I can follow to keep my code readable in spite of using asynchronous code and callbacks?

答:
It's highly unlikely that you can achieve with plain js the same level of conciseness and expressiveness in working with callbacks that C# 5 has. The compiler does the work in writing all that boilerplate for you, and until the js runtimes will do that, you will still have to pass an occasional callback here and there.

However, you may not always want to bring callbacks down to the level of simplicity of linear code - throwing functions around doesn't have to be ugly, there's an entire world working with this kind of code, and they keep sane without async and await.

For instance, use higher-order functions (my js may be a bit  rusty):

```<code>// generic - this is a library function
function iterateAsync(iterator, action, onSuccess, onFailure) {
var item = iterator();
if(item == null) { // exit condition
    onSuccess();
    return;
}
action(item,
    function (success) {
        if(success)
            iterateAsync(iterator, action, onSuccess, onFailure);
        else
            onFailure();
    });
}

// calling code
var currentImage = 0;
var imageCount = 42;

// you know your library function expects an iterator with no params,
// and an async action with the current item and its continuation as params
iterateAsync(
// this is your iterator
function () {
    if(currentImage >= imageCount)
        return null;
    return "http://my/server/GetImage?" + (currentImage++);
},

// this is your action - coincidentally, no adaptor for the correct signature is necessary
LoadImageAsync,

// these are your outs
function () { console.log("All OK."); },
function () { console.log("FAILED!"); }
);
</code>```

Body:
It's highly unlikely that you can achieve with plain js the same level of conciseness and expressiveness in working with callbacks that C# 5 has. The compiler does the work in writing all that boilerplate for you, and until the js runtimes will do that, you will still have to pass an occasional callback here and there.

However, you may not always want to bring callbacks down to the level of simplicity of linear code - throwing functions around doesn't have to be ugly, there's an entire world working with this kind of code, and they keep sane without async and await.

For instance, use higher-order functions (my js may be a bit  rusty):

// generic - this is a library function
function iterateAsync(iterator, action, onSuccess, onFailure) {
var item = iterator();
if(item == null) { // exit condition
    onSuccess();
    return;
}
action(item,
    function (success) {
        if(success)
            iterateAsync(iterator, action, onSuccess, onFailure);
        else
            onFailure();
    });
}

// calling code
var currentImage = 0;
var imageCount = 42;

// you know your library function expects an iterator with no params,
// and an async action with the current item and its continuation as params
iterateAsync(
// this is your iterator
function () {
    if(currentImage >= imageCount)
        return null;
    return "http://my/server/GetImage?" + (currentImage++);
},

// this is your action - coincidentally, no adaptor for the correct signature is necessary
LoadImageAsync,

// these are your outs
function () { console.log("All OK."); },
function () { console.log("FAILED!"); }
);


答:
Simply put, JavaScript doesn't have the syntactic sugar of await.

But moving the "end" part into the bottom of the function is easy; and with an inmediately executing anonymous function, we can avoid declaring a reference to it.

```<code>disableStartButton();

(function(i, count) {
    var loadImage = arguments.callee;
    myData = myRepository[i];

    LoadImageAsync("http://my/server/GetImage?" + myData.Id,
        function(success, data) {
            if (!success) {
                write("error loading image " + myData.Id);

            } else {
                myData.Image = data;
                if (i < count) {
                    loadImage(i + 1, count);

                } else {
                    write("success");
                    enableStartButton();
                    return;

                }

            }

        }
    );
})(0, myRepository.length);
</code>```

You could also pass the "end" part as a success-callback to the function.

Title: How do you keep code with continuations/callbacks readable?

Body:
Summary: Are there some well-established best-practice patterns that I can follow to keep my code readable in spite of using asynchronous code and callbacks?

I'm using a JavaScript library that does a lot of stuff asynchronously and heavily relies on callbacks. It seems that writing a simple "load A, load B, ..." method becomes quite complicated and hard to follow using this pattern.

Let me give a (contrived) example. Let's say I want to load a bunch of images (asynchronously) from a remote web server. In C#/async, I'd write something like this:

```<code>disableStartButton();

foreach (myData in myRepository) {
    var result = await LoadImageAsync("http://my/server/GetImage?" + myData.Id);
    if (result.Success) {
        myData.Image = result.Data;
    } else {
        write("error loading Image " + myData.Id);
        return;
    }
}

write("success");
enableStartButton();
</code>```

The code layout follows the "flow of events": First, the start button is disabled, then the images are loaded (await ensures that the UI stays responsive) and then the start button is enabled again.

In JavaScript, using callbacks, I came up with this:

```<code>disableStartButton();

var count = myRepository.length;

function loadImage(i) {
    if (i >= count) {
        write("success");
        enableStartButton();
        return;
    }

    myData = myRepository[i];
    LoadImageAsync("http://my/server/GetImage?" + myData.Id,
        function(success, data) {
            if (success) {
                myData.Image = data;
            } else {
                write("error loading image " + myData.Id);
                return;
            }
            loadImage(i+1);
        }
    );
}

loadImage(0);
</code>```

I think the drawbacks are obvious: I had to rework the loop into a recursive call, the code that's supposed to be executed in the end is somewhere in the middle of the function, the code starting the download (loadImage(0)) is at the very bottom, and it's generally much harder to read and follow. It's ugly and I don't like it.

I'm sure that I'm not the first one to encounter this problem, so my question is: Are there some well-established best-practice patterns that I can follow to keep my code readable in spite of using asynchronous code and callbacks?

Body:
Simply put, JavaScript doesn't have the syntactic sugar of await.

But moving the "end" part into the bottom of the function is easy; and with an inmediately executing anonymous function, we can avoid declaring a reference to it.

disableStartButton();

(function(i, count) {
    var loadImage = arguments.callee;
    myData = myRepository[i];

    LoadImageAsync("http://my/server/GetImage?" + myData.Id,
        function(success, data) {
            if (!success) {
                write("error loading image " + myData.Id);

            } else {
                myData.Image = data;
                if (i < count) {
                    loadImage(i + 1, count);

                } else {
                    write("success");
                    enableStartButton();
                    return;

                }

            }

        }
    );
})(0, myRepository.length);

You could also pass the "end" part as a success-callback to the function.


问:
Challenges in multi-player Android Game Server with RESTful Nature
I'm working on an Android Game based on Contract Bridge, as a part of my college Summer Internship project. The game will be multi-player such that 4 Android devices can play it, so there's no BOT or CPU player to be developed. At the time of getting project, I realized that most of the students had already worked on the project but none of their works is reusable now (for variety of reasons like, undocumented code and design architecture, different platform implementation).

I have experience working on several open source projects and hence I emphasis to work out on this project such that components I make become reusable as much as possible. Now, as the game is multi-player and entire game progress will be handled on server, I'm currently working on Server's design, since I wanted to make game server reusable such that any client platform can use it, I was previously confused in selecting Socket or REST for Game Server's design, but later finalized to work on REST APIs for the server.

Now, since I have to keep all players in-sync while they make movements in game, on server I've planned to use Database which will keep all players' progress, specific for each table (in Bridge, 4 players play on single table, and server will handle many such game tables).

I don't know if its an appropriate decision to use database as shared medium to track progress of each game table (let me know if there's an appropriate or better option). Obviously, when game is completed for the table, data for that table on server's database is discarded.

Now the problem is that, access to REST service is an HTTP call, so as long as client doesn't make any request, server will remain idle, and consider a situation where

A player has played a card on his device and the device requests to apply this change on the server.

Now, I need to let rest of the three devices know that the player has played a card, and also update view on their device.

AFAIK, REST cannot provide a sort-of Push-notification system, since the connection to the server is not persistent.

One solution that I thought was to make each device constantly poll the server for any change (like every 56 ms) and when changes are found, reflect it on the device. But I feel this is not an elegant way, as every HTTP request is expensive. (and I choose REST to make game play experience robust since, a mobile device tends to get disconnected from Internet, and if there's Socket-like persistent connection then entire game progress is subject to lost. Also, portability on client-end is important)

Also, imagining a situation where 10 game tables are in progress and 40 players are playing, a server must be capable to handle flooded HTTP requests from all the devices which make it every 56 ms. So I wonder if the situation is assumed as DoS attack.

So, explaining the situation, am I going on the right track for the server design? I wanted to be sure before I proceed much further with the code.

答:
Using rest to send/receive data to/from the server is a fine choice, its a well known and stable protocol for client-server communication.  However, you're going to need a system to push updates (or notifications) to the clients as they change on the server, and to  do that you need something other than http web connections.

On an Android device, you're best off using push technology - Google has a few sites that talk about implementing this kind of thing. When you receive the notification, if it doesn't already contain the data, it can be used as a trigger for the app to retrieve the data using your usual methods (ie automatically click the 'refresh' button)

If you don't want to use the push systems, then the other answer is to open a persistent tcp/ip socket to the server while the players are actively playing and receive notifications and data directly through that.


答:
Have a look at the Gherkin & Cucumber approach - write your tests in natural language, wire them up and run them by hand or through CI (by far the best way).

https://github.com/cucumber/cucumber-jvm

Title: introducing automated testing without steep learning curve

Body:
We're a group of 4 developers on a ajax/mysql/php web application. 2 of us end up focusing most of our efforts on testing the application, as it is time-consuming, instead of actually coding. When I say testing, I mean opening screens and testing links, making sure nothing is broken and the data is correct.

I understand there are test frameworks out there which can automate this kind of testing for you, but I am not familiar with any of them (neither is anyone on the team), or the fancy jargon (is it test-driven? behavior-driven? acceptance testing?)

So, we're looking to slowly incorporate automated testing. We're all programmers, so it doesn't have to be super-simple. But we don't want something that will take a week to learn... And it has to match our php/ajax platform...

The Question: Which testing framework will allow us to jump in right away without spending a lot of time learning the syntax and/or a new programming language.


问:
How can Java be improved so that it no longer needs to perform type erasure?
The official Java tutorial on generics explains type erasure and why it was added to the compiler:

When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.

This most likely was a pragmatic approach, or perhaps the least painful one. However, now that generics is widely supported across the industry, what can be done in order for us to not need type erasure? Is it feasible with out needing to break backwards compatibility, or if it is feasible, is it practical?

Has the last statement in the quote above become self referential? That is: "type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created with Java versions that perform type erasure."

答:
The end-of-life applies to the Java Development Toolkit and Java Runtime Environment. And only the Oracle (Sun) versions. But it does not apply to applications written by third parties. The intention is to never break code that has ever run on the JVM, thus it's unlikely Java will ever stop doing type erasure.

Of course C# also introduced generics in later version in backward-compatible manner without doing type erasure, but it basically meant duplicating all the collection classes. Which I suppose is what Java designers don't want to do and thus why they chose type erasure in the first place. Without value types the advantage of non-type-erased generics is not that big.


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

答:
I would say that knowing the spec inside out is not a requirement to knowing how to program in C++ or even to become a excellent C++ programmers.

I would say though that being able to find information from the spec is important, if there is a part of the language that you are using that isn't very well documented.

It is also important knowing where your compiler doesn't meet the spec if you want you code to protable between compilers.

Title: Do you ever read language specs?


问:
How should I start with Lisp?
I've been programming for years now, working my way through various iterations of Blub (BASIC, Assembler, C, C++, Visual Basic, Java, Ruby in no particular order of "Blub-ness") and I'd like to learn Lisp. However, I have a lot of intertia what with limited time (family, full time job etc) and a comfortable happiness with my current Blub (Java).

So my question is this, given that I'm someone who would really like to learn Lisp, what would be the initial steps to get a good result that demonstrates the superiority of Lisp in web development? Maybe I'm missing the point, but that's how I would initially see the application of my Lisp knowledge.

I'm thinking "use dialect A, use IDE B, follow instructions on page C, question your sanity after monads using counsellor D". I'd just like to know what people here consider to be an optimal set of values for A, B, C and perhaps D. Also some discussion on the relative merit of learning such a powerful language as opposed to, say, becoming a Rails expert.

Just to add some more detail, I'll be developing on MacOS (or a Linux VM) - no Windows based approaches will be necessary, thanks.

Notes for those just browsing by

I'm going to keep this question open for a while so that I can offer feedback on the suggestions after I've been able to explore them. If you happen to be browsing by and feel you have something to add, please do. I would really welcome your feedback.

Interesting links

Assuming you're coming at Lisp from a Java background, this set of links will get you started quickly.

Using Intellij's La Clojure plugin to integrate Lisp (videocast)

Lisp for the Web

Online version of Practical Common Lisp (c/o Frank Shearar)

Land of Lisp a (+ (+ very quirky) game based) way in but makes it all so straightforward

Install Clojure and Sublime 2 on MacOS an excellent getting started guide

Look at the Clojure in Action book. Worked for me.

答:
Already a lot of great answers, but assuming you want to dive head-first into web development with a Lisp, I have a few more ideas.

Clojure is the first Lisp I've seen to have really excellent full-stack web frameworks that are ready for prime-time.

Noir is a solid web framework with routing, templating, etc., similar to Sinatra but a bit more feature-rich. It uses Ring, which is basically Clojure's equivalent of Rack in Ruby.

Korma is a SQL abstraction library that pairs really well with Noir.

Pinot is a client-side framework written entirely in ClojureScript, which brings us to:

Clojurescript is a compiler for Clojure which targets Javascript.

If you hadn't noticed, I just covered the entire web stack and it's all written in Clojure.

I find Clojure a bit easier to get started with then Common Lisp, with far better feature set/library support than Scheme.

If you're coming from a Java background at all, it has the added benefit of running on the JVM, which gives you access to the whole Java stdlib when you need it.

The available documentation isa work-in-progress, as are the frameworks themselves. But there's a pretty good tutorial right here.

As far as editors go... if you're comfortable with vim, you can use vim with SLIMV. If you like emacs, emacs/SLIME is okay. There's pretty good Eclipse and NetBeans support for Clojure (or so I'm told), but I generally use TextMate (although Sublime Text 2 is quickly becoming my editor of choice). I know I'm missing out on a little Lisp magic not using a more integrated environment, but I'm happy to hit ⌘-Tab to swap between my editor and REPL; your mileage may vary.

If you want a book to jumpstart you, I recommend Programming Clojure by Stuart Halloway and Aaron Bedra. The 2nd edition just came out from PragProg, so it's up-to-date.

Happy Lisping!

Title: How should I start with Lisp?


问:
what exactly is system programming?
I have never understood what system programming meant. The usual definition given is "...doing something close to the Os or extending Os features...".

Does using Windows API directly rather than some libraries to say do file i/o make it system programming? Was writing Android OS system programming? If I write something that would expose linux kernel through a console like app on Android am I doing system programming? If I am writing software to control a washing machine am I writing system programming?

I am a beginner in programming and this is confusing me to no end. Please explain contrasting it with "application programming".

答:
There are several questions you can ask yourself to gain practice in deciding that question.

Was the system originally sold without this program? Angry Birds may be a "Killer App" for a smart phone (the reason why someone buys it), but it is still a separate third-party app written long after the phone was introduced. Writing it would have been applications programing. But the display driver of the same smart phone is essential to using it at all, so it would have been systems programming.

Can you imagine porting the code to another platform without largely rewriting it? TeX and troff have been ported to virtually any system with few changes, so they are applications, even though they are located towards the bottom of the tool chain that people typically use. The file system that TeX writes its output to, e.g. UFS or VFAT, is a borderline case. You could port a  file system to a different OS if it was totally awesome, but usually people just take over awesome ideas and write their own file system for their own OS. That makes file systems system software.

Is the functionality implemented in the kernel or in separate binaries? (File systems occupy a middle ground here as well. many parts of many file systems are in fact kernel code, but many have substantial parts in user-space.) Graphics display drivers can in principle be pluggable external components, but they are often implemented in the kernel or at least with privileged direct access to the kernel (or even to the hardware). That would be systems programing. On the other hand, computer games that use the graphics display stack are applications.

To your questions, writing the Android OS was definitely systems programming. Writing a program that uses Windows API calls is application programming. It is not as portable as if would be if you used cross-platform libraries such as SDL or OpenGL, but it can in principle be ported, it is third-party-code, and it runs in user space. A console app that exposes the state of the Linux kernel is an interesting thought experiment. I would definitely say it involves systems programing, since you'd have to know a lot about the structure of Linux (note that "Linux" is properly only the kernel, not the distribution) to write, and probably even to use it!

Title: what exactly is system programming?

ContentLicense: CC BY-SA 4.0


答:
Using the Windows API directly was, at one point, a common way to write applications for Windows. So no, that's not systems programming.

Systems programming is not just "close to the OS" -- it's something essential to the core functioning of the computer system. So writing an OS is systems programming. Writing video drivers, filesystem drivers, network drivers for that OS is systems programming. Writing a compiler for a particular combination of language/chipset is systems programming.

Title: what exactly is system programming?

Body:
I have never understood what system programming meant. The usual definition given is "...doing something close to the Os or extending Os features...".

Does using Windows API directly rather than some libraries to say do file i/o make it system programming? Was writing Android OS system programming? If I write something that would expose linux kernel through a console like app on Android am I doing system programming? If I am writing software to control a washing machine am I writing system programming?

I am a beginner in programming and this is confusing me to no end. Please explain contrasting it with "application programming".


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

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

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

答:
IANAL, but the language of this agreement is overly broad. If it is enforceable in the state (or country) where you work (work-for-hire laws vary from state to state (and, obviously, country to country), and in some cases may preclude contractual clauses like this), it would effectively bar you from making any contributions to open-source projects, creating any software of your own, or even posting ideas for software to internet discussion groups without

those ideas becoming the sole property of the employer, and

exposing yourself to liability for disclosing the intellectual property of your employer.

I for one would never sign or advise anyone else to sign an agreement this broad, partially because software is my main hobby as well as my job, and mostly because Github Is Your New Resumé.

Most companies that have contacted me with job offers had already found my Github profile, seen my open-source contributions. Many recruiters I talk to at conferences say they would never hire anyone who didn't have significant activity on Github.

If this is a job you are considering, get a lawyer to review the agreement first. If it's for your current employer, look for a new job.

It occurs to me that based on the license, you may be able to contribute patches to existing open-source projects, if that interests you. But I'm pretty sure doing a startup-weekend or hackathon style event and owning the result is impossible if this agreement is indeed binding. Either way, this type of agreement is far too stringent, and certainly not standard. It might have been common decades ago; Steve Wozniak had to offer the original Apple to Hewlett-Packard, where he worked at the time. Luckily, they weren't interested.

Today, this sort of contractual obligation would make it very, very hard for a company to attract good developers. That's something to consider, as well — would you want to work with developers who were willing to sign their every idea over to the company?


问:
Is Entity Framework ready for production?
I'm looking into Entity Framework for a new project that I'm going to be taking on and as part of my research into it I'm asking some industry professionals if it's stable and ready for 'real world' implementation.

In the running is:

EF

NHibernate

DevExpress XPO

I already have a great deal of experience with XPO, but I'm not particularly happy with it.

答:
We have been using EF in several production applications.  We also have NHibernate in several production apps.  The comment by STW that EF works best "when used as Microsoft intends" is certainly true.  It is also true of NHibernate that it works best when used following the patterns that the NHibernate team intended.  I have no knowledge or experience with XPO.

I do not regret putting NHibernate into production.

I do not regret putting Entity Framework into production.

One of the driving factors to use EF was the integration with LINQ.  I know that NHibernate has done a lot of work with LINQ as well but have not had the time to investigate that as yet.


问:
Why are there so many string classes in the face of std::string?
It seems to me that many bigger C++ libraries end up creating their own string type. In the client code you either have to use the one from the library (QString, CString, fbstring etc., I'm sure anyone can name a few) or keep converting between the standard type and the one the library uses (which most of the time involves at least one copy).

So, is there a particular misfeature or something wrong about std::string (just like auto_ptr semantics were bad)? Has it changed in C++11?

答:
Most of those bigger C++ libraries were started before std::string was standardized.  Others include additional features that were standardized late, or still not standardized, such as support for UTF-8 and conversion between encodings.

If those libraries were implemented today, they would probably choose to write functions and iterators that operate on std::string instances.

OwnerDisplayName: fish

OwnerDisplayName: Ben Voigt


答:
Actually... there are several issues with std::string, and yes it gets a bit better in C++11, but let's not get ahead of ourselves.

QString and CString are part of old libraries, therefore they existed prior to C++ being standardized (much like the SGI STL). They thus had to create a class.

fbstring address very specific performance concerns. The Standard prescribes an interface and algorithmic complexity guarantees minima, however it is a Quality of Implementation details whether this end up being fast or not. fbstring has specific optimizations (storage-related, or a faster find for example).

Other concerns that were not evoked here (en vrac):

in C++03 it is not mandatory that the storage be contiguous, making interoperability with C potentially difficult. C++11 fixes this.

std::string is encoding unaware, and has no special code for UTF-8, it's easy to store a UTF-8 string in it and corrupt it inadvertendly

std::string interface is bloated, many methods could have been implemented as free-functions and many are duplicated to conform both to an index-based interface and an iterator-based interface.

Title: Why are there so many string classes in the face of std::string?

Body:
It seems to me that many bigger C++ libraries end up creating their own string type. In the client code you either have to use the one from the library (QString, CString, fbstring etc., I'm sure anyone can name a few) or keep converting between the standard type and the one the library uses (which most of the time involves at least one copy).

So, is there a particular misfeature or something wrong about std::string (just like auto_ptr semantics were bad)? Has it changed in C++11?

OwnerDisplayName: Matthieu M.