问:
how to expose certain tables of an internal database on a public site
I have an internal database at my work. At the moment we are using excel to import data, but this is very error prone, so I would like to replace this with some javascript based application which exposes some of the data in lookup tables in dropdown menus, for our customers to fill in, on a public website.

So my internal database lives on an internal server not viewable by the public.

How should I go about building an application that communicates with the internal database, and only exposes certain tables?

Is some middleware like Django, that rather than using an SQL database uses some other way of getting the lookup values (I have a REST interface set up on the main database).

(To clarify, I am looking for a server side technology that I can put on a public facing server, that will communicate with the internal server).

答:
Since you already have a REST interface setup to access your data, I would consider using Javascript, jQuery, and Backbone to create a browser client to interact with the data.  Backbone very much embrases REST, so you should find it pretty straight-forward to use.  If you take an approach similar to this, you will need to make sure that your REST I/F is accessible to your customers.  If your REST I/F is part of your DB, I'd be pretty nervous about exposing that directly to the "world".  If your REST I/F is a different middle-ware, that can probably be exposed while still remaining secure.  When you explore Backbone, you might also look at backbone-relational, which provides a nice way to relate different models together (if you have a complex set of tables/data).  You might also consider using Marionette with Backbone, which provides some nice helpers and organization to the out-of-the-box Backbone setup (by default, Backbone let's you make a bunch of decisions, which means writing more code - Marionette makes a bunch of those decisions for you, which means less code to write).

