答:
The classes you've shown are implementations of nodes in some kind of tree structure.  The IsCollection property determines if this is a leaf node or a branch(?) node.  If IsCollection is true, then there is no "data" at this node, so you have to continue down the tree.  If IsCollection is false, then this is a leaf node, so it's valid to look at the Contract property.

The domain model seems to indicate that a contract can be made up of other contracts, and so on.

The most likely reason for it being the way it is, is because originally we just had ContractImplementation1, and then they realized that contracts could be nested like this.  So someone created the IContract interface for the generic node-in-a-tree (and really should have named it IContractNode or something) and then created ContractImplementation2 to be the branch.  This wasn't really the right way to do it.  The right way would be more like:

```<code>interface IContractNode
{
    bool IsLeaf { get; }
    // Only access this is IsLeaf is true
    Contract Contract { get; }
    // Only access this if IsLeaf is false
    ReadOnlyCollection<IContractNode> Children { get; }
}

class ContractNodeLeaf : IContractNode
{
    public ContractNodeLeaf(Contract contract)
    {
        if(contract == null) throw new ArgumentNullException("contract");
        this.Contract = contract;
    }
    public bool IsLeaf { get { return true; } }
    public Contract Contract { get; private set; }
    public ReadOnlyCollection<IContractNode> Children
        { get { return new List<IContractNode>().AsReadOnly(); }
}

class ContractNodeBranch : IContractNode
{
    public ContractNodeBranch(ReadOnlyCollection<IContractNode> children)
    {
        if(children== null) throw new ArgumentNullException("children");
        this.Children= children;
    }
    public bool IsLeaf { get { return false; } }
    public Contract Contract
        { get { throw new InvalidOperationException("I'm not a leaf!"); }
    public ReadOnlyCollection<IContractNode> Children { get; private set;}
}
</code>```

... where Contract is the original class, from before the change.

Title: Novel polymorphism - any reasons for this code?

Body:
As part of my work on a legacy C# application I've come across a novel (to me) use of an interface & concrete implementations.  I can't think of any reason why you'd do the following, but I'm pretty thick, so maybe someone else can?

```<code>public interface IContract
{
    ContractImplementation1 Contract { get; }
    bool IsCollection { get; }
    bool Touched { get; set; }
}

public class ContractImplementation1 : IContract
{
    public ContractImplementation1(string propertyOne, string propertyTwo, string propertyThree, string propertyFour)
    {
        PropertyOne = propertyOne;
        PropertyTwo = propertyTwo;
        PropertyThree = propertyThree;
        PropertyFour = propertyFour;
    }

    public ContractImplementation1 Contract { get { return this; } }
    public bool IsCollection { get { return false; } }
    public bool Touched { get; set; }

    public string PropertyOne { get; private set; }
    public string PropertyTwo { get; private set; }
    public string PropertyThree { get; private set; }
    public string PropertyFour { get; private set; }

    public override string ToString()
    {
        if (string.IsNullOrEmpty(PropertyFour))
            return string.Format("{0} => {1}: {2}", PropertyOne, PropertyTwo, PropertyThree);
        else
            return string.Format("{0} => {1}: {2} {3}", PropertyOne, PropertyTwo, PropertyThree, PropertyFour);
    }

}

public class ContractImplementation2 : IContract
{
    public ContractImplementation1 Contract { get { return null; } }
    public bool IsCollection { get { return true; } }
    public bool Touched { get; set; }

    public List<ContractImplementation1> Contracts = new List<ContractImplementation1>();
}
</code>```

I can't get my head around the super-type having a property that is a sub-type of itself.

Following Cosmin's answer: I can't get my head around why you'd have the sub-type as a property given that the property returns itself on the implementation (rather than a 'parent' of the same type i.e. a different instantiation of the super-type).

Body:
The classes you've shown are implementations of nodes in some kind of tree structure.  The IsCollection property determines if this is a leaf node or a branch(?) node.  If IsCollection is true, then there is no "data" at this node, so you have to continue down the tree.  If IsCollection is false, then this is a leaf node, so it's valid to look at the Contract property.

The domain model seems to indicate that a contract can be made up of other contracts, and so on.

The most likely reason for it being the way it is, is because originally we just had ContractImplementation1, and then they realized that contracts could be nested like this.  So someone created the IContract interface for the generic node-in-a-tree (and really should have named it IContractNode or something) and then created ContractImplementation2 to be the branch.  This wasn't really the right way to do it.  The right way would be more like:

interface IContractNode
{
    bool IsLeaf { get; }
    // Only access this is IsLeaf is true
    Contract Contract { get; }
    // Only access this if IsLeaf is false
    ReadOnlyCollection<IContractNode> Children { get; }
}

