答:
The reasons for not writing bug-free programs are mostly economical.

There are mathematical methods to prove the correctness of a program. In a high-quality Computer Science course they will be mentioned. There are programming languages invented especially for this purpose. In theory, programming without bugs is possible.

Yes, there is the imperfect hardware which may sometimes change a bit value because a neutrino fired from a distant supernova millions of years ago just happened to hit your processor at the right place. Okay, every theory has its assumptions and abstractions. But assuming that the processor works as advertized, there are matmematical tools to make sure the program works correctly too.

Some highly voted answers in this topic are misleading. For example, Gödel's incompleteness theorem and halting problem only imply that you can't have e.g. an automated tool which would decide correctness or incorrectness of any program. But we don't want to decide the correctness of any program, we only want a proof of correctness of one specific program.

(Analogically, just because you can't write a program for automatically deciding truth of any mathematical theorem, that does not mean that you can't prove one specific mathematical theorem.)

The problem, instead, is this:

Although it is in theory possible to write a bug-free program, doing so would be very expensive. Writing a code with a proof of its correctness is more complicated than just throwing something at a wall a seeing if it sticks. Even if "seeing if it sticks" is done by unit tests; and many programmers don't bother even doing that. Most programmers wouldn't even know how to do that, which means that as a company you would have to hire more expensive ones.

Considering all costs, a typical customer is more happy with a cheap software which works well 99% of the time (and 99.9% of the time after installing additional updates) than to have perhaps a thousand times more expensive software which works well 100% of the time. Also, the customer wants to have this software now, and not in ten or twenty years.

Therefore, people knowingly produce software which has some chance of bugs, trying to hit the optimal combination where the bugs are not too frequent and not too serious, and the production is fast enough and cheap enough. The combination which provides the most profit in real life. (Sometimes it even means releasing a software full of bugs before your competitors release anything, and only releasing a more decent version 2.0 when your competitors are ready to release their first decent version.)

If you freeze the development as long as it needs to be, can you actually fix all the bugs until there is simply not a single bug, if such a thing could be verified by computers?

Mathematically speaking, you could. Economically speaking, why would anyone do that? It would mean spending perhaps twenty years and a few million dollars. Meanwhile, customers would want new features, and your frozen applications could not provide them. So in the time your perfect version is ready, the market is already taken by your competitors.

Reasoning economically is OK. We live in a world where money and time matter. But just because we don't do something for economical reasons, we shouldn't speak nonsense about how that can't be done even in theory. Who knows... maybe in a few years we will have some new programming languages and tools which could make correctness proving easy.


问:
Release Management Tools with DVCS (Mercurial)
My development team is migrating from SVN to Mercurial. Having researched DVCS best practices, it has been suggested that we develop against feature branches of the repo mainline, test them separately, then cherry-pick the features we want in each release, before merging those selected branches into the mainline and eventually releasing it.

Question: What I'm looking for is recommendations for some sort of software tool that will make my role of "software release manager" easier, in that it will allow me to control (cherry-pick) which branches (features, bug fixes, etc) are merged (using Git, or Mercurial) into which software releases (in each environment), and be able to produce the binary deployment artefact.

Our applications are mostly Java Web apps, with a handful of Java Applications, and the projects built using Maven (v2).

I've looked around for release management tools, but nothing really fits the bill.

NB: Not all changes are released as soon as they are completed and pass QA - some are to be released at a later date, as part of a themed release

Things dismissed so far (based on recommendations in similar questions, in other SE threads):

Trac (seems to be just PM type stuff, which we already have with the Atlassian OnDemand offering)

Jenkins (plus other CI tools) - am looking for something to manage my releases, rather than a CI tool (we have used Jenkins in the past).

Mercurial Patch-Queues - I may well need this, but was looking at some sort of "nicer" interface to help me manage it.

ERP offerings - TBH, I didnt look too much into this option, as my initial feeling was that they were too heavy-weight.

BuildMaster, by Inedo - This was the closest match, by far, but was not quite suitable due to its lack of VCS branch picking/merging functionality. I would say however that this is a very nice piece of software, and would recommend it, if it fits your use-case, and is sensibly priced, even for Enterprise use.

Am currently evaluating the following tools:

Bitbucket Feature Branch management (since we use Bitbucket for our projects, seems prudent to evaluate their approach)

Since DVCS is new to us, these things may have been dismissed prematurely, so feel free to re-educate me. :)

答:
While I can see how you build your workflow for release (is it tag in default branch or special separate branch-per-release) and topology of your repository (does later releases inherit all features from previous releases or not), I'll try only some iterations:

As already noted, I think, TortoiseHG will be good main tool

If previously-merged features inherited in later releases and naming of branches follow <some pattern> and all branches are open (differ only by the condition "already merged or not yet") and releases are tags you can use in TortoiseHG the following revsets in filter (but for producing lists CLI is better, from my POV - revset with templates will give nice output)

Not merged feature-branches

branch(re:some pattern) and not ancestors(tag())