An alternative approach would be to use a more standard non-AJAX-ish, non-REST-ish ... more traditional "web app" approach: You could use Rails or Java or PHP, etc., and their many frameworks to build a web app that provides access to the data.  Depending on how you approach this, you would write code for that App Server that creates the HTML served to the browser, and likely have little Javascript (though that's still an option), but much more code on the server side.

These are trade-offs you have to decide between based on your experience and the details of the project.  Also, note that Backbone and Marionette are much newer technologies, so you may find less documentation and helpful websites, but you may also find more people excited to work on that project since they get exposed to those technologies. Since you already have a REST API, I'd probably lean toward the Backbone type approach.  Obviously, all of this is just my opinion based on my experiences working with these technologies.  There are certainly other approaches and technologies that you could consider also.


问:
Is there any difference between interfaces and abstract classes that have abstract methods only?
Let's say we have an abstract class and let this class has only abstract methods. Is this abstract class different from an interface that has same methods only?

What I am looking to know is if there are any differences both philosophically, objectively and in the underlying programming language implementation between an Abstract Class with only abstract members and an equivalent Interface?

答: Yes, they are different.  Otherwise the language designers wouldn't have provided both.  I know of two languages that separate classes and interfaces: Java and C#, mutant clone of Java.  The designers created interfaces to avoid supporting multiple class inheritance.  Most other languages support multiple class inheritance and consequently don't separate classes and interfaces.</p>

ContentLicense: CC BY-SA 3.0


问:
JavaScript static methods retrieval
I have been thinking about it and wanted some feedback, recently I thought about doing it like this:

```<code>function foo(){
   if ( !foo.prototype.statics ){
       foo.prototype.statics = {
          // declare static functions/vars here
       }
   }
   if ( !(this instanceof foo) ){
        return foo.prototype.statics;
   }

   var statics = foo.prototype.statics; // shortcut
   // if it reaches here then it's an instance (new foo())
}

foo().callStaticMethod();
(new Foo()).callInstanceMethod();
</code>```

Is this a good way to do it or do you think of any reason why this can be an anti-patern?

答:
Those aren't static methods they are on the prototype.  Instances of foo would be able to call static methods by just doing this.statics.method.  True statics would be applied to just foo itself. It is also cleaner than putting logic in the constructor to handle statics.

```<code>function foo() {

}

foo.statics = {

}

console.log(new foo().statics)
//undefined
console.log(foo.statics)
// {}
</code>```

The framework that we write in allows statics this way, it is a nice way to keep enums and constants.  It also gets around problems that happen when instance sharing is not needed and non primatives are placed on prototype, which for some reason happens all of the time on SO. Problems arise during inheritance though since static methods defined this way won't be inherited.  The inheritance problem mostly arises after due to parent classes having methods that do this.class.statics.staticFn if the class is inherited from those methods won't work but that can easily be fixed.

update

Having to invoke a function to get at the statics and having logic in the constructor to have it handle and know about it having statics is bad in my opinion.  The user has to know that the statics need to be accesses by invoking a function and the constructor needs to know that it has statics and to handle the case where the new operator is not used.

Problems can arise when instances don't know that they are modifying statics.  In this case lets replace the name statics with config.

```<code>function foo(){
   if ( !foo.prototype.config ){
       foo.prototype.config = {
           a: 1,
           b: 2
       }
   }
   if ( !(this instanceof foo) ){
        return foo.prototype.config;
   }
}

foo.prototype.foobar = function() {
  this.config.a = 5;
}

foo()
>Object {a: 1, b: 2}
new foo().foobar();
foo();
> Object {a: 5, b:2}
</code>```

Title: JavaScript static methods retrieval

Body:
Those aren't static methods they are on the prototype.  Instances of foo would be able to call static methods by just doing this.statics.method.  True statics would be applied to just foo itself. It is also cleaner than putting logic in the constructor to handle statics.

function foo() {

}

foo.statics = {

}

console.log(new foo().statics)
//undefined
console.log(foo.statics)
// {}

The framework that we write in allows statics this way, it is a nice way to keep enums and constants.  It also gets around problems that happen when instance sharing is not needed and non primatives are placed on prototype, which for some reason happens all of the time on SO. Problems arise during inheritance though since static methods defined this way won't be inherited.  The inheritance problem mostly arises after due to parent classes having methods that do this.class.statics.staticFn if the class is inherited from those methods won't work but that can easily be fixed.

update

Having to invoke a function to get at the statics and having logic in the constructor to have it handle and know about it having statics is bad in my opinion.  The user has to know that the statics need to be accesses by invoking a function and the constructor needs to know that it has statics and to handle the case where the new operator is not used.

Problems can arise when instances don't know that they are modifying statics.  In this case lets replace the name statics with config.

function foo(){
   if ( !foo.prototype.config ){
       foo.prototype.config = {
           a: 1,
           b: 2
       }
   }
   if ( !(this instanceof foo) ){
        return foo.prototype.config;
   }
}

foo.prototype.foobar = function() {
  this.config.a = 5;
}

foo()
>Object {a: 1, b: 2}
new foo().foobar();
foo();
> Object {a: 5, b:2}


问:
Simple method to authenticate human input into a form for relaying via email to a 3rd party
I put up a webpage advertising a particular birthday party. A simple html page served by apache2 on ubuntu server 12.04. I have a link on the page to a cgi script-Python-that asks the requester to submit text values that will be formatted and relayed in an email to the bithrday boy. What's a simple way to authenticate that a human being is filling out the form, so that I can avoid having the birthday boy receiving spam. Using standard CGI because I do not expect an overload of concurrent requests.

I am aware of things like reCaptcha, but am looking for canonical strategies for quick and dirty authentication. Not being paid for this and the site will be up for but 9 days, so I don't want to put time into a solution more robust that what I actually need. Would asking a human answerable question suffice? If so could I get a away with a dropdown box of selectable answers. I want quick and dirty, but I also don't want to wind up with boat loads of spam because I underestimated the intelligence of spam bots.

答:
Why not copy Google?

These days they insist on a mobile phone number when you sign up for mail, G+ etc.
Every now and then when you log in from a strange address they tell you to check your phone and look for an SMS message containing an authentication code.

You enter the code in the login screen and proceed as normal.

You could do something similar by requesting a mobile number, sending a verification code via SMS and only responding to mails with a valid verification code.


答:
I'd try something that's trivial and based on the page, but requires context so a standard bot won't pick up on it.

Specific suggestions:

Type the birthday boy's name backwards

Type the birthday boy's initials

What is the name of the birthday boy's mother?

What day is the birthday?

It'd be trivial to write a bot that could answer these, but nothing pre-existing ought to pick up on it, and it wouldn't be practical or worthwhile to do so in that timeframe.

Title: Simple method to authenticate human input into a form for relaying via email to a 3rd party

Body:
I put up a webpage advertising a particular birthday party. A simple html page served by apache2 on ubuntu server 12.04. I have a link on the page to a cgi script-Python-that asks the requester to submit text values that will be formatted and relayed in an email to the bithrday boy. What's a simple way to authenticate that a human being is filling out the form, so that I can avoid having the birthday boy receiving spam. Using standard CGI because I do not expect an overload of concurrent requests.

I am aware of things like reCaptcha, but am looking for canonical strategies for quick and dirty authentication. Not being paid for this and the site will be up for but 9 days, so I don't want to put time into a solution more robust that what I actually need. Would asking a human answerable question suffice? If so could I get a away with a dropdown box of selectable answers. I want quick and dirty, but I also don't want to wind up with boat loads of spam because I underestimated the intelligence of spam bots.


答:
I assume that you are sending this site as a link to the invitees.  Why not have the link be something like www.yourbirthdaysite.com/24387921854781987458714590349839849394?  Only accept connections to that address, not the root address.  This is an effective way to keep content private when you don't need overkill security.  Google uses it as a sharing option for sharing Google Docs, for example.

If you want people to be able to access the root address directly (if they need to type it in rather than clicking on a link), I would do two things:

Disable Google Indexing and don't link from anywhere public (your site is not targeted to the general public anyway).  This will remove the main source of traffic for spambots to your site.  Security through obscurity is not a good practice generally.  But a site that is not indexed on search engines and is only visible for nine days is very obscure.  Realistically, you are unlikely to get spam in that time.

Have a simple question and answer verification.  Have a few questions about the birthday boy that would be known to the party attendees.  Make it fun, and it will add to the site overall.


问:
How to prepare yourself for programming interview questions?

Possible Duplicate:

  Really “wow” them in the interview

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

答:
Michael Pryor has a site dedicated to technical interview questions.

A good interview though will contain a lot of questions about the technology they are hiring for.  And you will probably also need to write code.  Unfortunately there is no shortcut for this, only experience will help you here.   This link also details a list of Programming Puzzles.

For the prior (or should I say pryor) you prepare by working through the questions and getting good at those types of questions.  For the later you should be preparing your whole career.

ContentLicense: CC BY-SA 2.5


问:
Is it 'safe' to expect myClasses to agree not to only call package Scope methods from other Package scope methods?
The questions says it all, but a quick overview of the situation.  I'm creating a Model which contains classes (all inherriting myObject) which have a large amount of interconnection.  I want the controller to be able to create any of these objects any time, without modifying the Model.  Only an explicit cal to the model to "AddToModel" would 'install' the object into the model (including updating all the connected objects).  myObjects will use a factory pattern, if a user tries to create something already represented in the Model the already-instanced object in the model will be returned instead of constructing a new one.

To help with encapsulation I want all of my Objects to be effectivly-immutable to the controller, no matter what he does with an object he can't change the Model without calling the Model's add/remove.  The model still has to be able to change myObject state; so I would put all of the objects into the Model package.  Each object will then have package scope methods for updating state, including add/remove methods which install them in the model and update connected objects.  So essentially Package scope methods can change model state, public can't.

My concern is that this will all break if any of myObjects calls one of their package scope methods from a public method; messing with my state without explcit calls to Model.  I am writing this all, so I can abide by the contract that "only package methdos can call other package methods" But what if someone comes by later and tries to call "addToModel" from a constructor because they didn't read my comments and don't realize this breaks an assumed contract?

Is it 'safe' to expect others to read comments and abide by such an implicit contract when messing with 'my' model?  Can I enforce this with some sort of pattern (preferable without too much abstraction/interfaces as it could confuse some of the other developers).

ps, I'm using Java if that helps.  I think I might even be able to enforce this with the security API, though that may just prove more confusing/complicated since it would result in an obscure runtime exception.

答:
No. Classes/objects should have manage their own state. It sounds like you are expecting the Model to manage the state of myObject.

To elaborate, it sounds like

myObject has public "read-only" methods, and package-access "mutator" methods.

If myObject invokes its own "mutator" methods,  Model will/might break.

Ideally, a future programmer should be able to change 'myObject' without breaking Model.


问:
Scrum: What to do with epics once the stories are clear?
When working on a backlog, you define epics and break them down into user stories. Epics are estimated and kept on the backlog as epics until they become important enough to be planned into one of the next sprints.

But once an epic is split into sprintable units, what do you do with the original epic? Do you keep it with the stories until all are done? Do you retire them into some kind of epic archive? Do you just delete them?

They seem like unnecessary balast once the splitting is done.

答:
I've struggled with this and have come to understand that it really depends on how you decompose. Let's say you have some epic like ' I want to modify what's in my shopping cart'. This can be decomposed in several fashions:

by method

I want to modify my cart detail by going to the cart detail page

I want to modify cart detail by a pop-up quick look modal

by process

View shopping cart

change item quantities

delete items

by persona perhaps

As a shopper, I want to change what's in my cart

As a CSR, I want to access a shoppers cart and change the items in it

In this example, if you use decomp method 1 then probably safe to drop the epic since these children are truly independent. But in 2 or 3, the children are still independent but to accomplish the goal of the original story then the children must all be satisfied. And how you estimate also depends on looking at the set (in method 3, the first story will get some points for loading the cart view that impacts the estimate for the CSR accessing the cart view).

Like justinpeck mentions above, tooling becomes very important (are the relationship links easy to set and view?).

OwnerDisplayName: arumbay


问:
Getting Overwhelmed: Tips for noobs
As a newbie, I am overwhelmed by the amount of information out there and the amount of self-direction that one needs to develop as a programmer. How did you get oriented in the programming world? Are textbooks really the way to go? Or is it best to find a mentor? Was there some sort of guide or should there be some sort of universal guide to follow when trying to improve programming skills?</p>

答:
If the beginner has a good "preface statement" before opening a tool, they can often eliminate overwhelm by nipping it in the bud.

I was hired as an instructor for company teaching programming to complete noobs.  (I use "noobs" as a term of endearment, aren't we all, in more areas than not?)  When I say complete noobs, I'm serious.  One first question I got was: "when you say Right Click, what do you mean?"

One of the first things I learned, was to keep the tone of my voice exactly the same, regardless of how often that question had been asked, and regardless of how noobish it was.  I learned to answer each question, as if it were equally valid, equally exciting, and equally valuable -- and as if it were the first time that question had ever been asked.

The Overwhelm-Eliminating preface statement I use, for any tool, goes like this: There is only one icon you will click on the opening screen -- at least for now.  This tool you are about to open, wasn't built just for you, nor just for this task we are about to accomplish.  The developers of this tool had to build it for a lot of people, who wanted to do a lot of things, and they had to include capability you will never use.  That clutters things up.  So you'll see a plethora of buttons and menu items, and anything you click may give you a new plethora of options.  But every time you open this tool, in three clicks you can be doing what you want.  I'm going to show you that easy secret path through the jungle of useless options."

Unfortunately, I didn't always get to say any kind of preface before one of my students opened something that looked complicated.  I could tell, because statements would start to come out of that student's mouth, like: "I just wasn't cut out for SQL" or "I just don't have what it takes to be a Java programmer," or my one of my favorite lies: "Crystal Reports is just too hard for me to learn."  What a crock!  Lies, decided (and believed) in a moment of frustration, because they thought the tool was a huge forest, when really all they needed was to get to one of the treehouses, in one of the trees.

Here are a few of my preface statements I have used over the years:

There are only 9 basic concepts you need to know, to be a programmer.  They are each easy to learn.  Every programming language allows you to implement these 9 concepts using a slightly different syntax.  As you learn these concepts, and play with some different languages, you don't just become a C++ programmer, you become Programmer, who can program in any language, including (but not limited to) C++.

Every task you want to do, can be broken down into single steps.  Even those long complex lines of code, or complicated-looking command lines, are just made up of very easy to understand single steps.  If you have a complicated task, just prove one step at a time, verifying each result, then start putting them together, one combination at a time, verifying each combination, until it is complete.

Excellent programmers aren't really excellent programmers.  They are excellent debuggers.  If you don't get an error when you first compile, you should be worried.  If you do, you're on the right path; you can start doing what you love.

Find your "heierarchy of resources" and use it.  Mine looks like this:  If I need to do something, I try it.  If it doesn't work, I experiment for a few minutes.  If that doesn't work I use the Help file.  If that doesn't work I use a web search.  If that doesn't work I turn to the closest programmer next to me, and bounce it off them.  If that doesn't work I call one of my friends, who is (or knows) and expert.  If that doesn't work I hire somebody on one of those freelance sites, to teach me how to do it.  I've only gotten to that last step twice in my life.  [Learning this skill, kept the students from assigning me as their primary source for solutions.]

Learning to learn, is more important than learning any subject.  Learning to love learning is more important than learning any subject.  If it takes you awhile to find your answers on the web, find a good tutorial on the web that teaches you how to do excellent web searches.

Because Visual Studio Express is free, and you can drop a button on a window, and make it say "Hello World" in just a few moments, many Windows programmers start there.  When you are learning, if you start with VB, at least also write the same program in C# at the same time.  Preferably also Java and a couple of other languages as well.  And it would be smart to also write it in at least one language that is command line based, like TCC (Tiny C Compiler.)  I highly recommend using multiple languages, for each learning project, until you realize it's not the language you are learning, it's the programming.  Otherwise you can end up limiting yourself and getting stuck in a mindset that isn't true.

When asked if you can do something, the answer is unequivocally "yes."  Learn to trust your learning skills enough to be able to say "yes" and mean it -- Then start learning.

If you're not making mistakes, you aren't learning.  Celebrate them.  Then fix them.

Enjoy the full process of learning.  Enjoy working out the bugs.  Become an expert.

I have many more of them, but it may be enough to know that, if you are frustrated, it's not the subject matter, nor the concepts, nor the tools, that are the problem.  And it's not you, nor your intelligence, nor your ability, that is the problem.  The problem is simply the way you are looking at it.

With the right perspective, nothing is overwhelming.

OwnerDisplayName: theLearningChan

Title: Getting Overwhelmed: Tips for noobs


问:
How can I determine how to charge for supporting SharePoint sites and SharePoint development?
I recently created a site in SharePoint and I need to setup a maintenance/support agreement for the site. In addition to the site, there are some custom modules that were developed that we monitor. What considerations should I be making when determining how much to charge for supporting the SharePoint site and any custom applications developed for the site?</p>

答:
Some determining factors should include your level of experience and the complexity of the custom applications and content that is hosted within SharePoint. Ask yourself this:

Are you SharePoint Developers?

Are you SharePoint Administrators?

Are you SharePoint Architects?

Are you SharePoint Designers?

All of the above?

You've spent years learning your skills so don't drop your pants on prices. Get paid what you're worth. Break-down all the different aspects of the work you will/could perform so that users/customers will understand that different jobs/tasks require different needs/skills. Don't complicate it, but let them briefly understand what's involved. Otherwise they will under-appreciate all you do and then question why your asking the prices you do.

And then also consider the services you are providing?

Are you writing custom applications for the clients hosted on your
servers?

What maintenance is being performed?

Break down your services into small bits, not large groups so that you are paid for all the things you do. Plus, this gives your customers a solid level of expectations.

I would certainly request fees in several areas ...

Monthly hosting fees ($30 - $200 / month)

Custom programming fees ($150 - $250 / hour)

Server maintenance fees ($150 - $250 / hour OR packaged fees by task)

Data maintenance fees ($150 - $250 / hour OR packaged fees by task)

Training fees ($25 - $150 / hour)

As far as contracts go ...

Create SLAs - service level agreements including timeframes and duties

Prices - state clearly your duties and the fees

Include server and data security topics

Add a section for backup/recovery - explain in brief detail what this mean - users will not understand unless you give them an explaination

Hours of operation and emergency contact information

Additionally, make sure you have an insurance policy with a reputable company. Insure yourself or your company with a "computer programming" policy and a "data" policy. These policies cover coding errors, etc. If you run into a problem AND you don't have a policy like this it could be a problem.

This is just a starting point, so I hope it helps. :)


答: It sounds like you are planning on making Model and all these object classes mutually dependent.  I think this is a bad idea that will make testing and maintenance very difficult.  Probably none of the object classes should depend on Model.  If the Model needs to react to object state changes, then you could have the Model observe the objects.

Title: Is it 'safe' to expect myClasses to agree not to only call package Scope methods from other Package scope methods?

Body:
The questions says it all, but a quick overview of the situation.  I'm creating a Model which contains classes (all inherriting myObject) which have a large amount of interconnection.  I want the controller to be able to create any of these objects any time, without modifying the Model.  Only an explicit cal to the model to "AddToModel" would 'install' the object into the model (including updating all the connected objects).  myObjects will use a factory pattern, if a user tries to create something already represented in the Model the already-instanced object in the model will be returned instead of constructing a new one.

To help with encapsulation I want all of my Objects to be effectivly-immutable to the controller, no matter what he does with an object he can't change the Model without calling the Model's add/remove.  The model still has to be able to change myObject state; so I would put all of the objects into the Model package.  Each object will then have package scope methods for updating state, including add/remove methods which install them in the model and update connected objects.  So essentially Package scope methods can change model state, public can't.

My concern is that this will all break if any of myObjects calls one of their package scope methods from a public method; messing with my state without explcit calls to Model.  I am writing this all, so I can abide by the contract that "only package methdos can call other package methods" But what if someone comes by later and tries to call "addToModel" from a constructor because they didn't read my comments and don't realize this breaks an assumed contract?

Is it 'safe' to expect others to read comments and abide by such an implicit contract when messing with 'my' model?  Can I enforce this with some sort of pattern (preferable without too much abstraction/interfaces as it could confuse some of the other developers).

ps, I'm using Java if that helps.  I think I might even be able to enforce this with the security API, though that may just prove more confusing/complicated since it would result in an obscure runtime exception.


问:
What are some ways to be more productive with Emacs?
I've used Emacs quite a bit, and I'm comfortable with the most basic commands/shortcuts, but I know Emacs has a lot more to offer than what I'm using. What are some of the lesser known features of emacs that can help me become a more productive programmer?</p>

答: I guess this is not the "lesser known" feature, but I tend to use Emacs for any repetitive text editing. Keyboard-macros rule! http://jamesthornton.com/emacs/node/emacs_487.html </p>

OwnerDisplayName: Tommy


答:
The epics are a tool to help you do your job. Once they stop being useful you can throw them away. Therefore, the answer to the question is "are the epics still useful to you?". I don't think we have enough information to answer that for you.

Don't get too about what you are supposed to do or not do. If you want to keep the epics around, do so. If they aren't useful to you, throw them away. If you don't know if they are useful or not, keep them for an entire release cycle and then decide what to do in a final retrospective.

Title: Scrum: What to do with epics once the stories are clear?

Body:
When working on a backlog, you define epics and break them down into user stories. Epics are estimated and kept on the backlog as epics until they become important enough to be planned into one of the next sprints.

But once an epic is split into sprintable units, what do you do with the original epic? Do you keep it with the stories until all are done? Do you retire them into some kind of epic archive? Do you just delete them?

They seem like unnecessary balast once the splitting is done.


问:
Oracle Database Integration with Team Foundation Server?
So my company is using TFS and SQL to Manage their Database (MS SQL Server). It integrates with the nightly build servers to do builds and produce scripts to build the entire Database. Also the Compare Schema tool that visual studio offers is really handy.

We want to do the same with Oracle, Preferably with TFS if that's even possible. It can be done without, but is this a possibility?

Also are there any tools to assist in automatically creating the Database in a Nightly Build?

What about Managing Upgrades?

Our Big worry is moving triggers and the MS SQL Service Broker to Oracle... this we might have to do manually though.

答:
This has nothing to do with TFS - all TFS does is call MSBuild that (basically) runs visual studio in batch mode, so if you can get your DB project deploying to Oracle then TFS will be happy. (though you'll be much better off using Jenkins as it kicks TFS's bottom).

So, you have to get the VS project to deploy your DB project to an Oracle DB, now this should be possible - as you just have to specify a different connection string in the DB project settings (or the .dbdeployment file). Chances are you'll end up with SQLServer-specific sql generated and deployed, or VS will refuse to use anything other than a SQLClient connection.

So, go direct and get the Oracle Developer Tools for Visual Studio which will give you the same DB projects, and its own schema compare tool.


问:
What is the best approach for overriding fields in a database?
I have a database that contains projects and each project contains many samples. I want a project level threshold value, to trigger highlighting when a field on the sample is above this threshold. I also want to be able to override the threshold at the individual sample level.

So I can see two ways to implement this:

keep the threshold field (only) on the sample, and trigger this to get filled in when the project is saved.

have both sample and project level threshold fields, and only use the sample field when it is relevant (there seems to be some redundancy with this model, though it more accurately represents the situation)?

Are there advantages / problems with either approach?

答:
Its actually a simple descision based on how often you update the project threshold vs. how often you query the samples.

If the project level threshold is not updated very often then I would copy the threshold to every sample row (with perhaps an extra column to indicate an overridden value). This will make any queries simpler and faster.

On the other hand if you update the default threshold frequently. The keep it at the project level and take the (slight) performance hit for the join for every query.


答:
Does your public web site have a database of it's own?

If so you could achieve this with Replication of specific tables from your internal work database to your public database.

You can use circular replication if you need to get data back to your work database, but it sounds like this is just for presentation purposes.

This will be a more secure way to solve the problem because you only have to deal with one permanent secure connection between the servers.

Title: how to expose certain tables of an internal database on a public site

Body:
I have an internal database at my work. At the moment we are using excel to import data, but this is very error prone, so I would like to replace this with some javascript based application which exposes some of the data in lookup tables in dropdown menus, for our customers to fill in, on a public website.

So my internal database lives on an internal server not viewable by the public.

How should I go about building an application that communicates with the internal database, and only exposes certain tables?

Is some middleware like Django, that rather than using an SQL database uses some other way of getting the lookup values (I have a REST interface set up on the main database).

(To clarify, I am looking for a server side technology that I can put on a public facing server, that will communicate with the internal server).


答:
Your 2nd option provides the most flexibility with minimal extra complexity.

In the sample record, have a nullable field that holds the local threshold level. Set the field to null if the sample is to use the default threshold from the project. If you are using SQL, it is straight-forward to join the tables and use isnull to grab the threshold value:

```<code>SELECT Field1, Field2, ISNULL(sample.threshold, project.threshold) as Threshold FROM ...
</code>```

Title: What is the best approach for overriding fields in a database?

Body:
I have a database that contains projects and each project contains many samples. I want a project level threshold value, to trigger highlighting when a field on the sample is above this threshold. I also want to be able to override the threshold at the individual sample level.

So I can see two ways to implement this:

keep the threshold field (only) on the sample, and trigger this to get filled in when the project is saved.

have both sample and project level threshold fields, and only use the sample field when it is relevant (there seems to be some redundancy with this model, though it more accurately represents the situation)?

Are there advantages / problems with either approach?

Body:
Your 2nd option provides the most flexibility with minimal extra complexity.

In the sample record, have a nullable field that holds the local threshold level. Set the field to null if the sample is to use the default threshold from the project. If you are using SQL, it is straight-forward to join the tables and use isnull to grab the threshold value:

SELECT Field1, Field2, ISNULL(sample.threshold, project.threshold) as Threshold FROM ...


问:
How to encapsulate 'global' variables in C#? /best practice
In C# what is the best practice for encapsulating variables I need to use in multiple methods? Is it OK to simply declare them at the top of my class above the two methods?

Also if I am using app settings from my config file should I use a getter? like this...

```<code>private string mySetting{ get { return WebConfigurationManager.AppSettings["mySetting"]; } }
</code>```

What best practice is?

答:
Encapsulating your settings in a constant manner is a great idea.

What I do is create a settings class either one static global one or multiple instance classes which I'll then manage with dependency injection. Then I load all the settings from configuration into that class on start up.

I've also written a little library that makes use of reflection to make this even easier.

Once my settings are in my config file

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="Domain" value="example.com" />
        <add key="PagingSize" value="30" />
        <add key="Invalid.C#.Identifier" value="test" />
    </appSettings>
</configuration>
</code>```

I make a static or instance class depending on my needs. For simple applications with only a few settings one static class is fine.

```<code>private static class Settings
{
    public string Domain { get; set; }

    public int PagingSize { get; set; }

    [Named("Invalid.C#.Identifier")]
    public string ICID { get; set; }

}
</code>```

Then using my library call either Inflate.Static or Inflate.Instance and the cool thing is I can use any key value source.

```<code>using Fire.Configuration;

Inflate.Static( typeof(Settings), x => ConfigurationManager.AppSettings[x] );
</code>```

All the code for this is in GitHub at https://github.com/Enexure/Enexure.Fire.Configuration

There is even a nuget package:

PM> Install-Package Enexure.Fire.Configuration

Code for reference:

```<code>using System;
using System.Linq;
using System.Reflection;
using Fire.Extensions;

namespace Fire.Configuration
{
    public static class Inflate
    {
        public static void Static( Type type, Func<string, string> dictionary )
        {
            Fill( null, type, dictionary );
        }

        public static void Instance( object instance, Func<string, string> dictionary )
        {
            Fill( instance, instance.GetType(), dictionary );
        }

        private static void Fill( object instance, Type type, Func<string, string> dictionary )
        {

            PropertyInfo[] properties;
            if (instance == null) {

                // Static
                properties = type.GetProperties( BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly );
            } else {

                // Instance
                properties = type.GetProperties( BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly );
            }

            // Get app settings and convert
            foreach (PropertyInfo property in properties) {
                var attributes = property.GetCustomAttributes( true );
                if (!attributes.Any( x => x is Ignore )) {

                    var named = attributes.FirstOrDefault( x => x is Named ) as Named;

                    var value = dictionary((named != null)? named.Name : property.Name);

                    object result;
                    if (ExtendConversion.ConvertTo(value, property.PropertyType, out result)) {
                        property.SetValue( instance, result, null );
                    }
                }
            }
        }
    }
}
</code>```

Body:
Encapsulating your settings in a constant manner is a great idea.

What I do is create a settings class either one static global one or multiple instance classes which I'll then manage with dependency injection. Then I load all the settings from configuration into that class on start up.

I've also written a little library that makes use of reflection to make this even easier.

Once my settings are in my config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="Domain" value="example.com" />
        <add key="PagingSize" value="30" />
        <add key="Invalid.C#.Identifier" value="test" />
    </appSettings>
</configuration>

I make a static or instance class depending on my needs. For simple applications with only a few settings one static class is fine.

private static class Settings
{
    public string Domain { get; set; }

    public int PagingSize { get; set; }

    [Named("Invalid.C#.Identifier")]
    public string ICID { get; set; }

}

Then using my library call either Inflate.Static or Inflate.Instance and the cool thing is I can use any key value source.

using Fire.Configuration;

Inflate.Static( typeof(Settings), x => ConfigurationManager.AppSettings[x] );

All the code for this is in GitHub at https://github.com/Enexure/Enexure.Fire.Configuration

There is even a nuget package:

PM> Install-Package Enexure.Fire.Configuration

Code for reference:

using System;
using System.Linq;
using System.Reflection;
using Fire.Extensions;

namespace Fire.Configuration
{
    public static class Inflate
    {
        public static void Static( Type type, Func<string, string> dictionary )
        {
            Fill( null, type, dictionary );
        }

        public static void Instance( object instance, Func<string, string> dictionary )
        {
            Fill( instance, instance.GetType(), dictionary );
        }

        private static void Fill( object instance, Type type, Func<string, string> dictionary )
        {

            PropertyInfo[] properties;
            if (instance == null) {

                // Static
                properties = type.GetProperties( BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly );
            } else {

                // Instance
                properties = type.GetProperties( BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly );
            }

            // Get app settings and convert
            foreach (PropertyInfo property in properties) {
                var attributes = property.GetCustomAttributes( true );
                if (!attributes.Any( x => x is Ignore )) {

                    var named = attributes.FirstOrDefault( x => x is Named ) as Named;

                    var value = dictionary((named != null)? named.Name : property.Name);

                    object result;
                    if (ExtendConversion.ConvertTo(value, property.PropertyType, out result)) {
                        property.SetValue( instance, result, null );
                    }
                }
            }
        }
    }
}


问:
How to manage a Closed Source High-Risk Project?
I am currently planning to develop a J2EE website and wish to bring in 1 developer and 1 web designer to assist me. The project is a financial app within a niche market.

I plan to keep the source closed. However, I fear that my would-be employees could easily copy the codebase and use it or sell it to a third party. The app development will take 4-6 months, perhaps more, and I may bring in additional employees after the app goes live.

But how do I keep the source to myself. Are there techniques companies use to guard their source?

I foresee disabling USB drives and DVD writers on my development machines, but uploading data or attaching the code in email would still be possible.

My question is incomplete. But programmers who have been in my situation, please advice. How should I go about this? Building a team, maintaining code-secrecy,etc.

I am looking forward to sign a secrecy contract with the employees if needed too.
(Please add relevant tags)

Update

Thank you for all the answers. I certainly won't be disabling all USB ports and DVD writers now. But I think I should be logging activity(How exactly should I do that?) I am wary of scalpers who would join and then run off with the existing code. I haven't met any, but I have been advised to be wary of them. I would include a secrecy clause, but given this is a startup with almost no funding and in a highly competitive business niche with bigger players in the field, I doubt I would be able to detect or pursue any scalpers.

How do I hire people I trust, when I don't know them personally. Their resume will be helpful but otherwise trust will develop only with time.

But finally even if they do run away with the code, it is service that matters after the sale is made. So I am not really worried for the long term.

答:
Why should your potential customers trust you with there finances?

After all you may run off with the money.

Companies like Microsoft, Google, IBM employ thousands of people to write reams of closed source software, and, are not unduly worried about their staff walking off with the code. Copyright protection and a clear "any code belongs to your employer" clause in the employment contract seems to cover it, and, court cases against former employees for stealing code are extremely rare.

Furthermore once you release your software to the wide world, unless the core involves some really advanced math, any competent team of programmers could reproduce your application without ever seeing the source code.


答:
Add this to your form then in your Python script just check that the posted form field called capt == "human";

```<code><input type="hidden" name="capt" id="capt" value="">
<script>
    document.getElementById('capt').value="human";
</script>
</code>```

Will fool 99% of bots that can not run JavaScript and will only reject friends that disable JavaScript, but then again that's probably a good test of a true friend ;)

Body:
Add this to your form then in your Python script just check that the posted form field called capt == "human";

<input type="hidden" name="capt" id="capt" value="">
<script>
    document.getElementById('capt').value="human";
</script>

Will fool 99% of bots that can not run JavaScript and will only reject friends that disable JavaScript, but then again that's probably a good test of a true friend ;)


问:
What is the etiquette of renaming an open source fork?
I want to fork on Github the TestNG java testing framework (Apache 2 license) so I can add/change some minor things to suit my needs.

It's unlikely that all of my changes would be approved in the main project or that other people would use my fork. This would in no way be a competition to the main project.

Now, in terms of naming, I want to change the artifact name (testng-mycompany) or the version (6.8.mycompany) so there's no confusion with the official version in my maven repository. Would this be considered poor etiquette? If yes, what is the best approach to distinguish your fork?

答:
Fork away and do your worst / best.

Open source software has always been about letting individuals adapt, change and challenge convention. The hard part about forking a project is developing a new community around you that believes in what you are doing.

For example I could download the source for Apache, make a few modifications and call it the next big thing.. but if no one else gets on-board then I'm stuck playing catchup to the zillions of new features and bug fixes provided by the core Apache community.

Reference : Game of Thrones.

Rather than fork TestNG it might be simpler to write modules / add-on for it on top of the existing Repo, that way you will only need to maintain your own code.

Alternatively if you feel the need to alter TestNG then perhaps it's simply the wrong tool for the job.

[ Disclaimer, I've never heard of TestNG till now ]


问:
Security comparison between xmlHttpRequest and HttpRequest
Is there a difference between HttpRequest and xmlHttpRequest in terms of security? Is one more secure than the other?

Is it more secure to send important data such as passwords via HttpRequest than via xmlHttpRequest ?

Is data packing in both done the same way?

答:
Short answer no. If your posting back to a https server in one and http in another then yes https is more secure.
They do the same things internally but are triggered differently and lead to different outcomes. Ajax (xmlHttpRequest ) returns some text - xml or plain by calling a javascript function in same page; a form post navigates to a new page - could be back to same but browser does not care -  it needs to re-render.

You can do a secure AJAX posting. Using https shoud be enough, to be extra careful can mask the sensitive data and clear (or change the value) of js variables and form that that holds password after sending to server. see https://stackoverflow.com/questions/12157970/codeigniter-how-can-i-encrypt-password-before-submitting-the-form-to-the-contro

https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest mozilla on the subject


问:
Scoring/analysis of Subjective testing for skills assessment
I am lucky in the sense that I have been given the opportunity to be a 'Technical Troubleshooter' for our offshore development team. While I am confident and capable of dealing with most issues, I have come across something that I am not. Based on initial discussions with various team members both on and offshore, a requirement for a 'repeatable, consistent' skills assessment has been identified.

In my opinion, the best way to achieve this would be a combination of objective and subjective tests. The former normally being an initial online skills assessment on various subjects, for example General C#, WCF and MVC. The latter being a technical test where the candidate would need to solve various problems and (hopefully) explain the thought processes involved with the  solution whilst doing so.

Obviously, the first method is consistent, repeatable and extremely accurate. The second is always going to be subjective and based on the approach, the solution (or possibly not) and other factors. The 'scoring' of this is also going to be down to the experience and skills of the assessor and this is where my problem lies;

The person that is expected to be the assessor initially (me) has no
experience.

The people that will ultimately continue this process for other
people will never remain the same due to project constraints and
internal reasons, this changes the baseline for comparison.

I am not aware of any suitable system that can be classed as
consistent and repeatable for subjective tests with the 2 factors
above, let alone if those did not exist.

So anyway, I have to present a plan that will ultimately generate a skills/gap analysis and it is unlikely that I will be able to use an objective method (budget constraints most likely reason). The only option left is the subjective methods and the issues above.

Does anyone have any suggestions for an approach that may tick all the boxes?

答:
The best interview question I ever had to do was to do a code review. They gave me the IDE with a project in it and said "we've written this but imagine its a junior dev who's just done this and its your job to review it - show us the bugs, the things you'd do differently". And so I got to show them I knew about code organisation and best practice as well as the usual trivial bits of programming.

Try that, considering there are no explicit "answers" you can come up with something that is gauging their thought processes as well as a few objective tests (ie a bug or obvious error) that they should find too.


问:
Send stdout or stderr to a new thread
For performance issue I want the logging send to a new thread.

While the main program can work, the new thread can write the error or other messages to a file without effect to the main program. How could I send all stdout to the new thread?

Work to be done:

create a new thread, ok

open a file, ok

create a pipe inside the thread, ok

send stdout to the new thread, with freopen or dup?

Every time the buffer gets full, or every 5 seconds the log file gets new data.

Because it is an MPI program, I can't fork the whole program. It has to be a Posix thread.

答:
That work as expected, but is a lot of work. What are you thinking about that?
These are the structs for my list.

```<code>typedef struct logger {
    struct timeval *time1;
    char message[255];
    struct logger *next;
} Logger;

typedef struct queue {
    struct logger *front;
    struct logger *rear;
} Queue;
</code>```

Inside the queue is the linked list. With folowing function, the linked list is filled with messages.

```<code>void addLogStruct(char* dummyMessage) {
    Logger *tmpLogger = malloc(sizeof(Logger));
    if (queue1.front == NULL ) {
        // first round initialice
        strncpy(logger1.message,
                "*** Laufzeitsystem ***",
                sizeof(logger1.message));
        static struct timeval tmpTime;
        gettimeofday(&tmpTime, NULL );
        logger1.time1 = &tmpTime;
        logger1.next = NULL;
        runLogger = &logger1;
        queue1.front = &logger1;
        queue1.rear = &logger1;
    } else {
        strncpy(tmpLogger->message, dummyMessage, sizeof(tmpLogger->message));
        static struct timeval tmpTime;
        gettimeofday(&tmpTime, NULL );
        tmpLogger->time1 = &tmpTime;
        tmpLogger->next = NULL;
        runLogger->next = tmpLogger;
        queue1.rear = tmpLogger;
        runLogger = runLogger->next;
    }
}
</code>```

In the main function I started a detached Posix Thread. The following method run every 0.05 seconds to check the list, if a new message is there. If there is one, it will be written to disk.

```<code>int messageQueueThread(void *dummy) {
    Queue *tmpQueue = malloc(sizeof(Queue));
    tmpQueue = (Queue*) dummy;
    Logger *runLog = malloc(sizeof(Logger));
    int must_stop = 0;
    do {
        if (tmpQueue->front != runLog) {
            // Create String for transfer to function
            char tmpString[255];
            char *tmpString2 = timeval2String(tmpQueue->front->time1);
            sprintf(tmpString, "%s %s.\n", tmpString2,
                    tmpQueue->front->message);
            // write message to disk
            writeMessageFile(tmpString);

            // another one
            runLog = tmpQueue->front;

            // reorder logger struct
            if (tmpQueue->front->next != NULL ) {
                tmpQueue->front = tmpQueue->front->next;
            }
            // delete old log message?
        } else {
            // reorder logger struct
            if (tmpQueue->front->next != NULL ) {
                tmpQueue->front = tmpQueue->front->next;
            }
        }
    } while (!busyWait(must_stop));
    return 0;
}
</code>```

It's not perfect. But it work more or less. I want it simpler, but can't do it.

Title: Send stdout or stderr to a new thread

Body:
That work as expected, but is a lot of work. What are you thinking about that?
These are the structs for my list.

typedef struct logger {
    struct timeval *time1;
    char message[255];
    struct logger *next;
} Logger;

typedef struct queue {
    struct logger *front;
    struct logger *rear;
} Queue;

Inside the queue is the linked list. With folowing function, the linked list is filled with messages.

void addLogStruct(char* dummyMessage) {
    Logger *tmpLogger = malloc(sizeof(Logger));
    if (queue1.front == NULL ) {
        // first round initialice
        strncpy(logger1.message,
                "*** Laufzeitsystem ***",
                sizeof(logger1.message));
        static struct timeval tmpTime;
        gettimeofday(&tmpTime, NULL );
        logger1.time1 = &tmpTime;
        logger1.next = NULL;
        runLogger = &logger1;
        queue1.front = &logger1;
        queue1.rear = &logger1;
    } else {
        strncpy(tmpLogger->message, dummyMessage, sizeof(tmpLogger->message));
        static struct timeval tmpTime;
        gettimeofday(&tmpTime, NULL );
        tmpLogger->time1 = &tmpTime;
        tmpLogger->next = NULL;
        runLogger->next = tmpLogger;
        queue1.rear = tmpLogger;
        runLogger = runLogger->next;
    }
}

In the main function I started a detached Posix Thread. The following method run every 0.05 seconds to check the list, if a new message is there. If there is one, it will be written to disk.

int messageQueueThread(void *dummy) {
    Queue *tmpQueue = malloc(sizeof(Queue));
    tmpQueue = (Queue*) dummy;
    Logger *runLog = malloc(sizeof(Logger));
    int must_stop = 0;
    do {
        if (tmpQueue->front != runLog) {
            // Create String for transfer to function
            char tmpString[255];
            char *tmpString2 = timeval2String(tmpQueue->front->time1);
            sprintf(tmpString, "%s %s.\n", tmpString2,
                    tmpQueue->front->message);
            // write message to disk
            writeMessageFile(tmpString);

            // another one
            runLog = tmpQueue->front;

            // reorder logger struct
            if (tmpQueue->front->next != NULL ) {
                tmpQueue->front = tmpQueue->front->next;
            }
            // delete old log message?
        } else {
            // reorder logger struct
            if (tmpQueue->front->next != NULL ) {
                tmpQueue->front = tmpQueue->front->next;
            }
        }
    } while (!busyWait(must_stop));
    return 0;
}

It's not perfect. But it work more or less. I want it simpler, but can't do it.


问:
How common is it for a team to write everything in-house?
In a recent interview I asked the interviewers "how do you go about evaluating new technologies and libraries (such as SignalR) and bringing them in to use?". They said they don't, that instead they write everything themselves so they don't have to rely on anyone else.

The firm doesn't work for the government or defence contractors or on any safety-critical projects or anything like that. They were just your average, medium-size software development firm.

My question is: how common is it for teams to write everything themselves? Should I be concerned by teams that do?

Edit -- Most every response has said this is something to be concerned by. Would a second interview be an appropriate time to ask them to clarify/repeat their position on writing everything in house?

答: That seems incredibly uncompetitive.  I've worked in shops that decided to skip the standard open-source libraries like Hibernate and roll their own due to some "critical" missing feature.  In the end the software was incredibly expensive to build and maintain.  Of course the expense of the in-house library was grossly underestimated.  And while the in-house library was written, the standard libraries advanced rapidly, adding new features that weren't available in the in-house library.  In the end, work that would take an hour using a standard library instead took two days.  And it was bad for the developer's careers, as the world passed them by.  I would avoid a shop like that.  I like to deliver, and don't have the patience to rewrite when I could reuse.</p>


答: Yes, definitely be concerned! That reeks of arrogance and (sorry to be harsh) stupidity. Any programmer with half a brain will use a library like signalR instead of writing it yourself. There is absolutely no point in wasting your time solving a problem that has already be solved. I would possibly try to find out more information first - they might have  misunderstood you (might be difficult though if the interviews are over!) </p>

Title: How common is it for a team to write everything in-house?

Body:
In a recent interview I asked the interviewers "how do you go about evaluating new technologies and libraries (such as SignalR) and bringing them in to use?". They said they don't, that instead they write everything themselves so they don't have to rely on anyone else.

The firm doesn't work for the government or defence contractors or on any safety-critical projects or anything like that. They were just your average, medium-size software development firm.

My question is: how common is it for teams to write everything themselves? Should I be concerned by teams that do?

Edit -- Most every response has said this is something to be concerned by. Would a second interview be an appropriate time to ask them to clarify/repeat their position on writing everything in house?


答:
An attitude of never using third-party libraries is preposterous.  Writing everything yourself is a horrible use of your company's time, unless there is a strict business requirement that every line in the codebase was written by an employee of the company -- but that is an unusual scenario, especially for a private-sector firm like you've described.

A more rational and thorough answer may have been that they would only use third-party libraries that:

Meet the needs of the code they would otherwise write themselves

Were available under a license compatible with the company's business model

Included tests

Passed a code review

If those criteria were met (and in my experience the code review is very flexible especially in the presence of good tests), you're no longer "relying on anyone else" -- you're relying on existing, available, and preferably robust code.

If the code is open source, then in the worst case, the third-party library becomes unmaintained.  But who cares?  The tests prove that the library is suited for your needs!

Moreover, an aversion to established third-party libraries seriously hinders programer productivity.  Let's say the company was writing web applications and refused to use (e.g.) jQuery, so instead wrote their own alternative cross-browser library for simplifying DOM manipulation.  With near-certainty we can assume that their implementation:

Will have an API foreign to developers already familiar to jQuery

Will not be as well-documented as jQuery

Will not have relevant Google results when encountering problems using the library

Will not be as field-tested as jQuery

All of those points are major barriers to programmer productivity.  How can a business afford to give up productivity like that?

You've updated your question to ask whether this is appropriate to bring up in a second interview.  It absolutely is.

Maybe you misinterpreted your interviewer's answer in the first interview, or maybe the interviewer just incorrectly explained the company's position and a new interviewer can clarify it.

If you explain that you're concerned about their stance on external libraries, there are at least two possible outcomes:

They're open to change, and your concern about their process makes you look better than some other candidates.

They are not open to change, and they think of you as "the kind of developer we wouldn't want to hire."  Doesn't matter, that's not the kind of place you want to work anyways.


答:
The shop has a disease called Not Invented Here.  It is a good reason to terminate the interview on the spot and leave immediately.  This can only be cured by a top-down house cleaning that is very unlikely to happen.

To answer your question, it is sadly much more common than you might think and it's definitely a reason to be concerned.


答:
Big companies write everything themselves.

There are several advantages in writing it yourself:

You're guaranteed to own the software yourself

You can correctly calculate work amounts that went into creating it

Repeating your steps becomes possible even if next time the libs are not available

It cuts down your requirement bloat

You're not repeating what others have done already

You're guaranteed to have enough people to maintain it

You can modify every part of the software

Software size is limited by amount of resources you have

Here's how each of the points break if you use someone elses library:

Someone else owns the lib

You don't know how much effort went into creating the lib

Your next version of product is impossible to create on new platform since same libs are no longer available

Ability to implement requirement is dependent on whether the lib implemented it years ago

Someone else also uses the same lib, getting same limitations and features

Since you didn't create the libs, you don't have enough people to maintain all the software in your product

Libs are binaries, nonmodifiable. Even if source is available, you don't have enough people to modify that large amount of code.

Maintaining the code you created + the libs is bigger effort than you originally estimated


答:
I have a couple of friends who have both (briefly) worked at software houses with not invented here syndrome. So the mentality is out there.

An observation they both made was around the culture the approach fostered in the development teams. They both ended up working with people who were quite insular in terms of their outlook on software development, and people who were not really driven to learn new things and push for quality. Regardless of what stage you're at in your career, you would always like to be working somewhere where you stand a chance of learning new things from your peers. This sort of environment however seems to generally not be found in places that wish to roll everything themselves.


答:
It's not common where I live, and I know a lot of companies though colleagues.
I'd go as far to say it's an immediate "no thanks" from me.

I won't regurgitate the good points already made, but I will add one thing.

They have just made hiring a lot more difficult.

All new hires have an even steeper learning curve than just the main part of the software/domain

The best candidates will be put off as they will not want their skills to become unused.

People are not likely to stay around long once they realise how bad it is not getting to use their favourite tools, and staff turnover is expensive

Now there will of course be people who like the challenge, but I think they'd be in the minority.

And equally, there will be some companies who operate on "Internet scale", Amazon, Facebook, etc., where they have insane custom needs, but again these are in the minority.


答:
I don't think a software company can survive today without relying on third party and/or open source software, and in order to remain competive they of course need to actively keep track of new technologies. There are often good reasons, however, to take at least a rather defensive view on it.

As an example, if you sell software and claim to provide 24/7 support and also are legally responsible for your software to operate correctly, then you need to have a very precise idea of what is going to happen if there is a problem with your software in, say, a factory where 1 hour of production downtime may cost several millions of dollars, and then a serious bug happens to be in that open source library you were using. Believe me, you will perform very thorough assessments of the software in question.

From what you've written this scenario does not seem to be at the heart of the matter, though.


答:
Honestly, like everyone else said, you just need to trust your programmers.

However, I will add to that by saying you should really consider that open sourcing your project in today's environment is more likely to help you than to hurt you, with the exception of a few specific markets. Just being more open to the idea will make you less worried about your source code growing legs and running off, even if you don't do it yourself. Garner all the goodwill you can, and you're more likely to earn money, in my opinion. Even if the Empire offered the best app in the world, I don't think Luke Skywalker would've downloaded it, because the Empire's ideals were in the wrong place.

Title: How to manage a Closed Source High-Risk Project?

Body:
I am currently planning to develop a J2EE website and wish to bring in 1 developer and 1 web designer to assist me. The project is a financial app within a niche market.

I plan to keep the source closed. However, I fear that my would-be employees could easily copy the codebase and use it or sell it to a third party. The app development will take 4-6 months, perhaps more, and I may bring in additional employees after the app goes live.

But how do I keep the source to myself. Are there techniques companies use to guard their source?

I foresee disabling USB drives and DVD writers on my development machines, but uploading data or attaching the code in email would still be possible.

My question is incomplete. But programmers who have been in my situation, please advice. How should I go about this? Building a team, maintaining code-secrecy,etc.

I am looking forward to sign a secrecy contract with the employees if needed too.
(Please add relevant tags)

Update

Thank you for all the answers. I certainly won't be disabling all USB ports and DVD writers now. But I think I should be logging activity(How exactly should I do that?) I am wary of scalpers who would join and then run off with the existing code. I haven't met any, but I have been advised to be wary of them. I would include a secrecy clause, but given this is a startup with almost no funding and in a highly competitive business niche with bigger players in the field, I doubt I would be able to detect or pursue any scalpers.

How do I hire people I trust, when I don't know them personally. Their resume will be helpful but otherwise trust will develop only with time.

But finally even if they do run away with the code, it is service that matters after the sale is made. So I am not really worried for the long term.


问:
Load Balancing for Listeners
How should we load balance listeners to a 3rd party service?

e.g. We need to read gtalk messages via XMPP Listener and build an application using the interactions of the user with a chatbot. In such a case, how would we ensure that we can have XMPP listeners on multiple servers and we load balance the messages between the listeners?

Thanks in advance.

答:
You might want to look at Twitter's Storm framework. It makes use of zookeeper to manage clusters of JVM's that can be configured to process incoming events.

From their fine tutorial:

The core abstraction in Storm is the "stream". A stream is an unbounded sequence of tuples. Storm provides the primitives for transforming a stream into a new stream in a distributed and reliable way. For example, you may transform a stream of tweets into a stream of trending topics.

A spout is a source of streams. For example, a spout may read tuples off of a Kestrel queue and emit them as a stream. Or a spout may connect to the Twitter API and emit a stream of tweets.

A bolt consumes any number of input streams, does some processing, and possibly emits new streams. Complex stream transformations, like computing a stream of trending topics from a stream of tweets, require multiple steps and thus multiple bolts. Bolts can do anything from run functions, filter tuples, do streaming aggregations, do streaming joins, talk to databases, and more.

Networks of spouts and bolts are packaged into a "topology" which is the top-level abstraction that you submit to Storm clusters for execution. A topology is a graph of stream transformations where each node is a spout or bolt. Edges in the graph indicate which bolts are subscribing to which streams. When a spout or bolt emits a tuple to a stream, it sends the tuple to every bolt that subscribed to that stream.

http://storm-project.net

It might be overkill, but looking at it might also inspire you to think of your problem differently even if you don't use it.

Title: Load Balancing for Listeners


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

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

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

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

答:
Mathematically it MIGHT be possible to write 'bugless' software of such complexity, depending on how you define 'bug'. Proving it MIGHT also be mathematically possible, by designing a test system that would exercise every line of code in every possible way - every possible use case. But I am not sure - if you are dealing with a system that does complex calculations, you may run into an 'infinity problem'...

Practically speaking, in a system of the size and scope you are talking about, this is IMPOSSIBLE. It might take a 1000 years to write such a 'bug free' system, and to write a system to prove it would take exponentially more time: you'd have to come up with every possible use case and write a system that would test each one - and I don't believe there is way of determining that you have actually covered every use case in a system of the size and scope you are talking about in anything resembling a reasonable amount of time.

IMO your question is a bit misdirected: Our goal as developers is not to write 'bugless' software. Our goal is to write USABLE, FLEXIBLE, EASILY MAINTAINABLE software.

Usable: The system fulfills the essential requirements it was designed for. There may be bugs - but they will be in 'edge cases' - outliers, or annoyances, not bugs that compromise the fundamentals of the system - robust.

Maintainable: Bugs can be easily isolated and fixed and DON'T create new bugs.

Flexible: Your system is easy to change and expand without significant redesign and downtime: Most changes require simply adding a new class or module that fits in with your already well designed patterns and framework.

Good design practices, good control practices, good teamwork, conscientious developers - that is the formula for GOOD SOFTWARE. (not PERFECT - but GOOD)


问:
If you spot a software bug and fix it, do you tell the client?
I spotted a bug today in a web application that I develop and maintain for a client. I let the client know that I had spotted a problem and after a short time I fixed it and reported back the full details to them.

In cases like these do you always tell your client? Even though it would be possible to fix the problem and tell no one?

答:
Depends on your relationship with the client and the nature of your employment: Are you are contractor being paid by the hour or an employee. If you're billing by the hour, you must give account for your time.

Is the client tech savvy or not? Do they understand that 'bugs happen' and don't make you a bad programmer? Will they look upon you more favorably if you tell them you found it and fixed it, or hold it against you?

Sometimes when dealing the clients, 'What they don't know, won't hurt them'.


答:
Essentially, no but you should do your best anyway.
I'll explain why (or just skip to the conclusion if you don't have enough patience)

Consider a problem as trivial as the implementation of binary search. One very popular implementation had a bug that went undetected for around two decades. If twenty lines take twenty years to get bug-free being widely used and even supposedly proven correct, can we really expect a huge program to be bug-free?

How many bugs can we expect a huge program to have anyway? One number I found was "10 defects per 1000 lines" (Code Complete 2nd edition, page 517 - merely used an example, not quoting any data)
That gives us around 200 000 to 300 000 bugs in your software.
Fortunately, we have ways to improve the quality of the program. Unit testing, code reviews and ordinary manual testing are known to reduce the number of bugs. Still, the number will still be high.

If we could solve 95% of all bugs that'd be incredible. And yet we'd still have 10 000 to 15 000 bugs in the software.

Fortunately, since the software is widely used (and, therefore, widely tested) bugs are going to be found. So we'll gradually get fewer bugs.
However, fewer bugs also mean that the remaining ones are harder to find - so don't expect a linear curve in bug fixing. The last few bugs will be really tricky to find and could escape detection for several years (assuming they are ever found).

You also seem to be mistakenly assuming that if the software doesn't change, no new bugs are going to appear. If the software depends on third party libraries, new versions may break some features - introducing new bugs even though the code of the application is still the same. New operating systems can also break an application that previously worked perfectly (see Windows Vista for a popular example). Consider also compiler bugs, etc.

It is unclear whether code proof tools can truly solve the problem of buggy software. It is certainly not possible to solve the halting problem for any program, but it might be possible to prove that a program behaves as specified... But then what? Maybe the proof program has a bug. Maybe the specification itself has a bug.

So clearly, we can greatly reduce the number of bugs, but it's really unlikely we'll ever get to zero.

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

(emphasis added)

You are correct. This statement is wrong. Here's an example:

```<code>int main() {
    int x[10];
    x[10] = 8; //Buffer overflow here
    return 0;
}
</code>```

Now, let's fix this bug:

```<code>int main() {
    int x[11];
    x[10] = 8; //No buffer overflow here
    return 0;
}
</code>```

See? We fixed a bug and introduced no new ones.

However, it is certainly correct that every time you fix a bug you risk creating a new one, though this risk can be mitigated (e.g. with unit testing).

Let's say that for every 100 bugs that I fix, I accidentally introduce a new one.
So if I fix 10 000 bugs, I introduce 100 new bugs. And if I fix those new bugs, I introduce one bug. But so what? The program now has 9 999 fewer bugs, so it's probably better than it was (assuming the new bug is not 10 000 times worst than the previous ones).

Also, fixing a bug can expose new ones. But those bugs can be fixed as well. If you do things right, eventually the software will be in a better state than it started in.

I was old by a few top programmers that it's better not to fix a lot
  of bugs because of the notion I mentioned in the OP.

This behavior is negligent. If there's a bug and you can fix it. Do it. Of course you should do your best to prevent adding new ones but if I introduce one small bug for every 10 serious bugs I fix, that is not a valid reason to stop fixing bugs. In fact, it is a good reason to keep fixing bugs.

So less bugs you
  fix, less bugs will come back at you in the future

The fewer bugs you fix, the more bugs will remain in your software, annoying your users.
Indeed, they won't "come back at you in the future". They won't come back because they never left in the first place.
The notion of "come back" is related to regressions. Again, it is possible to reduce the risk of regressions.

Some bugs can't be fixed because they became so widely used that people started to depend on them and fixing the bug would break the program for those users. It happens. However, can they really be considered bugs in that case?

The "fix a bug, make a bug" mentality might be related to That Horrible Monster - code that is so unreadable and unmaintainable that merely touching it creates bugs. If you have a monster in your code base, you might first need to un-monsterify it before getting anything done.

Finally, if you are a terrible programmer, there's the risk that anything you touch creates new bugs. This would obviously make senior programmers nervous. However, saying "Don't do anything. Don't touch anything. Don't even breath." is probably not the right way to create a healthy work environment. Education is better.

Conclusion:

Software that keeps getting tons of new features but no bug fixes will inevitably suck.

Software that gets a moderate number of new features but gets its bugs fixed has a better chance of being usable.

Those who try to have few bugs have (on average) fewer bugs than those who do not care.

It is not reasonable to expect a program to eventually become bug-free.

Senior programmers are not necessarily competent.

Fix your bugs.

Adopt methodologies that improve the quality of your software.

Title: Is it possible to reach absolute zero bug state for large scale software?

Body:
I am talking about 20-30+ millions lines of code, software at the scale and complexity of Autodesk Maya for example.

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

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

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

Body:
Essentially, no but you should do your best anyway.
I'll explain why (or just skip to the conclusion if you don't have enough patience)

Consider a problem as trivial as the implementation of binary search. One very popular implementation had a bug that went undetected for around two decades. If twenty lines take twenty years to get bug-free being widely used and even supposedly proven correct, can we really expect a huge program to be bug-free?

How many bugs can we expect a huge program to have anyway? One number I found was "10 defects per 1000 lines" (Code Complete 2nd edition, page 517 - merely used an example, not quoting any data)
That gives us around 200 000 to 300 000 bugs in your software.
Fortunately, we have ways to improve the quality of the program. Unit testing, code reviews and ordinary manual testing are known to reduce the number of bugs. Still, the number will still be high.

If we could solve 95% of all bugs that'd be incredible. And yet we'd still have 10 000 to 15 000 bugs in the software.

Fortunately, since the software is widely used (and, therefore, widely tested) bugs are going to be found. So we'll gradually get fewer bugs.
However, fewer bugs also mean that the remaining ones are harder to find - so don't expect a linear curve in bug fixing. The last few bugs will be really tricky to find and could escape detection for several years (assuming they are ever found).

You also seem to be mistakenly assuming that if the software doesn't change, no new bugs are going to appear. If the software depends on third party libraries, new versions may break some features - introducing new bugs even though the code of the application is still the same. New operating systems can also break an application that previously worked perfectly (see Windows Vista for a popular example). Consider also compiler bugs, etc.

It is unclear whether code proof tools can truly solve the problem of buggy software. It is certainly not possible to solve the halting problem for any program, but it might be possible to prove that a program behaves as specified... But then what? Maybe the proof program has a bug. Maybe the specification itself has a bug.

So clearly, we can greatly reduce the number of bugs, but it's really unlikely we'll ever get to zero.

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

(emphasis added)

You are correct. This statement is wrong. Here's an example:

int main() {
    int x[10];
    x[10] = 8; //Buffer overflow here
    return 0;
}

Now, let's fix this bug:

int main() {
    int x[11];
    x[10] = 8; //No buffer overflow here
    return 0;
}

See? We fixed a bug and introduced no new ones.

However, it is certainly correct that every time you fix a bug you risk creating a new one, though this risk can be mitigated (e.g. with unit testing).

Let's say that for every 100 bugs that I fix, I accidentally introduce a new one.
So if I fix 10 000 bugs, I introduce 100 new bugs. And if I fix those new bugs, I introduce one bug. But so what? The program now has 9 999 fewer bugs, so it's probably better than it was (assuming the new bug is not 10 000 times worst than the previous ones).

Also, fixing a bug can expose new ones. But those bugs can be fixed as well. If you do things right, eventually the software will be in a better state than it started in.

I was old by a few top programmers that it's better not to fix a lot
  of bugs because of the notion I mentioned in the OP.

This behavior is negligent. If there's a bug and you can fix it. Do it. Of course you should do your best to prevent adding new ones but if I introduce one small bug for every 10 serious bugs I fix, that is not a valid reason to stop fixing bugs. In fact, it is a good reason to keep fixing bugs.

So less bugs you
  fix, less bugs will come back at you in the future

The fewer bugs you fix, the more bugs will remain in your software, annoying your users.
Indeed, they won't "come back at you in the future". They won't come back because they never left in the first place.
The notion of "come back" is related to regressions. Again, it is possible to reduce the risk of regressions.

Some bugs can't be fixed because they became so widely used that people started to depend on them and fixing the bug would break the program for those users. It happens. However, can they really be considered bugs in that case?

The "fix a bug, make a bug" mentality might be related to That Horrible Monster - code that is so unreadable and unmaintainable that merely touching it creates bugs. If you have a monster in your code base, you might first need to un-monsterify it before getting anything done.

Finally, if you are a terrible programmer, there's the risk that anything you touch creates new bugs. This would obviously make senior programmers nervous. However, saying "Don't do anything. Don't touch anything. Don't even breath." is probably not the right way to create a healthy work environment. Education is better.

Conclusion:

Software that keeps getting tons of new features but no bug fixes will inevitably suck.

Software that gets a moderate number of new features but gets its bugs fixed has a better chance of being usable.

Those who try to have few bugs have (on average) fewer bugs than those who do not care.

It is not reasonable to expect a program to eventually become bug-free.

Senior programmers are not necessarily competent.

Fix your bugs.

Adopt methodologies that improve the quality of your software.


答:
As Mikey mentioned, writing bugless code is not the goal. If that is what you are aiming for, then I have some very bad news for you.

The key point is that you are vastly underestimating the complexity of software.

First things first--You're ignoring the bigger picture of how your program runs. It does not run in isolation on a perfect system. Even the most basic of "Hello World" programs runs on an operating system, and therefore, even the most simple of programs is susceptible to bugs that may exist in the operating system.

The existence of libraries makes this more complex. While operating systems tend to be fairly stable, libraries are a mixed bag when it comes to stability. Some are wonderful. Others ... not so much ... If you want your code to be 100% bug free, then you will need to also ensure that every library you run against is completely bug free, and many times this simply isn't possible as you may not have the source code.

Then there are threads to think about. Most large scale programs use threads all over the place. We try to be careful and write threads in such a way where race conditions and deadlock do not occur, but it simply is not possible to test every possible combination of code. In order to test this effectively, you would need to examine every possible ordering of commands going through the CPU. I have not done the math on this one, but I suspect that enumerating all of the possible games of Chess would be easier.

Things go from hard to impossible when we look at the machine itself. CPU's are not perfect. RAM is not perfect. Hard drives are not perfect. None of the components within a machine are designed to be perfect--they're designed to be "good enough". Even a perfect program will eventually fail due to a hiccup by the machine. There's nothing you can do to stop it.

Bottom line: Can you write "Bug free software"?

NO

Anyone who tells you otherwise is clueless.

Just try to write software that is easy to understand and maintain. Once you've done that, you can call it a day.

EDIT: Some people commented about an excellent point that I had completely overlooked: the compiler.

Unless you are writing in assembly, it is entirely possible that the compiler will mess up your code (even if you prove that your code is "perfect").

A list of bugs in GCC, one of the more commonly used compilers: http://gcc.gnu.org/bugzilla/buglist.cgi?product=gcc&component=c%2B%2B&resolution=---


问:
QT-C++ vs Generic C++ and STL
Been brushing up on my C++ lately, on Ubuntu QQ. I love the Qt framework  for everything, especially building GUI's. I became quite familiar with it when using PyQt over the last few years.

When using PyQt, I had some issues that are now more pronounced when using C++ with Qt: Qt has many extensions to C++ that are Qt specific - QString being just one common example, not to mention automated garbage collection. It is possible to write Qt applications using C++ without knowing much at all about C++ and the STL.

I may have to hit the job market again soon and I'd like to be able to consider C++ positions - but I'm afraid binding myself too much to Qt will limit my abilities to work with generic C++, which were once quite formidable but are now long dormant and rusty.

Should I avoid Qt? Would I be better off using WxWidgets or GTK++ for building GUI's?

What's the best GUI framework to use that allows/requires the most use of generic C++ and the STL? How do I make myself most marketable as a C++ programmer when it comes to GUI frameworks, etc?

答:
I wouldn't refrain from using Qt just for those reasons. You are not required to use all of Qt's utility classes; for the ones that replace the STL, you'll at most be forced to use QString and, possibly, QStringList. Also, there's usually much more to a program than the GUI. You can always use exclusively generic C++ for the rest of your program, and use Qt just for the GUI.

In my opinion, working with STL is more about understanding what underlying data structures are used and their complexities, and consequently at which times you should use each container. And when it comes to C++ programming, it's especially about knowing how to use the very essential < algorithm > header, which should also work on Qt's containers, since they're STL-compatible.

I don't see much harm in using all those extensions Qt provides, as long as you know (or ate least have a general idea of) how they are internally implemented. Make sure you know that things like Q_OBJECT, SIGNAL(), SLOT(), foreach(), aren't magic, but macros that expand to valid C++ statements.
For instance, it's not all that complicated to understand how the implicitly shared classes and parent-child relationships that make Qt feel more Java-like are implemented.  You can always try to recreate some functionality in a separate project just to see if you could do it with generic C++, and then not feel bad for using them in Qt.

Also, take a look at the Boost libraries. They provide extra utilities that the standard C++ library doesn't, and are a really good way to get a little closer to generic C++, since they essentially follow the same conventions as generic C++. Some of the libraries have fairly complex templated classes, and simply trying to understand how they work is, in itself, a good study in C++. Boost has many utilities that cannot be found in Qt, and others that implement the same or similar concepts as some of Qt's classes and can be used in their stead.

If you do hit the job market working with C++, chances are you're going to be working with Qt or another framework that, similarly to it, will have it's own utility classes that try to make C++ simpler.

Title: QT-C++ vs Generic C++ and STL


问:
unique_ptr and references - coding style question
I'm pretty sure this is a question purely about aesthetics but I wanted to get all your opinions on it before I start proliferating this type of code in my codebase. Consider the following code:

```<code>//Foo.h
class Bar;
class Foo
{
    public:
       Bar& GetBar(){return *bar.get();}
    private:
       std::unique_ptr<Bar> bar;
};

//Bar.h
class Bar
{
     public:
         DoSomething(){//did something...}
};
</code>```

This allows us to forward declare Bar in Foo.h and avoid having to #include Bar.h.
This leads to using Foo's Bar in the following way:

```<code>Foo foo;
foo.GetBar().DoSomething();
</code>```

Personally, I think this would look a lot nicer:

```<code>Foo foo;
foo.bar.DoSomething();
</code>```

To achieve that, I've written:

```<code>//Foo.h
class Bar;
class Foo
{
    public:
        Foo();
        Bar& bar;
    private:
        std::unique_ptr<Bar> bar_ptr;
};

//Foo.cpp
#include "Bar.h"
Foo::Foo() : bar_ptr(new Bar()), bar(*bar_ptr) {}
</code>```

This allows me to forward declare Bar and use the 'bar.' syntax.

Ugly? Not Ugly? The downside is that I have 2 member vars for only 1 object.

答:
It's usually not a good idea to use a reference as a class member.

If you use a reference, you are required to define the object that it references to in the constructor, and you can never again change the object that that reference points to again. Consequently, you'll have serious problems if you ever call bar_ptr.reset() and try to access bar.

Also, using a reference the way you are using is essentially the same as declaring Bar as a public non-pointer variable. I honestly don't see a reason for all that inconvenience just so you don't have to #include a header.


问:
How would I programmatically verify gift cards on a website?
I'm trying to include a feature on my website that verifies retail gift card balances on cards previously registered at the retailer's website by the card holder. Can this simply be done by writing an algorithm that pulls and aggregates this data on my site?</p>

答:
I'd do this by querying a database to verify if a particular gift card has value on it or not. Each time a gift card is issued, it gets scanned and then has value added to it. In a database, you'd create a new row with the card number and card balance. Then when you want to verify value, you'd query the balance of a given card.

Be warned, this method may not be secure.

A database table like so:

Gift_Card_ID Gift_Card_Balance

123456789       30.00

Now some SQL:

```<code>SELECT Gift_Card_Balance FROM Gift_Cards
WHERE Gift_Card_ID = '123456789'
</code>```

Be aware that this is just an example to illustrate the concept and in no way implies working code to be used an production environment.

You'd need more than just SQL to integrate this into a web environment but that's the basic idea in terms of operation.

Body:
I'd do this by querying a database to verify if a particular gift card has value on it or not. Each time a gift card is issued, it gets scanned and then has value added to it. In a database, you'd create a new row with the card number and card balance. Then when you want to verify value, you'd query the balance of a given card.

Be warned, this method may not be secure.

A database table like so:

Gift_Card_ID Gift_Card_Balance

123456789       30.00

Now some SQL:

SELECT Gift_Card_Balance FROM Gift_Cards
WHERE Gift_Card_ID = '123456789'

Be aware that this is just an example to illustrate the concept and in no way implies working code to be used an production environment.

You'd need more than just SQL to integrate this into a web environment but that's the basic idea in terms of operation.


问:
Is the average number of bugs per loc the same for different programming languages?
I have been told that the average number of bugs/defects per line of code is "constant" for different programming languages. 10 KLOC of Ruby would have the same number of bugs as 10 KLOC of c++. The argument is usually used to promote the use of expressive languages (think python/ruby over c++/assembly) since the number of lines to describe the same functionality would be smaller.

Does anybody know where this claim comes from? Does higher-level languages lead to fewer bugs?

答: I would expect that a key factor in coding errors relates to what I call the "semantic gap" between a particular type of solution definition and the code to solve it - where these are close reformulation errors would be more apparent, where the code is very different, many errors could be expected.  The paradigm of certain languages closely match certain problem domains - spreadsheets are very appropriate to everyday business calculations, resulting in both very little "code" and the "code" being very close to the problem domain.  The expected code is both very concise (little KLOC) and few errors.  Conversely using assembler would require many KLOC and is likely to produce immense number of errors.</p>