答:
Massively tedious repetition of millions of tests, as on the low-level methods, but higher up.

That's a straw man... Naturally, you're testing the same functionality higher up, but at a different level of abstraction.  Higher-level tests also exercise the interactions between components.  Were your premise true, we could simply dispense with unit tests altogether and just use higher-level tests.

Condense "is the date valid" down into a separate method which I reuse in my behaviour tests, so although I do check that the date is valid, it's only one line per test.

That's called refactoring.  It's a valid programming technique, and one that I would have assumed you already used here, in exactly the manner you described.

the actual validation routine being used is an implementation detail, blah blah.

If this bothers you, follow the practice of TDD'ers everywhere, and only test public methods.  Naturally, this doesn't preclude you making your "is the date valid" method a public method, and testing it independently.  It does have the virtue of making you think about your public API, and promoting code reuse by exposing those methods that are likely to be used more than once.

At the end of the day, common sense rules.  If a piece of internal functionality is complex enough that you believe it needs to be covered by its  own tests, then by all means, write tests for it.  Conversely, I seldom write tests for trivial getter/setter methods, or methods that are prima facie correct.

Title: BDD/TDD - exhaustively testing details which are low-level, but still behaviour

Body:
We're looking to concentrate more on testing behaviour (as opposed to every class/method individually) in all our automated tests, as espoused by various high-profile online discussions recently.  I like the idea of thinking about only what goes in and out of certain logical well-defined boundaries between components, but I'm having a hard time imagining how that relates to quite low-level detail of behaviour, that is only a small part of the overall requirement but still important to be correct.

As an example:

We have a component which accepts a customer order and takes some kind of significant action with it, let's say accepts it and starts processing manufacture.  The main thrust of the requirement is about accepting and manufacturing, but there are many small things which need to be correct, and which if incorrect should cause an exception, for example that the order date needs to be valid.  If we assume that I don't implicitly trust whatever date validation routine is being used, then there are loads of things I need to test there: basic format, leap years, not in the future, etc etc.  In "non-behavioural" TDD I would definitely test those at the class/method level, and then never worry in my other tests about whether they'll work. But if I'm only testing behaviour, do I need to take all those success/fail cases and test them on the component boundary, for every situation where I'm interested in the date?

I can see a few options:

Massively tedious repetition of millions of tests, as on the low-level methods, but higher up.

As above, but condense "is the date valid" down into a separate method which I reuse in my behaviour tests, so although I do check that the date is valid, it's only one line per test.  This is much more likely than the first option...

Test only broad behaviour higher-up, and do have a low level set of tests just to ensure the validation routines work.  This seems sensible, but the importance of behaviour tests not relying on implementation details has been stressed - the actual validation routine being used is an implementation detail, invisible at the component boundary, so even if I test that routine, can I officially then not test it elsewhere as well somehow?

I'm leaning towards the middle option, but I'm quite new to this, and would be interested what you think about it!

Higher-level tests also exercise the interactions between components.
  Were your premise true, we could simply dispense with unit tests
  altogether and just use higher-level tests.

I think that's true (if taken to extremes), and there are people who would try to achieve exactly that.  Understanding the reasons not to do that are partly the driver for my question.

I think potentially the difference between certain situations is to what extent these low-level behaviours are perceptible at the component boundary - in the case of date validation they are, I can feed lots of different values that I know should be valid or invalid in different ways into the interface and see differences in response; in other cases the unit in question does its work invisibly, at least from a behaviour perspective (I could test loads of stuff in a unit test, but perhaps the way it's being used in the larger component being tested doesn't give it much scope for variation).

Repetition vs Refactoring

The main reason I included the hyperbolic "millions of tests" option is another (unstated) principle that I also understand is good to aim for: "don't do too much in any one test, test one thing only".  If you're also trying to follow that as much as possible, and think of the various validation failure cases as separate "things", it seems to conflict a bit with normal DRY/refactoring approaches - you can't squish the validation into one method and use it over and over, because then when it goes wrong you haven't got such specific feedback about what to fix (although you do at least have a valuable works/doesn't work response).

If this bothers you, follow the practice of TDD'ers everywhere, and only test public methods. Naturally, this doesn't preclude you making your "is the date valid" method a public method

