问:
Can the version of Git vary between team members?
We are about 40 developers working on the same code base and we use Git for version control.

My question is: can there be problems if, for example, some developers have a much older version of Git installed on their system ? Or should we try to enforce some rule that says something like "you should upgrade Git on your machine to the latest version at least once per year" ?

Maybe in older versions of Git, the structure of the objects may be slightly different. Or there may be some bugs in the algorithm that calculates which lines were added/removed from files. These issues can cause corrupt repositories or different values for the SHA-1 hashes in places where it should have the same value.1

Obviously, since Git is a distributed VCS, a corrupt repository won't ever mean critical loss of data, since there are 40 other people from which you can clone a new copy.

So it's more a curiosity than a concern. I suspect that backwards-compatibility is something extremely important when it comes to releasing a new version of Git; but still: the potential issues mentioned above are a possibility.

1 = as far as I know, we had no such problems... yet.

答:
The repository format only changes very rarely, and it never changes in a way that is backwards-incompatible. IIRC, the last incompatible changes in repository format were back during the original 12-day period when Linus wrote Git, i.e. even before he published the code.

I think there was one backwards-incompatible change in one of the remote protocols many many years ago. However, in that case, the server will tell you that you have to upgrade your client and even which minimum version to upgrade to.

Of course, if you go far enough back you will arrive at a version that doesn't even know the current HTTP protocol at all.

But in all of the above cases, we are talking about clients that are several years out of date.


问:
Tools that can catch "fake coverage"?
Hypothetical scenario: codebase is exercised by unit tests run by a TeamCity build-bot, that also uses the built-in dotCover tool to provide coverage metrics. The build will fail if less than X% of the code is covered.

Unscrupulous developer running NCrunch (or a pre-tested commit in TC) sees that his next checkin will drop the coverage percentage below the threshold and break the build, because he didn't write good unit tests (TDD or otherwise). So, he writes a new test that runs some lines of code that NCrunch shows aren't covered, but makes no assertions about their behavior. Tests pass by default (because the executed code throws no exceptions), coverage stays above X%, and to find the problem, someone must discover the test, inspect it and see there are no assertions (or no meaningful assertions) made during its execution.

Since we currently don't have a code review process, and it would be detrimental to productivity to perform reviews prior to every commit, I want this behavior to break the build. If the test runner runs a method marked with a [Test] attribute (we're using NUnit) and, upon completion, sees that the code has made no calls to NUnit's Assert methods, nor thrown the ExpectedException, TC should raise Cain. Ideally, the tool would be smart enough to also discover that all assertions will be true by definition, such as Assert.AreEqual(1,1);, and fail the build in a similar way.

Is there something "off-the-shelf" that I can plug into TeamCity, or a way I can configure its built-in runners/coverage metrics to find this type of bad behavior, short of performing a custom static code analysis? Of course we'll find it eventually, but in our environment (small in-house dev team) there may only be one or two developers familiar with the full codebase of a given application, and so this blatant end run around test quality checks may not happen until the guy responsible is long gone and someone else takes over primary ownership of the codebase.

答:
IMHO If this is happening enough that you are looking for a tool you either:

need to reevaluate your policy (you are asking for tests over something that resists testing or the tests provide little value or over a branch that is too early in the process to always have things figured out far enough to write good test harnesses, dummys and mocks)

or reevaluate the makeup of your team (testing is appropriate here but your coworkers aren't very good / honest / whatever)

Personally I have experienced far more of the first case than the second case so I generally only examine code coverage when a feature branch is about to be merged back to the master/main.

There are many many more ways to defeat code coverage than there are tools to calculate it or enforce it so this is time that I would choose to spend elsewhere.

ContentLicense: CC BY-SA 3.0

Title: Tools that can catch "fake coverage"?


答:
Only a human is going to be able to tell the difference between a "good test" and a "tautology test".

Even if assertions are included in the test, what's to say they are meaningful? Is checking that the return value is not null enough? Or does the test need to check particular values of the result? Even if the right thing is tested, is the test itself written horribly/confusingly/unmaintainably? And how is an automated tool every going to catch this?

I've run a 30+ person project for years now, and we do code review on every task completion. A task may be multiple commits, but a task is almost always only a few days of work. There is no way that code review "slowed us down".

Title: Tools that can catch "fake coverage"?

Body:
Hypothetical scenario: codebase is exercised by unit tests run by a TeamCity build-bot, that also uses the built-in dotCover tool to provide coverage metrics. The build will fail if less than X% of the code is covered.

Unscrupulous developer running NCrunch (or a pre-tested commit in TC) sees that his next checkin will drop the coverage percentage below the threshold and break the build, because he didn't write good unit tests (TDD or otherwise). So, he writes a new test that runs some lines of code that NCrunch shows aren't covered, but makes no assertions about their behavior. Tests pass by default (because the executed code throws no exceptions), coverage stays above X%, and to find the problem, someone must discover the test, inspect it and see there are no assertions (or no meaningful assertions) made during its execution.

Since we currently don't have a code review process, and it would be detrimental to productivity to perform reviews prior to every commit, I want this behavior to break the build. If the test runner runs a method marked with a [Test] attribute (we're using NUnit) and, upon completion, sees that the code has made no calls to NUnit's Assert methods, nor thrown the ExpectedException, TC should raise Cain. Ideally, the tool would be smart enough to also discover that all assertions will be true by definition, such as Assert.AreEqual(1,1);, and fail the build in a similar way.

Is there something "off-the-shelf" that I can plug into TeamCity, or a way I can configure its built-in runners/coverage metrics to find this type of bad behavior, short of performing a custom static code analysis? Of course we'll find it eventually, but in our environment (small in-house dev team) there may only be one or two developers familiar with the full codebase of a given application, and so this blatant end run around test quality checks may not happen until the guy responsible is long gone and someone else takes over primary ownership of the codebase.


问:
Rewriting C# Formula Calculations in T-SQL
We have a 3-tier application with a C# client that connects to a C# web service via WCF and requests data from a SQL Server database.

One feature in our application is a user-created form app in which our customers setup forms that have fields.  The fields refer to values that can be imported, entered by the user, or calculated.  The calculations can be thought of as Operation / Value / Timeframe.  Each value referenced in a calculation might also be a calculated value.  (Care is taken to ensure circular calculations do not exist.)

For example, a user might setup a field that shows Cash Over / Short that subtracts the value Total to Account For and Total Accounted For.  These fields might in turn add up sales, credit card payments, cash totals, etc.  Changing Grocery Sales in the form UI would trigger a change that recalculates the Total to Account For, and that field's change triggers the Cash Over / Short field to recalculate itself.

Complicating the calculations are historical values.  Some calculations might be phrased in English like "Subtract Today's Totalizer Value from Yesterday's Totalizer Value".  Or, someone might simply set a Last Year Sales field to the value of Total Sales exactly 365 days ago.

All this calculation is done in the C# user interface.  The C# code builds dependency trees and sets up event handlers when values change.  Changing a value triggers an event, and calculations that depend on the changed value are recalculated.

