问:
Application connecting to database server
I'm working on an application which requires user credentials and so on. So a database is required on the backend.

What is the best practice to connect to a database without hardcoding your password into it? The program could be reverse engineered and one might get the password which is something we obviously don't want.

答:
I just went though this myself.  Assuming you're using SQL Server, I actually created user accounts on the database server for every user (you can do this from t-sql).  I have one general user account that I can use to first verify that I can make a connection, and select from a Version table that makes sure the version of the software running matches the database schema version.

Users who have the ability to add/remove users in the application also need to have rights to administrate users on the database server.  This is actually a problem since the users are defined at the database server level, not at the database level.  That means someone with the ability to add/remove database server users could potentially create a new user that could access another database.  For this reason, I suggest running a separate instance of the database server for this.

There are other ways to go about it:

If your users login to Windows with unique accounts, you can use integrated security where they just authenticate with the Windows credentials.  Ideal if it works for you (we had some shared computers, so it didn't).

You can have a common user and hard-code the credentials in the connection string, but only give that user access to stored procedures, not tables.  Then in the stored procedures you have to pass login credentials every time, and the stored proc does the authentication.  This has the advantage of allowing more granular security (you can limit what rows they can get back, so for instance, they wouldn't be able to see another user's timesheet records, but they could see their own).

If you need only rudimentary protection of some data, just have two users: NormalUser and AdministratorUser.  Only store the NormalUser's password in the connection string.  When you need to do something that requires administrator level permissions, have them enter the AdministratorUser's password, and open a new connection.

Put the database into local-only mode (no remote connections) and create a web service that runs on that machine and acts as your data access layer.  This will let you do really advanced security (gives you full control over what a user can see) and it means the rest of your application basically sees the data as business objects rather than rows and columns.  The web service, obviously, needs to handle the authentication.


答:
The best practice is to give each user their own account on the database, and to set permissions on that account to restrict their access as you see fit.

The user's credentials go into a configuration file for the application.

ContentLicense: CC BY-SA 3.0

Title: Application connecting to database server

Body:
I'm working on an application which requires user credentials and so on. So a database is required on the backend.

What is the best practice to connect to a database without hardcoding your password into it? The program could be reverse engineered and one might get the password which is something we obviously don't want.


答:
Can you use integrated authentication? For example, in SQL Server 2008 R2, the following connection string accesses the local master database using Windows credentials.

```<code>Data Source=localhost;Initial Catalog=master;Trusted_Connection=true
</code>```

And I would never recommend creating SQL users for an application. You are now giving direct database access to your users, who should always be using the application (unless you explicitly allow them direct access). Additionally you are restricted by what tools SQL offers you for authentication. A common problem is per-row access, your application can do the filtering pretty easily, but creating stored procedures to duplicate it is non-trivial.

To be fair though, you do need to worry about escalation of rights attacks when using a proxied account.

Body:
Can you use integrated authentication? For example, in SQL Server 2008 R2, the following connection string accesses the local master database using Windows credentials.

Data Source=localhost;Initial Catalog=master;Trusted_Connection=true

And I would never recommend creating SQL users for an application. You are now giving direct database access to your users, who should always be using the application (unless you explicitly allow them direct access). Additionally you are restricted by what tools SQL offers you for authentication. A common problem is per-row access, your application can do the filtering pretty easily, but creating stored procedures to duplicate it is non-trivial.

To be fair though, you do need to worry about escalation of rights attacks when using a proxied account.


问:
Unit test coding standards
Usually when talking about coding standards we refer to the code of the program itself, but what about the unit tests? Are there certain coding standards guidelines that are unique to unit tests? What are they? </p>

答:
The main thing is to remember that unit tests are essentially mini-specifications. This means that the emphasis must always be on readability.

Firstly, this means that names must clearly communicate what is under test and what is being asserted.

Secondly though, which is sometimes forgotten, is that as specifications they should be doing just that - specifying behaviour. That is, unit tests should not contain logic - or potentially they fall into the trap of repeating the program's functionality rather than testing it.

Sometimes the tests will involve objects which are complex to set up, you should strive to keep this set up logic separate from your tests using something like an object mother or a test data builder.

I'll just round off with a few book recommendations:

xUnit Test Patterns: Refactoring Test Code: Excellent book, some say it's a bit dry but I don't think so. Goes into a lot of detail about lots of different ways of organising tests and how to keep them maintainable. Relevant if you're using something like NUnit etc.

The Art of Unit Testing: With Examples in .Net: The best book on the nitty-gritty of writing and maintaining tests. Despite being really new I find the mocking sections a little dated already as AAA syntax is now pretty standard rather than just another way of doing it.

Growing Object-Oriented Software, Guided by Tests: This book is just amazing! By far the best unit testing book and the only advanced one which puts unit testing as a first class citizen in the design process. Was reading this when it was a public beta and been recommending since. Excellent real-worldish worked example used throughout the book. Would recommend reading Roy's book first though.

ContentLicense: CC BY-SA 2.5

Title: Unit test coding standards

ContentLicense: CC BY-SA 4.0


问:
Is it common for business analysts (or other non-development team members) to have stories tracked alongside developers?
We're using JIRA with Greenhopper, and currently our business analyst has tasks for their analysis which will eventually lead to new stories placed in the backlog, running alongside the stories for the current sprint, and it feels kind of messy - especially because they don't overlap the workflow for the development stories.

Is it common for this to be the case? Should it be? It feels like the analysis ought to be an external process that feeds in to the product backlog, not something that tags along the sprint backlog, but I am new to scrum.

I consulted the scrum guide and didn't see anything explicit, and while we don't really have a Product Owner (although at times I would say our manager fills that role, other times so does the business analyst), I guess I could also phrase the question as:

Should Product Owners track their tasks next to the stories that the development team works on?

答:
In my experience ...

Pros:

It gives developers a warm feeling that they're not the only ones expected to be transparent.

It does help the Product Owner understand the process.

Cons:

It gives Product Owners the belief that what they do is comparable somehow to what developers do.

It complicates the work board unnecessarily.

It offers very little genuinely useful information to anyone.

Personally, I think the pros can be achieved in other ways. But the cons are not unacceptable, so if the Product Owner REALLY wants it, let them have it until it proves a waste of time.


问:
Application Logic Vs DB Triggers for database cleaning
When cleaning out old data from a set of database tables, is it safer to have the logic in the application or in a database trigger?

I am upgrading an application that I wrote a while back (and in a hurried fashion) and one of the things I want to clean up first is ensuring that data which is no longer being used is propmtly deleted. Currently this is being done in my application itself via a number of SQL calls to various tables. Some of these queries take a bit of time to run and as the application is PHP driven, I don't want users having to wait too long.

I was therefore thinking about creating a database trigger on one table that would merrily clean up all the other tables and then allow the single row delete to occur from my master table.

I am considering these pros and cons at the moment:

Database trigger

(+) Invisible to the application

(+) Simplifies application logic - new objects can be simplified

(-) Adds complexity to overall maintenance - have to maintain code and triggers during table changes etc.

Application Logic

(+) Keeps all maintenance tasks in one place

(-) Longer page loads on certain tasks

(-) More chance of a request timing out - orphaning data

If you have any further insight, considerations I haven't thought of here, experience with one vs the other or can point me towards some reading on the matter I would love to hear it.

Edit: I originally thought that my pages would run quicker, but if I am creating a Before Delete trigger, will the page loads be the same - as in the application sends a tiny query through but it won't be actioned until the entire set of statements in the trigger complete?

答: You can use ON DELETE CASCADE but it will be time-consuming if you have many child records. Many dbas will not allow you to use it as it can lock up the system. Personally, if the users want to see the data gone immediately, I would use an is_deleted flag field on the parent table (with a view that shows only the non-deleted.) and then really delete the records in batches  during non-production times. </p>


答:
If you have just one application which has write access to your database (or at least to the relevant tables here), and your CRUD operations are in one place of that application, then there is normally no need for using triggers for keeping your data consistent. Triggers are a good thing when you don't know beforehand who and what processes/applications will access your db in the future, and you want to keep a lot of consistency rules in one place, mostly in your DB. So, my "rule of thumb":

when you have the only one application which does write access to your DB under your control, put the db logic (like deletion rules) completely in your application, because of easier maintenance

when the DB shall keep its data consistent by itself, because you have a growing number of applications developed by bunch of people, and you cannot assure every developer of that team understands all consistency rules of every part of your database, then use triggers

And as you have seen by yourself, performance may or may not influence your decision, but often the differences are negligible, and bottlenecks may be solved different anyhow.

Title: Application Logic Vs DB Triggers for database cleaning

Body:
When cleaning out old data from a set of database tables, is it safer to have the logic in the application or in a database trigger?

I am upgrading an application that I wrote a while back (and in a hurried fashion) and one of the things I want to clean up first is ensuring that data which is no longer being used is propmtly deleted. Currently this is being done in my application itself via a number of SQL calls to various tables. Some of these queries take a bit of time to run and as the application is PHP driven, I don't want users having to wait too long.

I was therefore thinking about creating a database trigger on one table that would merrily clean up all the other tables and then allow the single row delete to occur from my master table.

I am considering these pros and cons at the moment:

Database trigger

(+) Invisible to the application

(+) Simplifies application logic - new objects can be simplified

(-) Adds complexity to overall maintenance - have to maintain code and triggers during table changes etc.

Application Logic

(+) Keeps all maintenance tasks in one place

(-) Longer page loads on certain tasks

(-) More chance of a request timing out - orphaning data

If you have any further insight, considerations I haven't thought of here, experience with one vs the other or can point me towards some reading on the matter I would love to hear it.

Edit: I originally thought that my pages would run quicker, but if I am creating a Before Delete trigger, will the page loads be the same - as in the application sends a tiny query through but it won't be actioned until the entire set of statements in the trigger complete?


问:
How much help should I give during technical interviews?
I'm asked to perform or sit in during many technical interviews. We ask logic questions and simple programming problems that the interviewee is expected to be able to solve on paper. (I would rather they have access to a keyboard, but that is a problem for another time.) Sometimes I sense that people do know how to approach a problem, but they are hung up by nervousness or some second-guessing of the question (they aren't intended to be trick questions).