(if release is not tag, but special branch - replace tag() with branch(release-branchname)

Branches heads (simplified version of previous revset)

head() - ancestors(tag()) or heads(all())

(may require to exclude heads of some named branches)

Merged into branch since last release (tag in branch)

p2(last(tag()):: & merge())

but in CLI it will be nicer with some additional templating

hg log -r "p2(last(tag()):: & merge())" --template "{branch}\n"

ContentLicense: CC BY-SA 3.0


问:
Logging failed login attempts exposes passwords
I started logging failed logins attempts on my website with a message like

Failed login attempt by qntmfred

I've noticed some of these logs look like

Failed login attempt by qntmfredmypassword

I'm guessing some people had a failed login because they typed their username and their password in the username field. Passwords are hashed in the database, but if somehow the db got compromised, these log messages could be a way for an attacker to figure out passwords for whatever small percentage of people end up having a failed login such as this.

Is there a better way to handle this? Should I even worry about this possibility?

答:
Why not to simply check if such username exists in database? This will leave you with 2 possible outcomes.

User entered a correct username.
You then can simply log what you log now.

User entered his password in in username field, therefore username is invalid.
Just enter a log entry saying that there was failed log in attempt by unidentified user?

And of course you can have an extra field to log ip, date and what not?


问:
How to word user stories which have been split from a larger epic
I have an epic which involves creating a mobile application which retrieves a user's data they have previously created in a web application and act on it locally. It seems logical to split the epic as follows;

Mobile app which acts on local, mocked up data

Mobile app which downloads data from the web app's api but with no authentication

Mobile app which downloads data from the web app's api with authentication

I'm struggling to word these stories. 1 is a scenario which would never happen for the end user, he wouldn't have any local data if it hadn't already been retrieved previously. How would I word this?

If 2 is 'As a user I want my mobile device to act on the [entities] which I previously created via the web interface' then what would 3 be? 'As a user I want my mobile device to act on the [entities] which I previously created via the web interface trusting they have been retrieved securely'??

答:
In story 1, I would just state what operations the user can/wants to do on data already present on the device, and add an explicit note that the origin of the data is out of scope for the story (possibly with a reference to the story that handles retrieving/updating the data)

Your own suggestion for story 2 looks reasonable, and story 3 could be something like ", but I don't want Joe Random User to be able to access those [entities]". That should give you the incentive to add the authentication feature, so the real user can prove he/she is not Joe Random User.

@thecapsaicinkid wrote in a comment:

If I'm splitting my stories in a way which requires me to fake data, is this an indication I'm not splitting in a helpful way?

Not necessarily. If the story that needs the fake data and the story that replaces the fake data with the real data are in the same sprint, it is not a problem at all. At the demo it should not even be noticeable that half-way down the sprint fake data was used.
If the two stories get scheduled for adjacent sprints, it would at most be a minor annoyance that the result of the first sprint can't be meaningfully deployed to the end-users. It might become a problem if the story to provide the real data gets pushed further down backlog, but that is not very likely.

A 'thin slice' which relies on fake data has value to the business;
  they can see the application working. But it has practically no
  benefit to the end-user. Should I try and simplify my slice even
  further (maybe a simpler UI) so I can find the time to get some real
  data into the system and have an app which does at least something
  useful to the end user?

It depends and should really be discussed with the customer representative.
Sometimes it would be better to slice an epic in vertical slices (several stories, where each story contains both data retrieval, manipulation and UI). And sometimes you just have to accept that it is impossible to split an epic in multiple stories that are all on their own relevant to the end-user.

If that is the case, don't worry too much. The customer representative will most likely understand the situation and try to prioritize the stories such that the entire epic gets completed in as few sprints as possible (it is in their interest as well).


问:
SQL Server + database design and non mandatory fields
I am developing an app which allows a user to upload a maximum of 20 photos, the straight forward way is of course adding 20 columns to my database table but if the user only uploads 1 image, the remaining columns becomes redundant. Anyone can advice me on a more efficient way to design it?

Thanks.

答:
In general I would not store photos in binary form in a database. What I would do is store photos on disk and store the path to that photo in the database.

Other answers already showed how to create a seperate table, use that but with the references instead of the binaries.


答:
Considerations:

Can you detect when this has occurred, as opposed to someone mistyping their username? Logging mistyped usernames can be useful for support purposes, i.e. answering the question "why can't I log on" with the answer "You have mistyped your username, that should be a dash not a dot", or "You have a leading colon then whitespace - have you cut and pasted it". If you have a small number of high-value paying users (i.e. not yet another social networking site) then you will probably have to supply this kind of support.

What is the appropriate action should someone do this? Usernames may be indicators of hacking attempts. The fact that the username doesn't appear in your list doesn't mean you don't need to know what it was. However if you believe this is a serious concern, and you could detect whose password it was, you could require the user to change their password after this has occurred.

What is industry practice?  Industry practice is to log the username field but not the password field. You are unlikely to get fired for doing this.

Unless you have out-of-the-ordinary considerations, I would suggest following industry practice, and log the username field, regardless. Consider forced password changes as suggestion 2 if you think this is inadequate.

Title: Logging failed login attempts exposes passwords

Body:
I started logging failed logins attempts on my website with a message like

Failed login attempt by qntmfred

I've noticed some of these logs look like

Failed login attempt by qntmfredmypassword

I'm guessing some people had a failed login because they typed their username and their password in the username field. Passwords are hashed in the database, but if somehow the db got compromised, these log messages could be a way for an attacker to figure out passwords for whatever small percentage of people end up having a failed login such as this.

Is there a better way to handle this? Should I even worry about this possibility?


问:
Why are semicolons and commas interchanged in for loops?
In many languages (a wide list, from C to JavaScript):

commas , separate arguments (e.g. func(a, b, c)), while

semicolons ; separate sequential instructions (e.g. instruction1; instruction2; instruction3).

So why is this mapping reversed in the same languages for for loops:

```<code>for ( init1, init2; condition; inc1, inc2 )
{
    instruction1;
    instruction2;
}
</code>```

instead of (what seems more natural to me)

```<code>for ( init1; init2, condition, inc1; inc2 )
{
    instruction1;
    instruction2;
}
</code>```

?

Sure, for is (usually) not a function, but arguments (i.e. init, condition, increment) behave more like arguments of a function than a sequence of instructions.

Is it due to historical reasons / a convention, or is there a good rationale for the interchange of , and ; in loops?

答:
Maybe this is something specific for C/C++, but I post this answer, because the syntax of the lagnuages you described is mostly influenced by the C-Syntax.

Besides the previously answered questions are true, from a technical point of view, that's also because in C (and C++) the comma is actually an operator, that you can even overload. Using a semicolon-operator (operator;()) would possibly make it harder to write compilers, since the semicolon is the axiomatic expression terminator.

What makes this intersting is the fact, that the comma is widely used as seperator all over the language. It seems like the comma operator is an exception, that is mainly used to get for-loops with multiple conditions working, so what's the deal?

In fact the operator, is built to do the same thing like in definitions, argument lists, and so on: It has been build to seperate expressions - something the syntactic construct , cannot do. It can only seperate what has been defined in the standard.

However the semicolon does not seperate - it terminates. And this is also what leads us back to the original question:

```<code>for (int a = 0, float b = 0.0f; a < 100 && b < 100.0f; a++, b += 1.0f)
    printf("%d: %f", a, b);
</code>```

The comma seperates the expressions in the three loop parts, whereas the semicolon terminates a part (initialization, condition or afterthought) of the loop definition.

Newer programming languages (like C#) may not allow overloading the comma-operator, but they most likely kept the syntax, because changing it feels somehow unnatural.

Body:
Maybe this is something specific for C/C++, but I post this answer, because the syntax of the lagnuages you described is mostly influenced by the C-Syntax.

Besides the previously answered questions are true, from a technical point of view, that's also because in C (and C++) the comma is actually an operator, that you can even overload. Using a semicolon-operator (operator;()) would possibly make it harder to write compilers, since the semicolon is the axiomatic expression terminator.

What makes this intersting is the fact, that the comma is widely used as seperator all over the language. It seems like the comma operator is an exception, that is mainly used to get for-loops with multiple conditions working, so what's the deal?

In fact the operator, is built to do the same thing like in definitions, argument lists, and so on: It has been build to seperate expressions - something the syntactic construct , cannot do. It can only seperate what has been defined in the standard.

However the semicolon does not seperate - it terminates. And this is also what leads us back to the original question:

for (int a = 0, float b = 0.0f; a < 100 && b < 100.0f; a++, b += 1.0f)
    printf("%d: %f", a, b);

The comma seperates the expressions in the three loop parts, whereas the semicolon terminates a part (initialization, condition or afterthought) of the loop definition.

Newer programming languages (like C#) may not allow overloading the comma-operator, but they most likely kept the syntax, because changing it feels somehow unnatural.


问:
Create a database for database tables
I'm working on a project where I have to give users the ability to build their own tables,
each user can create more than one table.

(the type of all data is string).

The user can create a table and specify what columns he wants inside it.

What is the best way to do that:

to create databases dynamically

to have a table for tables (key,value ...).

something else

Another issue is: is it better to separate my database into two, so one is for the internal use (users, accounts,....) and the other is for the tables of the users (or for the table of tables)?

答:
How many users are you expecting? I would advise against creating new tables for users. This could create a very large database rather quickly.

Take a look at the EAV (Entity–attribute–value) model. This is quite flexible. http://en.wikipedia.org/wiki/Entity%E2%80%93attribute%E2%80%93value_model.

This way, you can have one table that stores the users 'tables'.

Title: Create a database for database tables


问:
How to prepare yourself for programming interview questions?

Possible Duplicate:

  Really “wow” them in the interview

Let's say I appear for an interview. What questions could I expect and how do I prepare?

答:
http://halcyon.usc.edu/~kiran/msqs.html

http://steve.yegge.googlepages.com/five-essential-phone-screen-questions

http://www.joelonsoftware.com/articles/GuerrillaInterviewing3.html

http://sites.google.com/site/sumedhshende/computerscience

ContentLicense: CC BY-SA 2.5


答:
I think the most sane approach would be to have a database for each user.  Most databases are built to handle security much better if one user has power over its own database and nothing else (you're going to want to use a special back-end user to be able to create the database, create the user, and assign permissions for that user to access that database -- anything else is a security risk).

Each user will have his or her own database with permissions to modify only that database.  This makes everything far more straightforward.  You no longer have to turn everything virtual since most problems on the database you can simply forward onto the user.  You would require a master database which keeps track of users, permissions, and their databases.  Many databases offer meta information, but I wouldn't recommend using it, at least not for users, since any extra information you would have to manage yourself anyway, and so you're likely doing what you'd have to do eventually anyhow.

One thing you should not have to save in master at this point is a table of tables -- This, you really should leave to the database to manage.  If you require a list of tables, you can query the meta for this info.

At this point, your only true concern is database name conflicts.  To solve this, you could do one of several things:

Provide the name yourself.  It's going to be an ugly name, and this isn't the most popular decision for users, but it's the easiest to do.

Let them provide the name, and you perform some sort of mapping of the virtual to actual name that you create yourself.  This is simple enough, with the exception that you need to parse queries and substitute the name yourself (I don't recommend it!).

Append the username on the left-hand side of the database name that they pick so there's no possibility of conflicting names (use some sort of character divider which cannot be used in the database name in order to not have to worry about user "me" with database "atloaf" and user "meat" with database "loaf" creating the same name).

This is obviously a database-heavy solution in that you rely mostly on the database engine to carry the logic behind what you can and can't accomplish, therefore I highly recommend that you know how to maintain the database (security being a major priority here) that you do ultimately pick.

With time, you can override certain functionalities if you require certain behaviors which you can't obtain normally with a database, but this approach is certainly advantageous in that you already have a lot of the logic completed for you with little or no tweaking.

Title: Create a database for database tables

Body:
I'm working on a project where I have to give users the ability to build their own tables,
each user can create more than one table.

(the type of all data is string).

The user can create a table and specify what columns he wants inside it.

What is the best way to do that:

to create databases dynamically

to have a table for tables (key,value ...).

something else

Another issue is: is it better to separate my database into two, so one is for the internal use (users, accounts,....) and the other is for the tables of the users (or for the table of tables)?


问:
Is Clojure's syntax really simpler than Scala's?
Argument which is always made in favour of Clojure is that.

The syntax is simpler and there is only one way of expressing code with no complicated rules.

However Scala has loads of different types of syntax and constructs as compared to Clojure.

But from last one week while trying to learn Clojure, I have noticed that the list of inbuilt macros are endless, Even though we write them with the same parenthesis syntax we need to learn how each works.

So in what sense is Clojure's syntax simpler ?
For LISPers it might be but for people from a different background learning different constructs in Scala seems simpler.

So from a neutral point of view, which syntax is simpler and readable?

答:
So from a neutral point of view, which syntax is simpler and readable?

Those are two very different questions.

Simpler means "composed of fewer parts". Clojure's syntax has fewer rules, ergo it is objectively simpler than Scala's.

Readability, however, is subjective. It mainly comes down to familiarity. For example, I find ECMAScript, C#, Java, D, Go, C++ and C to be nearly incomprehensible, but for someone who is used to reading that kind of syntax, they are fairly readable. This part of the question cannot be answered objectively or "from a neutral point of view".


答:
Even though we write them with the same parenthesis syntax

And that's basically the answer to your question.

we need to learn how each works.

While it is possible to introduce DSLs with a not so lispy syntax like Common Lisps loop using regular macros (I'll leave reader macros out of this), they are mostly used to control evaluation, and will still use regular s-expression syntax. One important feature is that even the more complex loop-like macros can be read using the same old sexpr reader.

While it's true that you'll have to learn about the different macros and the form of input they take, say Common Lisp's cond with its more nested vs. Clojure's cond reducing one layer of nesting, that doesn't only hold for macros, but also for regular functions. Imagine a usual function taking a quoted list of a particular structure as an argument – you'll still have to conform to the expected input structure, whether the function transforms code, expects some kind of alist, plist, a tree or something entirely different.

Whenever you encounter new functionality, there will be some API you'll have to learn. That would also hold for a language that only allowed strictly function(arg1, arg2, …, argN) syntax – you'd still have to learn what the expected arguments are, what side effects occur, and what the output of any given function is.

What's easier about Lisp syntax compared to a language like Scale, is that everything is represented more or less the same, and also that the code itself used these representations and data structures (that would be the homoiconicity everyone is talking about). This difference in syntactic complexity would become pretty clear if you tried to write a Lisp or Clojure parser and then a Scala parser. You'll have to cope with a much more complicated grammar – more complex rules concerning precedence, whitespace, ambiguities, more exceptions, and so on.

Title: Is Clojure's syntax really simpler than Scala's?

Body:
Argument which is always made in favour of Clojure is that.

The syntax is simpler and there is only one way of expressing code with no complicated rules.

However Scala has loads of different types of syntax and constructs as compared to Clojure.

But from last one week while trying to learn Clojure, I have noticed that the list of inbuilt macros are endless, Even though we write them with the same parenthesis syntax we need to learn how each works.

So in what sense is Clojure's syntax simpler ?
For LISPers it might be but for people from a different background learning different constructs in Scala seems simpler.

So from a neutral point of view, which syntax is simpler and readable?


答:
From the wikipedia definition:

In computer science, the syntax of a programming language is the set
  of rules that defines the combinations of symbols that are considered
  to be correctly structured programs in that language

Since clojure is a lisp, you have s-expressions + the list of reader macros and that's all.

In scala, you have classes, case classes, implicit lambda with _, implicit keyword, traits, generic annotations, variance annotations, etc

Clojure has a simpler syntax because features can be implement as macros or special forms. This is impossible with scala, in his you have to add syntax in order to support some features.


问:
Create Offline Demo Environment Database Substitute
I would like to know if there is a best practice for creating demo environments that substitutes database interaction into other forms of resource

i.e. creating .json files containing the data that was supposedly returned from a webservice call.

I wanted to know if there is already a standard way of obtaining the same result.

Thanks

答:
Databases are easy to set up, and all of the major databases are either free or have a free version available.  Therefore I would use an actual database in the demo environment. Advantages:

Complete consistency with production environment (or at least very close).

No need to write special handling for the different interface.

Easy to generate sample data (some tables could be taken directly from production.  If there is sensitive data in your production database, you could write a simple routine to anonymise it--replace with fake names and addresses, for example.)

If the size of your demo environment is not a big deal, I would even access the database via a local web server if that helps the environment stay similar to production.  There are prebuilt packages (such as XAMPP, which includes Apache, MySQL, and other tools) that make this sort of thing easy.  Setting up some extra programs is easy, while making changes to your original program is hard.  Therefore, minimize the latter whenever possible.

If duplicating a production-like environment is too heavyweight for your demo purposes, you could use a lightweight database (such as SQLite), and still have an interface that is fairly similar.


答:
I'm unsure what do you want to do here. Create a showcase of your application (1)? Test it in staging/development environment (2)? Unit test it (3)?

If you want to have a demo version of your application (for example in order to show to a potential customer what she gets, without actually letting the person to have an access to all the features and without polluting the production database), just duplicate the database. In most cases, the simple 1 to 1 duplication will work; if not, you may enhance the demo database with security restrictions which would make it impossible to change what should be changed only in production (for example the password of the demo user).

If your goal is to have a staging environment, the same technique of database duplication would be used. Here, you don't change anything: you have to have an exact duplicate of the database schema. The development environment will be based on a copy of a database too, given that there, the database may contain developer-specific changes.

Finally, if you're asking about unit testing, then mocking is generally used to make it easy to test the classes in a database-agnostic and data-agnostic way. Here, effectively, the database (and the data access layer in general) would be substituted with a mock which will provide specific answers to specific requests, like:

```<code>class SampleCustomerMock
{
    Customer FindCustomerById(int id)
    {
        // Just return a sample customer, without taking in account the `id`.
        return new Customer("John", "Miller", 36, Gender.Male);
    }
}

class MissingCustomerMock
{
    Customer FindCustomerById(int id)
    {
        throw new RecordNotFound();
    }
}
</code>```

Title: Create Offline Demo Environment Database Substitute

Body:
I would like to know if there is a best practice for creating demo environments that substitutes database interaction into other forms of resource

i.e. creating .json files containing the data that was supposedly returned from a webservice call.

I wanted to know if there is already a standard way of obtaining the same result.

Thanks

Body:
I'm unsure what do you want to do here. Create a showcase of your application (1)? Test it in staging/development environment (2)? Unit test it (3)?

If you want to have a demo version of your application (for example in order to show to a potential customer what she gets, without actually letting the person to have an access to all the features and without polluting the production database), just duplicate the database. In most cases, the simple 1 to 1 duplication will work; if not, you may enhance the demo database with security restrictions which would make it impossible to change what should be changed only in production (for example the password of the demo user).

If your goal is to have a staging environment, the same technique of database duplication would be used. Here, you don't change anything: you have to have an exact duplicate of the database schema. The development environment will be based on a copy of a database too, given that there, the database may contain developer-specific changes.

Finally, if you're asking about unit testing, then mocking is generally used to make it easy to test the classes in a database-agnostic and data-agnostic way. Here, effectively, the database (and the data access layer in general) would be substituted with a mock which will provide specific answers to specific requests, like:

class SampleCustomerMock
{
    Customer FindCustomerById(int id)
    {
        // Just return a sample customer, without taking in account the `id`.
        return new Customer("John", "Miller", 36, Gender.Male);
    }
}

class MissingCustomerMock
{
    Customer FindCustomerById(int id)
    {
        throw new RecordNotFound();
    }
}


问:
What common apporaches exist for database versioning for a feature driven development?
It's not clear how data consistency is provided for different branches.

We have a large knowledgebase which is filled by the experts and delivered as updates to our clients. This data is also used for testing the product.

But if we have quite a few feature branches (being developed in parallel)  and each feature requires its own slightly different db schema won't it be a hell?

Definitely some way of populating all DBs from one centralized store must exist.
And here comes the question? What are these methods?

Now the only solution I see is to create some mapping mechanism and to save mappings in the corresponding DB, yet I believe more elegant approaches exist.

Update:

To clarify the problem.

We have one (let's call it master db).
And N databases with slightly 'narrower' schemas comparing to the chema of master.
I.e. master is has the richest schema: other dbs have fewer tables/columns.

答:
Your database build and schema changes need to be under source control. Instead of shipping a database file with the knowledge base data already in it, have a separate build that will do an import of the knowledge data after the database is built or altered. The source of the data could be from text/xml files.

The import scripts would also be under source control since they have to handle the particular schema for this branch.

This is going to be sort of a hell if you don't get it under control and automated. If it were easy, everybody would be doing it.


答:
When I work in Scala, there is often a phase of my development (especially with for comprehensions) where I have to make all the types work out correctly which is a big plus for big projects, but a definite negative for small ones.  I expected that I could just forget types and focus on "getting the job done" in Clojure the way I vaguely remember doing in Perl or Awk, but so far it hasn't worked out that way for me.  My experience is that instead of "making the types work out" in the code/compile phase, I am getting exceptions when I try to run my code.  This is not a simplification; the problem hasn't gone away, it's just moved to a more dangerous/expensive part of the development cycle.

There is a delightful simplicity to Lisp-ish syntax.  One of the big strengths of Emacs is being able to execute arbitrary lisp code by hitting a special key sequence at the closing paren of a block of code at any time in any buffer.  The simple parenthesis-delimited nature of lisp syntax makes this elegant in a way that would be awkward (having to introduce curly braces?) in most other languages.  Also, the regularity of (function arg, arg...) and (operator arg, arg...) makes thinking about functions and operators as first-class citizens and thinking about anonymous functions very natural, in a way that the infix operators of other languages like Scala do not.

My limited experience with Scala prevents me from saying that the syntax is simpler or more readable.  Sure, there is some non-lispish syntax in Clojure using macros, but my perception is that these macros only open a little window into imperative thinking in a syntax that is otherwise very functional.  Imposing a preference for functional or imperative syntax in the language can simplify things.  I would have to give a point to Clojure, Java, and Haskell for this.

My concern with Scala is the same concern I had with C++ or Perl (though to a lesser degree); the syntax of the language accommodates several different thinking styles (Haskell and Java).  This makes it fun to write, but could be problematic for readability.  Even as I write that, I remember that Clojure supports Domain Specific Languages and wonder to what extent that undermines my point.

Your question is a very interesting one.  Ultimately, the comparison is a complex one.  But based on my current knowledge I would have to agree that the syntax of Clojure is simpler than Scala, but maybe not a whole order of magnitude simpler.


问:
What does Private Cloud mean?
I read through a few discussions in SE about Cloud Computing . From them, I understand cloud as "computing / data-storage facility that is owned by a different entity; using hardware & software architecture that make it easily scalable on-demand, therefore support rentable-scalability  models."

Also, "the owning entity has a big-size data center, where virtualisation concepts are put to use to cater to multiple different customers from same hardware".  Plus "redundancy, security etc are assumed to be taken care by the provider. "

I read a discussion in SE about explaining Cloud Computing to grandmother. The 'garden vs supermarket', 'own-house vs hotel' examples suit perfectly.

With this understanding, I am unable to visualise 'private cloud'. Frankly, 'private cloud' sounds like an oxymoron to me. (relate with 'private supermarket' , 'owned hotel' etc). Pardon my ignorance.

So, what is 'private cloud' ?

答: Virtual Private Cloud or Private Cloud can be defined as an integral part of a shared or public cloud. There prevail no changes in the eminent features, when compared to public or shared cloud network. In fact a Private Cloud network is rewarded with features like: better enterprise and customer control, enhanced security and no more tinkering issues related to regulatory compliance.</p>

Title: What does Private Cloud mean?


答:
Just to be safe, the logging in my current app does not store parameters passed to login or password-reset methods. The log call has an optional parameter that controls this, which, when set to true, replaces the stored parameters object with [Redacted]. Sure, so I miss out on a little data, but I have their IP addresses, and I'd rather not risk getting something that sensitive in plaintext.

If you really want to log this kind of thing, I'd suggest that when logging a login attempt, you check the database for users with a name matching what you have in the username field, and only store it if you have a match. Otherwise, you just store it as "unknown user". You could get fancy, checking if this value contains that or whatever, but there's always the risk that you get combinations like [User][Password] and [UserPas][sword], in which case you can check against the IP and deduce that you've inadvertently stored the start of someone's password in the clear. You could extend this to the unlikely-but-possible [User][Password] and [UserPassword][??], in which case you can see "unsuccessful login by UserPassword" followed by "Successful login by User" and deduce all of User's password. Generally, to be safe I'd say to not log usernames unless the login is successful.

Edit to add:

Most of the arguments people are posting for logging the username for failed login attempts are, in my opinion, better handled through other methods.

For example, it's been said that when a customer asks "why can't I log on?", logged usernames would allow you to point out typos. This is true, but it's not worth the risk of also catching passwords; I'd do this by instead redirecting the user back to the login form on failure, highlighting the username field and repopulating it with whatever they typed so that they can see for themselves.

Another argument was that it lets you identify hacking attempts; a string of failures against one username may well be an attempt to brute-force a password. I'd do this by having a "BadLogins" column on the Users table, which is incremented each time a login fails with a username matching this user, and is reset to zero on a successful login, after telling the user "there have been x unsuccessful login attempts since your last login" and advising them on what to do if they don't think the attempts were from them. If you want to be really thorough, you could have another column that stores the last value of the BadLogins column even after the successful login, and/or a column that stores the highest-ever value of this column, and/or a column that stores the total number of failed logins this account has ever had.


问:
Why can't we declare 'extern C' for C++ macro's?
I am new to C/C++. Wanted to know why we cannot declare 'extern C' for C++ macro's similar to methods/functions...which will allow macro's defined in C++ file to be accessed in .c files.

Thanks in Advance

答:
Macros in both C and C++ are a text replacement mechanism. Because of that, you can't define a macro in one source file and use it in a different source file.

What you can do is define a macro in a header file and include that header in both C and C++ source files where you want to use that macro.
Such a header would need to contain only code that comes from the common subset of C and C++ so it will be acceptable in both languages.


答:
I wanted to know if there is already a standard way of obtaining the same result.

The standard for seperating businesslogic from databaseaccess is to use the repository pattern .

Your app can have

one implementation to access the real data for production and

a 2nd implementation that reads the data from demo implementation and ignores the saveToDatabase calls.


问:
What's the formal name of this diagram?

I'd also want to know how can I draw them.

答:
That looks like SQLite's syntax diagrams.

Their FAQ says:

How are the syntax diagrams (a.k.a. "railroad" diagrams) for SQLite generated?

The answer is a link to this wiki page on "Generating Syntax Diagrams Using Tk".

The wiki links to this Tcl source code for generating the diagrams.

Title: What's the formal name of this diagram?


答:
Definition of The Cloud is very broad, can mean IaaS (Infrastructure as a Service), PaaS (Platform as a Service) or SaaS (Software as a Service). But let's focus only on IaaS. Typically this means providing full stack virtual servers with automated provisioning, abstracting away the hardware and making services easily scalable. This doesn't mean that whoever is operating the data-center needs to be a separate commercial entity though.

There are two typical private cloud setups:

true Private Cloud, is a cloud which is operated entirely and exclusively by single entity for it's internal use;

Virtual Private Cloud, which is a portion of a public cloud firewalled from the rest of public and typically available via VPN.

hybrid Private Cloud, which is a hybrid of above two. This is useful for so called Cloud Bursting, in other words offloading short burst of computing to the public cloud. This way organization doesn't need to over-commit resources.

Title: What does Private Cloud mean?

Body:
I read through a few discussions in SE about Cloud Computing . From them, I understand cloud as "computing / data-storage facility that is owned by a different entity; using hardware & software architecture that make it easily scalable on-demand, therefore support rentable-scalability  models."

Also, "the owning entity has a big-size data center, where virtualisation concepts are put to use to cater to multiple different customers from same hardware".  Plus "redundancy, security etc are assumed to be taken care by the provider. "

I read a discussion in SE about explaining Cloud Computing to grandmother. The 'garden vs supermarket', 'own-house vs hotel' examples suit perfectly.

With this understanding, I am unable to visualise 'private cloud'. Frankly, 'private cloud' sounds like an oxymoron to me. (relate with 'private supermarket' , 'owned hotel' etc). Pardon my ignorance.

So, what is 'private cloud' ?


问:
Is GCC dying without threads support on Windows?
I need some opinion. GCC was always a very good compiler, but recently it is losing "appeal".
I have just found that on Windows GCC does not have std::thread support, forcing Windows users to use another compiler because the most exciting feature is still missing.

But why really doesn't GCC still have threads support under Windows? License problems? ABI incompatibilities? (Well there are already several cross-platform libraries using multithreading: boost, POCO, SDL, wxwidgets, etc. Wouldn't it be simple to use already existing, and MIT/libpng licensed, code to fit this hole instead of shipping GCC releases with no thread support?)

Recently, looking at compiler comparisons, GCC has the widest support for C++11 features with respect to other compilers, except for the fact that on Windows this is not true because we are still lacking atomics, mutexes and threads :/

I'd like to know more about this topic, but the only thing I can find is people asking for help because:

"thread" does not exist in std namespace

Looking at tickets tracking and mail discussions of GCC/TDM-GCC, there were requests for thread support since 2009. Possible that after 4 years still no solution? What's really happening?

答:
The reason why it takes a lot of time is because it takes a lot of work to get a solid foundation to build the headers on top of. The way mingw-w64 seems to bo is to build a solid pthreads-like library on Windows. There's less upstream grumpiness over that than introducing a dependency on the native threading of the Windows API.

mingw-w64 implements <thread> and the other C++11 headers on top of their own winpthreads library. This should be available for testing in both Mingw-builds and rubenvb's distributions of the mingw-w64 toolchain. I would recommend following the mingw-w64 mailing lists if you want to track where most of the work on native Windows GCC work is done.

The Qt Project has a wiki page detailing their current recommendation and an over view of GCC toolchains on windows, see this Qt Project wiki page.


问:
What is the best programming language to do crypto running time measurement?
I am trying to measure the running time of different crypto algorithm. e.g. how long it takes to encrypt/decrypt a block of plaintext. May I ask if C with OpenSSL is the best PL to do this?

答:
By far, the language question is a matter of fashion. The best language for getting stuff done is the one you know. The best language for personal development is one you don't.

C would work just fine.


答: The same (both PL and library) that you'd use for production because libraries differ in implementation details, and benchmark from one PL/library is not representative of performance with another PL.</p>

Title: What is the best programming language to do crypto running time measurement?

Body: I am trying to measure the running time of different crypto algorithm. e.g. how long it takes to encrypt/decrypt a block of plaintext. May I ask if C with OpenSSL is the best PL to do this?


问:
Naming of related classes and interfaces
I have created an ObjectParser class which parses data into strongly typed objects using an IObjectParserDataSource as the data source (the data could be an Excel file, text file, array, query string, etc).

Examples of my implementations of IObjectParserDataSource are:

TextFileObjectParserDataSource

ExcelFileObjectParserDataSource

These class names feel really long and convoluted to me.

I could name them:

TextFileDataSource

ExcelFileDataSource

But this introduces a level of ambiguity and they don't became as clearly related to IObjectParserDataSource at first glance.  This becomes important because defining these data sources will happen in client code and I wish to minimize potential confusion and uncertainty.

How would you name these classes in such a scenario?

答:
I generally try to get around this problem by sticking all similar objects into one namespace and simplifying their names (if I can do it).

For example, would have

```
namespace ObjectParserDataSources
|
|-> class TextFileSource
|-> class ExcelFileSource
```

Or, if the collection of objects working with/servicing ObjectParser becomes large enough, I'd make a separate folder tree or project devoted just to ObjectParser:

```<code>namespace ObjectParser
|
|-> class ObjectParser
|-> interface IObjectParserDataSource
|
|-> namespace DataSources
|   |
|   |-> class TextFileSource
|   |-> class ExcelFileSource
|
|-> other stuff...
</code>```

Within any given file, the import statements and the code context would usually make it pretty clear that TextFileSource is the ObjectParser data source.  If there are multiple similarly named classes in the same piece of code, you can refer to TextFileSource by its full name:

```<code>var parserSource = new ObjectParser.DataSources.TextFileSource(/*...*/);
</code>```

It usually occurs very rarely and I don't mind typing out extra few words.

Body:
I generally try to get around this problem by sticking all similar objects into one namespace and simplifying their names (if I can do it).

For example, would have

namespace ObjectParserDataSources
|
|-> class TextFileSource
|-> class ExcelFileSource

Or, if the collection of objects working with/servicing ObjectParser becomes large enough, I'd make a separate folder tree or project devoted just to ObjectParser:

namespace ObjectParser
|
|-> class ObjectParser
|-> interface IObjectParserDataSource
|
|-> namespace DataSources
|   |
|   |-> class TextFileSource
|   |-> class ExcelFileSource
|
|-> other stuff...

Within any given file, the import statements and the code context would usually make it pretty clear that TextFileSource is the ObjectParser data source.  If there are multiple similarly named classes in the same piece of code, you can refer to TextFileSource by its full name:

var parserSource = new ObjectParser.DataSources.TextFileSource(/*...*/);

It usually occurs very rarely and I don't mind typing out extra few words.


问:
Functional Programming: right ideas about concurrency and state?
FP proponents have claimed that concurrency is easy because their paradigm avoids mutable state.  I don't get it.

Imagine we're creating a multiplayer dungeon crawl (a roguelike) using FP where we emphasize pure functions and immutable data structures.  We generate a dungeon composed of rooms, corridors, heroes, monsters and loot.  Our world is effectively an object graph of structures and their relationships. As things change our representation of the world is amended to reflect those changes.  Our hero kills a rat, picks up a shortsword, etc.

To me the world (current reality) carries this idea of state and I'm missing how FP overcomes this.  As our hero takes action, functions amend the state of the world.  It appears to be every decision (AI or human) needs to be based on the state of the world as it is in the present.  Where would we allow for concurrency?  We can't have multiple processes concurrently ammending the state of the world lest one process base its outcomes on some expired state.  It feels to me that all control should occur within a single control loop so that we're always processing the present state represented by our current object graph of the world.

Clearly there are situations perfectly suited for concurrency (i.e. When processing isolated tasks whose states are independent of one another).

I'm failing to see how concurrency is useful in my example and that may be the issue.  I may be misrepresenting the claim somehow.

Can someone better represent this claim?

答:
I'll try to hint on the answer. This is not an answer, only an introductory illustration. @jk's answer points to the real thing, zippers.

Imagine you have an immutable tree structure. You want to alter one node by inserting a child. As a result, you get a whole new tree.

But most of the new tree is exactly the same as old tree. A clever implementation would reuse most of the tree fragments, routing pointers around the altered node:

Okasaki's book is full of examples like this.

So I suppose you could reasonably alter small parts of your game world each move (pick up a coin), and only actually change small parts of your world data structure (the cell where the coin was picked up). Parts that only belong to past states will be garbage-collected in time.

This probably takes some consideration in designing the data game world structure in an appropriate way. Unfortunately, I'm no expert in these matters. Definitely it must be something else than a NxM matrix one would use as a mutable data structure. Probably it should consist of smaller pieces (corridors? individual cells?) that point to each other, as tree nodes do.


答:
GCC's popularity and usability is not questionable.

GCC is still great compiler and most widely used.

GCC supports languages that clang does not aim to, such as Java, Ada,
FORTRAN, etc.

GCC supports more targets than LLVM.

GCC is supporting C++11

From
  https://stackoverflow.com/questions/12210102/does-gcc-4-7-1-support-threads
  mingw build at http://code.google.com/p/mingw-builds/downloads/list
  supports threads.

But important consideration is License.

GCC is licensed under the GPL license. clang uses a BSD license, which allows it to be embedded in software that is not GPL-licensed.

The primary reason for switching from GCC to Clang is the incompatibility of GCC's GPL v3 license with the goals of the FreeBSD project.

FreeBSD has an uneasy relationship with the GPL. BSD-license advocates
  believe that truly free software has no usage restrictions. GPL
  advocates believe that restrictions are necessary in order to protect
  software freedom, and specifically that the ability to create non-free
  software from free software is an unjust form of power rather than a
  freedom. The FreeBSD project, where possible, tries to avoid the use
  of the GPL (For details
  https://unix.stackexchange.com/questions/49906/why-is-freebsd-deprecating-gcc-in-favor-of-clang-llvm)

Other important Considerations

From http://clang.llvm.org/comparison.html#gcc

The Clang ASTs and design are intended to be easily understandable by
anyone who is familiar with the languages involved and who has a
basic understanding of how a compiler works. GCC has a very old
codebase which presents a steep learning curve to new developers.

Clang is designed as an API from its inception, allowing it to be
reused by source analysis tools, refactoring, IDEs (etc) as well as
for code generation. GCC is built as a monolithic static compiler,
which makes it extremely difficult to use as an API and integrate
into other tools. Further, its historic design and current policy
makes it difficult to decouple the front-end from the rest of the
compiler.

Various GCC design decisions make it very difficult to reuse: its
build system is difficult to modify, you can't link multiple targets
into one binary, you can't link multiple front-ends into one binary,
it uses a custom garbage collector, uses global variables
extensively, is not reentrant or multi-threadable, etc. Clang has
none of these problems.

For every token, clang tracks information about where it was written
and where it was ultimately expanded into if it was involved in a
macro. GCC does not track information about macro instantiations when
parsing source code. This makes it very difficult for source
rewriting tools (e.g. for refactoring) to work in the presence of
(even simple) macros.

Clang does not implicitly simplify code as it parses it like GCC
does. Doing so causes many problems for source analysis tools: as one
simple example, if you write "x-x" in your source code, the GCC AST
will contain "0", with no mention of 'x'. This is extremely bad for a
refactoring tool that wants to rename 'x'.

Clang can serialize its AST out to disk and read it back into another
program, which is useful for whole program analysis. GCC does not
have this. GCC's PCH mechanism (which is just a dump of the compiler
memory image) is related, but is architecturally only able to read
the dump back into the exact same executable as the one that produced
it (it is not a structured format).

Clang is much faster and uses far less memory than GCC.

Clang aims to provide extremely clear and concise diagnostics (error
and warning messages), and includes support for expressive
diagnostics. GCC's warnings are sometimes acceptable, but are often
confusing and it does not support expressive diagnostics. Clang also
preserves typedefs in diagnostics consistently, showing macro
expansions and many other features.

Clang inherits a number of features from its use of LLVM as a
backend, including support for a bytecode representation for
intermediate code, pluggable optimizers, link-time optimization
support, Just-In-Time compilation, ability to link in multiple code
generators, etc.

Clang's support for C++ is more compliant than GCC's in many ways
(e.g. conformant two phase name lookup).

From
   http://www.linuxquestions.org/questions/slackware-14/gcc-vs-llvm-931034/

The advantage of llvm/clang is its modular design, so it can be

interfaced and used for example to create static code analysis tools,
what becomes more and more important ()

From http://clang.debian.net/

clang is now ready to build software for production (either for C,
C++ or Objective-C). This compiler is providing many more warnings
and interesting errors than the gcc suite while not carrying the same
legacy as gcc.

Title: Is GCC dying without threads support on Windows?

Body:
I need some opinion. GCC was always a very good compiler, but recently it is losing "appeal".
I have just found that on Windows GCC does not have std::thread support, forcing Windows users to use another compiler because the most exciting feature is still missing.

But why really doesn't GCC still have threads support under Windows? License problems? ABI incompatibilities? (Well there are already several cross-platform libraries using multithreading: boost, POCO, SDL, wxwidgets, etc. Wouldn't it be simple to use already existing, and MIT/libpng licensed, code to fit this hole instead of shipping GCC releases with no thread support?)

Recently, looking at compiler comparisons, GCC has the widest support for C++11 features with respect to other compilers, except for the fact that on Windows this is not true because we are still lacking atomics, mutexes and threads :/

I'd like to know more about this topic, but the only thing I can find is people asking for help because:

"thread" does not exist in std namespace

Looking at tickets tracking and mail discussions of GCC/TDM-GCC, there were requests for thread support since 2009. Possible that after 4 years still no solution? What's really happening?


答:
Generally, you should not use macros in C++ at all.  The main reason is that macros do not respect scope. They simply drop a chunk of code in the middle of your source file. This can cause all manner of bugs, which will be very hard to find, because you would have to do this textural insertion in your head.

In C++, if the cost of a function call is your performance bottleneck, then you should use inline functions, which do respect scope, instead of macros.

If you need to share code between C++ and C, then you probably should write a proper C function and declare that as extern "C". If you need to be able to call C++ code from C, then you should write a very thin C wrapper function around it.

IMHO, the simplest thing to do is to just use C++. The only reason to use C would be if you are working on an embedded platform, which doesn't have a C++ compiler.

Title: Why can't we declare 'extern C' for C++ macro's?

Body:
I am new to C/C++. Wanted to know why we cannot declare 'extern C' for C++ macro's similar to methods/functions...which will allow macro's defined in C++ file to be accessed in .c files.

Thanks in Advance


问:
Why did Apple choose to design its programming language with future and past tense method names?
There are a lot of methods like this in iOS/Objective C:

```<code>- viewDidLoad
- viewWillAppear:
- applicationDidFinishLaunching
</code>```

I've just been having a discussion with some colleagues about this design choice and why they would choose to be so verbose in preference of the more "standard" ways of event propagation for instance:

```<code>- onViewLoad
- onViewAboutToAppear
- onApplicationFinishLaunching
</code>```

I didn't have an answer and rather put it down to just personal preference of the team designing the language. However, I'm wondering if there's more to it - whether this is a preferred option. Or whether the team just wanted to differentiate themselves from other languages, or from the norm.

If anyone has any insight that would be very interesting.

Thanks

答:
Or whether the team just wanted to differentiate themselves from other languages, or from the norm.

First, I'll point out that the names in question come from frameworks, not from the programming language (Objective-C) itself.

It's impossible to say what the team was thinking unless you were part of it, but I'd imagine that the names come from the fact that the methods are called before or after a given event has happened. For example, -viewWillAppear is called just before the view is shown on the screen, and -viewDidAppear is called just after the view is shown. Together, these methods let you prepare for something that's about to happen and respond to something that just happened. I don't think these names were chosen just to be different from other frameworks (indeed, the frameworks from NextStep that became Cocoa predate many of today's object frameworks), but more likely were just meant to be descriptive.

Note that the ...Did... and ...Will... methods aren't the only ways that events are communicated to your code. For example, touches have a more complex lifecycle, so you have methods like -touchesBegan:..., -touchesMoved:..., -touchesEnded:..., and -touchesCancelled:....


答:
9000's answer is half the answer, persistent data structures allow you to reuse unchanged parts.

You may already be thinking however "hey what if I want to change the root of the tree?" as it stands with the example given that now means changing all the nodes. This is where Zippers come to the rescue. They allow element at a focus to be changed in O(1), and the focus can be moved anywhere in the structure.

The other point with zippers is that a Zipper exists for pretty much any data type you want

Title: Functional Programming: right ideas about concurrency and state?

Body:
FP proponents have claimed that concurrency is easy because their paradigm avoids mutable state.  I don't get it.

Imagine we're creating a multiplayer dungeon crawl (a roguelike) using FP where we emphasize pure functions and immutable data structures.  We generate a dungeon composed of rooms, corridors, heroes, monsters and loot.  Our world is effectively an object graph of structures and their relationships. As things change our representation of the world is amended to reflect those changes.  Our hero kills a rat, picks up a shortsword, etc.

To me the world (current reality) carries this idea of state and I'm missing how FP overcomes this.  As our hero takes action, functions amend the state of the world.  It appears to be every decision (AI or human) needs to be based on the state of the world as it is in the present.  Where would we allow for concurrency?  We can't have multiple processes concurrently ammending the state of the world lest one process base its outcomes on some expired state.  It feels to me that all control should occur within a single control loop so that we're always processing the present state represented by our current object graph of the world.

Clearly there are situations perfectly suited for concurrency (i.e. When processing isolated tasks whose states are independent of one another).

I'm failing to see how concurrency is useful in my example and that may be the issue.  I may be misrepresenting the claim somehow.

Can someone better represent this claim?


问:
Why does Haskell have built-in "if/then/else" instead of defining it as a simple library function?
Why does Haskell have a built-in if/then/else, which is dependent on the Bool type, instead of having a simple library function? Such as

```<code>if :: Bool -> a -> a -> a
if True  x _ = x
if False _ y = y
</code>```

答: It's purely for the nice sugar of the if, then, and else keywords; in fact, GHC (with the RebindableSyntax extension enabled) will desugar the syntax by simply calling whatever ifThenElse function is in scope.


问:
What is the best way to prove that in-code documentation is greater than extensive external documentation?
What is the best way to prove to my boss that in code documentation is greater than extensive external documents containing documentation and screenshots of code/ui?

We have a group in the company running SAP code.  Their documentation process involves hours of laborious documentation and screenshots of the code and the interface (before and after).

They want us (C# developers) to follow the same rubric as they do.  I want to argue that using comments in the code, and a great, self documenting language such as C# is fulfilling the need for documentation the same as, or greater than the other team's document method.

Is there any published research by big companies that say external documentation is out dated and that in code comments are more efficient? (or something similar to this point)

This has nothing to do with users.  This is NOT user training documentation. Only internal use.

This has nothing to do with Design Documents or Architectural Documents.  It's comparing screenshots of code, before and after a change, and screenshots of forms, before and after the change, and putting them into a document with extensive documentation, opposed to simply having great incode documentation.

Would you really want to have to screenshot your code before and after every single baby change and then write a document explaining the change in great depth? when no one will ever use these documents as reference material in the future?

答:
They're not intended to do the same thing.  Sure there could be some overlap, but in general in-code documentation is going to be at a lower level describing what this one section of code does, whereas external documentation is going to be better at describing the application at a higher level, or even as a whole, beyond the scope of just one code file.

I'd say it's not a question of one or the other.  Both should be used.


答:
Functional style programs create lots of opportunities like that to use concurrency. Anytime you transform or filter or aggregate a collection, and everything is pure or immutable, there's an opportunity for the operation to be sped up by concurrency.

For example, suppose you perform AI decisions independently of each other and in no particular order. They don't take turns, they all make a decision simultaneously and then the world advances. The code might look like this:

```<code>func MakeMonsterDecision curWorldState monster =
    ...
    ...
    return monsterDecision

func NextWorldState curWorldState =
    ...
    let monsterMakeDecisionForCurrentState = MakeMonsterDecision curWorldState
    let monsterDecisions = List.map monsterMakeDecisionForCurrentState activeMonsters
    ...
    return newWorldState
</code>```

You have a function to compute what a monster will do given a world state, and apply it to every monster as part of computing the next world state. This is a natural thing to do in a functional language, and the compiler is free to perform the 'apply it to every monster' step in parallel.

In an imperative language you'd be more likely to iterate over every monster, applying their effects to the world. It's just easier to do it that way, because you don't want to deal with cloning or complicated aliasing. The compiler can't perform the monster computations in parallel in that case, because early monster decisions affect later monster decisions.

Body:
Functional style programs create lots of opportunities like that to use concurrency. Anytime you transform or filter or aggregate a collection, and everything is pure or immutable, there's an opportunity for the operation to be sped up by concurrency.

For example, suppose you perform AI decisions independently of each other and in no particular order. They don't take turns, they all make a decision simultaneously and then the world advances. The code might look like this:

func MakeMonsterDecision curWorldState monster =
    ...
    ...
    return monsterDecision

func NextWorldState curWorldState =
    ...
    let monsterMakeDecisionForCurrentState = MakeMonsterDecision curWorldState
    let monsterDecisions = List.map monsterMakeDecisionForCurrentState activeMonsters
    ...
    return newWorldState

You have a function to compute what a monster will do given a world state, and apply it to every monster as part of computing the next world state. This is a natural thing to do in a functional language, and the compiler is free to perform the 'apply it to every monster' step in parallel.

In an imperative language you'd be more likely to iterate over every monster, applying their effects to the world. It's just easier to do it that way, because you don't want to deal with cloning or complicated aliasing. The compiler can't perform the monster computations in parallel in that case, because early monster decisions affect later monster decisions.


问:
What are the worst false economies in software development?
What are the worst false economies (that is ways of saving money that ultimately cost more than they save) prevalent in the software industry and how do you combat them?</p>

答:
Buying off the shelf software instead of developing it internally.

I have experience of entreprise scale management systems, focussed on both HR and Biological Laboratories.

An off the shelf solution cost £50-100k and needed further development and customisation to meet the business requirements.

The internally developed solution took (<6) months to develop, with other projects being worked on in parallel, and utilized an already employed developer.

I went from the public sector where we had an internally developed LIMS (lab information management system) up and running, to a large international pharmaceutical where the implemention of an off the shelf solution had taken over a year and was nowhere complete.

(6 months of an already hired developer working on other projects in parallel. So ~10k. And that doesn't include the support costs associated with the off shelf solution). The major point is that the internally developed system was actually being used! So you then have the added cost benefit associated with that, which I cannot calculate.

I'd agree for basic websites etc, why bother developing your own. But for any large complex systems and if you already have in house skills, I'd build it myself.


答:
The only comparison to go on that I have experience with is Microsoft's event patterns.

Microsoft frameworks use two styles for these events one in Windows Forms and ASP.NET Web Forms, the other appears in WPF/Silverlight/WinRT.

In Forms based applications, the framework uses imperfect tense for (something's happening) and perfect tense for (something happened). One example is INotifyPropertyChanging/INotifyPropertyChanged interface pair (which provide the PropertyChanging and PropertyChanged events, respectively).

For WPF et al, the framework uses Preview[EventName] and EventName. No past tense is used here for example PreviewMouseClick and MouseClick are the event pair for a mouse click event.

I think the choice between the three naming methods is subjective as long as they are consistently used within a given framework.

Title: Why did Apple choose to design its programming language with future and past tense method names?

Body:
There are a lot of methods like this in iOS/Objective C:

```<code>- viewDidLoad
- viewWillAppear:
- applicationDidFinishLaunching
</code>```

I've just been having a discussion with some colleagues about this design choice and why they would choose to be so verbose in preference of the more "standard" ways of event propagation for instance:

```<code>- onViewLoad
- onViewAboutToAppear
- onApplicationFinishLaunching
</code>```

I didn't have an answer and rather put it down to just personal preference of the team designing the language. However, I'm wondering if there's more to it - whether this is a preferred option. Or whether the team just wanted to differentiate themselves from other languages, or from the norm.

If anyone has any insight that would be very interesting.

Thanks


答:
I think you need to be some where in the middle.  Different audiences require different levels and styles of documentation.

Your SAP peers may be overdoing for developer's consumption, but I would imagine their documentation transitions nicely into Help Pages or a Users Guide.  Code comments don't help sell the application to management in the early stages.  Requirements and high-level design documents don't fit well in the code either but are certainly critical to everyone's understanding of correct/expected behavior.

Title: What is the best way to prove that in-code documentation is greater than extensive external documentation?

Body:
What is the best way to prove to my boss that in code documentation is greater than extensive external documents containing documentation and screenshots of code/ui?

We have a group in the company running SAP code.  Their documentation process involves hours of laborious documentation and screenshots of the code and the interface (before and after).

They want us (C# developers) to follow the same rubric as they do.  I want to argue that using comments in the code, and a great, self documenting language such as C# is fulfilling the need for documentation the same as, or greater than the other team's document method.

Is there any published research by big companies that say external documentation is out dated and that in code comments are more efficient? (or something similar to this point)

This has nothing to do with users.  This is NOT user training documentation. Only internal use.

This has nothing to do with Design Documents or Architectural Documents.  It's comparing screenshots of code, before and after a change, and screenshots of forms, before and after the change, and putting them into a document with extensive documentation, opposed to simply having great incode documentation.

Would you really want to have to screenshot your code before and after every single baby change and then write a document explaining the change in great depth? when no one will ever use these documents as reference material in the future?


问:
Is this an MVC framework?
I have built a framework for my applications that has been working well, and I have always referred to it in my mind as an MVC. However, after reading some more on what an MVC is (not that I didn't to start with, but I gave it a very brief overview, and looked at other frameworks that used the mvc pattern), and it has given me pause for thought.

The structure is as follows:

The framework has a bootstrap that loads the required files for the framework and the initiation file for the application (app_bootstrap.php).

The app_bootstrap.php file has three functions.

First, it creates constants for the framework to use (i.e. Database connection setup, profiling setup, base url path, and internal file paths).

Second, it requires all the files that would be pertinent to the application, primarily, what I have called "model" classes which contain information on the name and structure of tables in the database, validation rules, associations to other "models", etc. These "models" extend an abstract class that contains static functions for selecting and creating rows from the database, which will create instances of an entity class that deals with the row, such as __get, __has, __set, __unset for fetching columns and associations, and save and delete for saving the row changes to the database.

Third, it calls functions within the router.php file that will setup bindings for environmental data (like the url, user login status, ssl, ajax, cookie existence, etc) to "controller" classes.

The framework then runs an execution function within router.php that will go through the defined environmental data rules, and determine which "controller" to load, if it finds one, it will require the file (from the application/controllers directory, throwing an error if not found) and call the class with the appropriate entry point function (index is none defined), or throw a 404 error.

Once the "controller" has been started, there are no more functions that the framework will execute, and once the "controller" has finished, the program will end (unless the profiling has been activated, where it will output the data, then end). But the framework provides functions to the "controller", and to name a few, an input class (for dealing with all input, such as $_GET, $_POST or $_SERVER variables, cookies, user agent, remote ip, etc, as well as providing a sanitized interface), an output class (for headers, cookies, status messages, etc), a queryBuilder class (for creating queries to the database in the event functionality that can't be done within the "model"), and a view class (for parsing variables into a view for rendering and returning to the client).

But after reading some more information on MVC's, it appears that the router.php acts similarly to a Controller, the "controller" acts like the model, the "model" acts like an ORM, and the view is pretty much correct. So, would this framework still be classed as an MVC, or does it fit under another pattern (if there is such a pattern)?

答:
Your Router is what's called the Front Controller; it handles the upfront processing of the request and hands it to your Controllers which from a 10k foot view sounds like a true MVC controller. Many developers leverage the same object model that the O/RM uses, but it sounds like your "Entity" classes are the true Model. Either way you look at it, it sounds like a valid MVC implementation to me.

One thing to note about software patterns... In general the pattern provides a guideline but not a strict implementation. It's always subject to the interpretation of the developer. Similar to Alexander's original work that software patterns were based on. Alexander's patterns described general solutions to a common problem in building spaces, but the actual realization of those solutions were subject to the aestethic of the builder.

OwnerDisplayName: cgoddard

Title: Is this an MVC framework?


问:
Do Flexibility and Inconsistency,Unsafety Overlap?
I was lately doing some research about different programming languages. I was interested particularly to learn unique features of popular programming languages and situations where these assets shine. I believe this can help me to decide what language to use depending upon the problem to solve.

I found that many languages offering high level of flexibility ("can adapt to new, different, or changing requirements") are also inconsistent,
for example in JavaScript (just an example, no offense to js people), arguments of a function get be manipulated either by naming them in the function declaration (classic approach):

```<code>function max(x,y)
</code>```

Or by using the arguments variable:

```<code>function max() {
    if (arguments[0] < arguments[1])
        return arguments[1];
    else
        return arguments[0];
}

c = max(1,2);
</code>```

The arguments variable is useful for many situations such as function overloading, however, it defeats the purpose of function prototyping (which is to give information about the function), and I saw many JavaScript samples where the argument variable is being used despite there is no need for it, which clearly makes the code harder to understand and debug.

I know that this depends heavily on the users of the language, but usually, code written in a language offering high flexibility tends to be unsafe, harder to understand,optimize and to debug.

Do flexibility and inconsistency overlap? How do languages designers make the choice?

Edit: I'm not critiquing any particular language here, I'm rather focusing on the relation between Flexibility,Safety,Consistency of programming languages.

答:
I don't think flexibility and inconsistency overlap or have a natural 1:1 relationship. More on this in a bit.

As for your other question, I would assume that language designers make these choices the same way they make any other choice; by comparing the pros and cons and deciding which one is the most suited for the language and the problem. Inconsistency is a con but there are pros that outweigh it.

For example, in your specific question about the arguments keyword, it's very useful in a functional context where you apply arguments to function calls. In fact, documentation for apply indicates such. Otherwise you would specifically have to loop through arguments that you might not even have named. This can be a significant benefit.

Consider:

```<code>function f() { console.log(arguments); }
f(); // [ ]
f(1, 2, 3); // [1, 2, 3]
</code>```

In JavaScript, the binding between named arguments happens automatically based on position, but you can provide any number of arguments to any function. Because of this behavior, it doesn't seem inconsistent to provide a facility to interact with the arbitrary arguments. Additionally, you could view the named argument binding as the special case; syntactic sugar over var arg1 = arguments[0]; etc.

As far as flexibility and inconsistency, I think they're primarily two separate measurements of modifications. I don't really have any references to discussions of the two forces, however, in C#, for example, you could increase the flexibility of generic constraints quite a bit by providing mechanisms to constrain generics to delegates or enumerations. This is completely consistent with the existing language.

It just so happens that often a price to pay for flexibility is inconsistency, for example, C++11 added trailing return type declarations simply to support lambdas and a couple other compile-time type inference features. This was completely inconsistent but it allowed a new dimension of flexibility which was deemed important enough to allow the inconsistency.

Body:
I don't think flexibility and inconsistency overlap or have a natural 1:1 relationship. More on this in a bit.

As for your other question, I would assume that language designers make these choices the same way they make any other choice; by comparing the pros and cons and deciding which one is the most suited for the language and the problem. Inconsistency is a con but there are pros that outweigh it.

For example, in your specific question about the arguments keyword, it's very useful in a functional context where you apply arguments to function calls. In fact, documentation for apply indicates such. Otherwise you would specifically have to loop through arguments that you might not even have named. This can be a significant benefit.

Consider:

function f() { console.log(arguments); }
f(); // [ ]
f(1, 2, 3); // [1, 2, 3]

In JavaScript, the binding between named arguments happens automatically based on position, but you can provide any number of arguments to any function. Because of this behavior, it doesn't seem inconsistent to provide a facility to interact with the arbitrary arguments. Additionally, you could view the named argument binding as the special case; syntactic sugar over var arg1 = arguments[0]; etc.

As far as flexibility and inconsistency, I think they're primarily two separate measurements of modifications. I don't really have any references to discussions of the two forces, however, in C#, for example, you could increase the flexibility of generic constraints quite a bit by providing mechanisms to constrain generics to delegates or enumerations. This is completely consistent with the existing language.

It just so happens that often a price to pay for flexibility is inconsistency, for example, C++11 added trailing return type declarations simply to support lambdas and a couple other compile-time type inference features. This was completely inconsistent but it allowed a new dimension of flexibility which was deemed important enough to allow the inconsistency.


问:
REST vs RPC for mobile development
As many know, mobile development is skyrocketing these days and, I believe, it affects what we code. To be specific, I am interested in developing web services for a mobile application.

I see two possible architectures - RPC and REST. I have developed both, REST and RPC services and what I have observed is that RPC services are way easier to code, especially in languages like PHP. The problem with it seems to be scalability - server-side can easily turn into a mess when many procedures are present.

REST, on the other hand seems to be a lot more structured, server-side becomes relatively easy to maintain but it has a potential to break data into multiple resources which is bad for mobile applications (for multiple reasons).

From what I have experienced, RPC seems a bit better in most cases:

Both, client- and server- sides, are concerned to minimize number of procedures available and calls made.

Following architectural rules does not counter with optimizations otherwise possible.

I don't really expect someone to explain me what REST and RPC are, the web is full of that. I want people who has experience developing mobile apps express their opinions about using these two architectures on the server-side. Tips are also welcomed (who doesn't love tips, huh?).

答:
There's little difference, RPC tends to be more binary-protocols than REST, but that doesn't have to be the case. Also RPC tends to be implemented as a single procedure point per call, but again that doesn't have to be - you can implement a single RPC procedure that takes a REST-style verb as the first argument. RPC sometimes has a semi/stateful approach, but again that doesn't have to be the case if you pass in a 'cookie' with each call.

Nowadays it all comes down to development support, and there are more REST APIs for web-based languages, and so people use REST. If you're taking a more user-centric view of development, then you'd probably be better off with a RPC mechanism instead, taking advantage of the flexibility to provide a more compressed binary protocol, then implement it how you like - single procedure that routes to a routine based on an id or 'verb' and is full stateless by passing an id. All of this can be implemented to look very REST-like but with significantly lower overhead.

There are several RPC systems, try protocol buffers or thrift for your mobile app.

Title: REST vs RPC for mobile development


答:
I think the rationale is that in Objective-C, selectors are supposed to be messages sent to the objects. Sending [viewController onViewAppear:] makes it sound like you're going to pass it a lambda telling it what to do, whereas [viewController viewWillAppear:] is better under the "I am sending this message to that object" paradigm. (I find it weird that the animated flag isn't in the selector in this case though.)

From there it makes sense to reduce length and extraneous particles by preferring future tense -viewWillAppear: over -viewAboutToAppear:.


问:
Use of pirated/cracked software for development
Disclaimer: I by no means condone the use of pirated software.

Have you ever witnessed the use of pirated software for development purposes? May be a company didn't have enough money to buy a piece of software and there were no free alternatives? May be a company wanted to try something out before buying and there were no trial licenses for that product. Whatever the circumstances, have you worked at a company where using pirated/cracked software was accepted? Were there any consequences to doing this?

答:
I've seen major misuse of MSDN licenses in the past.

People using MSDN products for production use, or sharing server products (or in some cases desktop products) from one MSDN license between multiple developers, either because they genuinely didn't understand the license or, I suspect, wilfully not wanting to understand it.

To be fair to them Microsoft licensing has been, and remains, so damn opaque you can understand why people don't want to engage with it, wrong as it is to copy software.


答:
You can generate help files from XML Comments in source code.
SandCastle can take those comments and create nice help files, which you can complement with conceptual documentation.

EDIT: The tools allows you to:

Brings your comments on the code to an external documentation

Your docs' source is versioned, without extra effort (since your source code already is, right?)

If you need to explain concepts to newer developers, the docs project manager app have an (semi-decent) editor to what is called "conceptual documents" in a XML-based language. I've used myself, the editor is good enough to it not being a problem.

I don't remember details from memory, but I believe you can link all that (code-based and conceptual) content to each other, allowing you to get something in the lines of VS help.

All this allows you to get all content from what already exist in your sources, and complement it with conceptual explanations (the "how this all fits on the puzzle?" stuff). And having the hability to export it to HTML, CHM Help and other formats.
I believe it would placate your management need for external documentation from the internals.

EDIT 2:
Answering to the OP's second editing, what he's looking for is some kind of changelog to answer why(and when) some changes happened.

You could implement it on code or an external "conceptual content" artifact that you change (or generate) from your source control system hooks. That way, each time you generate the documentation, it get's the "What's new in this release" document in a easily presentable format.

It can even be an different documentation project file from your documention main project (which means it can be generated separately and with different presentation settings).

BTW, seems your boss is looking for some model to follow. SAP process appear to be way too much, but you can show him what he's trying to achieve (which is traceability of the changes: the "who, when and what" question) in a automated (and presentable) way.

PS.: An bug tracking system would help here too, as you can include the change request (or bug file #) that motivated the change too.


问:
What is the best way to understand code in a project with null documentation?
It is our first game and we are a start-up. We had a programmer who suddenly is seeming to be a dead weight. Though we knew him personally we thought that he was as motivated as we are and hence I never looked for a code review or documentation. Now it seems that he is slacking a lot and we want him out.

Now during a conversation he said that he would not document the code so as we could be dependent on him. I looked at the code and there is no documentation.

The code is all over the place. What would be the best way to understand his code?

Details of the code:

Written in C# and targeting a mobile platform using Unity3D.

The game play mechanic and camera is scripts are the main and they have no documentation.

Too much of Send/Broadcast messages so I am not able to see the references through Mono.

Again hefty use of strings in either invoking methods or passing parameters

Update function everywhere which could have been reduced to coroutines.

Naming is poor and inconsistet

Absolutely no pooling with usage of destroy and instantiation. I am expecting memory leaks.

What protocols should I adopt to understand the code and work on top it?

答:
very simple?

I would just use the code and refactor/rewrite parts of it that need a change whenever it's necessary.

You don't need to rewrite all his code if it just works.

Edit:

Coming to think about the fact that he may be THAT Kind of coder,

There may be a few solutions that may be impractical but they may be worth mentioning:

1.hire an ex-coworker of his that knows his coding style.

2.hire someone that doesn't comment his code, this kind of people understand each other best.


答:
You may think code is "self documenting" but I can assure you you're wrong. The only reason you think it is, is because you have the knowledge on how your code works hiding inside your head - its like having an invisible, unwritten set of documentation memorised. Work on someone else's code and you'll begin to see this (usually this manifests itself as the "my colleagues code is crap" syndrome, really its just because you're missing any documentation on how it works).

"external" documentation is every bit as important as the code, you must be able to communicate what the code does, how it does it (in broad design terms) and why it does it. These things cannot be embedded within the fine-grained codebase. Sure, you can do internal code docs too, and they can be auto-generated, but I always found them to be a little pointless compared to just reading the code (and the embedded comments).

Where you're right is that documentation doesn't have to be a laborious task, written in huge Word documents. You can make the task much easier by writing it in a lightweight markup language (eg ASCIIDoc or ReStructured Text) which can then be compiled into Word or HTML formats. This documentation 'source' can then be edited within your IDE as they're only text files, and you can apply code review tools and your SCM to it too. This approach makes the necessary documenting task significantly easier for developer teams.


问:
How do distributed version-control systems deal with fragmentation?
Here is the scenario:

X is the author of a software. X releases v1.0 on an open source license on Github and moves on. People interested in the software fork and improve the software. Now there are 15 different flavours of the software. Few also try to send a pull request back, however since X no longer works on the software, the pull request is just sitting idle on his project page.

As a new user wanting to use the most active and stable release of the software, how does he learn which out of the 15 he should clone and use? He certainly would like to use the more active branch, since it may have more bug fixes and features upgrades.

I see that the model works for bigger open-source projects, because the author of the software is usually well-known in the community. As a result, the user base inadvertently knows which branch to clone from. However, how does one solve a problem for a software, where the author, maintainer and several contributors all are practically unknown in the open-source community?

答:
This is a serious and not fully solved problem.  You only have to look at the state of RubyGems to see how bad it can be (with multiple gems that have the same name, divergent versioning schemes, and incompatible APIs).

At the end of the day, if you want to have a community build and maintain a piece of high quality software, I think it is almost always necessary to have a single "blessed" repository with maintainer(s) that do releases.

The distributed development is still key because it lets people experiment on their own copy and later merge changes back in to the slower and more stable mainline.


问:
Is it possible to reach absolute zero bug state for large scale software?
I am talking about 20-30+ millions lines of code, software at the scale and complexity of Autodesk Maya for example.

If you freeze the development as long as it needs to be, can you actually fix all the bugs until there is simply not a single bug, if such a thing could be verified by computers? What are the arguments for and against the existence of a bug-free system?

Because there is some notion that every fix you make creates more bugs, but I don't think that's true.

By bugs I meant from the simplest typos in the UI, to more serious preventative bugs that has no workaround. For example a particular scripting function calculates normals incorrectly. Also even when there are workarounds, the problem still has to be fixed. So you could say you can do this particular thing manually instead of using the provided function but that function still has to be fixed.

答:
Yes.

But as you know, it requires far too much effort to be worth it.

Before I can defend my answer, we must first define what a bug is:

A bug is a behavior that is contrary to the specification.

However, glitches in the specification (e.g. the 0th law of robotics) do not count as software bugs.

Extra features do not count as bugs, unless prohibited by the specification.

For the sake of argument, contradictions within the specification do not count as software bugs, either.

Now, as you hopefully already know, good software architectures are modular, so that each module can be unit tested (or manually tested, or whatever) individually. Through discipline and careful testing, it is possible to write individual modules that do not have bugs in them.

"But wait!" I hear you protest, "What if an unexpected (but nonetheless correct) behavior of one module causes a bug in another?" Then the bug is in the second module. Bug-free modules can be treated as APIs, and APIs, as you know, require some care to be used correctly.

Writing bullet-proof code requires extensive knowledge of edge cases and flow logic on the part of the developer, and most software developers either aren't smart enough to learn or simply don't care. Or more often, they're on a deadline.

"But give me a place to stand, and I will move the world." - Archimedes

ContentLicense: CC BY-SA 4.0