We also have a recalculation engine that verifies the totals are correct before making permanent changes (i.e. before drafting someone's account, so the amounts better be correct).  This recalculation engine uses the same C# calculation engine across multiple threads.  This incurs penalties of reading from the database, creating the C# objects, performing calculations, and writing to the database.

The timeframe dependencies mean we really need to calculate in some kind of day order.  I could use some kind of cursor to move day-by-day, gather up all the data on each day, figure out the dependencies, join to historical values, but...

My question: how would you approach performing complex user-defined calculations in a set-based manner in SQL?  I don't see how to do this without RBAR operations on each calculated value.

答:
LINQ to SQL is an option, and here's a walkthrough that loosely does what you described.  However, it's essentially a row by row solution.

Entity Framework may also provide additional ways to solve your challenge.  This SO Question and this P.SE Question have some relevant information in comparing L2S and EF.

Another option to consider is a noSQL database like MongoDB or Cassandra or pick-your-flavor.  Queries against static data like your example of "Last Year's Sales" can be pretty quickly performed within an noSQL / non-relational database.

The challenge will be deciding where you handle each calculation.  Generally, complex calculations are best done in code since they aren't set operations.  Likewise, relational DBs can make short work of something that is essentially a set operation.  noSQL DBs provide a degree of a hybrid approach, but can require restructuring your data.  Unfortunately, you need to evaluate each calculation and identify what the optimal environment will be for processing.


问:
Do these specific tables need surrogate keys?

Background

I have this tables

```<code>+-------------------------+  +------------------------+
|Airport                  |  |Country                 |
|-------------------------|  |------------------------|
|airport_code string (PK) |  |country_code string (PK)|
|address string           |  |name string             |
|name  string             |  +------------------------+
+-------------------------+

+-------------------------+
|Currency                 |
|-------------------------|
|currency_code string (PK)|
|name string              |
+-------------------------+
</code>```

airport_code is the IATA (International Air Transport Association ) airport code, you can see them in your luggage tags when you travel by plane.

country_code is the ISO 3166-1 A3 standard country code, you can see them in the olympics.

currency_code is the IS0 417 standard 3-chars currency code, you can see them in international currency exchange display boards.

Questions

Are these natural PKs good enough ?

Is using world respected standards, which are accepted by whole industries good enough for PKs ?

Do this tables need surrogates no matter what ?

答:
While having surrogate keys on the fields is fine and there is nothing wrong with that something to consider might be the index page size itself.

Since this is a relational database you'll be doing a lot of joins and having a surrogate key of a numerical type might make it easier on the database to handle i.e. the index page size will be smaller and thus faster to search trough. If this is a small project it won't matter and you'll get by without any issues however the bigger the application gets the more you'll want to reduce bottlenecks.

Having a BIGINT, INT, SMALLINT, TINYINT or whatever integer-like data type might save you some trouble down the road.

Just my 2 cents

UPDATE:

Small project - used by a few, perhaps even a few dozen people. Small scale, demo project, project for personal use, something to add to a portfolio when presenting your skills with no experience, and the like.

Large project - used by thousands, tens of thousands, millions of users daily. Something you'd build for an national / international company with a huge user base.

Usually what happens is a select few of the records get selected often, and the server caches the results for fast access, but every now and then you need to access some less used record, at which point the server would have to dip into the index page. (in the above example with the airport names, people often fly domestic airlines, say Chichago -> Los Angeles, but how often do people fly from Boston -> Zimbabwe)

If VARCHAR is used that means the spacing is not uniform, unless the data is always the same lenght (at which point a CHAR value is more effective). This makes searching the index slower, and with the server already being busy handling thousands and thousands of queries per second now it has to waste time going trough a non-uniform index, and do the same thing again on the joins (which is slower than regular selects on an un-optimized table, take DW as example where there are as few joins as possible to speed up data retrieval). Also if you use UTF that can mess with the database engine as well (I've seen some cases).

Personally, from my own experience, a properly organized index can increase the speed of a join by ~70%, and doing a join on an integer column can speed up the join by as much as around ~25% (depending on the data). As the main tables start to grow and these tables get used on them, would you rather have an integer datatype occupy the column that has a few bytes vs having a VARCHAR / CHAR field that will occupy more space. It comes down to saving on disk space, increasing performance and the overall structure of a relational database.

Also, as James Snell mentioned:

Primary keys must also be immutable, something IATA airport codes are definitely not. They can be changed at the whim of the IATA.

So taking this into consideration, would you rather have to update 1 record that is bound to a number, vs having to update that one record plus all the records in the table on which you join to.


问:
65.000.000.000 tests to run
I was asked about how to run a suite of 65.000.000.000 tests and I wonder if it is normal to have a project with such a huge amount of tests.

Have you worked in projects with this characteristic?

答:
With 65 billion tests, it sounds like you're being asked to test all possible inputs. This is not useful--you'd essentially be testing that your processor functions correctly, not that your code is correct.

You should be testing equivalence classes instead. This will drastically reduce your range of test inputs.

Also consider whether you can subdivide your system into smaller pieces. Each piece will be easier to test in isolation, and then you can perform some integration tests which bring all the pieces together.

If you still want that reassurance that some of those input combinations work, perhaps you could try fuzz testing. You will get some of the benefits of testing lots of different inputs, but without running all 65 billion of them.

Title: 65.000.000.000 tests to run


问:
What is the advantage of using UI binder in GWT?
Mention the pros and cons of UIBinder in GWT.

I want to develop a big project. Is it flexible to use UIBinder for my project?

答:
UI Binder lets you write your display elements using a xml/html like language, and in a declarative way. This is generally cleaner than not using it and creating your display elements in Java code.

Also, if you work with designers, they will be much more comfortable working the UIBinder to modify the display of a page, rather than Java code. I would recommend using UIBinder if you can.


答:
If this is a real test suite, then you don't want to get anywhere near working on it.

The whole job of a tester is to strike a balance between testing thoroughly enough to be confident you've got the "right" results and writing few enough tests that they can be run in a reasonable amount of time.

Many tests can be abstracted into "equivalence classes", which means that rather than run 3 billion tests, you run 1 that gives you a reasonable level of confidence that all other tests in that equivalence class would run successfully, if you decided to waste the time running them.

You should tell whoever is thinking of running 65 billion tests that they need to do a better job abstracting tests into equivalence classes.

Title: 65.000.000.000 tests to run

Body:
I was asked about how to run a suite of 65.000.000.000 tests and I wonder if it is normal to have a project with such a huge amount of tests.

Have you worked in projects with this characteristic?


答:
Is this "normal"?, no.  Where "normal" is defined as the average or typical experience.  Can't say I've ever had to work on a project like that, but I have been on a project where one in every few million bits would get flipped.  Testing that one was ... a challenge.

Is it potentially required?  Well, that depends upon the guarantees and specifics of the project.  It's a bit incredulous to comprehend at first, but your question is light on specifics.

As others (MichaelT) have pointed out, the time to complete this task with serial testing makes this impractical.  So parallelization becomes your first consideration.  How many test systems can you throw at this problem, and what support do you have for collating the results of those multiple systems?

What guarantees do you have that the device or algorithm you're testing is being reliably replicated? Software is pretty reliable in replication, but hardware devices (especially first generation) can have manufacturing issues. A false test failure in that case could indicate either a bad algorithm or the device didn't assemble correctly.  Do you need to distinguish between those two cases?

You'll also need to consider how you're going to validate the testing systems themselves.  Presuming a legitimate reason for that many test cases, you're going to need a lot of automation.  That automation needs to be inspected to make sure it doesn't err in generating your test cases.  Spot checks for errors would truly be the equivalent of finding a needle in the haystack.

This arstechnica link may or may not shed some insight on your testing considerations.  GPU clusters are commonly used for brute-force cracking passwords.  The one cited in the article can can cycle through as many as 350 billion guesses per second, so that kind of puts your 65B tests in perspective.  It's likely a different domain, but it shows how approaching the task from different angles may yield a viable solution.

Title: 65.000.000.000 tests to run


答:
I don't think it is feasible to maintain 6.5e+10 tests it the first place, so running them may be moot. Even biggest projects, like Debian with all its packages, have only several hundred million SLOCs total.

But if you have to run a huge number of tests anyway, there are a few strategies.

Don't run them all. Most probably not every test depends on every code path. Define dependencies between subsystems and their tests, and between test suites, and you'll be able to only run unit tests relevant to a particular change, only the integration tests depending to these unit tests, etc.

Run them in parallel. With code base that huge, you probably have a massive build farm (back at JetBrains, a relatively small operation, we used to have 40-50 build agents running on the IDEA continuous build / integration farm alone). Since unit tests are independent, and integration tests can reuse already built code, tests are relatively easy to parallelize.

Stop running early. If you know that a particular test suite depends for its reasonable functioning on correctness of another test suite, you can cut the whole chain once you see one link fail.

Disclaimer: I'm not a professional testing engineer. Take the above with a grain of salt.

Title: 65.000.000.000 tests to run


答:
More than likely, you arrived at your figure of 65 billion tests by calculating all possible combinations of inputs into the system under test, or by computing the cyclomatic complexity and assuming a test must be written for each of these unique execution paths.

This is not how real tests are written, because as other posters and commenters have indicated, the technical power required to execute 65 billion tests is staggering. This would be like writing a test that exercises a method to add two integers by plugging in every possible permutation of two 32-bit values and checking the result. It's utter insanity. You have to draw the line and identify a subset of all possible test cases, which between them would ensure that the system will behave as expected throughout the range of inputs. For instance. you test adding a few "ordinary" numbers, you test a few negative-number scenarios, you test technical limits like overflow scenarios, and you test any scenarios that should result in error. As was mentioned, these various types of tests exercise "equivalence classes"; they allow you to take a representative sample of the possible inputs, along with any known "outliers", and say with an extremely high confidence that because these scenarios pass, all scenarios similar to these will pass.

Consider one of the basic code katas, the Roman Numeral Generator. The task, to be performed using TDD techniques in a "dojo" style, is to write a function that can accept any number from 1 to 3000 and produce the correct Roman numeral for that number value.

You don't solve this problem by writing 3000 unit tests, one at a time, and passing them in turn. That's lunacy; the exercise normally takes between one and two hours, and you'd be there for days testing each individual value. Instead, you get smart. You start with the simplest base case (1 == "I"), implement that using a "least-code" strategy (return "I";), and then look for how the code you have will behave incorrectly in another expected scenario (2 == "II"). Rinse and repeat; more than likely, you replaced your initial implementation with something that repeats the "I" character as often as necessary (like return new String('I',number);). That will obviously pass a test for III, so you don't bother; instead, you write the test for 4 == "IV", which you know the current implementation won't do correctly.

Or, in a more analytical style, you examine each conditional decision that is made by the code (or needs to be), and write a test designed to enter the code for each possible outcome of each decision. If you have 5 if statements (each having a true and false branch), each of them fully independent of the other, you code 10 tests, not 32. Each test will be designed to assert two things about a particular possible decision; first that the correct decision is made, and then that the code entered given that condition is correct. You don't code a test for each possible permutation of independent decisions. If the decisions are dependent, then you have to test more of them in combination, but there are fewer such combinations because some decisions are only ever made when another decision had a particular outcome.

Title: 65.000.000.000 tests to run


问:
VPS versus Shared Hosting
Is there any compelling reason a programmer would host on a shared platform versus just having a VPS account somewhere?</p>

答:
It's a simple cost + feature balance:

Shared - cheap, managed, less isolated, fewer choices

VPS - less cheap, sometimes less managed, more isolated, more choices, can be more work

You really need to determine how much you want to spend, how much you can responsibly manage yourself, and what features you need.

Other points:

Security is not inherently different between the two (either can be secure or insecure based on your actions, your host's setup, and the actions of others).

Unlimited things are never unlimited, so comparing shared hosting features to VPS features is misleading. If it's important, you want guarantees for bandwidth, storage, etc.

Both shared and VPS hosts offer different levels of management.  There are fully managed VPSs, for example, as well as mostly-unmanaged shared hosts.

Pricing of both shared and VPS hosts vary widely (as do features).

Bandwidth and uptime also vary widely between both types of hosts, look for 3rd party verification for any host you pick.

ContentLicense: CC BY-SA 2.5

Title: VPS versus Shared Hosting


问:
Session or request scope for account details
I have a (browser based) web application. On each page, I want to have a little label and link in a corner that displays the user's username and other account information along with a logout button. The information that will be displayed is immutable.

Should I store that account information in session attributes when a user logs in and forget about it or should I use a filter/interceptor and load it on each request in the request attributes?

答:
You could do both,

If your application is big, and you choose to load the user's account info and display it on the page, it will cost you an sql query per page, which is an overhead.

To escape the overhead of making same sql query per page, use sessions!


问:
Best Practice: Should error messages be handled by the API or by the App?
I am designing an application that interacts with a RESTful API.

When returning error messages like Unable to sign up user

Should the error message be generated by the app? or by the API? I am looking for best practices.

答:
Simply put an error page url in your configuration file (web.config if asp.net), that displays the error page in case if an error has occured.

Using the api? never heard of it, but if it is global enough to trigger a message on any error, then may be it is good enough..

Use the app's configuration to trigger a custome error. If you cant use your own code, but put it somewhere that responds to any request , no matter what type of request, otherwise you will have errors slipping by!


问:
How to test functions or the code inside $(document).ready() using Jasmine?
I have multiple functions and a lot of code inside $(document).ready(function()). I am using jasmine to test the functions inside the ready function as well as the code inside ready() but when the test cases inside describe are executed it is not able to access the code inside the ready function.

```<code>$(document).ready(function () {
    function testMe(){
        testVar = true;
    }
});
</code>```

Jasmine test suite

```<code>describe("test suite", function(){
    beforeEach(function () {
        testme = false
    });
    it("Test Alert Box Message For Change Modal", function() {
        expect(testme).toEqual(true);
    });
});
</code>```

Kindly suggest what approach needs to be taken for the above approach.

答:
What is inside the ready function is encapsulated in a separate scope from everything globally.

Put your test cases in the same scope to work.

There other approaches to be taken, is to do with closures, wrapping the anonymous function (in the ready event handler), putting it in a variable and then passing it to ready..
And then using that variable to pass to the test suites.
It can be complex to explain and implement to someone who doesnt know object oriented javascript..

```<code>var testMe;
$(document).ready(function () {
    testMe=function testMe(){
        testVar = true;
    }
});
</code>```

testMe is now defined. That created a closure.
I forgot the names of those techniques, I think i created hoisting..

anyway..an excellent book to read is Effective Javascript, to familiarize your self with good javascript techniques..It isnt like your usual programming language

Body:
What is inside the ready function is encapsulated in a separate scope from everything globally.

Put your test cases in the same scope to work.

There other approaches to be taken, is to do with closures, wrapping the anonymous function (in the ready event handler), putting it in a variable and then passing it to ready..
And then using that variable to pass to the test suites.
It can be complex to explain and implement to someone who doesnt know object oriented javascript..

var testMe;
$(document).ready(function () {
    testMe=function testMe(){
        testVar = true;
    }
});

testMe is now defined. That created a closure.
I forgot the names of those techniques, I think i created hoisting..

anyway..an excellent book to read is Effective Javascript, to familiarize your self with good javascript techniques..It isnt like your usual programming language


答: At the very least, the REST api needs to return an error code (e.g. 123) and/or an error key (e.g. "cannotRegister") which the application can then pick up in order to display a related message. This also helps when you're dealing with an application that is available in multiple languages. The app can then pick the related message from the appropriate resource bundle (translation). The API doesn't need to know in what language the user is viewing the application.</p>

Title: Best Practice: Should error messages be handled by the API or by the App?

Body:
I am designing an application that interacts with a RESTful API.

When returning error messages like Unable to sign up user

Should the error message be generated by the app? or by the API? I am looking for best practices.


问:
Should a surrogate key ever be exposed to a user?
Often in a table that has no natural key, it is still useful for users to be able to have a uniquely generated identifier.  If the table has a surrogate primary key (and in such a case you would certainly expect it to) should that key be exposed to the user or should another field be used for that purpose?

One reason not to expose the surrogate key is that now you can't do operations that preserve the relationship between records, but change the key values, such as certain kinds of deletion/re-insertion, many methods of copying data from one database to another, etc.

The main advantage of exposing the surrogate key is the simplicity of using a field you have anyway.

Under what circumstances is it better to directly expose the surrogate key to users?

答:
You need to be ready for any identifier that is exposed to users/customers needing to be changed, and changing the identity of a row in a database and propagating that change to all foreign keys is just asking to break data.

If the data has no natural business key, you can add an additional field for a "business identifier". This should be optimized for the processes it is used for. Telephone keypad entry means numeric only. Over the phone/verbal means avoid similar sounding symbols (B/D, M/N, etc). You can even autogenerate some easily memorable phrase ("green jelly").

The effect of this is that the business can later change how they want to refer to records, and the only data schema change is either adding a new column for that style of id or transform the ids already there. The change doesn't propagate through the entire database, and you still have one id (the surrogate) that is valid over time.

In short, I would avoid exposing surrogate keys to users. As the comments point out, surrogate keys should almost never change. Conversely, businesses want to change everything. If the surrogate key is exposed, it is just a matter of time before the business wants to change it.

As a side note, when I say "exposing" here, I mean to give the key to the user with the expectation that they use it directly (like calling in to support with their order number).


问:
When to bail on a proposed solution?
Here's a *hypothetical* issue.

There is a performance issue in the current release.  Its difficult to find the cause of this issue because the performance tests haven't been run in roughly 10+ releases (with anywhere from 10 - 100 changes per release).  My idea is to automate the process of running the performance tests in each release.  However, this automation took a bit longer than expected to get running.

My (again *hypothetical*) response to the automation taking too long would be to simply perform the tests manually, and then run through the results with a set of scripts that I'd already written.

In the end, this automation would be SOO beneficial to have, but it could take longer than is normal for a task to be completed.

Is that the right response to what could feel like a rapidly diminishing ROI on a proposed solution?

答:
I wonder about the relative terms you use in your question.  In particular, you said "rapidly diminishing ROI", which I'm not seeing within your question.  Difficult to find bugs can greatly tarnish a company's reputation.  So I wonder if you're looking at the full scope of this benefit equation.

You have two principle drivers here, Cost and Benefit.

Cost is amount of development time to automate the performance tests.

Benefit is the amount of improvement in client satisfaction from avoiding the next performance issue.

All you need to do is weigh those out for a few more hypotheticals.

How bad was the reaction from this last release?

Do you know for certain the performance tests would have caught the issue?

Lay out best, realistic, and worst case estimates for coding the automation.

If your worst case cost is justified by the benefit, then go with it.  If it's marginal, discuss it with your team and determine where the inflection point is at.

Title: When to bail on a proposed solution?


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
At my last job, "standards" would be a very strong term for what I was given by the guy who hired me.  Programming websites in ColdFusion and SQL, I was given coding requirements like:

Don't use includes. I like one big page

Always separate words in variable and column names with underscores (except isactive, firstname, etc.)

Never use abbreviations -- always write out firstname (he frequently wrote fname and so forth)

Don't use confusing names (like amount_charged and charge_amount, which measured differnt but related things)

Don't use DIVs, and use minimal CSS -- use nested tables instead (I found some six layers deep, once).

Don't cache any queries. Ever.

Going to use a variable on more than one page? Application scope.

Each page is its own try/catch block. We don't need/want a global error handler.

I started changing these as soon as he quit.


答:
I could now write an essay about how to do cost/benefit analysis of automation projects, but this image says more than I could ever write about this subject:

source: http://xkcd.com/1205/

Title: When to bail on a proposed solution?

Body:
Here's a *hypothetical* issue.

There is a performance issue in the current release.  Its difficult to find the cause of this issue because the performance tests haven't been run in roughly 10+ releases (with anywhere from 10 - 100 changes per release).  My idea is to automate the process of running the performance tests in each release.  However, this automation took a bit longer than expected to get running.

My (again *hypothetical*) response to the automation taking too long would be to simply perform the tests manually, and then run through the results with a set of scripts that I'd already written.

In the end, this automation would be SOO beneficial to have, but it could take longer than is normal for a task to be completed.

Is that the right response to what could feel like a rapidly diminishing ROI on a proposed solution?


问:
Building a tool to fix compiler errors automagically
When a program doesn't compile, error messages are sometimes esoteric. Often a simple Google search leading to a site like stack exchange solves the problem. Now why can't we automate this?

How about a Siri for coding? By Siri, I mean an intelligent personal assistant. Not talking about speech recognition here.

I wonder if there is anybody out there (startups/ research labs) building a cool product like this. It will cut down debugging time drastically.

答: It's been done, long ago.  The Cornell PL/C compiler for the PL/I language, auto-fixed any problems it found, with the goal of always producing a compilable and runnable program, no matter how little it resembled the original input.  Some of the changes were simple, and made good sense.  Others were not.  It was a common joke at the time to drop a deck of randomly-selected punched cards into PL/C and see what happened :-)


问:
Why is binary search,which needs sorted data, considered better than linear search?
I have always heard that linear search is a naive approach and binary search is better than it in performance due to better asymptotic complexity. But I never understood why is it better than linear search when sorting is required before binary search?

Linear search is O(n) and binary search is O(log n). That seems to be the basis of saying that binary search is better. But binary search requires sorting which is O(n log n) for the best algorithms. So binary search shouldn't be actually faster as it requires sorting.

I am reading CLRS in which the author implies that in insertion sort instead of using the naive linear search approach it is better to use binary search for finding the place where item has to be inserted.  In this case this seems to be justified as at each loop iteration there is a sorted list over which the binary search can be applied. But in the general case where there is no guarantee about the data set in which we need to search isn't using binary search actually worse than linear search due to sorting requirements?

Are there any practical considerations that I am overlooking which make binary search better than linear search? Or is binary search considered better than linear search without considering the computation time required for sorting?

答:
Imagine two phone books.

One phone book has the names in alphabetical order.  To find the entry you want, you open in the middle, check the entry, then move forward or backward depending on whether you overshot or undershot.

The other phone book has the names in random order.  To find the entry you want, you start at the beginning and continue until you find what you want.

Will the second book work in any reasonably sized city?


问:
What's the difference between "Add to home screen" safari HTML5 webapp vs HTML5 webapp wrapped in UIWebView?
Someone asked me this. The answer he gave was HTML5 in UIWebView can cache the app data so it can run offline. I thought the same thing can be achieved using safari add to home screen, no?

答:
Safari "add to home screen" simply puts a bookmark to the webpage on the home screen - that's not the same as saving the page onto the phone. Because of memory limitations on mobile devices, Safari (and other mobile browsers) limit how much they cache. Adding a bookmakr to the home screen will not make a page available offline.

Creating your own app which displays your data with UIWebView means that you can configure your own caching scheme within your app. Or you can just include the HTML5 data within the app when the get it from the store. Either way, you control the offline ability of the app.


答:
In layman's words:

Surrogates should be hidden from the user.

You should expose some other business candidate key to the user.

If no other candidate key exist you should show the PK. But in this case the PK is not considered a surrogate since it's not a substitute for other column.

Title: Should a surrogate key ever be exposed to a user?

Body:
Often in a table that has no natural key, it is still useful for users to be able to have a uniquely generated identifier.  If the table has a surrogate primary key (and in such a case you would certainly expect it to) should that key be exposed to the user or should another field be used for that purpose?

One reason not to expose the surrogate key is that now you can't do operations that preserve the relationship between records, but change the key values, such as certain kinds of deletion/re-insertion, many methods of copying data from one database to another, etc.

The main advantage of exposing the surrogate key is the simplicity of using a field you have anyway.

Under what circumstances is it better to directly expose the surrogate key to users?


问:
How can I return generated HTML and a response too?
My web application will use AJAX calls often and so I have set up some JavaScript to handle "messages" or "responses". These responses are returned (from my ASP.NET application) as JSON objects that act as feedback once a function is complete.

Suppose my responses have three basic elements.

Type (error, warning, info, success)

Title

Message

For example

Save unsuccessful

Your data was not saved because of XYZ.

Sometimes, however, I want my function to generate and return some HTML. That's easy enough, but what if I still want to return a message to the user (or some other JSON)?

Should I return the HTML as part of the JSON?

Should I only return one or the other?

Should I return HTML, then make another AJAX call for the response?

Should I return HTML and store the response in data- tags?

Can someone point me in the right direction?

答:
Keep your interface and implementation simple. Since you're using http request, you should take advantage of its features. For example, instead of creating new interface "type", you can use http status code.

If you use http status code, then on your javascript side, you can take that advantage too. For example, if you use jquery, it has handlers for your ajax calls which uses http status code as  a factor to decide if it should call error or success handler.

If you still need to return json & html, you have your interface returning data in both format based on http Accept header value set by the client when making ajax call. Then your code for displaying html doesn't need to know about the returned data format because it only gets what it needs, which html.


问:
License change of original source from Apache 2.0 to LGPL
About a year or so ago, I forked a project licensed under Apache 2.0 and made extensive changes and additions to the code, a good portion of which I contributed back freely to the community.

Recently, the code moderator changed the licensing to LGPLv3, and I wanted to find out if I was correct in my belief that this licensing change does not apply to the code I checked out more than a year ago, specifically not forcing me to comply to LGPL and leaving me free to do as I wish under Apache 2.0 as long as I do not "taint" my fork with new code from the original project that was written under the new licensing scheme.

Or am I mistaken?

答: The code moderator cannot retroactively force a new license on you for the original code that was written under the original license.</p>


问:
Drawing controls and sub controls unaware of their location in parent
Applications and operating systems have a ton of windows and controls, sub windows and sub controls. I've noticed its common to have sub controls have their coordinate systems reset to start at 0 making drawing much easier. However I'm not sure how that is done and how I'd be able to do that.

I'm going to be creating an application that does a lot of 2d drawing and includes things like my own implemented scrollbars and lots of controls that have sub controls. I want the coordinate system of sub controls to reset to 0 and I want the controls to have minimal knowledge of their location within parent controls, and parent parent controls, ect.

The only thing I can think of is to pass in transform coordinates and have each sub control when drawing add the x and y transform coordinates to their objects being drawn so it gets transformed to the correct location. That quickly gets very tiring when I know there are better ways.

I'm not sure what I'll be using, weather it will be GDI+, OpenGL, or Direct2D. I'm just looking for general information on how this done so sub controls can draw at x and y 0 and it pops up at whatever location the actual control is located at.

答:
I did this once before, at the time I even implemented the drawing algorithms. About the way it works in Windows at least, it requires a handle for a device context (DC), that handle identifies an unit in the screen, a window, a control, etc.

With that handle you have an extra layer that converts relative positions to an actual position in the screen, and that also has the clipping area, so you don't draw outside of it, and other stuff. The transform matrix you refer to kinda exists, it's called viewport (I can not say if it's implemented like that). Each time you are going to paint a control you request the DC and call drawing functions to work with that DC.

If you want to implement all of that by yourself you may still use standard windows and use the device context provided by them. Or you may simulate each unit in the window, and create that layer that will handle the drawing operations. In this case you also need to distribute events to the target control, but you will require the coordinates of the control.


问:
What class of problem is this, and what math do I need to know to solve it?
Mushroom cultivation requires fairly precise chemical composition of substrate (a.k.a. growing medium). Let's pretend we're growing shitakes and that this is the required composition of their substrate:

```<code>Nitrogen | Benzene | Toluene | Dioxygen Diflouride
5%       | 5%      | 10%     | 80%
</code>```

We want to create an appropriate substrate from materials we have on hand which we know the chemical composition of.

```<code>Material | Nitrogen | Benzene | Toluene | Dioxygen Diflouride
apples   | 5%       | 0%      | 5%      | 90%
oranges  | 20%      | 20%     | 50%     | 10%
Etc...
</code>```

How does one calculate this?  It reminds me of solving matrices in high school.  Is this something that can be done with matrices?  What is this problem called?  What do I need to know to solve it?

答:
This is called Linear Programming. It is NP-Hard for integer constraints but there are methods of dealing with this, see Jeff Erickson's notes on the subject. The most common method is know as the Simplex Algorithm.

Basically you're finding the vertices of shapes formed geometrically by the linear equations representing your constraints. You proceed till you find the optimal one. In this case, the ratio of needed substrate components.


问:
How to write unit tests for utility programs
I am working on a C# console application that loads the data from a third party and bulk inserts into tables. Basically the code consists of a static method with logging statements. In these scenarios, how does one write the unit test cases?

Example code

```<code>void Main(string[] args)
{
    // for loop here to read config from XML file

    // initialize third party library
    ReportLib objLib = new ReportLib();

    DataTable dt = objLib.Refresh("test");

    //call SQL bulk copy
    DBHelper.BulkCopy(dt, dictmappings, destTblName);//dbhelper is static class

}
</code>```

答:
Move all of your code that actually does the work into a stand alone library. Break it out into small chunks and write a test for each chunk. If you can look at a block of code and say "this code does (insert action) and..." then it needs to be two or more separate methods or classes. Write your data access layer in such a way that you can write mock classes to pass in fake data to your logic when testing.

If you structure your application in logic layers, then you can easily fake out the parts you don't care about when testing a single piece of code.


答:
use a mock data source, mock data interface, and mock log.  If your code just reads in data and calls someone else's methods, that's what your unit test.

Feel free to use your unit test framework to test the whole process if possible, but that may be more of an integration test.

Title: How to write unit tests for utility programs

Body:
I am working on a C# console application that loads the data from a third party and bulk inserts into tables. Basically the code consists of a static method with logging statements. In these scenarios, how does one write the unit test cases?

Example code

```<code>void Main(string[] args)
{
    // for loop here to read config from XML file

    // initialize third party library
    ReportLib objLib = new ReportLib();

    DataTable dt = objLib.Refresh("test");

    //call SQL bulk copy
    DBHelper.BulkCopy(dt, dictmappings, destTblName);//dbhelper is static class

}
</code>```


问:
What is the optimal algorithm for estimating number of lines of text in a file?
Given a file > 5Gb, simply with lines like Apache's access.log.

I need to get number of lines.

Any constructions like

```<code>file(filename).read().counter('\n')
</code>```

would read all of the file and it would take a very long time.

On the other hand, e.g.

```<code>os.stat(filename).st_size
</code>```

works very fast.

It is possible to get at least an estimate for the number of lines, by the size of first lines in bytes and total size of the file.

Is there a more accurate way?

答:
Scan a representative sample of lines (say, 100) for the average line length, then take the file's total length and divide by said average.

If the lines are highly irregular, line count may be less useful than file size as a metric.  If the lives are highly regular and complex, parsing into a relational table may be useful.  (if it's highly regular and simple, line-length will be accurate.)

If this is a request you get often, consider adjusting the log file to include a alphanumeric counter, allowing you to just find and parse the last and first row's values.

If this is a one-time ad-hoc operation, just count \ns.

If at all possible, reduce log file size.

ContentLicense: CC BY-SA 4.0


答:
If I understand your question, you want to be able to ESTIMATE the number of lines in a file, without having to iterate through file. A few things spring to mind:

ESTIMATION based on file size
Estimation always assumes a trade off: a reasonable approximation with less work is better than an absolute value with more work. I like your idea of establishing an average line size; say that your files generally follow the same pattern (for example, {x, y, z} coordinates from some experiment), then it would be reasonable to assume that a file might be made up of:

```<code>HEADER
{x, y, z}(1),
{x, y, z}(2),
...
{x, y, z}(n)
FOOTER
</code>```

If the HEADER and FOOTER are of the same template in all files, then you can almost disregard them as constants. Which means, you are left with a file size that is dependent on the number of lines of {x, y, z}. You could make some assumption (based on observation) of the average size of these lines and then make your estimation from there. There is no reason that this scenario couldn't be adapted to any situation where the file follows a particular format (of course if the file doesn't have a regular format then it is going to be tough).

Alternative: put the number of lines into the HEADER
Using Python's ability to iterate over a file, you could calculate the number of lines once, and then you could query this value as often as you like (think of it like sorting an array once, and then doing a binary search over it many times). If you regularly need to know how many lines are in a file, this could be a reasonable, and accurate way to go about it.

In Python, you can count the number of lines without having to load the entire file into memory:

```<code>number_lines = sum(1 for line in open(my_file))
</code>```

Using a generator like this is also optimised in Python, so it is as fast as Python will get :)

Title: What is the optimal algorithm for estimating number of lines of text in a file?

Body:
Given a file > 5Gb, simply with lines like Apache's access.log.

I need to get number of lines.

Any constructions like

```<code>file(filename).read().counter('\n')
</code>```

would read all of the file and it would take a very long time.

On the other hand, e.g.

```<code>os.stat(filename).st_size
</code>```

works very fast.

It is possible to get at least an estimate for the number of lines, by the size of first lines in bytes and total size of the file.

Is there a more accurate way?

Body:
If I understand your question, you want to be able to ESTIMATE the number of lines in a file, without having to iterate through file. A few things spring to mind:

ESTIMATION based on file size
Estimation always assumes a trade off: a reasonable approximation with less work is better than an absolute value with more work. I like your idea of establishing an average line size; say that your files generally follow the same pattern (for example, {x, y, z} coordinates from some experiment), then it would be reasonable to assume that a file might be made up of:

HEADER
{x, y, z}(1),
{x, y, z}(2),
...
{x, y, z}(n)
FOOTER

If the HEADER and FOOTER are of the same template in all files, then you can almost disregard them as constants. Which means, you are left with a file size that is dependent on the number of lines of {x, y, z}. You could make some assumption (based on observation) of the average size of these lines and then make your estimation from there. There is no reason that this scenario couldn't be adapted to any situation where the file follows a particular format (of course if the file doesn't have a regular format then it is going to be tough).

Alternative: put the number of lines into the HEADER
Using Python's ability to iterate over a file, you could calculate the number of lines once, and then you could query this value as often as you like (think of it like sorting an array once, and then doing a binary search over it many times). If you regularly need to know how many lines are in a file, this could be a reasonable, and accurate way to go about it.

In Python, you can count the number of lines without having to load the entire file into memory:

number_lines = sum(1 for line in open(my_file))

Using a generator like this is also optimised in Python, so it is as fast as Python will get :)


答:
you should ONLY expose a field to a user that provides useful information to the user, either directly or in reporting defects to you.

conversely, you should ALWAYS expose "surrogate primary keys" when they are the principal means of identifying a record (simple or complex) for an interaction the user performs.


答:
In some cases, surrogate keys are expected and make sense to users. My favorite example is "order number". Order number isn't really a natural key: a natural key might be timestamp plus user, or maybe more than that if you expect users to generate more than one order within the granularity of your timestamp.

Nonetheless, users understand and expect the convenience of an order number.  There is no harm, and lots of value, if you let users know about them.

On the other hand, some surrogate keys make no sense to a user.  Sure, my health insurance company has some surrogate key that identifies me based on my member id, date of birth, carrier, etc, but I don't care about that, I care about the info on my card (which often includes ids based on my employer and are not unique across the universe... Hence the surrogate key at the insurance company).


问:
How is programming affected by spatial aptitude?

Background

The longer I work on a project, the less clear it becomes. It's like I cannot seperate various classes/objects anymore in my head. Everything starts mixing up, and it's extremely hard to take it all apart again. I start putting functions in classes where they really don't belong, and make silly mistakes such as writing code that I later find was 100% obsolete; things are no longer clearly mappable in my head. It isn't until I take a step back for several hours (or days sometimes!) that I can actually see what's going on again, and be productive.

I usually try to fight through this, I am so passionate about coding that I wouldn't for the life of me know what else I could be doing. This is when stuff can get really weird, I get so up in my head that I sort of lose touch with reality (to some extent) in that various actions, such as pouring a glass of water, no longer happen on a concious level. It happens on auto pilot, during which pretty much all of my concious concentration (is that even a thing?) is devoted to borderline pointless problem solving (trying to seperate elements of code). It feels like a losing battle.

So I took an IQ test a while ago (Wechsler Adult Intelligence Scale I believe it was) and it turned out my Spatial Aptitude was quite low. I still got a decent total score, just above average, so I won't have to poke things with a stick for a living, but I am a little worried that this is such a handicap when writing/engineering computer programs that I won't ever be able to do it seriously or professionally.

Question

I am very much interested in what other people think of this...

Could a low spatial aptitude be the cause of the above described problems?

How is programming affected by spatial aptitude?

Maybe I should be looking more along the lines of ADD or something similar, because I did get diagnosed with ADD at the age of 17 (5 years ago) but the medicine I received didn't seem to affect me that much so I never took it all that serious.

As far as I know people are born with low/med/high spatial aptitude, so I think it's interesting to find out if the more fortunate are better programmers by birth right.

答:
Ech... this deserves more than a comment.

"I usually try to fight through this"

Stop fighting. You're getting things twisted and making mistakes right? You may well have some unique issues but the manner in which your brain is rebelling is normal for anybody that's spent too long hyper-focused on a problem. When I was younger, way too much of my day was spent thinking at that highly conscious level and I wasn't doing myself any favors. Your problem isn't that you're not trying hard enough it's that you don't know when to quit.

I finally learned to appreciate the value of putting things on the back burner when I figured out that the only way to get to sleep at a reasonable hour was to will myself to think about absolutely nothing and was shocked to discover that within 10 minutes or so I'd fall asleep whereas normally I'd be thinking-thinking-thinking for at least a couple hours before crashing from mental exhaustion.

From there I found it easier to learn to recognize when I was putting way too much conscious thought into a problem and to just let it go for a while. I was surprised to discover how much this actually contributes to helping you work out a problem.

I recommend the following:

When something is getting twisted in your head and you don't have the luxury of being able to take break and go for a walk or something, try to switch gears and focus on a very different piece of the problem for a while.

Never skip lunch and always leave the office. Give yourself until you get to the door to come to a stopping point or just drop it. Anything worth keeping in your head will be there when you come back to it and all the stuff you didn't need will be gone. The more you discover this, the easier it gets.

Regularly will yourself to think about nothing throughout the day. Even if it's just for a minute while you get yourself that glass of water.

Try to leverage OOP or any more problem-domain-centric architectural approach to think about less. Who are the actors in your code at the highest level? They shouldn't have complex relationships with each other. That allows you to focus more on one piece of the problem at a time.

Some Coding Principles That Might Help

DRY is to general coding practice as "Stealing is wrong" can be applied to almost all ethics/morality. There are very rare exceptions. Keep them very rare.

If you're in the habit of over-solving for problems you might face eventually in the future, knock it off. Nothing is more future-proof or "scalable" than code that is no more complex than it needs to be. "Enterprise" is lies.

Complex patterns often promise long bullet point lists of rewards. There are only 3 things that should matter most of the time. It's easy to read. It's easy to re-use. It's easy to modify. Think in terms of minimum use of force that a martial artist might and apply that principle to complexity. Exactly enough to solve the problem is ideal.

Write your interface first. And no I don't mean the C#/Java constructs which should be used only when needed, I mean the API of your objects. What does the class/object need to do? Write those empty methods and give them arg names. Don't fill in the blanks until you're completely done. It's okay to make tweaks later but once you've established what it needs to be able to do, you can focus on how each thing, one at a time, needs to be done. The reason you may find yourself trying to hold as much in your head as you often do may be because you've got implementation happening for problems that should have been solved long before you got to a given stage of a process. Got lots of is and has methods? That's what I'm talking about. The thing that knew what it was or had should have solved the problem before it got to where you're invoking those methods.

Diagnosis?

I think the spatial awareness concern has been well-covered. Whatever you decide on that front, I'd give the ADD thing a revisit, especially if you were reluctant about it the first time. This definitely sounds a lot like hyper-focus gone to an extreme. Ultimately, let that love of coding drive you to find ways to mitigate these issues and I expect your career will turn out just fine.


问:
Why use protocol, not call the method directly?
I was asked this question in an interview. For eg: UITableviewDelegate protocol has CellForRowAtIndexpath. Why make it a delegate method in a protocol not a method in the UITableView class and call it directly?

答: Protocols are used to define a set of methods to interact with regardless of the type of the object implementing them. It allows you to easily interchange external resources that the view interacts with and reduces the overall coupling of your code. This is in contrast to directly calling the resource with knowledge of its type. </p>


问:
Is the List interface a leaky abstraction?
If I have a variable containing a List it could contain objects of a lot of different types e.g. ArrayList or LinkedList. The difference between a LinkedList and an ArrayList is pretty big. The big O behavior of the methods differs greatly. For example sorting the List and then using it to do binary searches is perfectly ok for an ArrayList but would not make sense with a LinkedList.

答: You are correct, a List is a leaky abstraction. The STL uses the idea of concepts to model this specific problem. To use your example, an ArrayList models a Random Access Iterator while a LinkedList models a Forward Iterator. Different concepts have different performance requirements, which make them appropriate for different algorithms.


问:
Coding convention regarding the usage of underscores
There seems to be divided opinion on this subject, and I wanted to get people's insights on whether they've found using underscore prefixes and suffixes to be helpful with coding or not.

You know, code like this:

```<code>class MyClass
{
  private int _someInteger;  // some advocate local vars prefixed with underscore

  private void DoSomething(bool someBoolParam_) {...} // and params suffixed_...
}
</code>```

答:
From a c/c++ point of view

Prefix underscores are only safe with lower case variables, and even then double underscores are reserved

Suffix underscores are always safe, but lead to very ugly constructions like member_->pointer or member_[3]


答:
My C# team use underscore prefix for private members, as it works very well with Intellisense because while coding you can type underscore and filter out everything but private members.

For the parameter suffix, I have never seen that style in C#. In C#, parameter names are a part of public visibility so suffix will be visible to class consumer as well. Discriminating style between the naming convention of public and private method's parameters will make it more confusing.

In .NET Framework, Camel-casing is recommended for parameter name.

Title: Coding convention regarding the usage of underscores

Body:
There seems to be divided opinion on this subject, and I wanted to get people's insights on whether they've found using underscore prefixes and suffixes to be helpful with coding or not.

You know, code like this:

```<code>class MyClass
{
  private int _someInteger;  // some advocate local vars prefixed with underscore

  private void DoSomething(bool someBoolParam_) {...} // and params suffixed_...
}
</code>```


问:
How are GPL-compatible licenses like MIT usable in GPL programs without being subject to the copyleft provision?
I'm currently examining the possibilities and implications of linking against a GPL library for an application in a commercial context.

From what I've understood of the GPL, as long as the application is used internally there is no obligation to release its code (even if a copy is moved to a controlled subsidiary).

What I don't understand is the following point from the FAQ :

If a library is released under the GPL (not the LGPL), does that mean that any software which uses it has to be under the GPL or a GPL-compatible license?
Yes, because the software as it is actually run includes the library.

If I take a look at the GPL-compatible licenses, some of them (like the boost one) don't seem to impose the release of the code. Using it would create a situation where you could be compliant with the GPL licence without having to respect its obligation of making your code public (which doesn't seem very credible).