I've never heard my boss give any help or hints. He just thanks the interviewee for the response (no matter how good or bad it is) and moves on to the next question or problem. But I know something about the rabbit hole that defeat and nerves can lead you down, and how it disables your mind, and I can't help wondering if providing a little help now and then would ultimately help us end up with more capable programmers instead of more failed interviews.

Should I provide hints and assistance for befuddled interviewees (and if so, how far should I go while still being fair to the more prepared candidates)?

答: I prefer to start interviews with an easy confidence-building question to get the candidate comfortable with the process.  When this works it still lets you glean as much information as possible from later questions without giving advantage to candidates who understand body language better than the job related material.</p>


问:
To be an interviewer - Java
The internet is full of references on how to get prepared for an interview. Many websites are loaded with questions and answers. But I can't find any useful information about what exactly an interviewer should do to evaluate a candidate.

What I mean is not just collecting good questions to be asked. I am asking about strategy for evaluating a candidate and find out if he is really good or just learnt the questions and answers well. I wonder if someone can share his experience in interviewing SWES, and what do you think about the following

What to expect from a junior java developer? what he should know?

What to expect from a senior java developer? what he should know?

答:
Have them write code on a whiteboard or on paper for something like
1. Reverse a linklist without using built in method in the java/std/.net API
2. Design/Create a stack using a linklist. For this they will need to understand some design patterns.</p>

Title: To be an interviewer - Java


问:
What is a Spring AOP 'advice'?
As the question states.

What is an 'advice'? More importantly, what does it even mean (semantics)?
What's the etymology of 'advice' in the Spring context?

答:
It's an established standard term of aspect-oriented programming. From Wikipedia:

In aspect and functional programming, advice describes a class of
  functions which modify other functions when the latter are run; it is
  a certain function, method or procedure that is to be applied at a
  given join point of a program.

[...]

The term advice goes back to the term advising as introduced by Warren Teitelman in his PhD thesis in 1966.

Title: What is a Spring AOP 'advice'?


问:
What backs up the claim that C++ can be faster than a JVM or CLR with JIT?
A reoccurring theme on SE I've noticed in many questions is the ongoing argument that C++ is faster and/or more efficient than higher level languages like Java. The counter-argument is that modern JVM or CLR can be just as efficient thanks to JIT and so on for a growing number of tasks and that C++ is only ever more efficient if you know what you're doing and why doing things a certain way will merit performance increases. That's obvious and makes perfect sense.

I'd like to know a basic explanation (if there is such a thing...) as to why and how certain tasks are faster in C++ than the JVM or CLR? Is it simply because C++ is compiled into machine code whereas the JVM or CLR still have the processing overhead of JIT compilation at run time?

When I try to research the topic, all I find is the same arguments I've outlined above without any detailed information as to understanding exactly how C++ can be utilized for high-performance computing.

答:
What the other answers (6 so far) seem to have forgotten to mention, but what I consider very important for answering this, is one of C++' very basic design philosophies, which was formulated and employed by Stroustrup from day #1:

You don't pay for what you don't use.