I don't think I like the sounds of making something arbitrarily public (without changing anything else) just so I can test it - I'm happy enough changing my APIs when I need to change them, rather than so they fit my testing approach.  Maybe bundling it off into another class (with public methods) if it might be useful, that makes more sense to me (and I've heard people suggest exactly that in TDD conversations).  But the question is not really concerned with getting access to the low-level detail, it's about whether testing at that level at all is a good idea.

At the end of the day, common sense rules. If a piece of internal functionality is complex enough that you believe it needs to be covered by its own tests, then by all means, write tests for it. Conversely, I seldom write tests for trivial getter/setter methods, or methods that are prima facie correct.

No argument from me about that!  Depsite what else I've written I'm sure we'll end up with a pragmatic mixture of approaches that we've chosen to give us the confidence in our code we need.  This is helping me decide what that might be!

So far I'm erring towards accepting slightly coarser tests at the API level (for e.g. things like our date validation example), while also setting up comprehensive unit tests for certain underlying classes - that way you get the full behaviour coverage, and nothing can slip through the net at the level which truly matters, but also you can have good confidence in and ease of maintenance for the complex low-level units.


问:
Finding metrics for development time in different languages
I'm trying to determine if a language I'm investigating (Groovy) is better for developing enterprise applications than our current language (Java).  Specifically I'm trying to figure out if it will save significant time in coding, re-factoring and maintenance.

But, I'm not actually asking that question here as it's waaaaay too broad, I'm just setting up my actual question:

What's the best approach to gathering metrics to compare the productivity of two languages?  I mean, it's easy to look at example code that says "see, this is easier to write in Groovy than Java" or "this functionality is missing in the tools available for Groovy, but exists with Java tools."  But it's much harder to figure out how that translates into time gained/lost in the real world.

I've been combing Google, but I'm honestly not even sure what I'm looking for.  I know the question is still a tad broad, but if anyone has some answers I would appreciate it...

答: Write a small, but non-trivial application in the candidate language, and make a qualitative evaluation of the learning curve, ease of development, relative friction of the tool chain, and developer productivity.</p>

ContentLicense: CC BY-SA 3.0


问:
What are factors to take into consideration in choosing a programming language/paradigm for a rule-based natural-language translation program?
I have experience with object-oriented programming languages (C++ and Java), but I am wondering what kinds of programming languages — including OOP languages– or programming paradigms might be suitable for a rule-based natural-language translation program.

Does existing machine-translation software tend to use a certain paradigm or language?

答:
In all honesty: natural language translation is so incredibly, mindbogglingly, insanely, hard in general that the choice of language is completely and utterly irrelevant. Even when programming in Malbolge, your 99.9999999% of your time, effort, resources, manpower and money is going to be spent researching and inventing the algorithms rather than implementing them.

There are basically two known approaches to machine translation that "work" (as in "produce results that are slightly better than complete garbage"): the classical approach and the Google approach:

classical approach:

hire a dozen or so researchers (alternatively: donate a couple of million dollars to a university)

wait twenty years

Google approach:

create a database of everything ever written in the entire history of humankind

pattern match your input text against documents where the same document was written in both the source and target language you want to translate from and to

There is also a third approach that IMO works best:

use the Google Translate API

Now, if you insist on doing it yourself, then whenever you hear the words "rule-based", you should think of languages like Prolog and Mercury or embedded DSLs such as KANREN and miniKANREN.


问:
Using SVN with multiple developers but without creating branches
I'm a computer science TA working with some students in a senior capstone course (effectively, a consultant for a small team). I met with them to discuss how to use version control, and they're in an interesting situation:

Their current practice to to complete their tasks on their own machines without committing. Then, at the end of an agile sprint, they all commit their work to the same branch, figuring out merge conflicts along the way. I suggested that they each create their own personal branches and commit to them more frequently, whenever they've completed a task, and then merge the branches at the end of the week.

However, they're working on the project for a client who is hosting the repository on his own server. The project already has dozens of branches, each of which takes up several gigabytes of space. (The team has been told to work in a particular branch, not on trunk.) As a result, the team will probably need permission from the client before they can create new branches, and they might not get that permission.

If the client tells the team not to use branches or takes a while to respond to them, how should they proceed? What are some reasonable SVN usage patterns when a team can't create new branches?

答:
"reasonable SVN usage patterns" is an oxymoron.

You can't create more branches on the client's server - that's the client's rules and they should be respected. At any rate SVN is not built to handle many small branches(or any number of branches that's bigger than 1), since they'll remain in history forever and since merging them all the time will be a pain.

If this was Git - while still having the one-branch rule - you could utilize Git's distributed nature and host your own server. The students will push to that server, merge the branches on that server, and at the end of the sprint organize everything and push it from the University's server to the client's server. The University's server will be the place where all the branching-merging mess happens, and the client will get their commits in a clean single-branch like they want.

Unfortunately, this is not Git, so you can't do that. Or can you?

There is a tool called git-svn that allows you to push and pull from Git to SVN. It's not as good as pure Git, but it should be enough for your to push from the Git repo you'll host on the University's servers to the SVN repo on the client's server. So, your students will work on the Git server with all it's branching and merging goodness, and at the end of the sprint, after they rebased all their work to a linear chain of new commits(so SVN could handle it), they use git svn dcommit from the University's Git server to push their changes to the client's SVN repository.


问:
Is there an excuse for short variable names?
This has become a large frustration with the codebase I'm currently working in; many of our variable names are short and undescriptive. I'm the only developer left on the project, and there isn't documentation as to what most of them do, so I have to spend extra time tracking down what they represent.

For example, I was reading over some code that updates the definition of an optical surface. The variables set at the start were as follows:

```<code>double dR, dCV, dK, dDin, dDout, dRin, dRout
dR = Convert.ToDouble(_tblAsphere.Rows[0].ItemArray.GetValue(1));
dCV = convert.ToDouble(_tblAsphere.Rows[1].ItemArray.GetValue(1));
... and so on
</code>```

Maybe it's just me, but it told me essentially nothing about what they represented, which made understanding the code further down difficult. All I knew was that it was a variable parsed out specific row from a specific table, somewhere. After some searching, I found out what they meant:

```<code>dR = radius
dCV = curvature
dK = conic constant
dDin = inner aperture
dDout = outer aperture
dRin = inner radius
dRout = outer radius
</code>```

I renamed them to essentially what I have up there. It lengthens some lines, but I feel like that's a fair trade off. This kind of naming scheme is used throughout a lot of the code however. I'm not sure if it's an artifact from developers who learned by working with older systems, or if there's a deeper reason behind it. Is there a good reason to name variables this way, or am I justified in updating them to more descriptive names as I come across them?

答:
I notice that the other answers don't mention the use of Hungarian Notation. This is orthogonal to the length debate, but relevant to naming schemes in general.

```<code>double dR, dCV, dK, dDin, dDout, dRin, dRout
</code>```

The "d" at the beginning of all these variables is meant to indicate that they're doubles; but the language is enforcing this anyway. Despite the terseness of these names, they're up to 50% redundant!

If we're going to use a naming convention to reduce errors, we're much better off encoding information which isn't being checked by the language. For example, no language will complain about dK + dR in the above code, even though it's meaningless to adding a dimensionless number to a length.

A good way to prevent such errors is to use stronger types; however, if we're going to use doubles then a more appropriate naming scheme might be:

```<code>// Dimensions:
// l  = length
// rl = reciprocal length
double lR, rlCV, K, lDin, lDout, lRin, lRout
</code>```

The language will still allow us to write K + lR, but now the names give us a hint that this might be incorrect.

This is the difference between Systems Hungarian (generally bad) and Apps Hungarian (possibly good)

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

Body:
I notice that the other answers don't mention the use of Hungarian Notation. This is orthogonal to the length debate, but relevant to naming schemes in general.

double dR, dCV, dK, dDin, dDout, dRin, dRout

The "d" at the beginning of all these variables is meant to indicate that they're doubles; but the language is enforcing this anyway. Despite the terseness of these names, they're up to 50% redundant!

If we're going to use a naming convention to reduce errors, we're much better off encoding information which isn't being checked by the language. For example, no language will complain about dK + dR in the above code, even though it's meaningless to adding a dimensionless number to a length.

A good way to prevent such errors is to use stronger types; however, if we're going to use doubles then a more appropriate naming scheme might be:

// Dimensions:
// l  = length
// rl = reciprocal length
double lR, rlCV, K, lDin, lDout, lRin, lRout

The language will still allow us to write K + lR, but now the names give us a hint that this might be incorrect.

This is the difference between Systems Hungarian (generally bad) and Apps Hungarian (possibly good)

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


问:
Who can learn to program?
I always hesitate when talking to professors about trying to improve the percentage of people who graduate with a CS type degree compared to the number that start out thinking that is what they want. On one hand I really do think it is important for professionals to be involved and give this feedback, on the other hand it would be better if less sub-par students ended up with CS degrees.

I don't think every mind is built for this field and you have to be a good life long student. You have to have a high degree of patience and problem solving skills just to eek by. If you do have the "right" kind of brain, those hard problems are what drives you to continue. If you just get a long list of easy problems you get bored so these people are actually not good at more repetitive jobs. I don't need to go into all the details... if you are reading this you probably know what I'm getting at.

So the question is: How do you find the balance of a degree program that is accessible to enough people to be funded and considered successful but also doesn't turn out people who aren't really cut out for the job? Maybe a better question is, what metric do you use to know if the changes you are making in a degree program are making it better? I don't know that a higher graduation rate is a good metric. And it seems that the feedback that you could try to capture many years later about the jobs that the graduates hold would be too far delayed.

I've struggled with this question for a long time, mostly because I don't think there is an answer. But I thought I'd ask to see if anyone knows of any research that has actually been done on it.

Addition: I recently had a very wise professor remind me that not everyone who graduates with a CS degree even wants to be a full-time programmer once they have actually discovered what that means. But, with the education that they received they could possibly make great Project Managers, Managers, system admins, etc. I think this was a very good point that I hadn't thought to consider here. There are a very high percentage of people who don't end up working in the field they majored in, CS isn't an exception to that. Having the extra folks helps not only in budget for the degree but also to expand the percentage of non-programmers who still know enough about it to work with programmers.

答: Ok, by popular demand ... Let the free market figure it out. You know, 95% of psychology majors end up doing something else. Not everyone with a CS degree/minor ends up programming, but they make better managers, analysts, project managers than those without. Do not carry the weight of the world on your shoulders. CS degree is just a piece of paper. Those with math, physics, chemistry, biology degrees go on to become programmers, and not everyone with a CS degree becomes a programmer. Without millions of kids aspiring to be the best baseball player, we would not have such great stars. The system is self-regulating.</p>

Title: Who can learn to program?

ContentLicense: CC BY-SA 2.5


答:
As much as I hate answers on SE that are 'do it a way differently than you are,' since they're not a real answer to the question, I think that has to be the answer here.

The workflow you described is a distributed version control system, such as git or mercurial, whereas subversion is a centralized version control system. The two share a lot of similarities, but have some fundamental differences as well. Trying to shoehorn that workflow into subversion is like trying to jam a square peg into a round hole, and is going to end up causing as many problems as it solves.

Either you need to get the students to adopt SVN's religion, or use a distributed version control system among yourselves, and push to the client's system separately.

Title: Using SVN with multiple developers but without creating branches

Body:
I'm a computer science TA working with some students in a senior capstone course (effectively, a consultant for a small team). I met with them to discuss how to use version control, and they're in an interesting situation:

Their current practice to to complete their tasks on their own machines without committing. Then, at the end of an agile sprint, they all commit their work to the same branch, figuring out merge conflicts along the way. I suggested that they each create their own personal branches and commit to them more frequently, whenever they've completed a task, and then merge the branches at the end of the week.

However, they're working on the project for a client who is hosting the repository on his own server. The project already has dozens of branches, each of which takes up several gigabytes of space. (The team has been told to work in a particular branch, not on trunk.) As a result, the team will probably need permission from the client before they can create new branches, and they might not get that permission.

If the client tells the team not to use branches or takes a while to respond to them, how should they proceed? What are some reasonable SVN usage patterns when a team can't create new branches?


问:
Static typing vs. dynamic typing
I'm developing my own programming language in my spare time as a hobby. It's an interpreted language. Currently the syntax for variables is this:

```<code>%<variable> = <value>
</code>```

Here are some examples:

```<code>%test = 10
%somevar = "Hello World"
</code>```

At the moment you can just declare as variable as shown above, regardless of the type. You can even change the type through the program if you want.

I've never studied Computer Science, so I'm not really aware of the Pros and Cons of static vs dynamic typing. Here are my questions:

Is it faster to program using dynamic types?

Is there any major advantage to going with static typing?

Is this syntax good for a static language?

Should a language that makes you write the type of the variable beside it when you create it allow you to change the type of a variable at run time?

Should I allow both static and dynamic typing?

Example Syntax:

```<code>%somevar int = 10
%another str = "Hello World"
</code>```

Here's a link to my GitHub, if your interested: https://github.com/reedoolang/reedoo

答:
I'm not sure there's good, clear, definitive answers for your questions, I would like to try and help.

There is no definitive proof one way or another. This is one of the great debates amongst programmers. Many argue it is faster to make the program due to lack of type annotations, while many others counter "but it doesn't work! Now you need to write all of the tests that static typing would do for you!". There's also disputes that arise because different solutions better fit different problems, different programmers work differently, etc.

Yes, this is well covered elsewhere.

Sure? You haven't included much, but it seems unambiguous which is the primary concern. Though it should be noted that beginners commonly overvalue syntax over semantics.

No. The type annotation is providing a contract or guarantee about that variable. Breaking that contract is very bad.

Maybe? It's your hobby. I would recommend not making both available. It will be easier to implement correctly and completely if you keep things simple.

Title: Static typing vs. dynamic typing


问:
Is a bad practice create database structure on the runtime?
I'm creating a crawler app that will always, in the beginning, when the Class constructor, ensure that the basic database structure exists.

Is this a bad practice? What is the advantage OS creating the structure directly on the database?

```<code>import psycopg2
from datetime import timedelta

class DBManager:
    def __init__(self):
        self.connected = False
        self.conn = None
        self.cursor = None
        try:
            self.conn = psycopg2.connect()
            self.cursor = self.conn.cursor()
        except:
            print "I am unable to connect to the database"

        try:
            self.cursor.execute("BEGIN TRANSACTION;")
            self.cursor.execute('CREATE TABLE IF NOT EXISTS proxy(id SERIAL NOT NULL PRIMARY KEY,ip VARCHAR(15) NOT NULL,active BOOLEAN NOT NULL, times_used smallint default 0, last_use timestamp DEFAULT CURRENT_TIMESTAMP not null );')
            self.cursor.execute('CREATE TABLE IF NOT EXISTS app_update (time TIMESTAMP NOT NULL);')
            self.cursor.execute("""
                CREATE OR REPLACE FUNCTION merge_proxy(_proxy VARCHAR(15)) RETURNS void AS $$
                    BEGIN
                        IF EXISTS( SELECT * FROM proxy WHERE ip = _proxy ) THEN
                            UPDATE proxy SET active = TRUE WHERE ip = _proxy;
                        ELSE
                            INSERT INTO proxy(ip,active,times_used,last_use) VALUES (_proxy,TRUE,0,CURRENT_TIMESTAMP);
                        END IF;
                    END;
                $$ LANGUAGE plpgsql;
            """)
            self.cursor.execute("END TRANSACTION;")
            self.connected = True
            print 'ending creating tables'
        except:
            print 'unable to create table'
</code>```

答:
It's generally considered a good idea to separate the environment setup from the main application. The usual practice for something like this is to have the database structures created by your installer or setup script. The application should not create its own structures, if it can help it.

One reason to separate them might be if you have slightly different versions of the schema for different database engines. If you have the database installer separate from the main application, the user can choose which database script is most appropriate for them, and then run your application, rather than letting your application try to guess what the user wants.

Also, how will your application handle failures in the database setup? Sometimes it happens that the standard setup that you want people to run might not work 100% in everyone else's database, so the DBA might want to tweak it for their own environment. Embedding the setup directly in the application prevents people from doing this, but might also prevent people from running your application, if they are unable to make necessary changes to the setup for their particular database.

...If you really want, you could have your application check for the database, and if it can't connect, ask the user if they want the setup to run. Then have your main application run your setup script before resuming the main application.


问:
Should "tests" be kept out of the main merge pipeline?
We all know sometimes a e.g. merge can go wrong.

If our [unit / integration] tests are in the same repository as the merge, is there then a weakness there that if the tests have merged incorrectly and do not appear in the final code then "we don't know what we don't know".

Should the unit test project then instead be a complete separate item?

In many ways I'd say no as it could litter a master branch with feature tests which are not yet relevant.

In compiled languages then the compilation will fail if the test's reliant code is missing, so will help to a certain degree. But perhaps a non-compiled language is better as it would highly specific missing items when running the test.

Does anyone have a workflow which it is possible to know which features may of merged incorrectly?

答:
Tests and code should merge at the same time.

Consider the opposite case.  What happens if a merge conflict loses your new lines of code?  If you still have the old test, so you would never know.

Modifying the regression becomes your record that you expected it the behavior to change, and should follow along with the code as it merges.


答:
It depends - mainly on the life cycle of your database(s) and the usage scenario. Creating the DB structures automatically makes sense if

the database is used exclusively (or at least primarily) by your application

you expect to have not just one database, but many different db instances of this structure in different places

the database is used as some kind of temporary storage, either archived or thrown away after use

there are no security requirements forbidding your application to change db structures

For example, when you are building a big enterprise OLTP database, with lots of different applications using it, creating the DB structure inside one of the applications is typically a bad idea. It won't actually make sense, since the DB is part of the environment you can expect to be be available for the application. In such an environment, normal applications will typically not even get the access rights to change any DB structures.

On the other hand, when you are building a database application for logging or storing a series of measurements over a fixed time period (lets say, for a day), things are different. Assumed for each of these periods you need a new db instance, the creating this instance automatically when it is not there makes a lot of sense. In such scenarios it is common not to use a full-fledged client/server database system, but a lightweight single-file db system.

I don't know into which of these categories your "crawler app" falls, but check your scenario according to the points I wrote above and make a decision.

Title: Is a bad practice create database structure on the runtime?

Body:
I'm creating a crawler app that will always, in the beginning, when the Class constructor, ensure that the basic database structure exists.

Is this a bad practice? What is the advantage OS creating the structure directly on the database?

```<code>import psycopg2
from datetime import timedelta

class DBManager:
    def __init__(self):
        self.connected = False
        self.conn = None
        self.cursor = None
        try:
            self.conn = psycopg2.connect()
            self.cursor = self.conn.cursor()
        except:
            print "I am unable to connect to the database"

        try:
            self.cursor.execute("BEGIN TRANSACTION;")
            self.cursor.execute('CREATE TABLE IF NOT EXISTS proxy(id SERIAL NOT NULL PRIMARY KEY,ip VARCHAR(15) NOT NULL,active BOOLEAN NOT NULL, times_used smallint default 0, last_use timestamp DEFAULT CURRENT_TIMESTAMP not null );')
            self.cursor.execute('CREATE TABLE IF NOT EXISTS app_update (time TIMESTAMP NOT NULL);')
            self.cursor.execute("""
                CREATE OR REPLACE FUNCTION merge_proxy(_proxy VARCHAR(15)) RETURNS void AS $$
                    BEGIN
                        IF EXISTS( SELECT * FROM proxy WHERE ip = _proxy ) THEN
                            UPDATE proxy SET active = TRUE WHERE ip = _proxy;
                        ELSE
                            INSERT INTO proxy(ip,active,times_used,last_use) VALUES (_proxy,TRUE,0,CURRENT_TIMESTAMP);
                        END IF;
                    END;
                $$ LANGUAGE plpgsql;
            """)
            self.cursor.execute("END TRANSACTION;")
            self.connected = True
            print 'ending creating tables'
        except:
            print 'unable to create table'
</code>```


问:
Organizing code in a 2 man team
I've been working with a buddy of mine on a school project. We forecast it'll take ~2 months, so it isn't a small scale project at all. Communication and splitting the work effectively has been a NIGHTMARE though.

He doesn't have a phone, which makes communicating outside of the one 1 hour class we have together difficult.

Basically what's been happening is we end up working on the exact same thing, or we write code for components that doesn't work with components the other person has written. Because of this, we spend about 20 or 30 minutes each day in class making both copies of our code work together, and figuring out what stays and what goes. It's horrible for efficiency.

I looked into github but it looks so ridiculously overkill for this 2 man team. Also I was unable to find github tutorials for specifically what I'm looking to do (They're all too technical for someone with 0 git expeience or tackle things unrelated to my needs).

How can we organize this project more effectively and efficiently?

答:
There are a couple of things here that need to be addressed.

First, there is the two code bases.  You've got your code.  Your friend has his code.  Wen you do a merge (somehow) you're doing it without the ability to see the changes that did it before.

You don't need github to do this.  You could have a master git repo on a thumb drive, and then merge to and from that.  Github makes it easier to do this (and harder to lose it).  Working from the thumb drive though, you wouldn't have as complete a set of tutorials on how to use it or the other things that github has that are quite nice.

Next, there are the issues.  You don't have a clear division of labor and tracking of this labor:

Who is working on what?

What changes fix what?

The github issue tracker within github allows you to assign who is working on a given issue and identify what state it is in.  It also hooks up nicely if you tag the commits with the issue number, which then shows back in the issue tracker part of Github.  This makes it clear when you later want to go back and see "what did I change to make issue #5 work?" - you can go to issue 5 and see the commits.

This doesn't prevent anyone from actually working on anything though.  You or your friend could disregard the issue tracker and work on whatever.  Working with other people takes discipline - properly communicating what you are doing, taking tasks, finishing tasks, and saying that they are done and then moving the changes into a place where other people on the project can make use of them.

If you, or your coworker are not disciplined to do this you will have problems.

Git or any VCS will not fix the problem of "basically what's been happening is we end up working on the exact same thing, or we write code for components that doesn't work with components the other person has written" on its own.  You could do that today - write out all the specs on paper and have a stack of index cards with all the things that need to be done.  Divvy up the index cards and work on them according to the written spec.  No git involved in that process at all.  An online version control system makes it easier to do this, if you are willing to work with it.  But, if you aren't going to take the steps to actually be disciplined in your work habits in the first place, its just going to be extra tedious work.

As to overkill?  Nope.  Its not overkill.  Its a very useful tool set that has a lot of features that you will use some day.  There are simpler version control systems (I used RCS back in the day and it worked fine for my college projects with partners (drunken checkins are easier to revert than begging the lab staff for a restore from the nightly backup). Aside from the cloud and server nature of git, it had just a steep of a learning curve as RCS.

Note that many IDEs today have git support built in that make using it much easier.  You've got this tagged with netbeans - consider reading Using Git Support in NetBeans IDE.

Title: Organizing code in a 2 man team


问:
Are Git branches, in fact, "homeomorphic endofunctors mapping submanifolds of a Hilbert space"?
As we all know:

Git gets easier once you understand branches are homeomorphic endofunctors mapping submanifolds of a Hilbert space

Which seems like jargon, but on the other hand,

All told, a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor.

is funny because it is true.

Can I avoid merging mistakes by reading this simple text?

答:
It's a joke, that is based on the monad joke, but without actually getting the monad joke.

The monad joke is funny on three levels:

it tries to explain abstract mathematical jargon with even more mathematical jargon, which is even more abstract

however, the explanation is actually correct

and once you dive deeper into category theory, you will actually start to see monads as "just a monoid in the category of endofunctors"

The Git thing, however, is just random gibberish. It is meant to resemble the monad joke, and might also be a jab at the darcs patch theory, but fundamentally, the person making the joke didn't understand the monad joke.

Sources:

This is the original tweet containing the quote:

Wil Shipley (@wilshipley): Sweet god I hate git.

Isaac Wolkerstorfer (@agnoster): @wilshipley git gets easier once you get the basic idea that branches are homeomorphic endofunctors mapping submanifolds of a Hilbert space.

And this is a comment on Quora by the original author of the tweet:

To confirm what Leo said, it was intended as a joke. […]

It was intended as firmly tongue-in-cheek. I actually love git, and I think its complexity is greatly overblown. At the same time, I'm sympathetic to the fact that advice from git gurus to novices can end up sounding like inscrutable gibberish.

It's not intended to have any deeper meaning. […]

The Leo he is referring to is another answerer in the same thread, a mathematician, who basically explains why that is nonsense. (Hilbert spaces are continuous, patches and branches are discrete.)

He also explains that he was inspired by this blog post (A Guide to GIT using spatial analogies), which actually does make sense.


问:
What is the purpose of a Code Review
I am in the process of trying to sell my organisation on the value of code reviews.  I have worked at several places where they were employed.  I have seen them used to nitpick styling choices, and functional decisions, and I have seen them used as nothing more than a gut check to make sure nothing dangerous is being implemented.  My gut feeling is that the most effective purpose is somewhere between the two options.

So, what is the purpose of a Code Review?

答:
I'd like to add two areas not covered by the other great answers:

One great reason for code reviews is the Hawthorne effect which in our case translates to:  If you know someone is going to look at your code afterwards then you are far more likely to write it better in the first place.

Another great reason is for better secure development practices.  One only needs to look at Apple's goto fail (an accidental duplicated line of code) or the Heartbleed bug (a basic failure in input validation) to understand the importance of proper code reviews in a secure development lifecycle.

Title: What is the purpose of a Code Review


问:
Logging instance information in Exceptions
During development on a large existing codebase I've started to capture variable values in my Exception logging. For example:

```<code>public int Foo(int a, int b)
{
   int returnInt;
   try{
      returnInt = bar(a) * b;
   }
   catch (Exception ex){
      ex.Message += "a: {0}, b: {1}", a, b;
      logger.log(ex);
   }

   return returnInt;
}
</code>```

While I'm not asking about this specific pseudocode I wondered if there were any valid reasons to not do this?

To me it would seem that logging instance variables in addition to the more general error message and stack trace is a positive thing. However I've never seen it done elsewhere.

答:
I'm not a security expert, but the only reason I can think of would be for security.

It may NOT be a good idea to log the variables when the values contains sensitive or personal user's information.  For example the user's name, address, SSN, credit card, etc...  I would try to log the transaction id or order id as a reference whenever possible.

Another situation would be the table definition or a SQL statement, which would disclose your architecture and design.

Sometimes it's hard not to implement some of these when they are the key value in determining the problem, so I think, it's a balance between support and security.


问:
Proper interface for calculator library?
As practice, I'm planning to implement a multivariable calculator library. The idea is that you can define a function, such as f(x, y) = sin(x)^2 + 3*y^3, and then you can evaluate it with specific variable values (e.g. f(4, 3)) or take the derivative with respect to a certain variable and get another function. The idea is that it might be used by a physics program or a calculator app that would more directly expose the functionality.

I'm not sure how to build the best interface. Using the style I'm most familiar with, I might define the above function with Function f = new Sum(new Exponent(new Sin(new Variable("x")), 2), new Product(new Constant(3), new Exponent(new Variable("y"), 3), but that's very long compared to the typical mathematical shorthand. Here are a few ways I could imagine the API working:

Function f = new Sum(new Exponent(new Sin(new Variable("x")), 2), new Product(new Constant(3), new Exponent(new Variable("y"), 3) (same as before)

Function f = Sum.create(Exponent.create(Sin.create(Variable.create("x")), Constant.create(2)), ... (same as before but with static builder methods)

Function f = sum(power(sin(getVariable("x")), getConstant(2)), product(getConstant(3), power(getVariable("y"), constant(3))) (shorter, but requires quite a few static imports)

Function f = FunctionGenerator.parse("sin(x)^2 + 3*y^3")

I like 4 because it's so much shorter, but I'm wary because I very rarely see it used; the two examples I've seen that jump to mind are Regex and MySQL, and those are both basically porting older text-based languages. Regex especially seems to make sense for a text-based API because it's used to text processing.

In short, I like #4 but I'm having a hard time justifying to myself this departure from convention.

(Note: I know that option #4 will require a parser. I've used ANTLR before, so this shouldn't be a problem.)

答: Speaking at a high level, I would perhaps build the interface so that option 1 is the "native" way to build your expression tree. Additionally, option 4 could provide an optional interface that offers a much more succinct notation. The result would be exactly what would be manually generated using option 1.</p>


答:
How is it going to be used? I think you need to look at it terms of the client code's usage patterns.

The code for a calculator app probably doesn't actually include much if any complex formulas. So the problem you are trying to address doesn't really come up. Something that a calculator app would want to is to be able to build a map of names to function implementations and none of your designs seem to facilitate that.

Some sort of physics modeling system probably does have complex formulas. But they also have the problem of symbol collision. I may have E=mc^2 as a formula. But what happens when I'm concerned about two objects?  They shouldn't share a mass, but I think in all your designs they probably do.

It looks to me like you are designing a system without a clear notion of what the client code could look like. I think that's not helpful. I think libraries like this are usually more helpful in the case that they are based on experience with writing applications that would use such a library. That way you've got a clear idea what you need.

Title: Proper interface for calculator library?

Body:
As practice, I'm planning to implement a multivariable calculator library. The idea is that you can define a function, such as f(x, y) = sin(x)^2 + 3*y^3, and then you can evaluate it with specific variable values (e.g. f(4, 3)) or take the derivative with respect to a certain variable and get another function. The idea is that it might be used by a physics program or a calculator app that would more directly expose the functionality.

I'm not sure how to build the best interface. Using the style I'm most familiar with, I might define the above function with Function f = new Sum(new Exponent(new Sin(new Variable("x")), 2), new Product(new Constant(3), new Exponent(new Variable("y"), 3), but that's very long compared to the typical mathematical shorthand. Here are a few ways I could imagine the API working:

Function f = new Sum(new Exponent(new Sin(new Variable("x")), 2), new Product(new Constant(3), new Exponent(new Variable("y"), 3) (same as before)

Function f = Sum.create(Exponent.create(Sin.create(Variable.create("x")), Constant.create(2)), ... (same as before but with static builder methods)

Function f = sum(power(sin(getVariable("x")), getConstant(2)), product(getConstant(3), power(getVariable("y"), constant(3))) (shorter, but requires quite a few static imports)

Function f = FunctionGenerator.parse("sin(x)^2 + 3*y^3")

I like 4 because it's so much shorter, but I'm wary because I very rarely see it used; the two examples I've seen that jump to mind are Regex and MySQL, and those are both basically porting older text-based languages. Regex especially seems to make sense for a text-based API because it's used to text processing.

In short, I like #4 but I'm having a hard time justifying to myself this departure from convention.

(Note: I know that option #4 will require a parser. I've used ANTLR before, so this shouldn't be a problem.)


答:
Your question is about code organization (as specified in the title) and many here seem to be talking about VCSs, that might not solve your problem at all. You do not seem to need version control, your problem seems to be something else.

Basically what's been happening is we end up working on the exact same
  thing, or we write code for components that doesn't work with
  components the other person has written.

If you got to talk to each other, you could decide what each of you will do, right? You are stepping on each other's toes by, as you said, working on the exact same thing.

I looked into github but it looks so ridiculously overkill for this 2
  man team. Also I was unable to find github tutorials for specifically
  what I'm looking to do (They're all too technical for someone with 0
  git expeience or tackle things unrelated to my needs).

I mean no offence. But if you fail to find GH tutorials, you will fail to find tutorials for anything. Give a try to Pro Git (or any introductory Git book). It may be overkill, but, in the end, it stills kill it. Plus, you are likely going to have to learn at least one VCS someday.

How can we organize this project more effectively and efficiently?

What about organizing it? No VCS will be able to merge what you are doing if you two are doing the exact same thing every day.

As you said, it is not a small scale project, so two things must be clear:

GitHub (or any VCS) is not overkill.

You two are likely to have different things to implement / refactor / work on.

He does not have a phone? Does he have internet access? Can he create an e-mail account? Use any messaging service?

Title: Organizing code in a 2 man team

Body:
I've been working with a buddy of mine on a school project. We forecast it'll take ~2 months, so it isn't a small scale project at all. Communication and splitting the work effectively has been a NIGHTMARE though.

He doesn't have a phone, which makes communicating outside of the one 1 hour class we have together difficult.

Basically what's been happening is we end up working on the exact same thing, or we write code for components that doesn't work with components the other person has written. Because of this, we spend about 20 or 30 minutes each day in class making both copies of our code work together, and figuring out what stays and what goes. It's horrible for efficiency.

I looked into github but it looks so ridiculously overkill for this 2 man team. Also I was unable to find github tutorials for specifically what I'm looking to do (They're all too technical for someone with 0 git expeience or tackle things unrelated to my needs).

How can we organize this project more effectively and efficiently?


问:
What are the motivations behind making true and false overloadable operators?
I asked this question on Stack Overflow and it was met with negative reception. I figured that Stack Overflow wasn't the right place to ask this question, so I decided to post it here.

Beside making types like SqlBoolean act more naturally, is there any other reason? If making three state boolean types is the only purpose of this decision, is it a good enough reason to add a feature that is so rarely used to a language?

Here's an example:

```<code>public class ThreeStateBool
{
    private bool? value;

    public ThreeStateBool(bool? value)
    {
        this.value = value;
    }

    public static bool operator false(ThreeStateBool tsb)
    {
        return tsb.value == false;
    }

    public static bool operator true(ThreeStateBool tsb)
    {
        return tsb.value == true;
    }
}
</code>```

Now that I've overloaded true and false, I can use this object in a conditional statement like:

```<code>if (new ThreeStateBool(false))
    Console.WriteLine("false");
else if (new ThreeStateBool(true))
    Console.WriteLine("true");
else if(new ThreeStateBool(null))
    Console.WriteLine("null");
</code>```

答:
You have to have a bit of context here: I think the main point missing is that this was a pre C#2.0 feature, which means it's a feature that came before nullable types. The page that describes the overloading of the 'true' operator is clearly geared towards the direction of having a nullable boolean without using a nullable type as support.

But there are other cases where you might want to treat an object instance as a boolean, for example where you want to check if the internal state of an object is ok, and you would want to write something C-style:

```<code>if (obj) {
    obj.DoSomething();
}
</code>```

It's a possibility, it's not a mandatory thing that you'd want to do. It's a tool to be used if needed, and, as you well noted, it is somehow superseded by the use of nullable types; however, you might want to write something similar to a ThreeStateBoolean when you know, for example, that 'false' means 'null or false'. Writing those checks inline every time is a boring affair.

Body:
You have to have a bit of context here: I think the main point missing is that this was a pre C#2.0 feature, which means it's a feature that came before nullable types. The page that describes the overloading of the 'true' operator is clearly geared towards the direction of having a nullable boolean without using a nullable type as support.

But there are other cases where you might want to treat an object instance as a boolean, for example where you want to check if the internal state of an object is ok, and you would want to write something C-style:

if (obj) {
    obj.DoSomething();
}

It's a possibility, it's not a mandatory thing that you'd want to do. It's a tool to be used if needed, and, as you well noted, it is somehow superseded by the use of nullable types; however, you might want to write something similar to a ThreeStateBoolean when you know, for example, that 'false' means 'null or false'. Writing those checks inline every time is a boring affair.


答:
Couple of points.

Since you already know about ANTLR you will probably already realise that your internal representation is going to be an AST, or something very near.

Using 'new' all the way is messy. Better to use factories, for clarity of code.

Yes, you will need a parser but it's nicer to get things started by building the AST directly. Then you can do the interesting things, like figuring out how to do differentation etc.

So I would recommend first:

```<code>var ast = AstFactory.create();
var f = ast.add(ast.exp(ast.sin(ast.var("x")), const(2)), ast.mul(ast.const(3), ast.Exp(ast.Var("y"), ast.const(3))
</code>```

Then you can build the AST efficiently using a fluent interface and postfix notation:

```<code>var f = AstGenerator.var("x").sin().const(2).exp().const(3).var("y").const(3).exp().mul().add();
</code>```

And finally, you still need this one (eventually):

```<code>var f = FunctionGenerator.parse("sin(x)^2 + 3*y^3")
</code>```

Body:
Couple of points.

Since you already know about ANTLR you will probably already realise that your internal representation is going to be an AST, or something very near.

Using 'new' all the way is messy. Better to use factories, for clarity of code.

Yes, you will need a parser but it's nicer to get things started by building the AST directly. Then you can do the interesting things, like figuring out how to do differentation etc.

So I would recommend first:

var ast = AstFactory.create();
var f = ast.add(ast.exp(ast.sin(ast.var("x")), const(2)), ast.mul(ast.const(3), ast.Exp(ast.Var("y"), ast.const(3))

Then you can build the AST efficiently using a fluent interface and postfix notation:

var f = AstGenerator.var("x").sin().const(2).exp().const(3).var("y").const(3).exp().mul().add();

And finally, you still need this one (eventually):

var f = FunctionGenerator.parse("sin(x)^2 + 3*y^3")


问:
Is my understanding of the license for JQuery.xmleditor correct?
Please correct me if I'm wrong, but I recently found myself in a pretty confusing situation and now I am unsure how to continue.

I found the jQuery.xmleditor plugin from the UNC libraries and thought it would be useful for one of our commercial products. That's where I typically first check how a library is licensed (in this case it was Apache License 2.0, which allows redistribution under certain preconditions). I started playing around with the plugin and realized that the actual text-based editor (the part I am interested in most) was a derivative of Cloud9, which is licensed under GPLv3. That made me suspicious, because typially GPL requires GPL on derivative projects. So I started a quick web search and found out that there is indeed an incompatibility.

This licensing incompatibility applies only when some Apache project software becomes a derivative work of some GPLv3 software, because then the Apache software would have to be distributed under GPLv3. This would be incompatible with ASF's requirement that all Apache software must be distributed under the Apache License 2.0.

For my current understanding the jQuery.xmleditor plugin is licensed wrong. However, I am not quite sure whether my current understanding is right. Can anybody perhaps enlighten me?

答:
The license incompatibility you found does not apply here. That restriction is a company policy of the Apache Software Foundation, but it is not part of the Apache License.

On the other hand, there is a license problem with jQuery.xmleditor. As they use code derived from a GPLv3 licensed library, the jQuery.xmleditor plugin must be distributed under the terms and conditions of the GPLv3 and everyone using the (unmodified) plugin is also bound by those terms and conditions for their project.

The fact that the GPL terms and conditions apply should have been made clear in the license information of jQuery.xmleditor.

Apart from giving incorrect information about which license terms are in effect, there are no further licensing problems. The authors of jQuery.xmleditor are within their rights to use a more permissive, GPL compatible, license for the code they wrote themselves. But those more permissive terms will only come into effect in modified versions where the GPL code has been removed.

If you are happy to comply with the GPL terms and conditions, you can go ahead and use the plugin under those terms.

Apart from that, it might be a good idea to inform the distributers of jQuery.xmleditor that the licensing information on their plugin appears to be incorrect due to their use of GPL licensed code.


问:
Why do some big projects, like Git and Debian, only use a mailing list and not an issue tracker?
Bug tracker for any decent sized project seem like a bit of a no-brainer to me - it makes it really easy to organise hundreds or thousands issues, without issues colliding or getting mixed up.

So when I see some really big projects, like Git, using a mailing list as the main method of coordinating maintenance and development, I get a bit blown away. Examples:

Git - Community page:

...Bug reports should be sent to this mailing list.

Debian bug tracking system, per Wikipedia:

...Its unique feature is that it doesn't have any form of web-interface to edit bug reports - all modification is done through email.

Many modern bug trackers have very good integration with email (you can receive comments or notifications about bugs you're watching, or that get assigned to you), as well as to version control systems (commits can be marked as resolving an issue, etc.). Much of this would have to be done manually with a mailing list, and you get tons of emails about bugs you're not interested in.

So what are the main advantages of a mailing list over a web-based bug tracker? Why do some big projects only use a mailing list?

答:
Keeps 9 year olds out.

No need to create a separate account for each forum.

[minor]Consistent user experience across different mailing lists and
a zero learning curve when subscribing to a new list.

Works offline. you could connect to the Internet and download a batch
of mails, then go hiking, write your replies while enjoying mother
nature and send them later.

Allows mail encrypting and/or signing via GPG.

Decentralized  - If the forum crashes, you'd still have  a copy, it's
also tamper resistant, an evil moderator/hacker cannot easily tamper
with what you've said. No one can undo history.

Allows filters, folders, and all the advanced organizational features of an
Email client.

"Push notifications"  - you can leave your Email client open and get
notifications of new replies.

One place to rule them all - no need to jump between different sites.

Immune to all the security vulnerabilities involving the web
(html/javascript/injections, etc)

No bloat - No badges, fancy moving signatures, ads, web beacons,
javascript bloat. It's all simple and to the point - discussion.

Less server burden than a LAMP setup.

One disadvantage of mailing lists that comes to mind is that forums are dividable into categories and subcategories while mailing lists are not.
This can be emulated by dividing a mailing list into several mailing lists, and then users can use the appropriate filters to put each message with its corresponding folder (Each folder being a category).
In web forums, this is automatic.


问:
How to signal that a method chain should not continue?
When doing method chaining, you have methods that return the object allowing you to continue the chain. However, you need to get values out of the object somehow.

Usually I've added a method that returns a value at the end, but this complicates matters if you add to the chain and that return method may not be valid anymore.

The way I view it each time you add a method onto a chain you are refining your result until you get your desired answer in the last method call. Having a final output method creates a restriction in that it needs to know about the last operation to know how to display the result.

Maybe you have a method that results in a string and one that results in an array your output method has to deal with both those cases. What if you add a method that stores your string result somewhere new? Now you have to update the output method to handle that case too.

Is there a way of letting a method know it's the last in the chain so should output its result?

答:
You can "signal" that a method chain should not continue by making the return type of the method void.  This wont "output" much but it will stop the method chain.  Also, depending on your language, you can stop it by returning a primitive like int.  But any time a method returns an object, that has a method on it, the chain can keep going.

In any OO language what normally comes out at the end (and at every step along the way) of a method chain is something called a "nameless temporary object".  It's nameless only because we didn't assign it to something to give it a name.  Instead we just stuck a dot next to it and called one of it's methods.  Once we do we get another "nameless temporary object" (which might be exactly the same object as before just now in a different state).  You can chain over and over until you get

(1) the behavior you want

(2) the type of object you want

(3) the object in the state you want

If the behavior is all that was wanted then you're finished.  If you wanted the last two then just stop chaining and you can give this a name by assigning it to something (or just pass the whole mess into something).

```<code>Greet.hello("world").hi("Mom");                                 // (1)
String max = Math.max(1,3).toString();                          // (2)
System.out.println( new Person().setName(name).setRank(rank) ); // (3)
</code>```

Typically every method in a chain is an "output" method.  You just stop when you have what you need.

Also, note that this:

```<code>Person person = new Person();
person = person.setName(name);
person = person.setRank(rank);
System.out.println(person);
</code>```

does exactly the same thing as (3).  A big advantage of a method chain is you don't have to stop and give things names that don't need names.

Body:
You can "signal" that a method chain should not continue by making the return type of the method void.  This wont "output" much but it will stop the method chain.  Also, depending on your language, you can stop it by returning a primitive like int.  But any time a method returns an object, that has a method on it, the chain can keep going.

In any OO language what normally comes out at the end (and at every step along the way) of a method chain is something called a "nameless temporary object".  It's nameless only because we didn't assign it to something to give it a name.  Instead we just stuck a dot next to it and called one of it's methods.  Once we do we get another "nameless temporary object" (which might be exactly the same object as before just now in a different state).  You can chain over and over until you get

(1) the behavior you want

(2) the type of object you want

(3) the object in the state you want

If the behavior is all that was wanted then you're finished.  If you wanted the last two then just stop chaining and you can give this a name by assigning it to something (or just pass the whole mess into something).

Greet.hello("world").hi("Mom");                                 // (1)
String max = Math.max(1,3).toString();                          // (2)
System.out.println( new Person().setName(name).setRank(rank) ); // (3)

Typically every method in a chain is an "output" method.  You just stop when you have what you need.

Also, note that this:

Person person = new Person();
person = person.setName(name);
person = person.setRank(rank);
System.out.println(person);

does exactly the same thing as (3).  A big advantage of a method chain is you don't have to stop and give things names that don't need names.


问:
What are the most common mistakes and anti-patterns NHibernate user programmers make?
What are the most common mistakes and anti-patterns NHibernate user programmers make? Please explain why those are bad practices or give link to resource for further reading.

For example:

One anti-pattern common for new NHibernate programmers is to use identity/native POID's instead of ORM style onces. Read more here...

答:
Trying to abstract it out so that you can switch to Entity Framework (or something else) at a later date.

This is much, much harder than most people who attempt it realise. There are numerous differences between the two that can trip you up in ways that can be quite subtle at times. It's also very uncommon for it to actually be needed in the end -- so much so that you can be meticulously trying to implement it for years before discovering that your approach is all wrong.

Also, it restricts you from using a whole lot of NHibernate's useful and important features such as second-level caching, interception, concurrency management, change tracking, prefetch queries and so on.

If there really were a valid need to switch between NHibernate and Entity Framework, there would be an actively developed project to support this on GitHub (perhaps something in a similar vein to CommonServiceLocator) with numerous contributors and pull requests.

OwnerDisplayName: Darius Kucinskas


问:
Speed up dynamic content delivery
Imagine a website operating from the US, providing some web services to customers around the world.

Sometimes is takes up to 200ms just to establish a connection between Australia and US.

It's pretty straightforward to accelerate static content delivery by introducing some CDN, but what are the options when dealing with dynamic web services?

Do any of the website accelerator businesses (akamai, cloudflare etc) actually own physical networks, or able to optimize routing between continents to speed up dynamic content delivery?

I know there is an option to clusterize the website itself across continents, but is it really the only way to go?

答:
If the dynamic parts repeat allot and are not unique per session, you can cache them for certain time.
for example, you can request a news list using AJAX and cache the response for 5 min.

The first request will pay the price of slowness but all the others will benefit from the CDN

Title: Speed up dynamic content delivery


问:
Should I worry about performance, even if there is no loss of convenience?
Assume an application that shows a data table. The data is loaded from a database when the program is initialized.

Each value in the table is represented by an input field, where each keypress in one of those fields causes a refresh:

The data is written to the database

Then, each value in the table is refreshed by reassigning the models to the data

My concern here is that each value is getting updated in order to recompute a summary, even those that weren't touched at all.

Yet, the application runs fast, the update is not causing any inconvenience to the user. Should I refactor my application nevertheless?

答:
I agree that accessing the database on every key press is not an optimal design.  I would not recommend that you write it that way if you were starting from scratch.

However, as a general rule, don't rewrite working code without a good reason.  If the application performs well, there is no reason to change it.  Just make sure that your assessment of the application as "fast" holds up in your real-world use case.  This means testing with enough records and enough concurrent connections to replicate what you expect in production.


答:
Conceptually, exceptions are to deal with "exceptional/unexpected" behavior of your application. If you want to log information, you should use a proper logging framework.

It's also much cleaner to see something like

```<code>...
} catch (Exception ex){
      logger.error(String.format("something went wrong with information %s %s", "infoA", "infoB"));
      throw ex;
}
</code>```

Title: Logging instance information in Exceptions

Body:
During development on a large existing codebase I've started to capture variable values in my Exception logging. For example:

```<code>public int Foo(int a, int b)
{
   int returnInt;
   try{
      returnInt = bar(a) * b;
   }
   catch (Exception ex){
      ex.Message += "a: {0}, b: {1}", a, b;
      logger.log(ex);
   }

   return returnInt;
}
</code>```

While I'm not asking about this specific pseudocode I wondered if there were any valid reasons to not do this?

To me it would seem that logging instance variables in addition to the more general error message and stack trace is a positive thing. However I've never seen it done elsewhere.

Body:
Conceptually, exceptions are to deal with "exceptional/unexpected" behavior of your application. If you want to log information, you should use a proper logging framework.

It's also much cleaner to see something like

...
} catch (Exception ex){
      logger.error(String.format("something went wrong with information %s %s", "infoA", "infoB"));
      throw ex;
}


答:
Quote from Nielsen. Response Times: The 3 Important Limits

The basic advice regarding response times has been about the same for thirty years [Miller 1968; Card et al. 1991]:

0.1 second is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.

1.0 second is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second, but the user does lose the feeling of operating directly on the data.

10 seconds is about the limit for keeping the user's attention focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect.

If you're designing GUI applications, performance should always be on your mind. If you should re-factor your current application however depends if the time investment is worth it.

Title: Should I worry about performance, even if there is no loss of convenience?

Body:
Assume an application that shows a data table. The data is loaded from a database when the program is initialized.

Each value in the table is represented by an input field, where each keypress in one of those fields causes a refresh:

The data is written to the database

Then, each value in the table is refreshed by reassigning the models to the data

My concern here is that each value is getting updated in order to recompute a summary, even those that weren't touched at all.

Yet, the application runs fast, the update is not causing any inconvenience to the user. Should I refactor my application nevertheless?


问:
Creating a websocket server on Linux
I want to create a websocket server and I've found a great article here. However C# will output an exe file.

I'd like to have it run on a linux box. What I want to do is to connect to the server, and when something happens on the filesystem to retrieve a message from the server (using the FileSystemWatcher on Windows or the iNotify daemon on linux) and the program will run the corresponding code.

So, how can such daemon for linux (in C#) or any other way to achieve this?

答: I develop a WebSocket component named WebSocketListener that supports Mono. Take a look on this guide about how to make it work with Mono.</p>

Title: Creating a websocket server on Linux


问:
Is a mocking framework useful if I'm unit testing a repository/database?
I'm trying to improve my testing skills. I frequently hear about mocking framework to build fake objects (as far as I understand). Right now I need to test my repository (the usual add, remove, update and GetById methods).

I do this test to be sure that every operation on the database happens correctly.

The question is: Do I really need to mock the repository? For instance, adding a fake repository, I will lose the database engine configuration test part (i.e. using a real repository, rather than a mock, my test will fail even if Entity Framework mapping is incorrect.)

Is this thought right? How should I handle this issue?

答:
There are several sides to unit-testing:

Unit-testing is meant to give you confidence that a component works as it should and that future changes don't break any of the current functionality.

Unit tests should be fast enough that you can execute them often without it feeling as a slowdown in your workflow. How fast they should exactly be and how often you should run them is open for debate (and depends to a large extent on the technology you use and your workflow), but you should still aim for them to be fast enough to not be an unwanted interruption.

Unit tests should be independent of execution order. If all tests pass, you should be able to execute them in all possible permutations of their execution order and still have all of them pass. In particular, no test must depend on being executed after another test.

With that in mind, lets go back to your question about mocking.

When testing the Repository itself, is mocking going to add anything to the points above? Probably not. The Repository is supposed to be the component that communicates with the Database and you want to verify that that happens correctly. And the tests are probably also not so extensive that it is hard to keep them independent and relatively fast.

When testing the rest of your application, it becomes a different story. As databases are generally very good at persisting stuff, also across test cases, and databases are not the fastest components around, the general experience is that testing against a real database makes it an order of magnitude harder to keep all your tests fast and independent.

As the tests of the Repository give you confidence that that component is working correctly, the advise is to stub/mock/fake it in the other tests. In those tests, your fake Repository can control exactly what gets returned and can do it directly from memory.

To round it all off, you also need a couple of end-to-end integration/acceptance tests to verify that the behavior of the stubs/fakes/mocks is consistent with the behavior of the real components.


答:
Testing against a DB is very easy - use transactions and rollback after you've performed your operation and checked the result. Alternatively, use a test DB where you populate a set of test data before every test run.

Unit testing doesn't have to be about isolating every tiny method - Martin Fowler describes a unit as a class plus connected classes when he talks about Agile. So a DB doesn't have to be a single insert statement against a purely empty DB (and shouldn't be as you'll want to check that it works against existing data that breaks constraints)

If you must unit test each method, the easiest way to do this with a DB is to put your SQL into stored procedures. Each procedures is, after all, a solitary method. Then you can test them just like any other method in your business logic classes - inside a transaction, set up some data (truncate, insert), run sproc, check result via a select or other return code, rollback. Easy.

Title: Is a mocking framework useful if I'm unit testing a repository/database?

Body:
I'm trying to improve my testing skills. I frequently hear about mocking framework to build fake objects (as far as I understand). Right now I need to test my repository (the usual add, remove, update and GetById methods).

I do this test to be sure that every operation on the database happens correctly.

The question is: Do I really need to mock the repository? For instance, adding a fake repository, I will lose the database engine configuration test part (i.e. using a real repository, rather than a mock, my test will fail even if Entity Framework mapping is incorrect.)

Is this thought right? How should I handle this issue?


问:
What does it mean when some technology is a "standard"?
I started learning Java EE 7 and I am frequently coming across this term "standard", and I don't understand what it means.

So, for example, here is a quotation from this book:

Contrary to SOAP and the WS-* stack, which rely on W3C standards, REST
  has no standard and is just a style of  architecture with design
  principles. REST applications rely heavily on many other standards:
  HTTP, URI, URL...

I have some idea of what that might mean, but I'm not sure.

The best explanation that I have come across is the definition from here.

答:
A standard is a standardized convention - either by a formal specification, or simply because a common convention has gained enough popularity to be dominant.

A de jure standard is a specification published by a standard committee. Some standard committees are ISO, ECMA, DIN, ANSI, and W3C.

Some examples of  de jure standards are the A4 paper size (ISO standard 219), the c# language (ECMA-334), etc.

The term 'de jure' is rarely used, and a 'de jure standard' is often just called a standard.

A de facto standard is a custom, convention, product, or system that has achieved a dominant position by public acceptance or market forces"

(source: wikipedia - I could't write it better myself)

A de facto standard does not necessarily follow any formal specification.

As Gudmundur Orn wrote in this answer, the Microsoft Office DOC format was a de facto standard. It had a dominant position, and it was normally assumed that people could read MS Word documents.

JSON is a funny beast, as it started out as a de facto standard. It has however since been formalized as ECMA-404, so it is now a 'de jure standard'.

It is however also the predominant format for exchanging data with HTTP-based APIs (to my knowledge), thus making it also the 'de facto standard' this purpose.


问:
Implementing a generic/dynamic custom property system in C#
I have an architecture design problem which I think is appropriate for this site.

Note that I have made an EDIT to this post below, reflecting my latest potential solution to this problem.

General problem description:

My primary goal is to design a software library/program (C#) to automate a very particular type of microscopy experiments. Our experimental setups consists of many distinct hardware devices that generally fall into a limited number of categories:

Point detector

XY sample stage

Autofocus device

...

The natural choice is to design an interface IDevice with some basic properties shared by all devices such as e.g. IDevice.Initialize(), IDevice.Name, ...

We can even design an abstract class, inheriting IDevice, e.g. DeviceBase implementing some functionalty common to all devices.

Likewise, we can also design interfaces for specific devices, each time implementing the common stuff (IXYSampleStage might hold e.g. IXYSampleStage.Move(posX, posY) or IXYSampleStage.AxisXStepSize).

Ultimately, I can implement all these interfaces in the final classes representing specific devices. I think I know what to do there.

However, not all devices of a class are exactly the same. Some manufacturers offer rich functionality on top of the standard stuff. An XY Stage might have e.g. any number of optional/non-standard parameters to set such as e.g. channel delays, PID control values or whatever.

To tackle this,

I need a mechanism to add additional properties (not methods,
  properties will suffice) to specific device classes. Higher level
  code, interacting with the devices should understand these added
  properties, be able to get/set them, however many there might be.

So much for the basic design problem.

What exists already

There is an OS software program, Micro Manager, which has such a system implemented, be it in C++ (full source here and no, I cannot use this SW directly for my purposes):

```<code>class PropertyBase
{
public:
   virtual ~PropertyBase() {}

   // property type
   virtual PropertyType GetType() = 0;

   // setting and getting values
   virtual bool Set(double dVal) = 0;
   virtual bool Set(long lVal) = 0;
   virtual bool Set(const char* Val) = 0;

   virtual bool Get(double& dVal) const = 0;
   virtual bool Get(long& lVal) const = 0;
   virtual bool Get(std::string& strVal) const = 0;

   // Limits
   virtual bool HasLimits() const = 0;
   virtual double GetLowerLimit() const = 0;
   virtual double GetUpperLimit() const = 0;
   virtual bool SetLimits(double lowerLimit, double upperLimit) = 0;

   // Some more stuff left out for brevity
   ...
};
</code>```

Subsequently, the Property class implements some of the pure virtual functions related to the limits.

Next, StringProperty, IntegerProperty and FloatProperty implement the Get()/Set() methods. These kinds of properties are defined in an enum which allows only these three kinds of property.

Properties can next be added to a PropertyCollection which is basically a kind of dictionary that is part of a device class.

This all works nicely. We use MM a lot in the lab for other types of experiments but when trying to do similar things in my C# solution I stumbled about a few more fundamental questions. Most of these have to do with not being quite sure how to leverage specific features offered by C#/.NET (generic but definitely also dynamics, ...) to perhaps improve the existing C++ implementation.

The questions:

First question:

To limit the types of properties allowed, MM defines an enum:

```<code>    enum PropertyType {
      Undef,
      String,
      Float,
      Integer
    };
</code>```

Whereas C# has reflection and a lot of built-in support for types/generics. I therefore considered this:

```<code>public interface IProperty<T>
{
   public T value { get; set; }

   ...
}
</code>```

I could next do an abstract PropertyBase<T> and ultimately

```<code>IntegerProperty : PropertyBase<int>
StringProperty : PropertyBase<string>
FloatProperty : PropertyBase<double>
</code>```

But this gets me in trouble when trying to put them into a collection because in .NET following is not possible:

```<code>PropertyCollection : Dictionary<string, IProperty<T>>
</code>```

Unless, perhaps, I adopt this strategy, i.e. have a non generic base class that only returns a type and then yet more base classes to actually implement my property system. However, this seems convoluted to me. Is there a better way?

I think that utilising the generic language features might allow me to do away with needing all these Get()/Set() methods in the MM example above, as I would be able to know the backing type of my property value.

I realise this is a very broad question but, there is a big gap between understanding the basics of some language features and being able to fully make the correct design decisions from the outset.

Second question

I am contemplating making my final device classes all inherit from a kind of DynamicDictionary (e.g. similar to the one from here):

```<code>    public class DynamicDictionary : DynamicObject
    {
        internal readonly Dictionary<string, object> SourceItems;

        public DynamicDictionary(Dictionary<string, object> sourceItems)
        {
            SourceItems = sourceItems;
        }
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (SourceItems.ContainsKey(binder.Name))
            {
                SourceItems[binder.Name.ToLower()] = value;
            }
            else
            {
                SourceItems.Add(binder.Name.ToLower(), value);
            }
            return true;
        }
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (SourceItems != null)
            {
                if (SourceItems.TryGetValue(binder.Name.ToLower(), out result))
                {
                    return true;
                }
            }
            result = null;
            return true;
        }
    }
}
</code>```

but instead of <string, object> I would then like to use <string, MyPropertyBase> where the string would be the alias for my property (which would correspond to the design choice from Q1).

Would doing such a thing make sense from a design standpoint?

I would actually only need to add custom properties to devices at design time (i.e. when writing a custom device driver). At runtime, I would only need to inspect my custom properties or get/set their values.

the C++ MM solves this by using a bunch of CreateProperty("alias", Property) methods in the device constructor, which again, works so maybe using dynamics here is overkill. But again, I am wondering if somebody could provide insight in possible advantages but certainly also disadvantages of going down the dynamic route.

To summarize

Are there .NET features (4.5) which I could leverage to implement some of the MM concepts in a more elegant way with a focus on the above mentioned specific matters?

Again, I do realise this is a very broad question and perhaps some of the possible answers are more a matter of taste/style than anything els but if so (this making the question unsuited for this platform), please provide feedback/comments such that I can adjust accordingly.

EDIT

I have spent some more thinking about this and tried to solve it in the following way:

First, an enum specifying the allowed propertytypes:

```<code>public enum PropertyType
{
    Undefined,
    String,
    Float,
    Integer
}
</code>```

Second, an interface IPropertyType that is responsible for checking values fed to a property of a specific type:

```<code>public interface IPropertyType
{
    Type BackingType { get; }

    PropertyType TypeAlias { get; }

    bool IsValueTypeValid(object value);
}
</code>```

Then, a base class implementing IPropertyType:

```<code>public bool IsValueTypeValid(object value)
    {
        if (value == null)
        {
            return true;
        }

        Type type = value.GetType();

        if (type == this.BackingType)
        {
            return true;
        }

        return false;
    }

...

public Type BackingType
    {
        get
        {
            switch (this.TypeAlias)
            {
                case PropertyType.Integer:
                    return typeof(long);
                case PropertyType.Float:
                    return typeof(double);
                case PropertyType.String:
                    return typeof(string);
                default:
                    return null;
            }
        }
    }
</code>```

I then have three IPropertyType: StringPropertyType, IntegerPropertyType and FloatPropertyType where each time, the property PropertyTypeAlias is set to one of the enum values.

I can now add my IPropertyType to IProperty types:

```<code>public interface IProperty
{
    string Alias { get; }

    /// If we want to limit the property to discrete values.
    Dictionary<string, object> AllowedValues { get; }

    bool HasLimits { get; }

    bool HasValue { get; }

    bool IsReadOnly { get; }

    /// Callback for HW operations using the property value.
    Func<PropertyFuncType, bool> PropertyFunction { set; }

    PropertyType TypeAlias { get; }

    object Value { get; set; }

    void AddAllowedValue(string alias, object value);

    void ClearAllowedValues();

    // On numeric properties, it might be usefull to limit the range of values.
    void SetLimits(object lowerLimit, object upperLimit);

    // These will do stuff on the HW...
    bool TryApply();

    bool TryUpdate();
}
</code>```

Here, the Value setter will run the validation on input value as defined by the IPropertyType.

IProperty is almost fully implemented in PropertyBase which also has a field of IPropertyType which gets set upon instance creation (and cannot be changed thereafter; a property cannot change type.

From the base class e.g.:

```<code>    enum PropertyType {
      Undef,
      String,
      Float,
      Integer
    };
</code>```0

That only leaves specific IProperty classes: StringProperty, IntegerProperty and FloatProperty where there is only one override, SetLimits() because it relies on comparison of values. Everything else can be in the base class:

```<code>    enum PropertyType {
      Undef,
      String,
      Float,
      Integer
    };
</code>```1

This way, I think I have a system that allows me to have a collection of IProperty that can actually hold data of different types (int, float or string) where for each type of IProperty I have the ability to implement value limits etc (i.e. stuff that is different, depending on the data type)...

However, I still have the impression that there are either better ways to do this sort of thing or that I am over engineering things.

Therefore, any feedback on this is still welcome.

EDIT 2

After more searching online I believe the last bits of code posted here in the previous edit are leaning towards the Adaptive Object Model "pattern" (if it really is that).

However, most resources on this topic seem to be quite old and I'm wondering if there are now better ways to achieve these types of things.

答: What you want pretty much sounds like WPF´s dependency properties and attached properties. You may want to look into the design of System.Windows.DependencyObject as a base class and System.Windows.DependencyProperty as the property class. It does involve a bit of overhead, but is really quite flexible.</p>


问:
How to measure (and improve) quality of bug-fixes?
I have the suspicion that many bug-fixes carried out by our developers sooner or later cause another bug, simply because the product is too complex.

I'd like to improve the quality of bug-fixes, i.e. make sure bug-fixes do not produce additional errors in the code. For that, I'd like to be able to measure how the quality changes as I apply various counter measures.

Is it a good idea to instruct bug-fixers to always look for the cause of their defect, and then evaluate the ratio of previous bug-fixes being such cause? I'm hesitant about this due to the obvious higher expenses and unwillingness of developers to blame themselves or fellow colleagues.

Is there a better approach?

答:
Are your developers working under time pressure? Do they have quiet working conditions? Do they have the best debugging tools the money can buy? Do you have testers?...

There are too many factors which can make bug solving a task which creates more bugs than it solves. Too many to be enumerated here. If you notice that for every closed ticket, QA opens two more, talk with your team, see what's wrong in the processes the team uses, find why the original bug existed in the first case.

For example, if a developer works under time pressure and pressure from the management and is assigned a ticket saying that when the original price is $0.89, the final one should be $1.20, the temptation would be to add:

```<code>if (price == 89) {
    return 120;
}
</code>```

This doesn't solve the problem when the price is $0.88 or $0.90, but the ticket is closed and the management is happy, for now.

Body:
Are your developers working under time pressure? Do they have quiet working conditions? Do they have the best debugging tools the money can buy? Do you have testers?...

There are too many factors which can make bug solving a task which creates more bugs than it solves. Too many to be enumerated here. If you notice that for every closed ticket, QA opens two more, talk with your team, see what's wrong in the processes the team uses, find why the original bug existed in the first case.

For example, if a developer works under time pressure and pressure from the management and is assigned a ticket saying that when the original price is $0.89, the final one should be $1.20, the temptation would be to add:

if (price == 89) {
    return 120;
}

This doesn't solve the problem when the price is $0.88 or $0.90, but the ticket is closed and the management is happy, for now.


问:
Is it overkill to wrap a collection in a simple class only for the sake of better readability?
I have the following map:

```<code>Map<Double, List<SoundEvent>> soundEventCells = new HashMap<Double, List<SoundEvent>>();
</code>```

This HashMap maps double values (which are points in time) to the corresponding SoundEvent 'cell': each 'cell' can contain a number of SoundEvents. That's why it's implemented as a List<SoundEvent>, because that's exactly what it is.

For the sake of better readability of the code, I thought about implementing a very simple static inner class like so:

```<code>private static class SoundEventCell {
    private List<SoundEvent> soundEvents = new ArrayList<SoundEvent>();
    public void addEvent(SoundEvent event){
        soundEvents.add(event);
    }
    public int getSize(){
        return soundEvents.size();
    }
    public SoundEvent getEvent(int index){
        return soundEvents.get(index);
    }
    // .. remove() method unneeded
}
</code>```

And than the map declaration (and a lot of other code) would look better, for example:

```<code>Map<Double, SoundEventCell> soundEventCells = new HashMap<Double, SoundEventCell>();
</code>```

Is this overkill? Would you do this in your projects?

答:
While it may aid in readability in some areas, it also can complicates things. I personally lean away from wrapping or extending collections for the sake of fluency, as the new wrapper, on initial reading, implies to me that there may be behavior I need to be aware of. Consider it a shade of Principle of Least Surprise.

Sticking with the interface implementation means I only need to worry about the interface.  The concrete implementation may, of course, house additional behavior, but I shouldn't need to worry about it. So, when I'm trying to find my way through someone's code, I prefer the plain interfaces for readability.

If, on the other hand, you're finding a use case that does benefit from added behavior, then you have an argument for improving the code by creating a full fledged class.


问:
Where to put database table/column names?
I'm making a web app that will be querying an existing database. I'm thinking of putting the names of the tables and columns and such into a single static class, and then referencing that when constructing queries. I think this would help with maintainability since if in the future a column gets renamed for some reason, it just needs to be changed in one place.

Is this a good way to do this? Is there a better way?

答:
In a properly decoupled architecture, your application should have no knowledge of the physical database model. To put the table and column names in your classes creates a dependency that could break your application if there are major changes to the database beyond simple table and column changes.

For an application of some size and complexity, the better practices are to use an object relational mapper (ORM) such as Entity Framework (as noted by Magus), NHibernate, or other more lightweight options. An ORM handles the mapping between the physical database and your classes so that each are independent.

Another option is to use a web service of some kind to provide that layer of abstraction between the physical database and your application.

These options allow you to make changes within a database or even switch database platforms, while keeping rework to a minimum.

If you are building a very simple application, and you don't anticipate many changes to the database, then an ORM or separate data service might be overkill. There's always a trade-off.


问:
How is Nginx handling its requests in terms of tasks or threading?
Recently I read up on Wikipedia about Nginx. What puzzled me was this paragraph:

Nginx uses an asynchronous event-driven approach to handling requests, instead of the Apache HTTP Server model that defaults to a threaded or process-oriented approach, where the Event MPM is required for asynchronous processing. Nginx's modular event-driven architecture[18] can provide more predictable performance under high loads.

Now I understand how both approaches, event-driven and threaded/process-oriented, work. But what I find confusing about this statement is that even asynchronous approaches need to delegate their work (once received) to some dedicated task/thread/process.

Or am I wrong?

答:
Every server that processes requests in parallel and shares a source of input (e.g., a port) has to delegate work somehow.  If you don't process requests in parallel, you have a single-threaded service; if you don't share a source of input, you have an array of single-threaded services.  The difference between the two models has more to do with how the work is carried out than how it's delegated.

The process- or thread-per-task model simplifies servicing a request because you can treat it as a single, linear task that runs from start to finish and stops when it needs to wait for something to happen.  The trade-off is that any time the task blocks or the OS decides its time slice is up, there has to be a context switch between what was running and what will be.  Every cycle you spend doing a context switch is a cycle you can't spend doing work, and there may be several of them involved in servicing a single request.

Programs that bill themselves as event-driven or asynchronous tend to treat work as a unit of data (i.e., a structure with information about the task at hand) rather than a unit of execution (i.e., a process or thread).  That means putting running worker threads on multiple cores that pull work units from a queue, handle some part of the job as described by the data and set it aside until the next thing happens. When the next thing does happen, whatever detected it just updates the task's information and puts it back on the queue to be handled.

Doing this reclaims all of the managing of state that was being done by the OS and puts it in the hands of the program.  The worker ends up a bit more complex, but because the state management can be tailored for the application, it ends up being a lot less ham-fisted (and therefore less expensive) than the wholesale register-and-stack swap you get during a context switch.  The OS can still force a context switch or the thread can voluntarily yield if it runs out of work, but either of those is a much-less-common event than the handful of them you'd get per request in the per-thread model.  This is a bit of an oversimplification, as there are other things you can do within this model to get even more out of the processors you have, but they're outside the scope of this answer.

That said, it is possible to write an event-driven program that uses the thread-per-task model, and it will have all of the same inefficiencies.


问:
Infinite while loop CPU usage
I'm coding an script in C, which is going to check constantly an array of events, the idea is to check if the Date and time of certain event is equal to de current time and trigger something, i'm doing this with a while(1){}, but this approach causes a high CPU usage, do you have any suggestion of how can i do this with a lower CPU usage ?</p>

答:
The quick and dirty solution is to add a sleep call to yield the processor to other applications.  This lowers the CPU usage tremendously.

A better solution if possible is to have your method invoked in a callback.  For example, Win32 UI event handling will let you register callbacks for specific events.

Title: Infinite while loop CPU usage