class ContractNodeLeaf : IContractNode
{
    public ContractNodeLeaf(Contract contract)
    {
        if(contract == null) throw new ArgumentNullException("contract");
        this.Contract = contract;
    }
    public bool IsLeaf { get { return true; } }
    public Contract Contract { get; private set; }
    public ReadOnlyCollection<IContractNode> Children
        { get { return new List<IContractNode>().AsReadOnly(); }
}

class ContractNodeBranch : IContractNode
{
    public ContractNodeBranch(ReadOnlyCollection<IContractNode> children)
    {
        if(children== null) throw new ArgumentNullException("children");
        this.Children= children;
    }
    public bool IsLeaf { get { return false; } }
    public Contract Contract
        { get { throw new InvalidOperationException("I'm not a leaf!"); }
    public ReadOnlyCollection<IContractNode> Children { get; private set;}
}

... where Contract is the original class, from before the change.


问:
Engineering interview candidate refuses to use whiteboard
Today I experienced a first in a technical interview. The candidate refused to use the whiteboard to solve an algorithm question, as I requested. There was no sort of disability at play or anything (outside of nervousness). He simply said that he is uncomfortable using a whiteboard for difficult questions.

Oddly enough, we were able to work through it with me standing over his shoulder looking at his notepad. He even communicated his thoughts effectively enough for me to help him over the inevitable bumps. After this I asked him how he felt about collaborative work (as collaboration here is heavy) and he said he loves it. I asked him if he likes to get together with other developers to hash over problems on the whiteboard to which he said yes.

Is this some sort of red flag or am I just reading too much into this? In our environment, collaboration is a must.

ADDITIONAL DETAIL:

The candidate was being evaluated for a lead development position, in which case he spends much of his time communicating with his developers and less time coding than an individual contributor.

答:
I'd be concerned with someone refusing a common request who doesn't feel the need to provide an explanation. Hopefully they phrased it as a preference and not a refusal. No indication that this is a temporary problem (twisted ankle?) That seems socially awkward to me.  When hiring your imagination is just going run wild and come up with the worse-case scenarios.

If the position allows you to insulate this individual from working at the board, it's less of a problem, but what problem has this symptom? Leading others requires you to recognize when you're not putting people at ease and should make an effort to explain the situation. I refuse to use this framework, period = WTF?

ContentLicense: CC BY-SA 3.0


问:
Is it possible to half-way synchronize javascript functions that include async calls?
I am wondering if there exists a way to half way synchronize javascript functions, where data is requested on the fly. I don't want to make it purely blocking (which I guess is impossible), I just want a nice way to write the overall algorithm in one piece.

Let's take the following example:

```<code>function(){
    command1;
    var x1 = something;
    async_function(x1, callback1);
}
function callback1(data){
    var x2 = command2(data);
    async_function2(x2, callback2);
}
function callback2(data1){
    command3(data1);
}
</code>```

I would like to write something like:

```<code>function(){
    command1;
    var x1 = something;
    call(async_function, [x1], callback1);
    var x2 = command2(data);
    call(async_function2, [x2], callback2);
    command3(data1);
}
</code>```

I tried playing around with the caller property of functions, but I'm not familiar enough with the execution environment.

I also tried writing a function "call" like above, using the apply function to pass in a custom callback which returns the result of the async function to it's caller.

What bugs me is that while programming\debugging, I have to follow the code from one function into another into another (just like the movie inception). I want one place to write the high-level algorithm without decomposing it into many functions.

For example, If I want to write A* algorithm, but the "getNeighbors" function is asynchronous.

答:
Since what you are really talking about here is a stylistic/readability issue (at least, that's the way I read it), you might be a little out of luck, because all the all alteratives I can think of aren't great.

Really you have two options, write multiple distinct functions like you have done above, or use closures to bring it all "inline" (as it were), where you will quickly run into issues with keeping the horizontal whitespace sane.

That being said, if you really do want to keep it all in a single block that looks like one procedure, I would probably go with the closure option:

```<code>function(){
    command1;
    var x1 = something;
    async_function(x1, function (data){
        var x2 = command2(data);
        async_function2(x2, function (data1){
            command3(data1);
        });
    });
}
</code>```

Which could of course be spaced out like this, quite close to your desired example:

```<code>function(){
    command1;
    var x1 = something;
    async_function(x1, function (data){
    var x2 = command2(data);
    async_function2(x2, function (data1){
    command3(data1);
    });});
}
</code>```

...but personally I would probably try and stick to the first version.

In general though I wouldn't do either. I would keep it broken down into small and obviously named routines, I find it makes for much more readable code in the long run and any sane IDE will allow you to jump from function call to function definition and vice versa, so navigation shouldn't be too much of an issue.

Body:
Since what you are really talking about here is a stylistic/readability issue (at least, that's the way I read it), you might be a little out of luck, because all the all alteratives I can think of aren't great.

Really you have two options, write multiple distinct functions like you have done above, or use closures to bring it all "inline" (as it were), where you will quickly run into issues with keeping the horizontal whitespace sane.

That being said, if you really do want to keep it all in a single block that looks like one procedure, I would probably go with the closure option:

function(){
    command1;
    var x1 = something;
    async_function(x1, function (data){
        var x2 = command2(data);
        async_function2(x2, function (data1){
            command3(data1);
        });
    });
}

Which could of course be spaced out like this, quite close to your desired example:

function(){
    command1;
    var x1 = something;
    async_function(x1, function (data){
    var x2 = command2(data);
    async_function2(x2, function (data1){
    command3(data1);
    });});
}

...but personally I would probably try and stick to the first version.

In general though I wouldn't do either. I would keep it broken down into small and obviously named routines, I find it makes for much more readable code in the long run and any sane IDE will allow you to jump from function call to function definition and vice versa, so navigation shouldn't be too much of an issue.


问:
How to represent calculated deadline is reasonable?
As a Lead Programmer my responsibilities include calculating the deadlines of the projects.

To do this I have discussion with related team players and calculate a deadline estimation. Sometimes, I got a scared voice from CTO saying that the estimated deadline is too much. Then I have to shorten the deadline. With a shorter deadline, programmers have to work with extra pressure.

How can I represent (points) to the CTO that the calculated deadline is reasonable?

答:
There is a huge body of work on software cost and schedule estimation.  At its heart, the fact is that there is always some uncertainty, which means that there is always a nonzero probability of missing the deadline (and! a nonzero probability of coming in early).  When you pull a deadline in, you are increasing the probability that you will miss the deadline, and you are increasing the probability that you are going to have other problems, because you are going to demand that your people cut corners, and cutting corners ALWAYS comes back to haunt you.

If you've kept historical data on projects and costs, you can calibrate an estimator to your organization, and you are then in a position to tell the CTO "This is what our historical data indicates we can do.  If you want us to pull the deadline in, we will, but understand that you are going to have to accept increased risk of a blown deadline and serious bugs in the product."

The worst case I ever saw was at General Dynamics.  A failure of the software source code control system meant that a bug was inadvertently introduced.  An accelerated release schedule meant that a critical test, intended to detect that specific kind of bug, did not get performed until a day or two after the release had been sent out to Edwards AFB for flight test.  The test showed a safety of flight issue that could result in loss of the test airplane and/or death of the test pilot.  (The test airplane cost many, many millions of dollars, far more than the production airplanes,because it was a hand-built one-of-a-kind bird.  Good test pilots cost almost as much, and they are very long-lead items.)  All hell broke loose.


问:
Unit testing for a scientific computing library
I've had a bit of experience with unit testing before, in what I call (not pejoratively) the classic software engineering project: an MVC, with a user GUI, a database, business logic in the middle layer, etc. Now I'm writing a scientific computing library in C# (yeah, I know the C# is too slow, use C, don't reinvent the wheel, and all of that, but we have a lot of people doing scientific computation in my faculty in C#, and we sort of need it). It's a small project, in terms of the software development industry, because I'm writing it mostly by myself, and from time to time with help of a few colleagues. Also, I don't get paid for it, and most important, is an academic project. I mean, I expect it to have professional quality some day, because I'm planning on going open source, and hopefully with enough time it will grow a community of developers.

Anyway, the project is getting big (around 18,000 lines of code, which I think is big for a one man's project), and its getting out of my hands. I'm using git for source control, and I think I got pretty all right, but I'm testing like old school, I mean, writing full console applications that test a big part of the system, mainly because I have no idea how to do unit testing in this scenario, although I feel that is what I should be doing. The problem is that the library contains mostly algorithms, for instance, graph algorithms, classifiers, numerical solvers, random distributions, etc. I just don't know how to specify tiny test cases for each of these algorithms, and since many of them are stochastic I don't know how to validate correctness. For classification, for instance, are some metrics like precision and recall, but these metrics are better for comparing two algorithms than for judging a single algorithm. So, how can I define correctness here?

Finally there is also the problem of performance. I know its a whole different set of tests, but performance is one of the important features of a scientific tools, rather than user satisfaction, or other software engineering metrics.

One of my biggest problems is with data structures. The only test I can come up for a kd-tree is a stress test: insert a lot of random vectors and then perform a lot of random queries, and compare against a naive linear search. The same for performance. And with numerical optimizers, I have benchmark functions which I can test, but then again, this is a stress test. I don't think these tests can be classified as unit tests, and most important, run continuously, since most of them are rather heavy. But I also think that these tests need to be done, I can't just insert two elements, pop the root, and yes, it works for the 0-1-n case.

So, what, if any, is the (unit) testing approach for this kind of software? And how do I organize the unit tests and the heavy ones around the code-build-commit-integrate cycle?

答:
I would say that scientific computing is actually quite well-suited for unit testing. You have definite inputs and outputs, clearly-defined pre- and postconditions that probably won't change around every other week according to some designer's whim, and no hard-to-test UI requirements.

You name some elements that might cause trouble; here's what to do about them:

randomized algorithms: there are two possibilities. If you actually want to test the randomizing itself, just schedule a big number of repetitions and assert that the expected proportion of cases meets the desired criterion, with big enough error margins that spurious test failures will be quite rare. (A test suite that unreliably signals phantom bugs is much worse than one that doesn't catch every conceivable defect.) Alternatively, use a configurable random source and replace the system clock (or whatever it is you use) with a deterministic source via dependency injection so that your tests become fully predictable.

algorithms defined only in terms of precision/recall: nothing stops you from putting in a whole set of input cases and measuring precision and recall by adding them all up; it's just a question of semi-automatically generating such test cases efficiently so that providing the test data doesn't become the bottleneck to your productivity. Alternatively, specifying some judiciously chosen input/output pairs and asserting that the algorithm computes exactly the desired input can also work if the routine is predictable enough.

non-functional requirements: If the specification really gives explicit space/time requirements, then you basically have to run entire suites of input/output pairs and verify that the resource usage conforms approximately to the required usage pattern. The trick here is to calibrate your own test class first, so that you don't measure ten problems with different sizes that end up being all too fast to measure, or which take so long that running the test suite becomes impractical. You can even write a small use case generator that creates test cases of different sizes, depending how fast the PU is that it's running on.

fast- and slow-running tests: whether it's unit or integration tests, you often end up with a lot of very fast tests and a few very slow ones. Since running your tests regularly is very valuable, I usually go the pragmatic route and separate everything I have into a fast and a slow suite, so that the fast one can run as often as possible (certainly before every commit), and never mind whether two tests 'semantically' belong together or not.


答:
I've been typing since I was 12 partially because I sucked at handwriting even then. If I'm handwriting a solution, 9/10 of my brain is on the writing part 1/20th is on the nervous part and what's left is some combination of what I ate that day, the funny thing my wife did, how the new guy compares to Leonard Nimoy and the problem. Give me a freaking computer not a whiteboard or a notepad. We don't all work and think in the same way.

More specific to your question, he doesn't like whiteboards? How does this hinder his ability to communicate to engineers in a world where we have 1,001 options to communicate any idea we want?

Title: Engineering interview candidate refuses to use whiteboard

Body:
Today I experienced a first in a technical interview. The candidate refused to use the whiteboard to solve an algorithm question, as I requested. There was no sort of disability at play or anything (outside of nervousness). He simply said that he is uncomfortable using a whiteboard for difficult questions.

Oddly enough, we were able to work through it with me standing over his shoulder looking at his notepad. He even communicated his thoughts effectively enough for me to help him over the inevitable bumps. After this I asked him how he felt about collaborative work (as collaboration here is heavy) and he said he loves it. I asked him if he likes to get together with other developers to hash over problems on the whiteboard to which he said yes.

Is this some sort of red flag or am I just reading too much into this? In our environment, collaboration is a must.

ADDITIONAL DETAIL:

The candidate was being evaluated for a lead development position, in which case he spends much of his time communicating with his developers and less time coding than an individual contributor.


问:
Does anyone work 10 hours shifts as a developer?
I would like to switch from a 5 day week to a 4 day, but maintain a 40 hour working week.

Would the 10 hour days affect your ability to be productive? I hate our public transit system so if I could reduce my transportation by 20% I would be happy.

If other developers who work 10 hours shifts could be clear as the their experiences with it that would help me.

I think my boss is flexible enough that he would be cool with it.

答:
If you're the odd one, at the first sign of stagnation someone will start wondering if you're not just pretending to work 2 hours more.

They will start checking on you and this will force you to look busy.

Trying to look busy will stress you out, make you miserable, and actually drain your energy, annihilating you productivity. This circumstance will rise more suspicions and you'll find yourself trapped into a vicious circle.

Then, there will be the day there's an emergency, and you're not available, and they'll talk behind your back. Then maybe you'll be able to solve that issue telecommuting for that day, but some bosses will hate having to pay you extra for that. Especially if it's a weekday.

Regular telecommuting presents other issues, but it might be more sustainable on the long run.


答:
I can't guarantee that this would solve the issues you're running into, but Queuing is often used to chain a series of asynchronous calls so that they happen one after another.

I wrote a Queue script a while ago which I will be using as an example:

```<code>(function () {
    var q = new Queue();
    q.queue(function (next) {
        //this gets run first
        //next is used to dequeue the next item in the queue
        someAsyncCall(someData, /*callback*/next);
    }, function (next) {
        //this gets run second
        someOtherAsyncCall(moreData, next);
    }, function (next) {
        //this gets run third
        moarAsync(allthedata, next);
    });
}());
</code>```

Queues allow for code flow to be written in a linear fashion without massive amounts of nesting. This particular implementation doesn't handle data passing directly.

Title: Is it possible to half-way synchronize javascript functions that include async calls?

Body:
I am wondering if there exists a way to half way synchronize javascript functions, where data is requested on the fly. I don't want to make it purely blocking (which I guess is impossible), I just want a nice way to write the overall algorithm in one piece.

Let's take the following example:

```<code>function(){
    command1;
    var x1 = something;
    async_function(x1, callback1);
}
function callback1(data){
    var x2 = command2(data);
    async_function2(x2, callback2);
}
function callback2(data1){
    command3(data1);
}
</code>```

I would like to write something like:

```<code>function(){
    command1;
    var x1 = something;
    call(async_function, [x1], callback1);
    var x2 = command2(data);
    call(async_function2, [x2], callback2);
    command3(data1);
}
</code>```

I tried playing around with the caller property of functions, but I'm not familiar enough with the execution environment.

I also tried writing a function "call" like above, using the apply function to pass in a custom callback which returns the result of the async function to it's caller.

What bugs me is that while programming\debugging, I have to follow the code from one function into another into another (just like the movie inception). I want one place to write the high-level algorithm without decomposing it into many functions.

For example, If I want to write A* algorithm, but the "getNeighbors" function is asynchronous.

Body:
I can't guarantee that this would solve the issues you're running into, but Queuing is often used to chain a series of asynchronous calls so that they happen one after another.

I wrote a Queue script a while ago which I will be using as an example:

(function () {
    var q = new Queue();
    q.queue(function (next) {
        //this gets run first
        //next is used to dequeue the next item in the queue
        someAsyncCall(someData, /*callback*/next);
    }, function (next) {
        //this gets run second
        someOtherAsyncCall(moreData, next);
    }, function (next) {
        //this gets run third
        moarAsync(allthedata, next);
    });
}());

Queues allow for code flow to be written in a linear fashion without massive amounts of nesting. This particular implementation doesn't handle data passing directly.


问:
Why do programming languages, especially C, use curly braces and not square ones?
The definition of "C-Style language" can practically be simplified down to "uses curly braces ({})."  Why do we use that particular character (and why not something more reasonable, like [], which doesn't require the shift key at least on US keyboards)?

Is there any actual benefit to programmer productivity that comes from these braces, or should new language designers look for alternatives (i.e. the guys behind Python)?

Wikipedia tells us that C uses said braces, but not why. A statement in Wikipedia article on the List of C-based programming languages suggests that this syntax element is somewhat special:

Broadly speaking, C-family languages are those that use C-like block syntax (including curly braces to begin and end the block)...

答:
Square braces [] are easier to type, ever since IBM 2741 terminal that was "widely used on Multics" OS, which in turn had Dennis Ritchie, one of C language creators as dev team member.

Note the absence of curly braces at IBM 2741 layout!

In C, square braces are "taken" as these are used for arrays and pointers. If language designers expected arrays and pointers to be more important / used more frequently than code blocks (which sounds like a reasonable assumption at their side, more on historic context of coding style below), that would mean curly braces would go to "less important" syntax.

Importance of arrays is pretty apparent in the article The Development of the C Language by Ritchie. There's even an explicitly stated assumption of "prevalence of pointers in C programs".

...new language retained a coherent and workable (if unusual) explanation of the semantics of arrays... Two ideas are most characteristic of C among languages of its class: the relationship between arrays and pointers... The other characteristic feature of C, its treatment of arrays... has real virtues. Although the relationship between pointers and arrays is unusual, it can be learned. Moreover, the language shows considerable power to describe important concepts, for example, vectors whose length varies at run time, with only a few basic rules and conventions...

For further understanding of historical context and coding style of the time when C language was created, one needs to take into account that "origin of C is closely tied to the development of the Unix" and, specifically, that porting OS to a PDP-11 "led to the development of an early version of C" (quotes source). According to Wikipedia, "in 1972, Unix was rewritten in the C programming language".

Source code of various old versions of Unix is available online, eg at The Unix Tree site. Of various versions presented there, most relevant seems to be Second Edition Unix dated 1972-06:

The second edition of Unix was developed for the PDP-11 at Bell Labs by Ken Thompson, Dennis Ritchie and others. It extended the First Edition with more system calls and more commands. This edition also saw the beginning of the C language, which was used to write some of the commands...

You can browse and study C source code from  Second Edition Unix (V2) page to get an idea of typical coding style of the time.

A prominent example that supports the idea that back then it was rather important for programmer to be able to type square brackets with ease can be found in V2/c/ncc.c source code:

```<code>/* C command */

main(argc, argv)
char argv[][]; {
    extern callsys, printf, unlink, link, nodup;
    extern getsuf, setsuf, copy;
    extern tsp;
    extern tmp0, tmp1, tmp2, tmp3;
    char tmp0[], tmp1[], tmp2[], tmp3[];
    char glotch[100][], clist[50][], llist[50][], ts[500];
    char tsp[], av[50][], t[];
    auto nc, nl, cflag, i, j, c;

    tmp0 = tmp1 = tmp2 = tmp3 = "//";
    tsp = ts;
    i = nc = nl = cflag = 0;
    while(++i < argc) {
        if(*argv[i] == '-' & argv[i][1]=='c')
            cflag++;
        else {
            t = copy(argv[i]);
            if((c=getsuf(t))=='c') {
                clist[nc++] = t;
                llist[nl++] = setsuf(copy(t));
            } else {
            if (nodup(llist, t))
                llist[nl++] = t;
            }
        }
    }
    if(nc==0)
        goto nocom;
    tmp0 = copy("/tmp/ctm0a");
    while((c=open(tmp0, 0))>=0) {
        close(c);
        tmp0[9]++;
    }
    while((creat(tmp0, 012))<0)
        tmp0[9]++;
    intr(delfil);
    (tmp1 = copy(tmp0))[8] = '1';
    (tmp2 = copy(tmp0))[8] = '2';
    (tmp3 = copy(tmp0))[8] = '3';
    i = 0;
    while(i<nc) {
        if (nc>1)
            printf("%s:\n", clist[i]);
        av[0] = "c0";
        av[1] = clist[i];
        av[2] = tmp1;
        av[3] = tmp2;
        av[4] = 0;
        if (callsys("/usr/lib/c0", av)) {
            cflag++;
            goto loop;
        }
        av[0] = "c1";
        av[1] = tmp1;
        av[2] = tmp2;
        av[3] = tmp3;
        av[4] = 0;
        if(callsys("/usr/lib/c1", av)) {
            cflag++;
            goto loop;
        }
        av[0] = "as";
        av[1] = "-";
        av[2] = tmp3;
        av[3] = 0;
        callsys("/bin/as", av);
        t = setsuf(clist[i]);
        unlink(t);
        if(link("a.out", t) | unlink("a.out")) {
            printf("move failed: %s\n", t);
            cflag++;
        }
loop:;
        i++;
    }
nocom:
    if (cflag==0 & nl!=0) {
        i = 0;
        av[0] = "ld";
        av[1] = "/usr/lib/crt0.o";
        j = 2;
        while(i<nl)
            av[j++] = llist[i++];
        av[j++] = "-lc";
        av[j++] = "-l";
        av[j++] = 0;
        callsys("/bin/ld", av);
    }
delfil:
    dexit();
}
dexit()
{
    extern tmp0, tmp1, tmp2, tmp3;

    unlink(tmp1);
    unlink(tmp2);
    unlink(tmp3);
    unlink(tmp0);
    exit();
}

getsuf(s)
char s[];
{
    extern exit, printf;
    auto c;
    char t, os[];

    c = 0;
    os = s;
    while(t = *s++)
        if (t=='/')
            c = 0;
        else
            c++;
    s =- 3;
    if (c<=8 & c>2 & *s++=='.' & *s=='c')
        return('c');
    return(0);
}

setsuf(s)
char s[];
{
    char os[];

    os = s;
    while(*s++);
    s[-2] = 'o';
    return(os);
}

callsys(f, v)
char f[], v[][]; {

    extern fork, execv, wait, printf;
    auto t, status;

    if ((t=fork())==0) {
        execv(f, v);
        printf("Can't find %s\n", f);
        exit(1);
    } else
        if (t == -1) {
            printf("Try again\n");
            return(1);
        }
    while(t!=wait(&status));
    if ((t=(status&0377)) != 0) {
        if (t!=9)       /* interrupt */
            printf("Fatal error in %s\n", f);
        dexit();
    }
    return((status>>8) & 0377);
}

copy(s)
char s[]; {
    extern tsp;
    char tsp[], otsp[];

    otsp = tsp;
    while(*tsp++ = *s++);
    return(otsp);
}

nodup(l, s)
char l[][], s[]; {

    char t[], os[], c;

    os = s;
    while(t = *l++) {
        s = os;
        while(c = *s++)
            if (c != *t++) goto ll;
        if (*t++ == '\0') return (0);
ll:;
    }
    return(1);
}

tsp;
tmp0;
tmp1;
tmp2;
tmp3;
</code>```

It is interesting to note how pragmatic motivation of picking characters to denote language syntax elements based on their use in targeted practical applications resembles Zipf's Law as explained in this terrific answer...

observed relationship between frequency and length is called Zipf's Law

...with the only difference that length in above statement is substituted by / generalized as speed of typing.

Body:
Square braces [] are easier to type, ever since IBM 2741 terminal that was "widely used on Multics" OS, which in turn had Dennis Ritchie, one of C language creators as dev team member.

Note the absence of curly braces at IBM 2741 layout!

In C, square braces are "taken" as these are used for arrays and pointers. If language designers expected arrays and pointers to be more important / used more frequently than code blocks (which sounds like a reasonable assumption at their side, more on historic context of coding style below), that would mean curly braces would go to "less important" syntax.

Importance of arrays is pretty apparent in the article The Development of the C Language by Ritchie. There's even an explicitly stated assumption of "prevalence of pointers in C programs".

...new language retained a coherent and workable (if unusual) explanation of the semantics of arrays... Two ideas are most characteristic of C among languages of its class: the relationship between arrays and pointers... The other characteristic feature of C, its treatment of arrays... has real virtues. Although the relationship between pointers and arrays is unusual, it can be learned. Moreover, the language shows considerable power to describe important concepts, for example, vectors whose length varies at run time, with only a few basic rules and conventions...

For further understanding of historical context and coding style of the time when C language was created, one needs to take into account that "origin of C is closely tied to the development of the Unix" and, specifically, that porting OS to a PDP-11 "led to the development of an early version of C" (quotes source). According to Wikipedia, "in 1972, Unix was rewritten in the C programming language".

Source code of various old versions of Unix is available online, eg at The Unix Tree site. Of various versions presented there, most relevant seems to be Second Edition Unix dated 1972-06:

The second edition of Unix was developed for the PDP-11 at Bell Labs by Ken Thompson, Dennis Ritchie and others. It extended the First Edition with more system calls and more commands. This edition also saw the beginning of the C language, which was used to write some of the commands...

You can browse and study C source code from  Second Edition Unix (V2) page to get an idea of typical coding style of the time.

A prominent example that supports the idea that back then it was rather important for programmer to be able to type square brackets with ease can be found in V2/c/ncc.c source code:

/* C command */

main(argc, argv)
char argv[][]; {
    extern callsys, printf, unlink, link, nodup;
    extern getsuf, setsuf, copy;
    extern tsp;
    extern tmp0, tmp1, tmp2, tmp3;
    char tmp0[], tmp1[], tmp2[], tmp3[];
    char glotch[100][], clist[50][], llist[50][], ts[500];
    char tsp[], av[50][], t[];
    auto nc, nl, cflag, i, j, c;

    tmp0 = tmp1 = tmp2 = tmp3 = "//";
    tsp = ts;
    i = nc = nl = cflag = 0;
    while(++i < argc) {
        if(*argv[i] == '-' & argv[i][1]=='c')
            cflag++;
        else {
            t = copy(argv[i]);
            if((c=getsuf(t))=='c') {
                clist[nc++] = t;
                llist[nl++] = setsuf(copy(t));
            } else {
            if (nodup(llist, t))
                llist[nl++] = t;
            }
        }
    }
    if(nc==0)
        goto nocom;
    tmp0 = copy("/tmp/ctm0a");
    while((c=open(tmp0, 0))>=0) {
        close(c);
        tmp0[9]++;
    }
    while((creat(tmp0, 012))<0)
        tmp0[9]++;
    intr(delfil);
    (tmp1 = copy(tmp0))[8] = '1';
    (tmp2 = copy(tmp0))[8] = '2';
    (tmp3 = copy(tmp0))[8] = '3';
    i = 0;
    while(i<nc) {
        if (nc>1)
            printf("%s:\n", clist[i]);
        av[0] = "c0";
        av[1] = clist[i];
        av[2] = tmp1;
        av[3] = tmp2;
        av[4] = 0;
        if (callsys("/usr/lib/c0", av)) {
            cflag++;
            goto loop;
        }
        av[0] = "c1";
        av[1] = tmp1;
        av[2] = tmp2;
        av[3] = tmp3;
        av[4] = 0;
        if(callsys("/usr/lib/c1", av)) {
            cflag++;
            goto loop;
        }
        av[0] = "as";
        av[1] = "-";
        av[2] = tmp3;
        av[3] = 0;
        callsys("/bin/as", av);
        t = setsuf(clist[i]);
        unlink(t);
        if(link("a.out", t) | unlink("a.out")) {
            printf("move failed: %s\n", t);
            cflag++;
        }
loop:;
        i++;
    }
nocom:
    if (cflag==0 & nl!=0) {
        i = 0;
        av[0] = "ld";
        av[1] = "/usr/lib/crt0.o";
        j = 2;
        while(i<nl)
            av[j++] = llist[i++];
        av[j++] = "-lc";
        av[j++] = "-l";
        av[j++] = 0;
        callsys("/bin/ld", av);
    }
delfil:
    dexit();
}
dexit()
{
    extern tmp0, tmp1, tmp2, tmp3;

    unlink(tmp1);
    unlink(tmp2);
    unlink(tmp3);
    unlink(tmp0);
    exit();
}

getsuf(s)
char s[];
{
    extern exit, printf;
    auto c;
    char t, os[];

    c = 0;
    os = s;
    while(t = *s++)
        if (t=='/')
            c = 0;
        else
            c++;
    s =- 3;
    if (c<=8 & c>2 & *s++=='.' & *s=='c')
        return('c');
    return(0);
}

setsuf(s)
char s[];
{
    char os[];

    os = s;
    while(*s++);
    s[-2] = 'o';
    return(os);
}

callsys(f, v)
char f[], v[][]; {

    extern fork, execv, wait, printf;
    auto t, status;

    if ((t=fork())==0) {
        execv(f, v);
        printf("Can't find %s\n", f);
        exit(1);
    } else
        if (t == -1) {
            printf("Try again\n");
            return(1);
        }
    while(t!=wait(&status));
    if ((t=(status&0377)) != 0) {
        if (t!=9)       /* interrupt */
            printf("Fatal error in %s\n", f);
        dexit();
    }
    return((status>>8) & 0377);
}

copy(s)
char s[]; {
    extern tsp;
    char tsp[], otsp[];

    otsp = tsp;
    while(*tsp++ = *s++);
    return(otsp);
}

nodup(l, s)
char l[][], s[]; {

    char t[], os[], c;

    os = s;
    while(t = *l++) {
        s = os;
        while(c = *s++)
            if (c != *t++) goto ll;
        if (*t++ == '\0') return (0);
ll:;
    }
    return(1);
}

tsp;
tmp0;
tmp1;
tmp2;
tmp3;

It is interesting to note how pragmatic motivation of picking characters to denote language syntax elements based on their use in targeted practical applications resembles Zipf's Law as explained in this terrific answer...

observed relationship between frequency and length is called Zipf's Law

...with the only difference that length in above statement is substituted by / generalized as speed of typing.


问:
Haskell AND Lisp vs. Haskell OR Lisp
I currently code with C, C++, and Python. I'm wanting to pick up a functional programming language, and right now I'm leaning toward Haskell. I do NOT want to start a "Haskell vs Lisp" war here; what I want to know is this: if I learn Haskell primarily for exposure to functional programming, what benefits, if any, will I gain from later learning Lisp?

答:
I suggest learning both, Haskell first, then Common Lisp. My experience with Haskell was that the static typing seemed to be a restricting annoyance at first, but once I got used to it, I noticed that most of my type errors had logic errors hiding behind them. When you get to this point, and the next milestone, which is learning to think in types and define your own types as a means of expressing your solution, you'll be ready for Common Lisp.

With Common Lisp, you can add monads, currying, and everything you liked from Haskell, but you also get multiple inheritance like Frank Shearar mentioned, and generic functions with multiple dispatch, and an advanced exception handling system.

So why not just learn Common Lisp first? Coming from a procedural and OOP background, my experience has been that I didn't really understand functional programming until I had to use it exclusively. Once functional programming is comfortable, you can add the rest of the tools that Common Lisp makes available, and use whatever tool is best at the task at hand.

Title: Haskell AND Lisp vs. Haskell OR Lisp

ContentLicense: CC BY-SA 2.5


问:
Designing status management for a file processing module
The background

One of the functionality of a product that I am currently working on is to process a set of compressed files ( containing XML files ) that will be made available at a fixed location periodically (local or remote location - doesn't really matter for now) and dump the contents of each XML file in a database. I have taken care of the design for a generic parsing module that should be able to accommodate the parsing of any file type as I have explained in my question linked below. There is no need to take a look at the following link to answer my question but it would definitely provide a better context to the problem

Generic file parser design in Java using the Strategy pattern

The Goal

I want to be able to keep a track of the status of each XML file and the status of each compressed file containing the XML files. I can probably have different statuses defined for the XML files such as NEW, PROCESSING, LOADING, COMPLETE or FAILED. I can derive the status of a compressed file based on the status of the XML files within the compressed file. e.g status of the compressed file is COMPLETE if no XML file inside the compressed file is in a FAILED state or status of the compressed file is FAILED if the status of at-least one XML file inside the compressed file is FAILED.

A possible solution

The Model

I need to maintain the status of each XML file and the compressed file. I will have to define some POJOs for holding the information about an XML file as shown below. Note that there is no need to store the status of a compressed file  as the status of a compressed file can be derived from the status of its XML files.

```<code>public class FileInformation {

    private String compressedFileName;
    private String xmlFileName;
    private long lastModifiedDate;
    private int status;

    public FileInformation(final String compressedFileName,
            final String xmlFileName, final long lastModified, final int status) {
        this.compressedFileName = compressedFileName;
        this.xmlFileName = xmlFileName;
        this.lastModifiedDate = lastModified;
        this.status = status;
    }
}
</code>```

I can then have a class called StatusManager that aggregates a Map of FileInformation instances and provides me the status of a given file at any given time in the lifetime of the appliciation as shown below :

```<code>public class StatusManager {
    private Map<String,FileInformation> processingMap = new HashMap<String,FileInformation>();

    public void add(FileInformation fileInformation) {
        fileInformation.setStatus(0); // 0 will indicates that the file is in NEW state. 1 will indicate that the file is in process and so on..
        processingMap.put(fileInformation.getXmlFileName(),fileInformation);
    }

    public void update(String filename,int status) {
        FileInformation fileInformation = processingMap.get(filename);
        fileInformation.setStatus(status);
    }

}
</code>```

That takes care of the model for the sake of explanation.

So whats my question?

Edited after comments from Loki and answer from  Eric : -

I would like to know if there are any existing design patterns that I can refer to while coming up with a design. I would also like to know how I should go about designing the status management classes.

I am more interested in understanding how I can model the status management classes. I am not interested in how other components are going to be updated about a change in status at the moment as suggested by Eric.

答:
The State pattern is used to define behavior of an object based on its current state, which isn't really a good fit for this problem if I read your question correctly (although I understood the instinct to look at that pattern). It'd work if you had code that was something like:

```<code>if (status.equals("COMPLETED"))
{
    doSomethingForCompleted();
}
else if (status.equals("FAILED"))
{
    doSomethingForFailure();
}
// You get the idea...
</code>```

Given the way your example is set up, I think you'd want a combination of the Observer pattern like gnat suggested, and the Mediator pattern, which you're largely doing with your StatusManager already. StatusManager can notify your code with the new set of statuses after add() or update() calls.

Body:
The State pattern is used to define behavior of an object based on its current state, which isn't really a good fit for this problem if I read your question correctly (although I understood the instinct to look at that pattern). It'd work if you had code that was something like:

if (status.equals("COMPLETED"))
{
    doSomethingForCompleted();
}
else if (status.equals("FAILED"))
{
    doSomethingForFailure();
}
// You get the idea...

Given the way your example is set up, I think you'd want a combination of the Observer pattern like gnat suggested, and the Mediator pattern, which you're largely doing with your StatusManager already. StatusManager can notify your code with the new set of statuses after add() or update() calls.


问:
What is a general solution to allow the client to choose the concrete instance of a method output?
What is the general solutions to allow the client to choose the concrete instance of a method output?

For example, in the Lucene API the search method receives and modifies the collector input parameter, but this is generally regarded as a bad practice:

```<code>IndexReader reader = DirectoryReader.open(index);
IndexSearcher searcher = new IndexSearcher(reader);
TopScoreDocCollector collector = TopScoreDocCollector.create(10, true);
searcher.search(q, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
</code>```

An alternative would be to provide a Factory as input and have the search method return the instance created.

What else?

答:
Generics - quite obviously? In C# it might look like:

```<code>public class Searcher
{
    public IEnumerable<T> GetResults<T>()
    {
        return new[] { default(T) };
    }
}
</code>```

And then:

```<code>var searcher = new Searcher();
IEnumerable<string> results = searcher.GetResults<string>();
</code>```

Body:
Generics - quite obviously? In C# it might look like:

public class Searcher
{
    public IEnumerable<T> GetResults<T>()
    {
        return new[] { default(T) };
    }
}

And then:

var searcher = new Searcher();
IEnumerable<string> results = searcher.GetResults<string>();


答:
Two of the major influences to C were the Algol family of languages (Algol 60 and Algol 68) and BCPL (from which C takes its name).

BCPL was the first curly bracket programming language, and the curly
  brackets survived the syntactical changes and have become a common
  means of denoting program source code statements. In practice, on
  limited keyboards of the day, source programs often used the sequences
  $( and $) in place of the symbols { and }. The single-line '//'
  comments of BCPL, which were not taken up in C, reappeared in C++, and
  later in C99.

From http://www.princeton.edu/~achaney/tmve/wiki100k/docs/BCPL.html

BCPL introduced and implemented several innovations which became quite
  common elements in the design of later languages. Thus, it was the
  first curly bracket programming language (one using { } as block
  delimiters), and it was the first language to use // to mark inline
  comments.

From http://progopedia.com/language/bcpl/

Within BCPL, one often sees curly braces, but not always.  This was a limitation of the keyboards at the time.  The characters $( and $) were lexicographically equivalent to { and }.  Digraphs and trigraphs were maintained in C (though a different set for curly brace replacement - ??< and ??>).

The use of curly braces was further refined in B (which preceded C).

From Users' Reference to B by Ken Thompson:

```<code>/* The following function will print a non-negative number, n, to
  the base b, where 2<=b<=10,  This routine uses the fact that
  in the ASCII character set, the digits 0 to 9 have sequential
  code values.  */

printn(n,b) {
        extern putchar;
        auto a;

        if(a=n/b) /* assignment, not test for equality */
                printn(a, b); /* recursive */
        putchar(n%b + '0');
}
</code>```

There are indications that curly braces were used as short hand for begin and end within Algol.

I remember that you also included them in the 256-character card code
  that you published in CACM, because I found it interesting that you
  proposed that they could be used in place of the Algol 'begin' and
  'end' keywords, which is exactly how they were later used in the C
  language.

From http://www.bobbemer.com/BRACES.HTM

The use of square brackets (as a suggested replacement in the question) goes back even further.  As mentioned, the Algol family influenced C.  Within Algol 60 and 68 (C was written in 1972 and BCPL in 1966), the square bracket was used to designate an index into an array or matrix.

```<code>BEGIN
  FILE F(KIND=REMOTE);
  EBCDIC ARRAY E[0:11];
  REPLACE E BY "HELLO WORLD!";
  WRITE(F, *, E);
END.
</code>```

As programmers were already familiar with square brackets for arrays in Algol and BCPL, and curly braces for blocks in BCPL, there was little need or desire to change this when making another language.

The updated question includes an addendum of productivity for curly brace usage and mentions python.  There are some other resources that do this study though the answer boils down to "Its anecdotal, and what you are used to is what you are most productive with."  Because of the widely varying skills in programming and familiarity with different languages, these become difficult to account for.

See also: Stack Overflow Are there statistical studies that indicates that Python is “more productive”?

Much of the gains would be dependent on the IDE (or lack of) that is used.  In vi based editors, putting the cursor over one matching open/close and pressing % will then move the cursor to the other matching character.  This is very efficient with C based languages back in the old days - less so now.

A better comparison would be between {} and begin/end which was the options of the day (horizontal space was precious).  Many Wirth languages were based on a begin and end style (Algol (mentioned above), pascal (many are familiar with), and the Modula family).

I have difficulty finding any that isolate this specific language feature - at best I can do is show that the curly brace languages are much more popular than begin end languages and it is a common construct.  As mentioned in Bob Bemer link above, the curly brace was used to make it easier to program as shorthand.

From Why Pascal is Not My Favorite Programming Language

C and Ratfor programmers find 'begin' and 'end' bulky compared to { and }.

Which is about all that can be said - its familiarity and preference.

Title: Why do programming languages, especially C, use curly braces and not square ones?

Body:
The definition of "C-Style language" can practically be simplified down to "uses curly braces ({})."  Why do we use that particular character (and why not something more reasonable, like [], which doesn't require the shift key at least on US keyboards)?

Is there any actual benefit to programmer productivity that comes from these braces, or should new language designers look for alternatives (i.e. the guys behind Python)?

Wikipedia tells us that C uses said braces, but not why. A statement in Wikipedia article on the List of C-based programming languages suggests that this syntax element is somewhat special:

Broadly speaking, C-family languages are those that use C-like block syntax (including curly braces to begin and end the block)...

Body:
Two of the major influences to C were the Algol family of languages (Algol 60 and Algol 68) and BCPL (from which C takes its name).

BCPL was the first curly bracket programming language, and the curly
  brackets survived the syntactical changes and have become a common
  means of denoting program source code statements. In practice, on
  limited keyboards of the day, source programs often used the sequences
  $( and $) in place of the symbols { and }. The single-line '//'
  comments of BCPL, which were not taken up in C, reappeared in C++, and
  later in C99.

From http://www.princeton.edu/~achaney/tmve/wiki100k/docs/BCPL.html

BCPL introduced and implemented several innovations which became quite
  common elements in the design of later languages. Thus, it was the
  first curly bracket programming language (one using { } as block
  delimiters), and it was the first language to use // to mark inline
  comments.

From http://progopedia.com/language/bcpl/

Within BCPL, one often sees curly braces, but not always.  This was a limitation of the keyboards at the time.  The characters $( and $) were lexicographically equivalent to { and }.  Digraphs and trigraphs were maintained in C (though a different set for curly brace replacement - ??< and ??>).

The use of curly braces was further refined in B (which preceded C).

From Users' Reference to B by Ken Thompson:

/* The following function will print a non-negative number, n, to
  the base b, where 2<=b<=10,  This routine uses the fact that
  in the ASCII character set, the digits 0 to 9 have sequential
  code values.  */

printn(n,b) {
        extern putchar;
        auto a;

        if(a=n/b) /* assignment, not test for equality */
                printn(a, b); /* recursive */
        putchar(n%b + '0');
}

There are indications that curly braces were used as short hand for begin and end within Algol.

I remember that you also included them in the 256-character card code
  that you published in CACM, because I found it interesting that you
  proposed that they could be used in place of the Algol 'begin' and
  'end' keywords, which is exactly how they were later used in the C
  language.

From http://www.bobbemer.com/BRACES.HTM

The use of square brackets (as a suggested replacement in the question) goes back even further.  As mentioned, the Algol family influenced C.  Within Algol 60 and 68 (C was written in 1972 and BCPL in 1966), the square bracket was used to designate an index into an array or matrix.

BEGIN
  FILE F(KIND=REMOTE);
  EBCDIC ARRAY E[0:11];
  REPLACE E BY "HELLO WORLD!";
  WRITE(F, *, E);
END.

As programmers were already familiar with square brackets for arrays in Algol and BCPL, and curly braces for blocks in BCPL, there was little need or desire to change this when making another language.

The updated question includes an addendum of productivity for curly brace usage and mentions python.  There are some other resources that do this study though the answer boils down to "Its anecdotal, and what you are used to is what you are most productive with."  Because of the widely varying skills in programming and familiarity with different languages, these become difficult to account for.

See also: Stack Overflow Are there statistical studies that indicates that Python is “more productive”?

Much of the gains would be dependent on the IDE (or lack of) that is used.  In vi based editors, putting the cursor over one matching open/close and pressing % will then move the cursor to the other matching character.  This is very efficient with C based languages back in the old days - less so now.

A better comparison would be between {} and begin/end which was the options of the day (horizontal space was precious).  Many Wirth languages were based on a begin and end style (Algol (mentioned above), pascal (many are familiar with), and the Modula family).

I have difficulty finding any that isolate this specific language feature - at best I can do is show that the curly brace languages are much more popular than begin end languages and it is a common construct.  As mentioned in Bob Bemer link above, the curly brace was used to make it easier to program as shorthand.

From Why Pascal is Not My Favorite Programming Language

C and Ratfor programmers find 'begin' and 'end' bulky compared to { and }.

Which is about all that can be said - its familiarity and preference.


答:
C (and subsequently C++ and C#) inherited its bracing style from its predecessor B, which was written by Ken Thompson (with contributions from Dennis Ritchie) in 1969.

This example is from the Users' Reference to B by Ken Thompson (via Wikipedia):

```<code>/* The following function will print a non-negative number, n, to
   the base b, where 2<=b<=10,  This routine uses the fact that
   in the ASCII character set, the digits 0 to 9 have sequential
   code values.  */

printn(n,b) {
        extern putchar;
        auto a;

        if(a=n/b) /* assignment, not test for equality */
                printn(a, b); /* recursive */
        putchar(n%b + '0');
}
</code>```

B itself was again based on BCPL, a language written by Martin Richards in 1966 for the Multics Operating system. B's bracing system used only round braces, modified by additional characters (Print factorials example by Martin Richards, via Wikipedia):

```<code>GET "LIBHDR"

LET START() = VALOF $(
        FOR I = 1 TO 5 DO
                WRITEF("%N! = %I4*N", I, FACT(I))
        RESULTIS 0
)$

AND FACT(N) = N = 0 -> 1, N * FACT(N - 1)
</code>```

The curly braces used in B and subsequent languages "{...}" is an improvement Ken Thompson made over the original compound brace style in BCPL "$(...)$".

Body:
C (and subsequently C++ and C#) inherited its bracing style from its predecessor B, which was written by Ken Thompson (with contributions from Dennis Ritchie) in 1969.

This example is from the Users' Reference to B by Ken Thompson (via Wikipedia):

/* The following function will print a non-negative number, n, to
   the base b, where 2<=b<=10,  This routine uses the fact that
   in the ASCII character set, the digits 0 to 9 have sequential
   code values.  */

printn(n,b) {
        extern putchar;
        auto a;

        if(a=n/b) /* assignment, not test for equality */
                printn(a, b); /* recursive */
        putchar(n%b + '0');
}

B itself was again based on BCPL, a language written by Martin Richards in 1966 for the Multics Operating system. B's bracing system used only round braces, modified by additional characters (Print factorials example by Martin Richards, via Wikipedia):

GET "LIBHDR"

LET START() = VALOF $(
        FOR I = 1 TO 5 DO
                WRITEF("%N! = %I4*N", I, FACT(I))
        RESULTIS 0
)$

AND FACT(N) = N = 0 -> 1, N * FACT(N - 1)

The curly braces used in B and subsequent languages "{...}" is an improvement Ken Thompson made over the original compound brace style in BCPL "$(...)$".


问:
Naming guard clauses that throw exceptions
I have a function evaluate() that parses a String for some variables and replaces them with their corresponding value:

```<code>public String evaluate() {
    String result = templateText;
    for (Entry<String, String> entry : variables.entrySet()) {
        String regex = "\\$\\{" + entry.getKey() + "\\}";
        result = result.replaceAll(regex, entry.getValue());
    }
    if (result.matches(".*\\$\\{.+\\}.*")) {    //<--check if a variable wasn't replaced
        throw new MissingValueException();
    }
    return result;
}
</code>```

Since the evaluate() function now does 2 things, it first replaces the variables with the values AND check for any variables that weren't replaced, I thought about refactoring it to:

```<code>public String evaluate() {
    String result = templateText;
    for (Entry<String, String> entry : variables.entrySet()) {
        String regex = "\\$\\{" + entry.getKey() + "\\}";
        result = result.replaceAll(regex, entry.getValue());
    }
    checkForMissingValues(result);
}

private void checkForMissingValues(String result) {
    if (result.matches(".*\\$\\{.+\\}.*")) {
        throw new MissingValueException();
    }
}
</code>```

Now is this a good name for the function checkForMissingValues? I mean it does check for missing values, but it also throws an exception.

I thought about renaming it to throwExceptionIfMissingValueWasFound(), but this name tells HOW the function does it more than WHAT the function is doing.

Is there a standard for naming such functions that check for a condition then throw an exception?

答:
I don't think this warrants a separate method.
I also noticed several things:

You create a Pattern object for each variable in your Map. Pattern object creation is expensive (requires parsing). You then evaluate the regex on the string with replaceAll. So if you have 100 variables that becomes 100 regexes parsed and created then string is scanned 100 times. That's inefficient.

Your regex to scan for missing variables is exceedingly expensive. It will scan each character in your string many many many times, especially if it contains ${.

What you need to do is flip the logic. Find strings ${x} in text and retrieve variables from your map to fill that, throwing an exception the first time you encounter a missing variable.

```<code>public String evaluate() {
    Matcher matcher = Pattern.compile("\\$\\{(\\.+?\\)}").matcher(templateText);
    StringBuilder result = new StringBuilder(templateText.length());
    while(matcher.find()) {
        String val = variables.get(matcher.group(1));
        if (val == null) throw new MissingValueException();
        matcher.appendReplacement(result, val);
    }
    matcher.appendTail(result);
    return result.toString();
}
</code>```

This will search the string only once with only a single regex. It will fail on first missing variable. If you have 100 variables defined but only 1 appears in the template only 1 replace is done.

Body:
I don't think this warrants a separate method.
I also noticed several things:

You create a Pattern object for each variable in your Map. Pattern object creation is expensive (requires parsing). You then evaluate the regex on the string with replaceAll. So if you have 100 variables that becomes 100 regexes parsed and created then string is scanned 100 times. That's inefficient.

Your regex to scan for missing variables is exceedingly expensive. It will scan each character in your string many many many times, especially if it contains ${.

What you need to do is flip the logic. Find strings ${x} in text and retrieve variables from your map to fill that, throwing an exception the first time you encounter a missing variable.

public String evaluate() {
    Matcher matcher = Pattern.compile("\\$\\{(\\.+?\\)}").matcher(templateText);
    StringBuilder result = new StringBuilder(templateText.length());
    while(matcher.find()) {
        String val = variables.get(matcher.group(1));
        if (val == null) throw new MissingValueException();
        matcher.appendReplacement(result, val);
    }
    matcher.appendTail(result);
    return result.toString();
}

This will search the string only once with only a single regex. It will fail on first missing variable. If you have 100 variables defined but only 1 appears in the template only 1 replace is done.


答:
Well first of all, methods in C# follow the Pascal convention, so it should be Evaluate  and not evaluate.

Second: It is natural for methods to throw exceptions in, well, exceptional scenarios so you DONT have to name your method to signify this.

Third: It is not normal to throw an exception due to an internal check (unless you have a specific need). Ideally the method should return a bool which states whether the check succeeded or failed. So the method signature should ideally be:

```<code>private bool IsMissingValues(String result)
</code>```

Next, a method name does not always have to explain every single detail of what it does, always read it in conjunction with the class in which it is defined.

Hence, String.Replace is sufficient; String.ReplaceThisStringWithAnother is overkill.

Speaking of which, your evaluate method should ideally be called Replace or something as that it what it essentially does.

Also private methods can be relatively less 'wordy' than public ones since no one else except you will see it (ok fine, that's debatable).

Title: Naming guard clauses that throw exceptions

Body:
I have a function evaluate() that parses a String for some variables and replaces them with their corresponding value:

```<code>public String evaluate() {
    String result = templateText;
    for (Entry<String, String> entry : variables.entrySet()) {
        String regex = "\\$\\{" + entry.getKey() + "\\}";
        result = result.replaceAll(regex, entry.getValue());
    }
    if (result.matches(".*\\$\\{.+\\}.*")) {    //<--check if a variable wasn't replaced
        throw new MissingValueException();
    }
    return result;
}
</code>```

Since the evaluate() function now does 2 things, it first replaces the variables with the values AND check for any variables that weren't replaced, I thought about refactoring it to:

```<code>public String evaluate() {
    String result = templateText;
    for (Entry<String, String> entry : variables.entrySet()) {
        String regex = "\\$\\{" + entry.getKey() + "\\}";
        result = result.replaceAll(regex, entry.getValue());
    }
    checkForMissingValues(result);
}

private void checkForMissingValues(String result) {
    if (result.matches(".*\\$\\{.+\\}.*")) {
        throw new MissingValueException();
    }
}
</code>```

Now is this a good name for the function checkForMissingValues? I mean it does check for missing values, but it also throws an exception.

I thought about renaming it to throwExceptionIfMissingValueWasFound(), but this name tells HOW the function does it more than WHAT the function is doing.

Is there a standard for naming such functions that check for a condition then throw an exception?

Body:
Well first of all, methods in C# follow the Pascal convention, so it should be Evaluate  and not evaluate.

Second: It is natural for methods to throw exceptions in, well, exceptional scenarios so you DONT have to name your method to signify this.

Third: It is not normal to throw an exception due to an internal check (unless you have a specific need). Ideally the method should return a bool which states whether the check succeeded or failed. So the method signature should ideally be:

private bool IsMissingValues(String result)

Next, a method name does not always have to explain every single detail of what it does, always read it in conjunction with the class in which it is defined.

Hence, String.Replace is sufficient; String.ReplaceThisStringWithAnother is overkill.

Speaking of which, your evaluate method should ideally be called Replace or something as that it what it essentially does.

Also private methods can be relatively less 'wordy' than public ones since no one else except you will see it (ok fine, that's debatable).


答:
```<code>public String evaluate() {
    String result = replaceVariablesWithValues();
       // Extract the for loop code to the new method listed above

    if (resultContainsVariables(result)) {
         // All variables should have been replaced
        throw new MissingValueException();
    }
    return result;
}
</code>```

Above is my proposal for how to refactor.

The proposed evaluate function describes succinctly both the general functionality (replace variables with values) as well as the exception case (if the result contains variables, throw an exception).

The details of the regex evaluations should be extracted to helper functions because one should not need to mentally parse the regex to understand the contract and control flow of evaluate. Also, I suggest making the regex prefix and suffix constants.

I suggest keeping the throw statement in evaluate. It is not obvious what a "check" or guard function does, but knowing what such a function does is required to understand the contract of evaluate.

Body:
public String evaluate() {
    String result = replaceVariablesWithValues();
       // Extract the for loop code to the new method listed above

    if (resultContainsVariables(result)) {
         // All variables should have been replaced
        throw new MissingValueException();
    }
    return result;
}

Above is my proposal for how to refactor.

The proposed evaluate function describes succinctly both the general functionality (replace variables with values) as well as the exception case (if the result contains variables, throw an exception).

The details of the regex evaluations should be extracted to helper functions because one should not need to mentally parse the regex to understand the contract and control flow of evaluate. Also, I suggest making the regex prefix and suffix constants.

I suggest keeping the throw statement in evaluate. It is not obvious what a "check" or guard function does, but knowing what such a function does is required to understand the contract of evaluate.


问:
Should I use abstract or virtual methods?
If we assume that it is not desirable for the base class to be a pure interface class, and using the 2 examples from below, which is a better approach, using the abstract or virtual method class definition?

The advantage of "abstract" version is that it is probably looks cleaner and forces the derived class to give a hopefully meaningful implementation.

The advantage of the "virtual" version is that it can be easily pulled in by other modules and used for testing without adding a bunch of underlying framework like the abstract version requires.

Abstract Version:

```<code>public abstract class AbstractVersion
{
    public abstract ReturnType Method1();
    public abstract ReturnType Method2();
             .
             .
    public abstract ReturnType MethodN();

    //////////////////////////////////////////////
    // Other class implementation stuff is here
    //////////////////////////////////////////////
}
</code>```

Virtual Version:

```<code>public class VirtualVersion
{
    public virtual ReturnType Method1()
    {
        return ReturnType.NotImplemented;
    }

    public virtual ReturnType Method2()
    {
        return ReturnType.NotImplemented;
    }
             .
             .
    public virtual ReturnType MethodN()
    {
        return ReturnType.NotImplemented;
    }

    //////////////////////////////////////////////
    // Other class implementation stuff is here
    //////////////////////////////////////////////
}
</code>```

答: My vote, if I were consuming your stuff, would be for the abstract methods.  That goes along with "fail early."  It may be a pain at declaration time to add all methods (though any decent refactoring tool will do this quickly), but at least I know what the problem is immediately and fix it.  I'd rather that than be debugging 6 months and 12 people's worth of changes later to see why we're suddenly getting a not implemented exception.</p>


问:
BackgroundWorker vs. Async/Await
I am new to C# development and wish to create a more responsive UI. In my preliminary research, I have seen two methods for achieving this:

Multi-threading in conjunction with the BackgroundWorker class.

The newer Async/Await modifiers.

Does newer mean better? What's the difference between the two methods? If I wish to create a new project, how do I choose which method to go with?

EDIT: Maybe I should specify. I am creating a Windows Forms application, where all necessary data will be saved/loaded on the local disk. I will also be communicating with several USB devices.

答:
You will be able to accomplish your task using BackgroundWorker. It is a well known class, and many people have used it.

The new C# 5 async and await keywords basically just make it easier to write readable asynchronous code. There may be fewer tutorials and examples of how to accomplish various tasks with these keywords rather than BackgroundWorker.

Unless you need to use an older version of C#, I suggest learning how to use async and await.

Title: BackgroundWorker vs. Async/Await


问:
Testing interaction with large CRM database
In our company we have two large systems, basically they are scoring and CRM. Both have large SQL Server databases running on Windows servers on the intranet. These two databases are managed by other department, which we have a direct contact with.

Neither of those systems have any external APIs except for some stored procedures (hereinafter "SPs"), which we use to input all the data from our (web-dev team) two applications, which are a public web site and a web-based CRM.

There are problems which make this kind of integration a nightmare:

There are no proper copies of databases for testing. There are some occasional copies which may or may not be up-to-date and being synced manually, which make them practically useless in "ASAP-situations" (all the time).

All sorts of modifications in stored procedures code are being made straight on the production databases (!!!), which obviously cause us a lot of problems.

Stored procedures code is not documented, poorly commented and mostly not well-written. Just to say that I've spent last two days "decrypting" two SPs, one of which is ~2400 SLOC long and has many magic numbers and vars like @str1.

To make it easier and safer:

We made kind of "API-server", which is basically a SOAP server which does queries to SPs and gives back whatever queries return together with some nice status messages. This helps us decouple our apps from the chaos, but it barely simplifies our task when it comes to writing and tesing new functionality.

We store some IDs and other constants from these databases in our databases to prevent using magic numbers in our code whenever possible, but still we have to collect and fill in all the data manually with sqlcmd (which is very uncomfortable because of the Windows cmd disability to handle copying, pasting and displaying text).

I wish we could have some proper process of testing interaction with those databases, but what we have today is just another copy of CRM database which we have to sync manually somehow.

My questions are:

How can we make all the changes made on production databases automatically propagate into testing copies? I can think of something like .bat-script, but maybe there are better tools. I doubt (because of previous experience) we can ask other department to do some replication, so I'm asking for something we can make ourselves and convince that other department to use.

How can we easily sync some data without copying all the data? For example, we need to have an up-to-date copy of all dictionaries/taxonomies, but not the data about clients (which is a lot of data and will take significant time to copy). Again, I'm thinking of some script, but may there be something with just a bunch of checkboxes to select.

What is the best approach for testing the interactions through our "API-server"? I mean, suppose I made a request via SOAP with some fake data and no errors occured - how can I be sure the data is there in that external DB and it is consistent? It is sort of black/grey box testing and I don't know how to deal with it.

答:
How can we make all the changes made on production databases automatically propagate into
  testing copies? I can think of something like .bat-script, but maybe there are better tools. I doubt (because of previous experience) we can ask other department to do some replication, so I'm asking for something we can make ourselves and convince that other department to use.

Use standard backup/restore mechanisms provided by your database vendor. If your other department makes a daily backup of the production database (automatically), they surely can make a daily backup for testing purposes using the same mechanism. See here

http://msdn.microsoft.com/de-de/library/ms187510.aspx

for information about the options of backing up an MS SQL Server.

How can we easily sync some data without copying all the data?

Well, the optimal way depends much on the data model, the number of records and the complexity of the schema. Copying only a part of the records may need a specifially designed program which transfers the data in the correct order, without violating constraints. Perhaps it is easier to make a full backup/restore first, and afterwards delete everything you don't need in the copy and keep the rest for further processing. That may be too slow in your case, or probably fast enough, impossible to know without further details. Another idea is to use differential backups, see here for further details.

but still we have to collect and fill in all the data manually with sqlcmd (which is very uncomfortable because of the Windows cmd disability to handle copying, pasting and displaying text)

If cmd is not powerful enough, why don't you use something more powerful like Powershell?

suppose I made a request via SOAP with some fake data and no errors occured - how can I be sure the data is there in that external DB and it is consistent

Simple - query for that data, either via your SOAP API, or by adding some SP to your test database especially designed for testing purposes. Of course, the re-adding of the SP code to the DB should be reproducible, so you can add it automatically to your testing copy of the database everytime you made a copy of the production DB.


答:
The async and await keywords will not make your application more responsive on their own. They simply make the calling and handling of methods that return Task objects more convenient. In order to make async/await actually use background threads, you will need to combine with the usage of things like:

Task.Start() - Starts a given task using the TaskScheduler.

PLINQ - Execute a series of operations in parallel, returns a Task.

TaskCompletionSource - A custom way to handle async tasks. One place I used this was to handle events coming from a WebBrowser control.

Other async methods, such as many of the functions in the Win 8 API.

In other words, async/await is an extension of the Task-Based Asynchronous Pattern.  You can find a large host of information, including many samples, here.

The BackgroundWorker is a WinForms component that creates 1 background thread using the Event-Based Asynchronous pattern, and you can populate the work done on this background thread with your own code in the DoWork event handler. In general, Microsoft no longer recommends using this pattern (see the bottom of the page here), though if you are familiar with it already it may still be a simple option.

Another option not mentioned, is the Reactive Extensions for .NET.  This is another great framework for adding responsiveness to your apps.

Title: BackgroundWorker vs. Async/Await

Body:
I am new to C# development and wish to create a more responsive UI. In my preliminary research, I have seen two methods for achieving this:

Multi-threading in conjunction with the BackgroundWorker class.

The newer Async/Await modifiers.

Does newer mean better? What's the difference between the two methods? If I wish to create a new project, how do I choose which method to go with?

EDIT: Maybe I should specify. I am creating a Windows Forms application, where all necessary data will be saved/loaded on the local disk. I will also be communicating with several USB devices.


问:
Is it okay to convert dataset from stored procedure to IEnumerable
So, I am working on a project with a team and we are using Entity Framework. We basically want to use linq to entities, and not use stored procedures. I use quite a bit of lists and IEnumerables and so does everyone else.

My question is, will converting the dataset produced by a stored procedure to an IEnumerable dramatically slow down the applications performance speed, say it parses through 1,000's of rows. Or would it be better to convert the store procedure to linq to entities(the procedure is a bit complex).

We have not set up testing unit tests and integration yet.

答:
Well, it depends.  On most of the projects I have worked on, converting to a list has worked out just fine.  As such, it is my usual first course of action in this situation.  However, there have been times where converting to a list is too slow.  My advice would be to try it and see if the performance is acceptable.  If it is, great.  If not, get out the profiler and make sure the list conversion is the real culprit.  If it is, try making the procedure in linq to entities and see how it compares.

TL/DR: Try it.  If it's not fast enough, try something else.


答:
Why don't you call it guardAgainstMissingValues() it's simple and conveys the message directly.

Just ask yourself what does this function do? It guards against Missing values. You said it yourself that it's a guard clause, so why don't you name it accordingly.

In addition I think that the term guard clause implies a check in its implementation, so you won't have to explicitly mention the check in the function's name.


问:
Novel polymorphism - any reasons for this code?
As part of my work on a legacy C# application I've come across a novel (to me) use of an interface & concrete implementations.  I can't think of any reason why you'd do the following, but I'm pretty thick, so maybe someone else can?

```<code>public interface IContract
{
    ContractImplementation1 Contract { get; }
    bool IsCollection { get; }
    bool Touched { get; set; }
}

public class ContractImplementation1 : IContract
{
    public ContractImplementation1(string propertyOne, string propertyTwo, string propertyThree, string propertyFour)
    {
        PropertyOne = propertyOne;
        PropertyTwo = propertyTwo;
        PropertyThree = propertyThree;
        PropertyFour = propertyFour;
    }

    public ContractImplementation1 Contract { get { return this; } }
    public bool IsCollection { get { return false; } }
    public bool Touched { get; set; }

    public string PropertyOne { get; private set; }
    public string PropertyTwo { get; private set; }
    public string PropertyThree { get; private set; }
    public string PropertyFour { get; private set; }

    public override string ToString()
    {
        if (string.IsNullOrEmpty(PropertyFour))
            return string.Format("{0} => {1}: {2}", PropertyOne, PropertyTwo, PropertyThree);
        else
            return string.Format("{0} => {1}: {2} {3}", PropertyOne, PropertyTwo, PropertyThree, PropertyFour);
    }

}

public class ContractImplementation2 : IContract
{
    public ContractImplementation1 Contract { get { return null; } }
    public bool IsCollection { get { return true; } }
    public bool Touched { get; set; }

    public List<ContractImplementation1> Contracts = new List<ContractImplementation1>();
}
</code>```

I can't get my head around the super-type having a property that is a sub-type of itself.

Following Cosmin's answer: I can't get my head around why you'd have the sub-type as a property given that the property returns itself on the implementation (rather than a 'parent' of the same type i.e. a different instantiation of the super-type).

答:
This looks like a (poorly done) implementation of the Composite pattern.  Its primary purpose is to allow you to treat an object the same as a collection of those objects, without having to differentiate between the two everywhere in the calling code.  I say poorly done because when properly used you shouldn't need the IsCollection property.

This happens to be a highly useful and common pattern with trees.  You can call methods on a node without worrying about if it is a leaf or contains a whole subtree.


答:
I'd say that async-await is much more flexible than BackgroundWorker. And if you want to do something that fits BackgroundWorker, you can do it with async-await too, with more readable and more type-safe code.

Because of that, I think you should prefer using async-await over BackgroundWorker.

Title: BackgroundWorker vs. Async/Await


答:
This depends on the usage of your class.

If the methods have some reasonable “empty” implementation, you have lots of methods and you often override just a few of them, then using virtual methods makes sense. For example ExpressionVisitor is implemented this way.

Otherwise, I think you should use abstract methods.

Ideally, you shouldn't have methods that are not implemented, but in some cases, that is the best approach. But if you decide to do that, such methods should throw NotImplementedException, not return some special value.

Title: Should I use abstract or virtual methods?

Body:
If we assume that it is not desirable for the base class to be a pure interface class, and using the 2 examples from below, which is a better approach, using the abstract or virtual method class definition?

The advantage of "abstract" version is that it is probably looks cleaner and forces the derived class to give a hopefully meaningful implementation.

The advantage of the "virtual" version is that it can be easily pulled in by other modules and used for testing without adding a bunch of underlying framework like the abstract version requires.

Abstract Version:

```<code>public abstract class AbstractVersion
{
    public abstract ReturnType Method1();
    public abstract ReturnType Method2();
             .
             .
    public abstract ReturnType MethodN();

    //////////////////////////////////////////////
    // Other class implementation stuff is here
    //////////////////////////////////////////////
}
</code>```

Virtual Version:

```<code>public class VirtualVersion
{
    public virtual ReturnType Method1()
    {
        return ReturnType.NotImplemented;
    }

    public virtual ReturnType Method2()
    {
        return ReturnType.NotImplemented;
    }
             .
             .
    public virtual ReturnType MethodN()
    {
        return ReturnType.NotImplemented;
    }

    //////////////////////////////////////////////
    // Other class implementation stuff is here
    //////////////////////////////////////////////
}
</code>```


问:
Design strategies for storing and validating serial numbers
We are writing software to track Foo Widgets. Each Foo Widget has a serial number. The serial number is an 32-character alphanumeric string. The string is separated into five sets. Each set is separated by a dash (so the s/n is 32-characters NOT including dashes).

So for example: 11111111-1111-1111-1111-111111111111. But this may change, since our software isn't actually creating the serial numbers.

I'd like to learn about different strategies for storing the serial number and doing user validation of the serial number in the UI.

To start with, I'd like get talk about strategies for storing the the serial number in our system. This issue came up at Foo Widgets Incorporated, and there was a disagreement about whether we should store each serial numbers with or without the dashes.

I think the most flexible way of doing this (but maybe not most simple) would be to store the serial number without the dashes, store the schema of the serial number (as a regular expression), and then create an identifier that is used to track which schema is used (so later if the manufacturer changes it we can support that and perhaps both schemas at the same time).

The counter argument to this was that the dashes "are a part of the data" and that it's "not like a phone number". I'm having some trouble understanding this point of view.

答:
Since you are obviously thinking about the way serial numbers are formed, it's pretty clear that the format of the number IS part of the number.

There's a big benefit to keeping the dashes in place - that's future proofing. In the event that a new serial number format is desired, if all you are doing is storing the text given (after validation), then when you get a new format all you have to do is properly validate and you're done.

If you've come up with some strategy (such as the regexes you mentioned) for storing the form, then you face the possibility that the new serial number format will be something that your mechanism can't cope with, and you'll have to scramble to amend it, possibly requiring extra db updates, etc, etc.

In the end, it's just serial numbers, and while there may be many of them, don't make it more complex than it has to be - have the input validation insure the number is well-formed (and passing internal consistency checks, if appropriate), and then store it as-is.

Unless you need to do weird reporting on sub-fields of the serial numbers, AND you have millions upon millions of them, it's not worth the trouble to do anything fancy.


答:
For the user validation part of your question, the guiding principle is Postel's law:  be conservative in what you send, liberal in what you accept.  That means you should always display the serial number with the dashes, but assuming you can correctly reconstruct the serial number without them, allow the users to enter serial numbers either with or without the dashes.

As for storage, it really depends on if you frequently need to do queries on subfields of the number.  If you don't, it's most robust to store it in the preferred format for reading it, that is, with the dashes.  That way a developer or database admin running a query from a non user-facing interface like a CLI won't have to parse it out in his head.

Title: Design strategies for storing and validating serial numbers

Body:
We are writing software to track Foo Widgets. Each Foo Widget has a serial number. The serial number is an 32-character alphanumeric string. The string is separated into five sets. Each set is separated by a dash (so the s/n is 32-characters NOT including dashes).

So for example: 11111111-1111-1111-1111-111111111111. But this may change, since our software isn't actually creating the serial numbers.

I'd like to learn about different strategies for storing the serial number and doing user validation of the serial number in the UI.

To start with, I'd like get talk about strategies for storing the the serial number in our system. This issue came up at Foo Widgets Incorporated, and there was a disagreement about whether we should store each serial numbers with or without the dashes.

I think the most flexible way of doing this (but maybe not most simple) would be to store the serial number without the dashes, store the schema of the serial number (as a regular expression), and then create an identifier that is used to track which schema is used (so later if the manufacturer changes it we can support that and perhaps both schemas at the same time).

The counter argument to this was that the dashes "are a part of the data" and that it's "not like a phone number". I'm having some trouble understanding this point of view.


问:
ASP.NET MVC 4 with Entity Framework 5 and SimpleMembership integrated into Repository and Unit Of Work pattern
I have a ASP.NET MVC4 project in which I would like to use the SimpleMembership. The application has a Person table that holds relevant information about users in the system.

I would like a link between the currently logged in user and the Person information. So I have made a foreign key in the Person table to the UserId column of UserProfile table (from SimpleMembership).

I use Entity Framework 5 as ORM and have implemented a generic repository to handle CRUD methods and so on.

Now I am at a point where I want to implement user profile creation. The creation consists of 2 parts parts:

login: username and password (to be stored in SimpleMembership tables)

personal information (to be stored in Person table)

In order to create a user I guess I need to:

Save user information through SimpleMembership

Save personal information together with userId from step 1 through my PersonRepository

I would like some kind of UserRepository that could save SimpleMembership data but I do not know if it's the right approach?
Is there a better approach?

答:
You could wrap this functionality up as a service.

In the service you would use both the SimpleMembership api and your own repository code.


答:
I always keep repositories so there a is a one to one relationship between a repository and a table in a database. And repositories do not know about other repositories. If you need to handle transactions between repositories I would implement a Unit of Work design pattern and on top of that a Service design pattern that handles the domain logic around the transactions.

Another option is to modify the UserProfile in SimpleMembership to contain the extra information that you have in the Person table.  UserProfile was designed to be customized and you can read about customizing it here.

Title: ASP.NET MVC 4 with Entity Framework 5 and SimpleMembership integrated into Repository and Unit Of Work pattern

Body:
I have a ASP.NET MVC4 project in which I would like to use the SimpleMembership. The application has a Person table that holds relevant information about users in the system.

I would like a link between the currently logged in user and the Person information. So I have made a foreign key in the Person table to the UserId column of UserProfile table (from SimpleMembership).

I use Entity Framework 5 as ORM and have implemented a generic repository to handle CRUD methods and so on.

Now I am at a point where I want to implement user profile creation. The creation consists of 2 parts parts:

login: username and password (to be stored in SimpleMembership tables)

personal information (to be stored in Person table)

In order to create a user I guess I need to:

Save user information through SimpleMembership

Save personal information together with userId from step 1 through my PersonRepository

I would like some kind of UserRepository that could save SimpleMembership data but I do not know if it's the right approach?
Is there a better approach?


答:
The virtual version is both bug prone and semantically incorrect.

Abstract is saying "this method isn't implemented here. you must implement it to make this class work"

Virtual is saying "I have a default implementation but you can change me if you need"

If your ultimate objective is testability then interfaces are normally the best option. (this class does x rather than this class is a x). You might need to break your classes into smaller components though for this to work nicely.


问:
Unit testing on visualization (3D graphics) frameworks
This is a follow up to this question. There I was asking how to do unit testing when you have a library of scientific algorithms. I have a similar problem now but with a different project.

I'm working on a 3D graphics engine framework abstraction for DirectX, OpenGl, WebGl, Silverlight, WPF, and basically whatever 3D API is out there, on C#, called Rendering .NET. The scenario is the following, the project is being developed by a small team of colleagues of mine, all working in the same office. We are all computer scientists, not much into the software engineering community and practices. I even had a hard time to convince to switch from Subversion to Git, and to publish the project on Codeplex. The project is getting big (around 80K lines of C#), and it now covers most of DirectX and OpenGl up to Shader Model 5.0, so its not a one man's project like the one described in the linked question. We also want to encourage the open source community to collaborate.

So far we've been testing by writing small applications that involve initializing all devices and resources, setting up a scene, and drawing. The thing is, I don't know how to make it different, I mean, how to design small test cases that test specific features of the framework, like resource allocation, primitive tessellation, shader compilation, etc., without having to recreate the entire engine initialization. For some of these cases I can think of useful mocks, but in general, how can I test the correctness of a rendering algorithm when the output is visual (an image, or an animated scene)? Right now the most clever thing we have come up is to render the same scene to a software renderer, DirectX and OpenGl, and compare them pixel by pixel, but tiny variations of the APIs make the resulting images different enough to fail the tests without being actual bugs.

So, what is the "correct" testing approach here?

答:
The "correct" testing approach would be to decouple your drawing logic from the DirectX or OpenGL calls, so you can mock the latter out (and as a another use case, use the same business logic either for DirectX or OpenGL).

You don't want to test if DirectX or OpenGL is working correctly - that is Microsoft's job. You also want your device initialization code to be written and tested only once (and then reused), so a manual test of that part should be affordable. If you want to test that part automatically, too, use your pixel-by-pixel approach, but with a very simple test drawing. Thus focus on writing automated regression tests for your decoupled drawing logic, that will bring you the most benefit.

So the whole idea is to split your code into really independent components - your DirectX initialization should not be coupled to the drawing logic, and the drawing logic should not depend on DirectX - this makes your program testable.

EDIT: found this former post on unit tests for OpenGL code, there were only a few answers, but perhaps it will bring some additional insights.