There are some other important underlying design principles that greatly shaped C++ (like that you shouldn't be forced into a specific paradigm), but You don't pay for what you don't use is right there among the most important ones.

In his book The Design and Evolution of C++ (usually referred to as [D&E]), Stroustrup describes what need he had that made him come up with C++ in the first place. In my own words: For his PhD thesis (something to do with network simulations, IIRC), he implemented a system in SIMULA, which he liked a lot, because the language was very good in allowing him to express his thoughts directly in code. However, the resulting program ran way too slow, and in order to get a degree, he rewrote the thing in BCPL, a predecessor of C. Writing the code in BCPL he describes as a pain, but the resulting program was fast enough to deliver results, which allowed him to finish his PhD.

After that, he wanted a language that would allow to translate real-world problems into code as directly as possible, but also allow the code to be very efficient.

In pursue of that, he created what would later become C++.

So the goal quoted above isn't merely one of several fundamental underlying design principle, it's very close to the raison d'etre for C++. And it can be found just about everywhere in the language: Functions are only virtual when you want them to (because calling virtual functions comes with a slight overhead) PODs are only initialized automatically when you explicitly request this, exceptions only cost you performance when you actually throw them (whereas it was an explicit design goal to allow the setup/cleanup of stackframes to be very cheap), no GC running whenever it feels like it, etc.

C++ explicitly chose to not to give you some conveniences ("do I have to make this method virtual here?") in exchange for performance ("no, I don't, and now the compiler can inline it and optimize the heck out of the whole thing!"), and, not surprisingly, this indeed resulted in performance gains compared to languages that are more convenient.


答:
Are the Business Analysts part of the Team?  If so, then consider that the Scrum Guide is pretty clear on not dividing the team into roles:

Scrum recognizes no titles for Development Team members other than
Developer, regardless of the work being performed by the person;
there are no exceptions to this rule;

Individual Development Team members may have specialized skills and
areas of focus, but accountability belongs to the Development Team as
a whole; and,

Development Teams do not contain sub-teams dedicated to particular
domains like testing or business analysis.

As such, either the BAs are equal members of the team, and thus their work is too, or they are not and it is not.  If they are part of the team, and there is a task with a measurable goal (you know when it's "done"), then it is a viable task in the Sprint Backlog.

Moreover, a User Story is a story about functionality the user is asking for.  It is not a list of work to be done, as such.  So again, what you are talking about isn't really a "story".

So, on the practical side, I'd suggest that you include folks with business analyst skills on your team and use them to help complete your stories.  The team won't know everything about a story before they start on a story--they just know there's something they need to learn about and solve.  The ones with business analyst skills are going to be really helpful in elaborating the stories and translating business speak to something that can be coded and tested. If, during sprint planning, you determine there are analysis tasks to be done, add them to your sprint backlog and have someone work on them.

Title: Is it common for business analysts (or other non-development team members) to have stories tracked alongside developers?

Body:
We're using JIRA with Greenhopper, and currently our business analyst has tasks for their analysis which will eventually lead to new stories placed in the backlog, running alongside the stories for the current sprint, and it feels kind of messy - especially because they don't overlap the workflow for the development stories.

Is it common for this to be the case? Should it be? It feels like the analysis ought to be an external process that feeds in to the product backlog, not something that tags along the sprint backlog, but I am new to scrum.

I consulted the scrum guide and didn't see anything explicit, and while we don't really have a Product Owner (although at times I would say our manager fills that role, other times so does the business analyst), I guess I could also phrase the question as:

Should Product Owners track their tasks next to the stories that the development team works on?


答:
I think it depnds on the interview situation and the questions. I have used both techniques.

Why might I want to not ask follow-up questions? When I am trying to find out the person's response to stress. I have interviewed people for some jobs that were in highly stressful environments and how well they could handle stress was a critical factor in our evaluations, so we asked some extremely difficult questions that no one could answer without some stress.

When I am trying to find out their technical knowledge, I ask follow-up questions that may contains hints as to what I am looking for. Contrary to the thought of the manager who said you have to ask everyone the same questions to be fair, I believe this is fair as long as several conditions are met. First everyone gets asked the same base question. Second, you should not ask follow up questions to help only one person. If you have let others flounder with no help, you need to let all flounder with no help. Second, you should compare candidates' performance on the question, not only in terms of their final answer but in terms of how hard it was to drag it out of them. This process still treats everyone fairly.

Title: How much help should I give during technical interviews?

Body:
I'm asked to perform or sit in during many technical interviews. We ask logic questions and simple programming problems that the interviewee is expected to be able to solve on paper. (I would rather they have access to a keyboard, but that is a problem for another time.) Sometimes I sense that people do know how to approach a problem, but they are hung up by nervousness or some second-guessing of the question (they aren't intended to be trick questions).

I've never heard my boss give any help or hints. He just thanks the interviewee for the response (no matter how good or bad it is) and moves on to the next question or problem. But I know something about the rabbit hole that defeat and nerves can lead you down, and how it disables your mind, and I can't help wondering if providing a little help now and then would ultimately help us end up with more capable programmers instead of more failed interviews.

Should I provide hints and assistance for befuddled interviewees (and if so, how far should I go while still being fair to the more prepared candidates)?


问:
Enterprise Wide Keys
I have for a long time been working on an ODS as well as Data Warehouse.  Both are integrating a wide variety of data sources from stove pipe applications.  One of the uses of the ODS is to provide data to other stove pipe applications.

Imagine one app maintains a database of personnel, and another app manages tracking sales.  Occasionally the Sales app may need to have a drop down of personnel that someone can pick from, say to credit a particular employee with a sale/commission.

The Sales application can query the ODS to get the list of personnel.  This allows the Personnel app to change its data structure, and the ODS modifies the ETL process to adapt to that change.  Thus all the other apps consuming that data will not be impacted by the change.

The Sales app will need to save a PersonnelID to that sale/commission record in its own database.  However, the next time the ODS is refreshed, if it is using a full load technique, the key will change.  Since the PersonnelID stored in the Sales database is a separate database, there is no straight forward way to cascade that change.

This creates a challenge where any changes made to the ODS have to be made very carefully, and may even limit certain designs because external applications are depending on those keys to never change.  I would usually avoid exposing keys to users, but in this case it seems necessary to allow external apps to reference enterprise wide entities in their own applications.

The same goes for lookup tables that are available in the ODS, where a lookup table has keys and text.

After a full load of the ODS I can ensure the keys satisfy referential integrity within the database, but not with external databases utilizing those keys.  Since there are some parts of the ODS currently coded as a full load, which would cause keys to be regenerated, I would need to recode that ETL to be incremental, so that external databases can reference those keys without fear of them changing.

What techniques are used when you have an enterprise wide data source, and other applications consume that data and need to store foreign keys referencing entities in that data?  How do you decouple the foreign key references as much as possible without complicating the access to that data?

Currently I am using table valued functions to provide access to data.  I chose this approach because it allows parameters, joins, and decouples access to underlying tables that may change later.

答:
You have to adhere to these rules:

OLTP applications don't change keys.

ODS generates its own Business Intelligence keys.

Datawarehouse database never references OLTP keys and must use keys generated by ODS (step 2).

There is no way to go lean about any of the above rules unless you do a full load every night.

Trying to get "deltas" (changed data only) from OLTP is usually a nightmare in large enterprise systems like Siebel, SAP, etc. unless your ETL provides "connectors" (canned queries against ERP and similar tools) and you have expertise in the source OLTP system. Even then, it is usually difficult because of the complexity of the such enterprise schemas.

Again, you have to adhere to the above rule and most probably, there is no other way. Kimball, has a good set of books on the subject if you care to dig for more.

Title: Enterprise Wide Keys


问:
In a resume, what all constitutes a Programming Language
In your resume, what would you classify as a Programming Language? For instance, under Programming Languages (or a similarly titled section of your resume), do you list C#, Java, C and leave it at that or do you go and add XML (because, well it is eXtensible Markup Language) and XSLT and jQuery and all that too?

If you are not going to add jQuery under languages, where exactly would you put it?

One resolution to this dilemma would be put in the technologies you have used under the project, but that way, you are forcing the recruiter to go through the projects that you have done rather than giving a highlight of the technologies and languages you are familiar in.

What are your thoughts?

答:
In my Resume, I have set 4 sections. They are written as:

Client-side Web Skills: HTML, CSS, JavaScript, JQuery, Photoshop, Flash/ActionScript

.Net Skills: C#, ADO.NET/LINQ, ASP.NET, AJAXControlToolkit, SQL Server 2005/T-SQL

PHP Skills: PHP, MySQL, PHPMyAdmin, Wordpress, Joomla

General IT Skills: SDLC, DBMS, UML, Communication Skills

This is just my way of writing CV, yours will be appreciable too.


问:
Generating different combinations from a list of muscles
Suppose we have a model of a human muscular system containing the following muscles each within a specific muscle group:

Arms

Biceps

Triceps

Forearms

Torso Front

Abs

Chest

Shoulders

Torso Back

Trapezius

Lats

Rear Shoulders

Lower Back

Lower Body

Quads

Hams

Hip & Butt

Calves

Now, given a list of selected muscles, I need to find combinations following the given rules:

If all muscles are selected from a group:

```<code>Full body (All muscles)
Arms
Torso
Torso Front
Torso Back
Lower Body
</code>```

If there are full groups together:

```<code>Arms and torso
Arms and torso front
Arms and torso back
Arms and lower body
Torso and lower body
Torso front and lower body
Torso back and lower body
</code>```

When both the front and back of the torso is selected it can be considered just "torso".

If there are more than 2 muscles selected from a group but not all:

```<code>Parts of torso (This is the case where there are muscles selected from both front- and back-torso)
Parts of torso back
Parts of lower body
</code>```

"Parts of torso front" and "Parts of arms" never occur on their own as they only have a total of 3 muscles, thus those cases can be represented by their names: eg. "biceps and triceps", etc.

Combinations of these aforementioned "parts"

```<code>Parts of arms and torso
Parts of arms and lower body
Parts of torso and lower body
Parts of  arms, torso and lower body.
</code>```

Parts = groups are not full and there are more than 2 muscles selected. This "rule of 2" is the most important one.

Examples of output

biceps, triceps and chest: parts of arms and torso

biceps, triceps, calves, tai biceps, triceps, quads, hams, hip & butt: Parts of arms and lower body

biceps, abs, calves: Parts of arms, torso and lower body

biceps, triceps: Biceps and triceps

biceps, triceps, forearms: Arms

chest, shoulders, abs, trapezius, lats, rear shoulders, lower back: Torso

and so on, there are multiple possible variations.

Now my problem is that I have no idea how to write this as clean and modular as possible, so that rules can be added or removed if necessary.

I could just write a massive if-elseif-else pile that would consider all cases, but you know why I won't.

How would you tackle this kind of task?

答:
I hate generalizing examples like this because you are always guessing and your brilliant generalization might get destroyed by the new rule they come up with.  So if possible ask the domain experts if your abstraction makes sense to them.

That being said, it sounds like you have a hierarchy.  It's mostly obvious from what you list, plus torso is a parent of front torso and back torso.  Each node in the hierarchy can describe itself with a string.  Your leaf nodes just print their name (e.g. "biceps").  Most of your interior nodes follow your "rule of 2" (either combining the string values of the children or replacing with another value as described in the question).  The torso node basically follows a "rule of 1", using the child's input only if there is exactly 1 child.  There is an implicit root node ("whole body node"?) that handles the "and" and "," logic.

You might have 4 different node classes here, or a strategy pattern, or 3 strategies one of which takes the "rule of X" parameter.

This records a bit more semantic information and might generalize better - until you find out that a finger and a toe combine into "digits" even though they are otherwise in a completely different branch of the hierarchy.  But I would probably do this over Doc Brown's simpler solution if I believed there would be many more such cases in the future and the domain experts thought they would fit this model.


问:
async & await - poll for alternatives
Now that we know what is in store for c#5, there is apparently still an opening for us to influence the choice of the two new keywords for 'Asynchrony' that were announced by Anders Heijsberg yesterday at PDC10.

```<code>async void ArchiveDocuments(List<Url> urls) {
    Task archive = null;
    for(int i = 0; i < urls.Count; ++i) {
        var document = await FetchAsync(urls[i]);
        if (archive != null)
            await archive;
        archive = ArchiveAsync(document);
    }
}
</code>```

Eric Lippert has an explanation of the choice of the current two keywords, and the way in which they have been misunderstood in usability studies. The comments have several other propositions.

Please - one suggestion per answer, duplicates will be nuked.

答:
yield async FetchAsync(..)

This goes perfectly with the async modifier you need to put on the method you're invoking. And also the semantic of the current yield return that is, you return and yields execution to the enumerating code while in this case you're yielding your execution to the asynchronous method.

Imagine if in the future there'll be other uses for yield, we could add a yield x where x is the shiny new feature instead of having all these different keywords for doing mostly the same thing, yield execution.

Frankly, I don't quite understand the 'not yielding execution' argument. After all, isn't the point of calling another method is already to 'yield execution' to that method? Regardless of whether it is asynchronous or not? I'm I missing something here?

And good for you if the async returns synchronously but having the keyword there should signify that there's a likely chance that the method would run asynchronously and that you'll be yielding execution to another method. Your method should account for that regardless of whether the method actually does asynchronous calls or not.

IMO I think the various 'not yielding' cases are an implementation detail. I'd rather vouch for consistency in the language (i.e. reusing yield).

Title: async & await - poll for alternatives


答:
It is mainly about memory (as Michael Borgwardt said) with a bit of JIT inefficiency added in.

One thing not mentioned is the cache - to use the cache fully, you need your data to be laid out contiguously (ie all together). Now with a GC system, memory is allocated on the GC heap, which is quick, but as memory gets used the GC will kick in regularly and remove blocks that are no longer used and then compact the remaining together. Now apart from the obvious slowness of moving those used blocks together, this means that data you're using may not be stuck together. If you have an array of 1000 elements, unless you allocated them all at once (and then updated their contents rather than deleting and creating new ones- that will be created at the end of the heap) these will become scattered all over the heap, thus requiring several memory hits to read them all into the CPU cache. A C/C++ app will most likely allocate the memory for these elements and then you update the blocks with the data. (ok, there are data structures like a list that behave more like the GC memory allocations, but people know these are slower than vectors).

You can see this in operation simply by replacing any StringBuilder objects with String... Stringbuilders work by pre-allocating memory and filling it, and is a known performance trick for java/.NET systems.

Don't forget that the 'delete old and allocate new copies' paradigm is very heavily used in Java/C#, simply because people are told that memory allocations are really fast due to the GC, and so the scattered memory model gets used everywhere (except for stringbuilders, of course) so all your libraries tend to be wasteful of memory and use a lot of it, none of which gets the benefit of contiguity. Blame the hype around GC for this - they told you memory was free, lol.

The GC itself is obviously another perf hit - when it runs, it not only has to sweep through the heap, but it also has to free all unused blocks, and then it has to run any finalisers (though this used to be done separately the next time round with the app halted)(I don't know if it still is such a perf hit, but all docs I read say only use finalisers if really necessary) and then it has to move those blocks into position so the heap is compacted, and update the reference to the new location of the block. As you can see, its a lot of work!

Perf hits for C++ memory comes down to memory allocations - when you need a new block, you have to walk the heap looking for the next free space that is big enough, with a heavily fragmented heap, this is not nearly as fast as a GC's 'just allocate another block on the end' but I think it is not as slow as all the work the GC compaction does, and can be mitigated by using multiple fixed-sized block heaps (otherwise known as memory pools).

There's more... like loading assemblies out of the GAC that requires security checking, probe paths (turn on sxstrace and just look at what it's getting up to!) and general other overengineering that seems to be much more popular with java/.net than C/C++.

Title: What backs up the claim that C++ can be faster than a JVM or CLR with JIT?

Body:
A reoccurring theme on SE I've noticed in many questions is the ongoing argument that C++ is faster and/or more efficient than higher level languages like Java. The counter-argument is that modern JVM or CLR can be just as efficient thanks to JIT and so on for a growing number of tasks and that C++ is only ever more efficient if you know what you're doing and why doing things a certain way will merit performance increases. That's obvious and makes perfect sense.

I'd like to know a basic explanation (if there is such a thing...) as to why and how certain tasks are faster in C++ than the JVM or CLR? Is it simply because C++ is compiled into machine code whereas the JVM or CLR still have the processing overhead of JIT compilation at run time?

When I try to research the topic, all I find is the same arguments I've outlined above without any detailed information as to understanding exactly how C++ can be utilized for high-performance computing.


问:
What's the best lesson you have learned in your career?
I think mine is "there's no such thing as a five minute job" - that programmers tend to be overly optimistic about development and that we should really think through a the implications before promising a quick solution to a problem and then diving in to code</p>

答:
There is always a better way to write your code.

No matter how excellent you find the code you write, you will be surprised how bad it is if you review it in a few years. Just because a few years before, you were unaware of some patterns you know today, or some language features you've learnt meanwhile, etc.


问:
What are the Characteristics of a Software "Center of Excellence" (CoE)?
Recently a new director of my department came in and expressed his wish that we become a "center of excellence". I expected that since he is my first boss who actually has a programming background that there would be some description of this. However, it was left at that.

As I reflected on this over the last few days, I am coming up empty on what a CoE actually means beyond just "being effective" at delivering the product. Here are the main items I am struggling with:

Is this just a term that is thrown around by management types?

What qualities make a group of software developers and testers excellent?

How do you measure excellence in this context?

答:
The first person that comes to mind when I think about "Software Center of Excellence" is Uncle Bob Martin

Uncle Bob is a long time advocate for excellence in software development in the form known as Software Craftsmanship. As wikipedia described it

Software craftsmanship is an approach to software development that emphasizes the coding skills of the software developers themselves. It is a response by software developers to the perceived ills of the mainstream software industry, including the prioritization of financial concerns over developer accountability.

Listen to him on the following podcast as he explains what Software Craftsmanship is:

Software Engineering Radio Episode 150 Software Craftsmanship with Bob Martin

Also check out the Manifesto for Software Craftsmanship, which highlights the importance of well crafted software, adding value, the community of professionals, and productive partnerships

Since a software center of excellence requires excellently trained programmers, you may also want to look at the following resources:

Programmer's Competency Matrix

What Every Computer Science Major Should Know

97 Things Every Programmer Should Know

97 Things Every Software Architect Should Know


答:
Think before you start coding.

There is nothing more permanent than temporary solutions :)