(NB : there are components in Adobe Photoshop licensed under boost and I don't think the code is available on demand)

The most reasonable explication would be that I'm missing something... Could you please tell me where I made a mistake ?

答:
By "GPL-compatible", they mean, a license that does not conflict with the GPL.  A less restrictive license, like the Boost license, is "compatible" with the GPL because it doesn't restrict users of the code from doing anything that the GPL would allow a user to do.  That is, the Boost license allows people to copy freely, which is what the GPL requires people are allowed.

An example of a license that is not "compatible" would be a license that required a fee to the original authors for users to distribute copies.  Since the GPL explicitly permits both free and paid distribution, this more restrictive license would not be compatible.

In other words, the GPL says "You must allow $A, $B and $C".  Any license that allows $A, $B, $C and also $D and $E is compatible.  A license that allowed $A and $B but not $C would not be.


答:
I hate noise in code that merely restates what is or should be obvious.  Silent noise like leading or trailing underscores is annoying.  Noise that destroys readability, like 'm_x' or 'xParam' or 'getX' is worse.

If you have so many variables in scope that you can't remember which are local and which are class members, you have too many variables in scope.  Either the method or the class should be divided.  Probably both.


问:
Will high reputation in Stack Overflow help to get a good job?
In a post, Joel Spolsky mentioned that 5 digit Stack Overflow reputation can help you to earn a job paying $100k+. How much of that is real?

Would anyone like to share their success in getting a high paid job by virtue of their reputations on Stack Exchange sites?

I read somewhere that, a person got an interview offer from Google because a recruiter found his Stack Overflow reputation to be impressive. Anyone else with similar stories?

答:
It's not a case of direct causation. That is, having a high reputation does not lead to a high-paying job. Being intelligent, articulate, passionate and knowledgable lead to a high-paying job. It's just that those qualities also lead to a (generally) higher reputation on Stack Overflow as well. So you shouldn't be aiming for a high reputation score. You should be aiming to be intelligent, articulate, passionate and knowledgeable.

A higher reputation will just be a bonus.

Edit: I just found the post where Joel says that. He's saying he would hire someone with a 5 digit reputation on Stack Overflow, not that you'd be able to get any $100k+ job with a 5 digit reputation. Also, he's not saying that he wouldn't look at the actual content of your profile, so if you've just posted hundreds of junk questions in the hopes of artificially raising your score, it's not going to help you. Basically, he's using your reputation score as an indication of those qualities I mentioned above.


答:
I'm of the opinion that style conventions should only be relied on to make the nature of a thing clear when naming well and applying the principle of least astonishment isn't quite enough.

So in JavaScript for instance capitalizations helps us with the following:

```<code>function plainOlFunction(){...
function ClassLikeConstructor(){...
</code>```

I consider that reasonable usage of a convention because functions can be used as class-like construct that builds instances or methods. Knowing the intent right off the bat is helpful.

Likewise in Java, C#, and I assume C++ classes get capitalized so we know the difference between:

```<code>SomeClass.someStaticMethod();
someInstance.someInstanceMethod();
</code>```

The reason I'm shy about excess style conventions, however, is that a lot of devs take them as license to be lazy about naming. I've worked under the guy whose parameters were all demarcated by p_ with no name after the p_ exceeding more than 4 characters. And his funcs started with f_, etc... Reading his code could be Hell. (hard to give the guy a nasty code review though since he also started the company)

So why _somePrivateField? If you're in the TransactionManager class, it should be pretty obvious that transactions is going to be a private field where all the transactions are stashed. It might be a local var or a param but usage and context should make that pretty clear.

Why someParam_? You should really know what the params of the function you're dealing with are unless somebody's gone and put way too many to easily remember (more than 4 is pushing it IMO). So in that case the necessity of param identification is really just an enabler of excess param use where data structures probably should have come into play or there needed to be more than one method.

So this?

```<code>function screwTheNextGuy(
    p_ew,
    p_bleah,
    p_yuck,
    p_ick,
    p_why,
    p_RUcRius,
    p_ugh,
    p_drlord,
    p_noob,
    p_nomore,
    p_coderage
){...
</code>```

or this?

```<code>function makeTheNextGuyHappy( relatedSetOfValues, anotherSetOfValues ){...
</code>```

Another common convention I disagree with is separating methods from non-methods somehow. Why do we need that when spoken language allows us to distinguish noun from verb? Do we need a hint to know if it's public or private or should that again be fairly obvious from the perspective of anything you wouldn't need to expose being private?

More specifically on the subject of underscores, important things to check for are the conventions of whatever language you're in because a lot exist. Single underscore prefix is popular for private vars but also for an include-like file and the same often applies to an object representing that file. I would generally never touch double-underscores for common usage since they represent magic vars, constants, reserved names, do-not-touch thingies and god knows what else typically. Mostly I use them as separators to indicate a style convention in the first place. For instance, that I mean $_jQueryObject rather than $phpDevWritingJavaScriptVarNames. So yes like that silly p_ but with a real name on the right of it.

The post-param underscore is definitely kind of odd. We read left to right so that would actually be fairly easy to miss on a quick scan. I wouldn't use that if I thought a style convention was needed.

As a general rule I think it's best to use style conventions sparingly and to make sure that when you establish conventions that you're thinking about the next guy as much as yourself because nobody should have to remember what p_fg and p_deo were supposed to be at line 500 of an enormous function with a dozen parameters. That they're obviously parameters isn't half as helpful as getting an idea of what values they hold.

Body:
I'm of the opinion that style conventions should only be relied on to make the nature of a thing clear when naming well and applying the principle of least astonishment isn't quite enough.

So in JavaScript for instance capitalizations helps us with the following:

function plainOlFunction(){...
function ClassLikeConstructor(){...

I consider that reasonable usage of a convention because functions can be used as class-like construct that builds instances or methods. Knowing the intent right off the bat is helpful.

Likewise in Java, C#, and I assume C++ classes get capitalized so we know the difference between:

SomeClass.someStaticMethod();
someInstance.someInstanceMethod();

The reason I'm shy about excess style conventions, however, is that a lot of devs take them as license to be lazy about naming. I've worked under the guy whose parameters were all demarcated by p_ with no name after the p_ exceeding more than 4 characters. And his funcs started with f_, etc... Reading his code could be Hell. (hard to give the guy a nasty code review though since he also started the company)

So why _somePrivateField? If you're in the TransactionManager class, it should be pretty obvious that transactions is going to be a private field where all the transactions are stashed. It might be a local var or a param but usage and context should make that pretty clear.

Why someParam_? You should really know what the params of the function you're dealing with are unless somebody's gone and put way too many to easily remember (more than 4 is pushing it IMO). So in that case the necessity of param identification is really just an enabler of excess param use where data structures probably should have come into play or there needed to be more than one method.

So this?

function screwTheNextGuy(
    p_ew,
    p_bleah,
    p_yuck,
    p_ick,
    p_why,
    p_RUcRius,
    p_ugh,
    p_drlord,
    p_noob,
    p_nomore,
    p_coderage
){...

or this?

function makeTheNextGuyHappy( relatedSetOfValues, anotherSetOfValues ){...

Another common convention I disagree with is separating methods from non-methods somehow. Why do we need that when spoken language allows us to distinguish noun from verb? Do we need a hint to know if it's public or private or should that again be fairly obvious from the perspective of anything you wouldn't need to expose being private?

More specifically on the subject of underscores, important things to check for are the conventions of whatever language you're in because a lot exist. Single underscore prefix is popular for private vars but also for an include-like file and the same often applies to an object representing that file. I would generally never touch double-underscores for common usage since they represent magic vars, constants, reserved names, do-not-touch thingies and god knows what else typically. Mostly I use them as separators to indicate a style convention in the first place. For instance, that I mean $_jQueryObject rather than $phpDevWritingJavaScriptVarNames. So yes like that silly p_ but with a real name on the right of it.

The post-param underscore is definitely kind of odd. We read left to right so that would actually be fairly easy to miss on a quick scan. I wouldn't use that if I thought a style convention was needed.

As a general rule I think it's best to use style conventions sparingly and to make sure that when you establish conventions that you're thinking about the next guy as much as yourself because nobody should have to remember what p_fg and p_deo were supposed to be at line 500 of an enormous function with a dozen parameters. That they're obviously parameters isn't half as helpful as getting an idea of what values they hold.


问:
Should I split a Python class with many methods into multiple classes?
I have a class that will end up having more than ~30 methods. They all make sense to be part of the same class because they require access to the same data.

However, does it make any sense to split up a large class into several smaller abstract classes (by functionality, type, use, etc.) and have the main class extend (i.e. multiple inheritance) from all the smaller classes?

答:
No.

If you create several different classes and inherit them all in a single class you've haven't really improved the situation. You've just one class which is pretending to be a whole bunch of classes. You've made the implementation a lot more complicated and you haven't actually separated the pieces at all. If A inherits from B and C, then A is as complicated as B and C.

Having more than 30 methods does suggest it could benefit from being split up. Maybe there is a clever way to split it up. Sometimes you just can't, and in that case I do recommend have a large class. But often there are clever ways to break the object into several objects.

OwnerDisplayName: Jace Browning


答:
Actually, given your case is really that small and simple as it looks like in your example code, I would probably omit any unit test and write an automated integration or system test instead.

Here is my outline of such a test:

provide a fixed XML config file as part of your test suite

clear the destination table in your test database

run your program (either as a separate process, or by moving the contents of your Main function into a separate function in a separate DLL you can easily reference and call from your test DLL)

check if the destination table now has the expected contents

You can use a tool like NUnit for such a kind of test, too, like for "real" unit tests (that's why people sometimes call these kind of tests incorrectly unit tests, too).


问:
Why Java does not allow function definitions to be present outside of the class?
Unlike C++, in Java, we cannot have just function declarations in the class and definitions outside of the class. Why is it so?

Is it to emphasize that a single file in Java should contain only one class and nothing else?

答:
I think part of it is that Java is very much a protectionist language that concerns itself with usage on large teams. Classes can't be overwritten or redefined. You have 4 levels of access modifiers that define very specifically how methods can and can't be used. Everything is strong/statically typed to protect devs from type mismatch hijinx caused by others or themselves. Having classes and functions as your smallest units makes it a lot easier to reinvent the paradigm of how to go about architecting an app.

Compare to JavaScript where dual-purposed noun/verb first-class functions rain down and get passed around like candy from a busted-open pinata, the class-equivalent function constructor can have its prototype altered adding new properties or changing old ones for instances that have already been created at any time, absolutely nothing stops you from replacing any construct with your own version of it, there's like 5 types and they auto-convert and auto-evaluate under different circumstances and you can attach new properties to damn near anything:

```<code>function nounAndVerb(){
}
nounAndVerb.newProperty = 'egads!';
</code>```

Ultimately it's about niches and markets. JavaScript is about as appropriate and disastrous in the hands of 100 (many of which will likely be mediocre) devs as Java once was in the hands of small groups of devs trying to write web UI with it. When you're working with 100 devs the last thing you want is one guy reinventing the damned paradigm. When you're working with UI or rapid development is a more critical concern, the last thing you want is to be roadblocked on doing relatively simple things quickly simply because it would be easy to do them very stupidly if you aren't careful.

At the end of the day though, they're both popular general use languages so there is a bit of a philosophical argument there. My biggest personal beef with Java and C# is that I've never seen or worked with a legacy codebase where the majority of the devs seemed to have understood the value of basic OOP. When you come into the game having to wrap everything in a class, perhaps it's just easier to assume you're doing OOP rather than function spaghetti disguised as massive chains of 3-5 line classes.

That said, there's nothing more awful than JavaScript written by somebody who knows only enough to be dangerous and isn't afraid to show it off. And I think that's the general idea. That guy supposedly has to play by roughly the same rules in Java. I would argue that the bastard will always find a way though.

Body:
I think part of it is that Java is very much a protectionist language that concerns itself with usage on large teams. Classes can't be overwritten or redefined. You have 4 levels of access modifiers that define very specifically how methods can and can't be used. Everything is strong/statically typed to protect devs from type mismatch hijinx caused by others or themselves. Having classes and functions as your smallest units makes it a lot easier to reinvent the paradigm of how to go about architecting an app.

Compare to JavaScript where dual-purposed noun/verb first-class functions rain down and get passed around like candy from a busted-open pinata, the class-equivalent function constructor can have its prototype altered adding new properties or changing old ones for instances that have already been created at any time, absolutely nothing stops you from replacing any construct with your own version of it, there's like 5 types and they auto-convert and auto-evaluate under different circumstances and you can attach new properties to damn near anything:

function nounAndVerb(){
}
nounAndVerb.newProperty = 'egads!';

Ultimately it's about niches and markets. JavaScript is about as appropriate and disastrous in the hands of 100 (many of which will likely be mediocre) devs as Java once was in the hands of small groups of devs trying to write web UI with it. When you're working with 100 devs the last thing you want is one guy reinventing the damned paradigm. When you're working with UI or rapid development is a more critical concern, the last thing you want is to be roadblocked on doing relatively simple things quickly simply because it would be easy to do them very stupidly if you aren't careful.

At the end of the day though, they're both popular general use languages so there is a bit of a philosophical argument there. My biggest personal beef with Java and C# is that I've never seen or worked with a legacy codebase where the majority of the devs seemed to have understood the value of basic OOP. When you come into the game having to wrap everything in a class, perhaps it's just easier to assume you're doing OOP rather than function spaghetti disguised as massive chains of 3-5 line classes.

That said, there's nothing more awful than JavaScript written by somebody who knows only enough to be dangerous and isn't afraid to show it off. And I think that's the general idea. That guy supposedly has to play by roughly the same rules in Java. I would argue that the bastard will always find a way though.


问:
When to use interfaces (unit testing, IoC?)
I suspect I've made a schoolboy error here, and am looking for clarification. A lot of the classes in my solution (C#) - dare I say the majority - I've ended up writing a corresponding interface for. E.g. an "ICalculator" interface and a "Calculator" class that implements it, even though I'm never likely to replace that calculator with a different implementation. Also, most of these classes reside in the same project as their dependencies - they really only need to be internal, but have ended up being public as a side-effect of implementing their respective interfaces.

I think this practice of creating interfaces for everything stemmed from a few falsehoods:-

1) I originally thought that an interface was necessary to create unit test mocks (I'm using Moq), but I've since discovered that a class can be mocked if its members are virtual, and it has a parameterless constructor (correct me if I'm wrong).

2) I originally thought an interface was necessary to register a class with the IoC framework (Castle Windsor), e.g.

```<code>Container.Register(Component.For<ICalculator>().ImplementedBy<Calculator>()...
</code>```

when in fact I could just register the concrete type against itself:

```<code>Container.Register(Component.For<Calculator>().ImplementedBy<Calculator>()...
</code>```

3) Using interfaces, e.g. constructor parameters for dependency injection, results in "loose coupling".

So have I gone mad with interfaces?! I'm aware of the scenarios where you would "normally" use an interface, e.g. exposing a public API, or for things like "pluggable" functionality. My solution has a small number of classes that fit such use cases, but I wonder if all the other interfaces are unnecessary, and should be removed? Regarding point 3) above, won't I be violating "loose coupling" if I was to do this?

Edit:- I'm just having a play with Moq, and it seems to require methods to be public and virtual, and have a public parameterless constructor, in order to be able to mock them. So it looks like I can't have internal classes then?

答:
I lean towards the idea that, if some logic is private, then the implementation of that logic should be of no concern for anyone, and as such shouldn't be tested. If some logic is complex enough that you want to test it, that logic probably has a distinct role and should therefor be public.
E.g. if I extract some code in a private helper method, I find that it's usually something that could just as well sit in a separate public class (a formatter, a parser, a mapper, whatever).

As for interfaces, I let the need for having to stub or mock the class drive me. Stuff like repos, I usually want to be able to stub or mock. A mapper in an integration test, (usually) not so much.


问:
Dependencies between services in pipeline
I am working on creating a new data processing system, where there are multiple steps each fulfilled by different services. For example, there is a scheduling service that kicks of something, an analysis service that does the processing, and a notification service that summarizes and emails out results. Data flows through in that order

My main question which design would be better, should the analysis service have to know about the notification service? Or should the notification service have to know about the analysis?

My initial thought is that by using a service bus, the notification service can simply be subscribed to any analysis results that get broadcast. That way if the notification service is replaced or changed there wouldn't need to be any change to the analysis service. This also means a client that wants to start an analysis and get a notification would have to call the notification service first to tell it how to handle the result it will eventually get before kicking off the actual analysis.

The opposing idea is that the analysis service should simply call directly into the notification service, so the analysis service needs to know what to do to create a call into notification. This means the client would have to bundle up notification specific instructions that get passed into the analysis service for it to later look at to know what to pass to the notification call.

It seems like the service bus approach of the notification service getting and processing analysis results would be better because we could also add other services in the future that then do something with a result without having to change the analysis service to call it explicitly.

Can anyone provide some insight on which approach would work better to be both easier to develop, maintain, support?

答:
I would advocate a third option for your architectural design.

You have a collection of services (analysis, notification, data transformations, data collection, etc.) that each take their input from an abstract source in a particular format (that can differ between the services) and produce output to an abstract destination, with a potentially different format. By chaining these services together, you can create a processing pipeline.

Next to these data processing services, the system also has a PipelineManager that can create and configure a pipeline of data processing services, based on requests from the client, and a scheduling service to kick off processing at specific points in time.

The idea behind the PipelineManager is that each individual service is unaware of the service that supplies it with data and the service that consumes its data, but that there is a component that knows about the available services and their input and output characteristics and that can tie them together. The PipelineManager doesn't even need to know exactly what the notification service does, as long as it knows that the service exists, takes data in format A and produces nothing that can be processed further.


问:
The 10 minutes technical interview
I must do a quick assessment of dozens of fresh students very quickly. I have 30 minutes meeting with each of them (in two or three days). I want to use most of the time to discuss non technical aspects. So I plan to use 10 minutes for technical questions. The same questions for all of them.

They are all hired already (they are students), what I need to know is the average level in order to prepare a training.

Ideally, the difficulty must be progressive in order to set a level for each. Level I will average, and I'll do an average on each question too.

If you had only 10 minutes and 10 questions to ask to a candidate, what would be your top 10 ?

答:
I'm looking for problem solving, a strong learning habit, professional development, and wide knowledge of approaches.

Can I see your portfolio?

What are the last 3 technical books you've read? Why?

Which programming text changed the way you think the most? Why?

How would you define a chicken as an object? How does it relate to other birds? How about mammals and animals?

Can you explain any one of (REST, Polymorphism, relational algebra, parser design, MVC) in layman's terms?

What is the most interesting (or best) piece of software you've built yourself?

Can you describe the languages you are proficient in from favourite to least favourite? What frustrates you about your least favourite languages?

I expect developers to:

Be resourceful and quick

Grasp basic concepts properly

Yearn to grok advanced concepts

Track success and failure (learning from it)

Learn constantly, thoughtfully

Communicate complex issues simply

Show balance and logic when discussing commonly dogmatic issues

Title: The 10 minutes technical interview


问:
Unit Test - an Enigma?
I am an objective-c/iOS apps developer and I was wondering if I perform Unit Tests on my code, how should I go about it?

What is unit test anyway? Ain't I testing a specific part of code while running the whole app itself?

What is its use?

I have read few articles, wikipedia etc. but I am not sure whether unit testing is a time consuming or a time saving process. I know the definition but I am in the dilemma about its purpose.

Plz guide a new bee here. :)
Have already gone through the following:

Unit testing best practices for a unit testing newbie

答:
I am an objective-c/iOS apps developer and I was wondering if I perform Unit Tests on my code, how should I go about it?

Probably by reading some objective-c/iOS-specific unit testing tutorials. I am sure there are many.

What is unit test anyway? Ain't I testing a specific part of code while running the whole app itself?

No, it's testing a specific part of the code ("unit") without all the rest of the app. If the whole app runs, it's an integration test, which is also valuable.

What is its use?

It allows you to test units of code very thoroughly, including special cases (e.g. error handling) that may be hard or impossible to reproduce in the running app. It also gives you tests that run very quickly and thus can be run anytime during development when you need reassurance that you haven't broken anything. This in turn gives you the ability to refactor your code freely, and maintain better quality.

I have read few articles, wikipedia etc. but I am not sure whether unit testing is a time consuming or a time saving process.

Both. Writing the tests consumers quite a lot of time. But overall, it more than makes up for it by catching bugs early and making refactoring easy. The confidence that you can at any time at the press of a button be reassured that the code contains none of the bugs your tests check against is priceless.

Title: Unit Test - an Enigma?


答:
Unit testing, depending on your background, is more or less counter intuitive. But if you've done it for a while it all seems to fall into place in grand scheme of things related to software development, because of several reasons:

Simpler architecture: Unit testing is making sure that small parts of your system or program works. Performing this as a process (with TDD, BDD, whatever) gives you an opportunity to think about your architecture a bit. If the tests are difficult to write, then the system-under-test (SUT) is difficult to use. This notion will hopefully make you stop and think the design of your software through or discuss with someone else if there is a simpler way to do one complex thing.

Regression -> Refactor: The major benefit you get from unit testing is that you accumulate regression tests. The value of these tests come when you refactor code, one of the most recurring bugs when refactoring is regressions; that functionality that once worked has stopped working. Once you have tests that tell you when things break, then you know if your refactoring still works or is busted.

Stubs/Mocks -> Modular architecture: Many miss, when they start out, that objects have dependencies that should be stubbed/mocked when running unit tests. Being able to mock things out leads to short-term benefit such as faster tests and also long-term benefits such as making sure that your component that you're building can stand on its own. Once you have all components/modules seperate you can make sure when one of them is broken by writing a failing test that exposes the bug and enables you to fix it.

I could go in depth discussion about what good unit testing practices are, but this question thread explains it better: What Makes a Good Unit Test @ StackOverflow. In summary, you should write tests that has business or practical value for you. It is time consuming, but the benefits outweigh the drawbacks if you're doing them in a smart way (ATRIP is a great mnemonic to keep in mind).

To be good at unit testing takes practice... lots of it. The best way to do so is to just dig in and start using a unit testing framework that helps you manage it. For Objective C there are plenty of unit testing frameworks that you can read here: What is the best way to unit test Objective C code? @ StackOverflow

Title: Unit Test - an Enigma?

Body:
I am an objective-c/iOS apps developer and I was wondering if I perform Unit Tests on my code, how should I go about it?

What is unit test anyway? Ain't I testing a specific part of code while running the whole app itself?

What is its use?

I have read few articles, wikipedia etc. but I am not sure whether unit testing is a time consuming or a time saving process. I know the definition but I am in the dilemma about its purpose.

Plz guide a new bee here. :)
Have already gone through the following:

Unit testing best practices for a unit testing newbie


答:
Edit: this does not work, see comments

Since you have no inequalities and no cost minimization here, you don't actually need linear programming, you can just solve it as a system of linear equations. E.g. apples+oranges=1, 0.05*apples+0.20*oranges=0.05 etc.

Title: What class of problem is this, and what math do I need to know to solve it?

Body:
Mushroom cultivation requires fairly precise chemical composition of substrate (a.k.a. growing medium). Let's pretend we're growing shitakes and that this is the required composition of their substrate:

```<code>Nitrogen | Benzene | Toluene | Dioxygen Diflouride
5%       | 5%      | 10%     | 80%
</code>```

We want to create an appropriate substrate from materials we have on hand which we know the chemical composition of.

```<code>Material | Nitrogen | Benzene | Toluene | Dioxygen Diflouride
apples   | 5%       | 0%      | 5%      | 90%
oranges  | 20%      | 20%     | 50%     | 10%
Etc...
</code>```

How does one calculate this?  It reminds me of solving matrices in high school.  Is this something that can be done with matrices?  What is this problem called?  What do I need to know to solve it?