If it is awfully hard to solve a problem, most likely the problem itself is badly posed from the very beginning.

Title: What's the best lesson you have learned in your career?

Body: I think mine is "there's no such thing as a five minute job" - that programmers tend to be overly optimistic about development and that we should really think through a the implications before promising a quick solution to a problem and then diving in to code</p>


答: That would be the lesson of humility.</p>

Body: That would be the lesson of humility.


答:
Keep studying every day. The knowledge of today is obsolete tomorrow.

Ironically this answer should be obsolete tomorrow too. But really, study hard one or two stuff and be certificated if it's possible, be the God of that things (maybe programming languages or system/network/database administration) and always keep an eye in other minor things, like other languages without importance to you.

I mean for example, be an awesome professional of Java and Oracle DB administration, but study a little of Python, PHP, C++, HTML5, Javascript, although no to a certification level. Study each web or language framework that exist. Study or try to have some (basic) experience with each database that exist, like SQL Server, MySQL, Cassandra, HBase, PostgreSQL, and the whole No-SQL world like MongoDB and CouchDB. Try to have some experience with linux administation and virtualization.

That's the biggest lesson that I learnt from my 16 years of experience. I was for almost 10 years a mono-language programmer, using Pascal in its era, and Visual Basic 6 at the beginning of the millenium, and a PHP developer since 9 years ago. But from then I learn that developers need to know at least a little of everything.


答:
"If your math is wrong, you're toast."

Learnt it the first time several years ago.
Learnt it again just two weeks ago.


答:
Software is never complete.

There is always some changes in requirements, improvements, bug fixes that you have to be prepared to handle. Thus, be flexible and accept the fact that "software is never complete" and always has room for improvements.


答:
Your software will live considerably longer than you think it will at the time that you write it.

I started my career in the 80's. I started on software that originated in the 70's and was still being used in the 90's (maybe longer, I don't know for certain of its fate). Some of my own open source code is half way through its second decade.


问:
Natural language detection for web application
I have my own thoughts how "ideal" multilingual web application or web site should behave. Can you think of better solution? What are the pros and cons of them? What are cons of the solution I am presenting bellow? Any comments?

My "ideal" solution:

application should read browser language (from Accept Language header)

user should be able to override his/her default language in options (logged-on users will see the web site in this language no matter of current browser settings; useful when one is travelling for example)

on top of this, when lang attribute is specified in URL (see example bellow), user will see the page in language specified by this attribute (both accept language and user settings would be overridden; this could be useful for book-marking, sharing, RSS feeds selection, web crawlers).

Example URL: http://www.example.com/index.html?lang=ex

答: One definite Pro from your approach is that it takes into account users traveling to international locations. I have recently moved to an Arabic speaking country and can't tell you how frustrated I get everyday with the numerous web applications that provide me with the Arabic version of the site, because they use my IP to find my location and present the site in that locations language.</p>


答:
Learning new languages is part of the job

I learned about four programming languages in school back in the 80's but have used one of them in a job. I've had four jobs where I didn't even know the language I was hired to use.

Overall, I've learned and used professionally perhaps a dozen languages in my career, including FORTRAN, c, c++, c#, java, perl, Tcl, ruby, groovy, awk,  python, sh, batch, DCL, javascript, and a few small DSLs. Doing a little math, I seem to average a new language every couple of years, though there's a lot of overlap.

If anything has been a constant in my career, it's change.


答:
EDIT  The following is probably what Doc Brown was already suggesting, except that I'm longwinded and make a lot of fuss about the set abstraction.

I'm not sure object oriented patterns are the right approach here. I think the main abstraction you need is simply a set.

Your primitive elements are "biceps", "triceps" etc. Your "universal" set is the complete set of those elements. "arms" and "torso front" are just sets - subsets of the universal set.

For your more complex criteria, you'd need a reasonable set of operations on sets - union, intersection, difference, counting elements etc. There are design patterns that you could use to specify functions based on those, but I would think "Abstract Syntax Tree" rather than "GOF pattern", and even that is probably overkill.

All you really need to define all your classification rules is a sequence (list, array, ... - maybe even a set) of records (or objects). The classification test itself can just be whatever representation of a function is most convenient in your language - maybe literally a function or lambda, maybe some kind of delegate. Accept the set of primitive muscles as a parameter and return true/false. That function is then just a field of each record.

You could define a short fat class hierarchy - a base class with a pure "test" method and a derived class for each classification test - but this seems like overkill to me. If you can include functions (or function pointers) in records, just include a field to hold the function. A more complex class hierarchy, attempting to define the muscle-set relationships within the class relationships, would just be OOP for it's own sake IMO - lot's of code to write for little or no benefit.

You might define a tree, but that would be a data structure rather than a class hierarchy, and even then only for optimization if you're dealing with a lot of muscles. If you're really dealing with a lot more than 14 muscles, you may even have some automatic tree-building logic. That would probably be based on a partial order (topological sort) based on comparing sets of combinations of primitive muscles, with is-subset-of as the ordering function. And that could be a fair bit of work...

The result wouldn't naturally form a tree - a small set may be a subset of many different larger sets - so there's definitely issues to work out. Either you make some arbitrary choices, or you build a DAG (Directed Acyclic Graph) rather than a tree.

The sets are of combinations, not muscles. Either you deal with a combinatorial explosion, or you need to deal with specifications of sets and classification tests in a more sophisticated way.

IOW, don't waste time on it unless you're sure you really need it.

Depending on how you use this precisely, the results may be a set too - a set of classifications that apply rather than a set of muscles. Each member of that would refer to one of your classification tests - depending on language and other issues, maybe by some kind of ID rather than by a pointer/reference to the record/object.

Title: Generating different combinations from a list of muscles

Body:
Suppose we have a model of a human muscular system containing the following muscles each within a specific muscle group:

Arms

Biceps

Triceps

Forearms

Torso Front

Abs

Chest

Shoulders

Torso Back

Trapezius

Lats

Rear Shoulders

Lower Back

Lower Body

Quads

Hams

Hip & Butt

Calves

Now, given a list of selected muscles, I need to find combinations following the given rules:

If all muscles are selected from a group:

```<code>Full body (All muscles)
Arms
Torso
Torso Front
Torso Back
Lower Body
</code>```

If there are full groups together:

```<code>Arms and torso
Arms and torso front
Arms and torso back
Arms and lower body
Torso and lower body
Torso front and lower body
Torso back and lower body
</code>```

When both the front and back of the torso is selected it can be considered just "torso".

If there are more than 2 muscles selected from a group but not all:

```<code>Parts of torso (This is the case where there are muscles selected from both front- and back-torso)
Parts of torso back
Parts of lower body
</code>```

"Parts of torso front" and "Parts of arms" never occur on their own as they only have a total of 3 muscles, thus those cases can be represented by their names: eg. "biceps and triceps", etc.

Combinations of these aforementioned "parts"

```<code>Parts of arms and torso
Parts of arms and lower body
Parts of torso and lower body
Parts of  arms, torso and lower body.
</code>```

Parts = groups are not full and there are more than 2 muscles selected. This "rule of 2" is the most important one.

Examples of output

biceps, triceps and chest: parts of arms and torso

biceps, triceps, calves, tai biceps, triceps, quads, hams, hip & butt: Parts of arms and lower body

biceps, abs, calves: Parts of arms, torso and lower body

biceps, triceps: Biceps and triceps

biceps, triceps, forearms: Arms

chest, shoulders, abs, trapezius, lats, rear shoulders, lower back: Torso

and so on, there are multiple possible variations.

Now my problem is that I have no idea how to write this as clean and modular as possible, so that rules can be added or removed if necessary.

I could just write a massive if-elseif-else pile that would consider all cases, but you know why I won't.

How would you tackle this kind of task?


问:
Are there any good, open-source change request systems?
I have a need to make a somewhat custom change request system (very high auditing requirements).

Instead of completely reinventing the wheel I was wondering if there's an open-source change request system, considered decent that I could write a custom module for?

I've done some searching but the ones I have found don't seem to encapsulate what a change request system should be (no way of recording test plans or work streams).

In my experience a change request system has (does) store test plans / technical specs and a log of work.

答:
Would a change request system differ greatly from an issue tracking system?

For a general web based feature tracking/issue tracking system I find mantis to be good.

The code is procedural, the UI is ugly, but it works and it's easy to modify.

http://www.mantisbt.org/


答:
I would say the best lesson I learnt is

"You should always go for the best approach possible and not your approach."


问:
not checking in from the project root
Whenever I do a check-in, I always check in from the root of the project... i.e. check in all the files in my working copy, so after the check-in the source control repo contains exactly the same set of files that I just finished testing in my local copy.  I also make sure my source control is set to flag local files that are not under source control.  In general, there are none of these files... if there are, I either add them to source control or mark them as "ignored".  I also check in all my changes together in one check-in.

A lot of colleagues check in much differently.  They carefully select each file to check in, as if they are a master jeweler selecting only the very best gemstones to set into the royal crown, and they check in each one as a separate check-in.  They rely only on their memory to figure out which files need to be checked in, or especially added to source control.

The results are quite predictable... frequent broken builds because they forget to add their new files to source control or forget to check in a changed file (especially changed project files).

I have mentioned this to them and they never seem to change.  When I mentioned it to the team lead he said, "this is just a different way of working".  To which I may respond: What if I want to drive my car with my eyes closed?  Is that just "a different way of driving"?

Am I right in being bothered by this practice?

答:
Yes, I think you are right.

At best (if they're always doing it correctly) what they're doing is just a slower way of doing what you're doing.

The bigger problem is that it's exposing less than ideal working practices. Firstly it looks like they're working on more than one thing at a time - so rather than working in small commitable steps they're doing some big change that's uncommitable and then have to do some other task in the middle and commit that. Or maybe they're not cleaning up after themselves and their uncommitted local changes have all sorts of junk in them (big blocks of commented out code, redundant methods, broken stuff that was just a temporary experiment).

I've worked with people who do this and it's always a nightmare - the worst situation is when they have uncommitted junk locally then when they update their local version gets borked, but some of the stuff they want to keep is in the same files as the junk. As a result they just get lost in sorting out stuff they want to keep from stuff they want to revert.

Title: not checking in from the project root


答:
Working well with others is very important.

"Show me your 'Go to guy' and I will show you your problem"

Slapdash Hero Coders - those who just crank out code with no regard for convention, readability or whatever anyone else is working on - can cause more harm than good.

Not saying that the people who can write tonnes of good quality code are bad thing. Just rare.


问:
Create code editor auto-suggest (like IntelliSense)
If one would to write auto-suggest for an IDE/code editor (like IntelliSense), does one generally need to write a parser for any language that should be supported, or do compilers/runtimes provide these things?

Neither the PHP or Python binaries seem to support just parsing files and generating some kind of raw output.

Eclipse seems to roll their own parser, but is this the only way to do it? Using the "native" parser would be awesome on so many levels :)

答:
PHP has token_get_all to parse a file and generate the list of tokens you can use to work with code, like doing static analysis, checking the style or implementing an auto-complete feature.

Python has Abstract Syntax Trees (AST), which seems even more helpful, and has also some neat features like the compile function which compiles the tree itself.

In general, it's a very bad idea to implement your own parser (aside from learning). It's hugely difficult and error prone and will become invalid as soon as the language specification changes. Such changes are unusual with well-designed languages like C#, but are not so unusual in languages like PHP which have lots of flaws and missing features (example: the recent implementation of namespaces in PHP). Also, by reinventing your own parser, you're reinventing the wheel already invented for a compiler: instead of doing exclusively your work (the auto-complete feature), you spend time writing lots of code related to parsing, the code you have to test and maintain later.

Some hints

You may be interested in a term of "compiler as a service". For example, Microsoft is working on a compiler as a service for C#, which will let you to extract programmatically the information from the compiler; such scenario might be helpful for an auto-complete feature.

You may also search for static checkers for the language of your interest. Many are open source, so looking at how they process the code source may give you some suggestions about the parsing.

Finally, some compilers are themselves open sourced. Depending on the license they use and the one you will use for your auto-complete-enabled product, you may be unable to reuse the code, but still it can give some hints too.


答:
It feels good to write top-notch, cutting-edge, clean code.

Even if I am asked to do some quick fix-workaround that would ruin the code base, I rather do it the good way.


答:
I have learned that best design principle is KISS (Keep it simple, Stupid!).

I have learned that keeping your code simple and clean should be the primary concern, and each team member should understand what you have code. The KISS principle states that most systems work best if they are kept simple rather than made complex, therefore simplicity should be a key goal in design and unnecessary complexity should be avoided.


问:
Unit test coding standards
Usually when talking about coding standards we refer to the code of the program itself, but what about the unit tests? Are there certain coding standards guidelines that are unique to unit tests? What are they? </p>

答:
Don't put logic in your unit tests. For example, let's say you're testing an add method, you could have something like this:

```<code>void MyTest_SaysHello()
{
   string name = "Bob";
   string expected = string.Format("Hello, {0}", name);
   IMyObjectType myObject = new MyObjectType();
   string actual = myObject.SayHello(name);
   Assert.AreEqual(expected, actual);
}
</code>```

In this particular case, you're likely repeating the same logic as what's in the test, so you're essentially testing "1 + 1 == 1 + 1", rather than "1 + 1 == 2", which is the "real" test. So what you would really want your test code to look like is:

```<code>void MyTest_SaysHello()
{
   string expected = "Hello, Bob";
   IMyObjectType myObject = new MyObjectType();
   string actual = myObject.SayHello("Bob");
   Assert.AreEqual(expected, actual);
}
</code>```

Title: Unit test coding standards

Body:
Don't put logic in your unit tests. For example, let's say you're testing an add method, you could have something like this:

void MyTest_SaysHello()
{
   string name = "Bob";
   string expected = string.Format("Hello, {0}", name);
   IMyObjectType myObject = new MyObjectType();
   string actual = myObject.SayHello(name);
   Assert.AreEqual(expected, actual);
}

In this particular case, you're likely repeating the same logic as what's in the test, so you're essentially testing "1 + 1 == 1 + 1", rather than "1 + 1 == 2", which is the "real" test. So what you would really want your test code to look like is:

void MyTest_SaysHello()
{
   string expected = "Hello, Bob";
   IMyObjectType myObject = new MyObjectType();
   string actual = myObject.SayHello("Bob");
   Assert.AreEqual(expected, actual);
}


答:
If it ain't broken, don't fix it !

Trying to extend and improve stuff that already works may give you a big headache


答:
There is no try

Lets say you have a task or bunch of tasks that are estimated to take 4 days. Then your boss or project manager asks if you could try to get it done in two days for some important reason. Wanting to be a good, flexible employee, you might be tempted to say: sure, you can try. Most likely outcomes from this is that you either miss the deadline, or you're going to do half-assed hack to get it done. And it's not your boss's fault for asking you to do it, that's his job. It's your fault for not saying no, which is your job.

You can't bargain with time. You can bargain with scope. Be professional and don't sell yourself short.


答:
Don't use fancy OOP features just because you can! -  YAGNI (You ain't gonna need it)

Use fancy OOP features because they have specific, demonstrable benefit to the problem you're trying to solve. You laugh, but i see this all the time. Most programmers never met an object they didn't like. I think it should be the other way around: these techniques are guilty until proven innocent in the court of KISS.


答:
Writing code is easy. Reading code is difficult. Even if the code is yours. So, whenever possible, go for readable approach.

You aren't smarter than others. Don't ever think you're approach is the best just because its yours.

Pay attention to WHAT is said, not BY WHOM it is said. Brilliant ideas might come for the most unexpected sources.

Don't be lazy. Take your time to write nice code. You'll have to fix it anyway at a higher cost.


答: "That will never happen" actually means "That will never happen until the first day in production"</p>


问:
Web services and business rules engines
We have a web service that takes in input different types of messages. The function of the webservice is to merely write in a database the content of the messages. There is about one table (with foreign keys to others) for every kind of message.

We have been asked to transform the webservice in a configurable product by using a business rules engine. To have full configurability, a collegue suggested that the best way could be transform the webservice from one that accepts many types of messages to one that accepts one type of message, but in the content of the message there is a field that indicates the type of the content. This way, there would be just one table for the messages (plus other tables for static informations), and  it would be more configurable using business rules engines.

What is the best way to tackle such situation?

Update: for the business rules engines we are very likely going to use an implementation of the Rete Algorithm, like Drools

答:
Your may problem try to code in terms of decision tree or decision table

Also, there is posts into Chris Smith's blog about decision trees:

Awesome F# - Decision Trees – Part I and
Awesome F# - Decision Trees – Part II

Title: Web services and business rules engines


问:
Studies on how well can a programmer understand code in unfamiliar languages?
Are there any serious studies on how well an experienced programmer who knows language X can understand code written by a competent programmer using language Y, for a good range of widely used languages as X and Y?

Of course the real world isn't so simple as a programmers knows just one language.  What we'd like to know is: if we do our project in, say, C#, and someday some old physicists who know only Fortran and Algol look at it, to what extent would it make sense to them?  Mathematical parts of it might read fine to them, if they ignore what to them are some random-ish punctuation marks.  Or, would a Python expert be able to find flaws in my clever Ruby script?

There could be issues from the level of superficial syntax to the level of grand concepts such as objects, template metaprogramming, functional and so on.  I'm not expecting the one programmer to fully understand every syntax detail of code in a "foreign language" or to follow the religion of some grand concept, but wondering to what extent they'd get the main flow of control, find the spot where something is drawn on the screen and what determines its color or size, verify that a robot programmed to drive a car will turn off the engine when it's done, those sorts of things.

A good quality study would include published academic research, an official report from some industry group or major software company, though I'll take systematic unbiased observations by experienced leaders of workshops and classes or other sources.  Not interested in short blogs, single-case examples, or anecdotes.  (Well, maybe a few anecdotes if they make for a good read.)

答:
Not sure about an academic conducted study reference, however well self-explanatory naming of methods, classes and functions in C#/C++/Java/Python or etc. languages should provide ease to understand the code base as well as business process flow.

Naming convention within the project and generally in software development is a very important aspect. However, its importance and  relevance to building quality software is often overlooked or ignored all together.

 Naming Guidelines used in .NET Framework and  General Naming Conventions used in .NET are good references to look as well.


答:
It obviously depends on the degree how related the languages are to each other. For example, if you have a C or C++ background and have either done some C# or Java programming, it should be easy for you to read and understand the other of the that two languages (Java or C#). If you know Lisp well, Scheme should not be much of a problem. I once debugged a PHP program without having any knowledge about PHP, just with my knowledge from C, C++ and Perl. I am pretty sure when that program would have been written in Haskell or Smalltalk, that would have been immense harder next to impossible for me.

In fact, I don't think an academic research on this topic would make any sense (at least, not a serious one). There is no such thing like a "standard experienced programmer who knows language X", so any study would miss assured basis data. People have  different knowledge, and even if they have run through the same schools, they are differently talented and motivated.

but wondering to what extent they'd get the main flow of control, find the spot where
  something is drawn on the screen

That may be hard even when you are very familiar with the language, either because the code quality is so low, or the used framework is so complex, or the code base is very big.

Title: Studies on how well can a programmer understand code in unfamiliar languages?

Body:
Are there any serious studies on how well an experienced programmer who knows language X can understand code written by a competent programmer using language Y, for a good range of widely used languages as X and Y?

Of course the real world isn't so simple as a programmers knows just one language.  What we'd like to know is: if we do our project in, say, C#, and someday some old physicists who know only Fortran and Algol look at it, to what extent would it make sense to them?  Mathematical parts of it might read fine to them, if they ignore what to them are some random-ish punctuation marks.  Or, would a Python expert be able to find flaws in my clever Ruby script?

There could be issues from the level of superficial syntax to the level of grand concepts such as objects, template metaprogramming, functional and so on.  I'm not expecting the one programmer to fully understand every syntax detail of code in a "foreign language" or to follow the religion of some grand concept, but wondering to what extent they'd get the main flow of control, find the spot where something is drawn on the screen and what determines its color or size, verify that a robot programmed to drive a car will turn off the engine when it's done, those sorts of things.

A good quality study would include published academic research, an official report from some industry group or major software company, though I'll take systematic unbiased observations by experienced leaders of workshops and classes or other sources.  Not interested in short blogs, single-case examples, or anecdotes.  (Well, maybe a few anecdotes if they make for a good read.)


问:
Should we ever delete data in a database?
I am new to databases and trying to understand the basic concepts. I have learned how to delete data in a database.  But one of my friends told me that you should never delete data in a database.  Rather, when its no longer needed, it's better to simply mark it or flag it as 'not in use'.

Is that true? If so, how would a big company like IBM handle their data for a hundred or more years?

答:
Lots of good answers here already. I just want to add one situation that no one has mentioned yet:

Sensitive data. If the user deletes it, then you better actually delete it!

One very common situation that comes to mind is change/reset password. You wouldn't want to store old passwords (even though they're hashed, salted etc) in your database. Users might be using their old (and bad) passwords on other sites.

Also, when it comes to laws regarding how long you are allowed to store certain types of data then of course soft deletes wont do. You have to actually delete it.

So I would ask myself: will the user (or someone else, the government for example) be mad if I make them believe the data has been deleted, but in fact I've still got it and can restore it at any time?


答:
Is it something related to Bug Tracking System?

If you are looking for something like that with some extensions, i would advice to look at the followings - Top 10 Open Source Bug Tracking System.

There is also an alternative Change Request Management tool from SourceForge.net that you may extend as required - Change Request Management

Title: Are there any good, open-source change request systems?

Body:
I have a need to make a somewhat custom change request system (very high auditing requirements).

Instead of completely reinventing the wheel I was wondering if there's an open-source change request system, considered decent that I could write a custom module for?

I've done some searching but the ones I have found don't seem to encapsulate what a change request system should be (no way of recording test plans or work streams).

In my experience a change request system has (does) store test plans / technical specs and a log of work.


答:
We use jira (10 users for 10 bucks) and it is great. We track almost everything in it. Bugs/ Tasks/ Feature requests.

Okay... it's not open source but these guys build like crazy and it just works out of the box.

We tried a lot of open source apps... but non really worked like we would like it to work.

Just give it a try... it's just 10 bucks :-)

http://www.atlassian.com/company/customers/?tab=jira


答: This article is a summary of a set of blog posts trying to compare speed of c++ vs c# and the issues you have to overcome in both languages to get high performance code.  The summary is 'your library matter way more than anything, but if you are in c++ you can overcome that.' or 'modern languages have better libraries and are thus get faster results with lower effort' depending on your philosophical slant.</p>


问:
What non-programming books should a programmer read to help develop programming/thinking skills?
There are a lot of questions about what programming books should be on the programmer's bookshelf. How about non-programming related books that can help you become a better programmer or developer? It would also be interesting to know why they would help.

My first choice would be Sun Tzu's "Art of War" (however cliché), because it made it obvious that the success of any project depends on the strength of its weakest link (and warfare is a big project).

答:
The 7 Habits of Highly Effective People
Stephen Covey


答: Your approach looks pretty good. I'd add only one more thing: say that the browser language (from the accept language header) is X, but when you try to determine the user's actual location (via IP or geolocation API), you get some place that uses language Y. In that case, I'd probably default to the browser language X (just as you were initially planning) but find a place in the UI to ask the user if they'd rather switch to language Y. If they say no, remember this (via cookie, session, or store with their account) and don't ask again. This same approach also works well if you add support for new languages that weren't supported before.

Title: Natural language detection for web application

Body:
I have my own thoughts how "ideal" multilingual web application or web site should behave. Can you think of better solution? What are the pros and cons of them? What are cons of the solution I am presenting bellow? Any comments?

My "ideal" solution:

application should read browser language (from Accept Language header)

user should be able to override his/her default language in options (logged-on users will see the web site in this language no matter of current browser settings; useful when one is travelling for example)

on top of this, when lang attribute is specified in URL (see example bellow), user will see the page in language specified by this attribute (both accept language and user settings would be overridden; this could be useful for book-marking, sharing, RSS feeds selection, web crawlers).

Example URL: http://www.example.com/index.html?lang=ex


问:
What's wrong with relative imports in Python?
I recently upgraded versions of pylint, a popular Python style-checker.

It has gone ballistic throughout my code, pointing out places where I import modules in the same package, without specifying the full package path.

The new error message is W0403.

W0403:    Relative import %r, should be %r

Used when an import relative to the package directory is detected.

Example

For example, if my packages are structured like this:

```<code>/cake
  /__init__.py
  /icing.py
  /sponge.py
/drink
</code>```

and in the sponge package I write:

```<code>import icing
</code>```

instead of

```<code>import cake.icing
</code>```

I will get this error.

While I understand that not all Pylint messages are of equal importance, and I am not afraid to dismiss them, I don't understand why such a practice is considered a poor idea.

I was hoping someone could explain the pitfalls, so I could improve my coding style rather than (as I currently plan to do) turning off this apparently spurious warning.

答:
The problem of import icing is that you don't know whether it's an absolute import or a relative import. icing could be a module in python's path, or a package in the current module. This is quite annoying when a local package has the same name  as a python standard library package.

You can do from __future__ import absolute_import which turns off implicit relative imports altogether. It is described, including with this justification about ambiguity, in PEP 328. I believe Python 3 has implicit relative imports turned off completely.

You still can do relative imports, but you have to do them explicitly, like this:

```<code>from . import icing
</code>```

Body:
The problem of import icing is that you don't know whether it's an absolute import or a relative import. icing could be a module in python's path, or a package in the current module. This is quite annoying when a local package has the same name  as a python standard library package.

You can do from __future__ import absolute_import which turns off implicit relative imports altogether. It is described, including with this justification about ambiguity, in PEP 328. I believe Python 3 has implicit relative imports turned off completely.

You still can do relative imports, but you have to do them explicitly, like this:

from . import icing


答:
There are a few good reasons:

Relative imports break easily, when you move a module around.

Imagine you have a foo.bar, a foo.baz and a baz module in your package. foo.bar imports foo.baz, but using a relative import.

Now, if you were to move foo.bar to bar, your module suddenly is importing a different baz!

Relative imports are ambiguous. Even without moving around the bar module in the above example, a new developer coming to your project could be forgiven for not realizing that baz is really foo.baz instead of the root-level baz package.

Absolute imports make it explicit what module is being used. And as import this preaches, explicit is better than implicit.

Python 3 has disabled implicit relative imports altogether; imports are now always interpreted as absolute, meaning that in the above example import baz will always import the top-level module. You will have to use the explicit import syntax instead (from . import baz).

Porting the example from Python 2 to 3 would thus lead to unexpected problems, using absolute imports now will make your code future-proof.

Title: What's wrong with relative imports in Python?

Body:
I recently upgraded versions of pylint, a popular Python style-checker.

It has gone ballistic throughout my code, pointing out places where I import modules in the same package, without specifying the full package path.

The new error message is W0403.

W0403:    Relative import %r, should be %r

Used when an import relative to the package directory is detected.

Example

For example, if my packages are structured like this:

```<code>/cake
  /__init__.py
  /icing.py
  /sponge.py
/drink
</code>```

and in the sponge package I write:

```<code>import icing
</code>```

instead of

```<code>import cake.icing
</code>```

I will get this error.

While I understand that not all Pylint messages are of equal importance, and I am not afraid to dismiss them, I don't understand why such a practice is considered a poor idea.

I was hoping someone could explain the pitfalls, so I could improve my coding style rather than (as I currently plan to do) turning off this apparently spurious warning.


问:
How have languages influenced CPU design?
We are often told that the hardware doesn't care what language a program is written in as it only sees the compiled binary code, however this is not the whole truth. For example, consider the humble Z80; its extensions to the 8080 instruction set include instructions like CPIR which is useful for scanning C-style (NULL-terminated) strings, e.g. to perform strlen(). The designers must have identified that running C programs (as opposed to Pascal, where the length of a string is in the header) was something that their design was likely to be used for. Another classic example is the Lisp Machine.

What other examples are there? E.g. instructions, number and type of registers, addressing modes, that make a particular processor favour the conventions of a particular language? I am particularly interested in revisions of the same family.

答: One thing nobody seems to have mentioned so far is that advances in compiler optimization (where the base language is largely irrelevant) drove the shift from CISC instruction sets (which were largely designed to be coded by humans) to RISC instruction sets (which were largely designed to be coded by compilers.)</p>


问:
How to handle security of temporary data on web server?
I'm primarily an ASP.NET developer but this question really applies regardless of language.  So obviously it is a good idea to prevent external attacks that arise from session hijacking and csrf attacks as well.  But what about internal attacks when the data involved is temporary, needed for the entire session but also sensitive and worth stealing?  There is the naturally just only hire trustworthy people route, but lets say that doesn't apply.

Say it is a given you already have code reviews and strict production data access permissions to prevent theft by developers.  The application encrypts sensitive data before storing to prevent theft by dbas.

How do you protect your temporary sensitive data against web server admins?  It seems that they could retrieve information by inspecting web server logs, traffic sniffing and inspection of process memory contents.  Naturally I would say production web server admins do not have access to the raw source code.

答: In my experience once a web application goes live then the web admins are responsible for it. Data should not be hidden from sys admins just in case emergency action needs to be undertaken to rectify a bug. At best you can obfusicate and encrypt data but that does not gurantee security. The only secure web server is one that is disconected from the internet and locked away in a safe.</p>


问:
How to prevent intentional over-estimation in user stories?
I am asking this from a purely hypothetical standpoint.

According to the Sprint Planning Meeting section in the Scrum Guide:  "The number of items selected from the Product Backlog for the Sprint is solely up to the Development Team. Only the Development Team can assess what it can accomplish over the upcoming Sprint."

Questions:

What is there to stop the development team from over-estimating intentionally the time it takes to complete user stories?

If there is a long-term contact with the product owner and development team, should this be defined in the contract as some sort of violation or breach of contract?

Who would be responsible for discovering such a violation?

How could the product owner prove that such a violation was taking place?

Thank you for reading.

答:
The key point of Velocity and user story estimation is to serve as relative measurement of what can developers finish during sprint. Velocity should not be used to compare to other teams. So, if the developers will over-estimate the user stories, the velocity will go up and they will be forced to either do more work next sprint or over-estimate again.

This is what agile developers should be aware of. If you have developers that consciously go against this system, then you have people that consciously go against agile development, and those people should be handled appropriately.

Also, the product owner IS part of the development team. He is not someone from outside. He is part of the team and should be present during all important team meetings.


问:
How can we make software development best practices more interesting to people without a software background?
Where I work there are a few experienced software developers with a software background, but the majority of developers are physicists or chemists with excellent domain knowledge but limited experience when it comes to developing high quality, maintainable software.  To address this we have started running regular talks and workshops.

What topics do you think we should discuss to help make these people more effective software developers?

In particular we are struggling to gain enthusiasm for these talks as many developers do not see software as an interesting subject.  How could we make these more interesting to people without a software background?

Thanks

答:
I think it's going to be hard, so be prepared for a struggle - but not impossible. At the end of the day programming (especially non-cowboy-hack'n'slash coding) is not going to be super-exciting to everyone. This is especially true for people already working in an area which is intellectually challenging and rewarding in its own right.

First of all make the talks and workshops fun in themselves - free food (make sure it's nice food!) and similar treats are a good place to start. Try to inject a bit of humour too and, at least initially, keep them fairly brief and as informal as you can.

Secondly make sure the talks and workshops are relevant. Try not to make them too abstract (even if the concepts being covered are abstract) and if you possibly can at all, ensure that they can try out what's been covered. Even better check on what they've done between sessions and provide positive feedback. If they're not relevant and they're not applying what you've discussed then they will (correctly) view them as a waste of time.

Finally try to introduce some basic coding standards, preferably ones which are not too intrusive in how they currently operate. If you're in the .net world Resharper is a good one to begin with as it will warn about things like naming conventions. You can take that further with StyleCop (which can be integrated into Resharper) - but make sure you customise the ruleset first. If you're not in .net then I'm sure similar tools will exist elsewhere. It's not much, but it's a start.

Don't expect instant results (except for maybe any automatically enforced coding standards) - I've heard 6, 9 and 12 months bandied around for the time to introduce best practices.

I've only flicked through it so far, but there seems to be a fair bit of good, relevant, advice for you in the forthcoming book Driving Technical Change.


问:
What does it mean by expected running time and average running time of an algorithm?
Let's say we want to analyze running time of algorithms. Sometimes we say that we want to find the running time of an algorithm when the input size is n and for the worst possible case it is denote it by O(n). Sometimes though I see books/papers saying that we need to find the expected time of an algorithm. Also sometimes the average running time is used .

What is "expected time"? In which cases is it useful to find expected time instead of worst case time?

Edit: I think there is a subtle difference between expected running time and average running time but I am not sure . Through this post I want to know the exact difference if any .

答:
Expected time is just the average, expected, running time of the algorithm using the intended input.

Say you've got some few million user records and want to sort them, you might want to use an algorithm which is the most suitable for your input, and as such gives the best expected running time, as opposed to an algorithm which has better worst-case running time but worse expected running time.

Sometimes for example the constant factors for the time-complexity of an algorithm are so high that it makes sense to use algorithms with worse time-complexity but smaller constant factors, as it gives you better expected running time with small input, even though it would get horribly outperformed with bigger input.

Perhaps a better example would be the classic quicksort algorithm, which has worst-case running time of O(n²) but expected average running time of O(n log n), regardless of input. This is because the algorithm uses(or rather, may use, depending on the implementation) randomization. So it's a so-called randomized algorithm. It runs a bit differently with every invocation even with the same input. As such, thre's no universal worst-case input for the implementation, because the worst-case input depends on the way the algorithm chooses the pivot for dividing the given input. And as such, one can't just supply some pre-defined input causing the worst-case running time. This is often the case with randomized algorithms, which aim for better expected, average running time regardless of the input.

It's all about using the right algorithm for the input at hand.


答:
The 68000 had MOVEM which was most suited to pushing multiple registers onto the stack in a single instruction which is what many languages expected.

If you saw MOVEM (MOVE Multiple) preceding JSR (Jump SubRoutine) throughout the code then you generally knew that you were dealing with C complied code.

MOVEM allowed for auto increment of the destination register allowing each use to continue stacking on the destination, or removing from the stack in the case of auto decrement.

http://68k.hax.com/MOVEM

Title: How have languages influenced CPU design?

Body:
We are often told that the hardware doesn't care what language a program is written in as it only sees the compiled binary code, however this is not the whole truth. For example, consider the humble Z80; its extensions to the 8080 instruction set include instructions like CPIR which is useful for scanning C-style (NULL-terminated) strings, e.g. to perform strlen(). The designers must have identified that running C programs (as opposed to Pascal, where the length of a string is in the header) was something that their design was likely to be used for. Another classic example is the Lisp Machine.

What other examples are there? E.g. instructions, number and type of registers, addressing modes, that make a particular processor favour the conventions of a particular language? I am particularly interested in revisions of the same family.


答:
In the majority of cases you should keep data just in case it is needed in the future. The business you work for may want to look at the historical data to base their decisions on which will steer the comapany in a certain direction.

You should add 'Date_Time_Removed' columns to each table and then instead of physically deleting the row(s) you set a date and time that the row has been virtually deleted. Then in your stored procedures or sql you would factor in the 'Date_Time_Removed' column e.g.
select blah
from table1
where date_time_removed is null

Of course rows that have been accidently added to a database should be removed permanently, especially test data.

By keeping all legit data you also have to option of using your database for warehousing in the future.

Title: Should we ever delete data in a database?

Body:
I am new to databases and trying to understand the basic concepts. I have learned how to delete data in a database.  But one of my friends told me that you should never delete data in a database.  Rather, when its no longer needed, it's better to simply mark it or flag it as 'not in use'.

Is that true? If so, how would a big company like IBM handle their data for a hundred or more years?


问:
Is there any reason to use varchar over text columns in a database?
Is varchar just a remnant from before text came around, or are there use cases where you would want to use a varchar?  (Or char for that matter..)

(I use Postgres and MySQL (MyISAM) daily, so those are what I'm most interested in, but answers for other databases are of course welcome.  ^_-)

答:
In General

text columns are non standard and implementation specific. In many cases, depending on the database they may have a combination of one or more of the following restrictions: not indexable, not searchable and not sortable.

In Postgres

All these types are internally saved using the same C data structure..

In MySQL

The text column is a specialized version of BLOB and has restrictions on indexing.

Just these two examples can be extrapolated to the other SQL RDBMS systems and should be reason enough to understand when to choose one type over the other.

Just to make it implicitly clear, you should never use TEXT as it is proprietary and non-standard. Any SQL you write against it will not be portable and will guaranteed to cause you problems in the future. Only use types that are part of the ANSI Standard.

Use CHAR when you know you have a fixed number of characters for every entry.

Use VARCHAR when you have a variable number of characters for every entry.

If you need more storage than VARCHAR can provide, CLOB with UTF-8 encoding or equivalent standard type.

NEVER use TEXT as it is non-standard.


答:
If these chemists and physicists are not primarily profesional developers, and are not intended to become so, I would suggest thinking differently at the problem.

The "real" developers should provide easy environments for them to develop into.  You should provide mentoring and you should provide peer review of their code with strong incentives to make the code good enough for passing in the first place.

In other words, do not treat them as equals, but provide all you can for them to excel on what they actually do that is their strength.

Title: How can we make software development best practices more interesting to people without a software background?

Body:
Where I work there are a few experienced software developers with a software background, but the majority of developers are physicists or chemists with excellent domain knowledge but limited experience when it comes to developing high quality, maintainable software.  To address this we have started running regular talks and workshops.

What topics do you think we should discuss to help make these people more effective software developers?

In particular we are struggling to gain enthusiasm for these talks as many developers do not see software as an interesting subject.  How could we make these more interesting to people without a software background?

Thanks


问:
eXtreme Programming (XP) Methodology Testing
I am about to undertake a project for university, and given the project scope I have decided to use XP/agile methodology. I have began with developing a use case diagram; gathering user stories for the first couple features.

I am in the process of helping the customer develop the acceptance test and my question is: can the user stories for each feature be used as a user acceptance test?

答:
You shouldn´t.

Acceptance tests are black box system tests. Each acceptance test represents some expected result from the system after a certain input.

For example, a valid user story for a calculator is:

"As a user, I want to sum two numbers"

An its acceptance tests:

0+0 = 0

1+1 = 2

876+154 = 1030


问:
How much help should I give during technical interviews?
I'm asked to perform or sit in during many technical interviews. We ask logic questions and simple programming problems that the interviewee is expected to be able to solve on paper. (I would rather they have access to a keyboard, but that is a problem for another time.) Sometimes I sense that people do know how to approach a problem, but they are hung up by nervousness or some second-guessing of the question (they aren't intended to be trick questions).

I've never heard my boss give any help or hints. He just thanks the interviewee for the response (no matter how good or bad it is) and moves on to the next question or problem. But I know something about the rabbit hole that defeat and nerves can lead you down, and how it disables your mind, and I can't help wondering if providing a little help now and then would ultimately help us end up with more capable programmers instead of more failed interviews.

Should I provide hints and assistance for befuddled interviewees (and if so, how far should I go while still being fair to the more prepared candidates)?

答: Part of what you want in an employee is someone who can interact with the rest of the team.  You need someone with required skill, true.  But you also need someone who knows when they need to reach out for help and has he self-knowledge and social skill to do that.  This latter sill set will set will build up the company better in the long run than any particular computer-language Du-jour.</p>


答:
No it is better to separate the two concepts :

Acceptance Tests define exactly what the system has to do before the customer will consider it "Done".They don't just include functional requirements; they also test the non-functional stuff like performance, security, and useability.  If functionally is not covered by the Acceptance Tests, it's not required by the customer.No story or feature can be said to be done until the suite of acceptance tests that define it are passing.

User stories are short, simple description of a feature told from the perspective of the person who desires the new capability, usually a user or customer of the system. They typically follow a simple template:

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

Below a couple of links for further readings :

http://www.mountaingoatsoftware.com/topics/user-stories

http://www.exforsys.com/tutorials/testing/what-is-user-acceptance-testing.html

Title: eXtreme Programming (XP) Methodology Testing

Body:
I am about to undertake a project for university, and given the project scope I have decided to use XP/agile methodology. I have began with developing a use case diagram; gathering user stories for the first couple features.

I am in the process of helping the customer develop the acceptance test and my question is: can the user stories for each feature be used as a user acceptance test?

Body:
No it is better to separate the two concepts :

Acceptance Tests define exactly what the system has to do before the customer will consider it "Done".They don't just include functional requirements; they also test the non-functional stuff like performance, security, and useability.  If functionally is not covered by the Acceptance Tests, it's not required by the customer.No story or feature can be said to be done until the suite of acceptance tests that define it are passing.

User stories are short, simple description of a feature told from the perspective of the person who desires the new capability, usually a user or customer of the system. They typically follow a simple template:

   As a <type of user>, I want <some goal> so that <some reason>.

Below a couple of links for further readings :

http://www.mountaingoatsoftware.com/topics/user-stories

http://www.exforsys.com/tutorials/testing/what-is-user-acceptance-testing.html


答:
The User Story itself cannot because it really answers the "why" question in understanding the value.

However, for each User Story you can create scenarios, and automate these scenarios to be your acceptance tests. Take a look at Behavior Driven Development (BDD).


答:
What role do they have in the company? If you need developers, then let them go if they aren't good developers and aren't interested in becoming good developers. If they are supposed to be physicists and chemists, you can run workshops, but don't expect them to maintain a high level of interest. If they're supposed to be both, raise expectations and make sure you're paying them enough to justify them taking on a software developer's role while maintaining complex domain knowledge and skills.

Unless part of someone's defined role is to be a developer, they will probably never be all that interested in developing high quality software. Just because someone is creating quick scripts and hacks doesn't necessarily mean they really want to be a software developer, it's just a means to an end, like an accountant figuring out complex Excel formulas. If you need high quality, maintainable software, then software developers should be creating it.