问:
Adding a new method to a class library for its new version and exposing a version option the users can select
Is it a bad idea to add a new method (that implements a new algorithm) to a class library for its new version and expose a version option the consumers can select?

It is  just for backward compatibility where an old application might need a constant sequence of random numbers for a certain seed number.

The following code might speak my idea much better. Hopefully you get the essence.

```<code>//Class Library:
namespace MyGenerator
{
    public sealed class MyRandom
    {
        public enum Version { One, Two }// add more options in the future
        private int current;
        private Version version;

        public MyRandom(int seed, Version version = Version.One)
        {
            current = seed;
            this.version = version;
        }

        public int Next()
        {
            switch (version)
            {
                case Version.One:
                    AlgorithmOne();
                    break;
                case Version.Two:
                    AlgorithmTwo();
                    break;
                // add more options in the future
            }
            return current;
        }

        private int AlgorithmOne()
        {
            current = (current * 1234567890 + 987654321) & 0x7FFFFFFF;
            return current;
        }

        private int AlgorithmTwo()
        {
            current = (current * current + current) & 0x7FFFFFFF;
            return current;
        }
        // add more algorithm in the future
    }
}
</code>```

and

```<code>//Console Application (for testing purposes):

using MyGenerator;
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            const int seed = 12345;
            MyRandom rnd = new MyRandom(seed, MyRandom.Version.Two);
            Console.WriteLine(rnd.Next());
            Console.ReadLine();
        }
    }
}
</code>```

答:
The likely answer is... because they don't want to.

Sounds like they are leaving their option open to switch to a different PRNG algorithm if a new one they prefer was to come along.  There's also the possibility that future .NET runtimes for entirely new platforms may require something different in terms of a PRNG algorithm, so they don't want to lock themselves into a certain algorithm.

They don't need to provide prior versions of their generators because they are flat out telling you not to rely on it for predictable results.  The purpose is to return a psuedo-random number.  Not a reproducible sequence of numbers.  There is no reason to ever care what version of algorithm they are using, because you are calling it to get a random number.

If you need predictable results, you should implement your own random number generator (preferably using one of the better tested, known algorithms).


问:
"C++ Templates: The Complete Guide" (c) 2002 -- up to date with C++11?
The book C++ Templates: The Complete Guide, (c) 2002, looks very appealing to me, but as it's 12 years old, I'm concerned it may be out of date.  There are some highly favorable Amazon reviews dated as recently as a year ago, and I don't see any other very recent titles on C++ templates.  Does anyone know whether a book about templates published in 2002 (as opposed to a book specifically about the STL) would have syntax or concepts that have been superseded or added to by, say, C++11?

The following is from the Amazon book description:

Templates are among the most powerful features of C++, but they are
  too often neglected, misunderstood, and misused. C++ Templates: The
  Complete Guide provides software architects and engineers with a clear
  understanding of why, when, and how to use templates to build and
  maintain cleaner, faster, and smarter software more efficiently.

C++ Templates begins with an insightful tutorial on basic concepts and
  language features. The remainder of the book serves as a comprehensive
  reference, focusing first on language details, then on a wide range of
  coding techniques, and finally on advanced applications for templates.
  Examples used throughout the book illustrate abstract concepts and
  demonstrate best practices.

Readers learn

The exact behaviors of templates

How to avoid the pitfalls associated with templates

Idioms and techniques, from the basic to the previously undocumented

How to reuse source code without threatening performance or safety

How to increase the efficiency of C++ programs

How to produce more flexible and maintainable software

答:
Updated (2016/08/24)

Recommended article with focus on C++11:

An introduction to C++'s SFINAE concept: compile-time introspection of a class member (Jean Guegant)

As a learner of C++ Template Metaprogramming a few months ago, I would still recommend to read this book.

It does not include C++11, but it lays out the syntax and the C++ specifications on how a compiler should process template code. The book covers a lot of less known corners which will become crucial if you need to use C++ templates substantially, whether or not metaprogramming is involved.

The missing parts from C++11 are:

Type Trait Support.

http://en.cppreference.com/w/cpp/types

For navigation, mouse over the "Type Support" near the top of the page. A list of is_* will be displayed.

decltype. http://en.cppreference.com/w/cpp/language/decltype

declval. http://en.cppreference.com/w/cpp/utility/declval

move http://en.cppreference.com/w/cpp/utility/move

forward http://en.cppreference.com/w/cpp/utility/forward

There is a construct which you will see a lot in code that is pasted onto Stackoverflow: std::enable_if. However, in practice, I find this quite difficult to use, because of the One-Definition Rule and SFINAE. This is why this book is important, because it goes over the basics.

If you use C++ templates substantially in a cross-platform library, you will need to test-compile your code in different compilers. This is because each compiler has different level of compliance to the C++ specification. Code that compiles fine on one may be reject by the other, and occasionally the compiler that accepts it is the one that breaks the specification.

Here is my reading notes when I go through this book. Hope it will be helpful.

Book reading notes - C++ Templates - The Complete Guide (2003)

Ch 2.5 - Function Templates - Summary

Overload resolution, and best practices

Ch 3.3 - Specialization of Class Templates

Ch 3.4 - Partial Specialization

Ambiguity (ODR error), and how to resolve it. ODR = One-Definition Rule

Ch 4.3 - Restrictions for Non-type Template Parameters

Example: string literals with external linkage

Ch 5 and Ch 6 - These two chapters are very depressing. You may want to skip it and then go back when you are emotionally ready for using templates.

Part II (Ch 8 - Ch ???) The section of advanced stuff.

Ch 8 - More rules

For a programmer already familiar with the entire Ch 3 (class templates - basics), Ch 8.1 and 8.2 should be read immediately following Ch 3, because the additional rules are just as important and relevant as the basic rules. This will save some pain.

Ch 8.3.1 (Page 106 in 12th Printing) mentions SFINAE for the first time.

Ch 8.3 - This section introduces a lot of circumstances where template argument substitution would have led to nonsensical syntactic expansions (and thus become invalid, which in return necessitates SFINAE). This chapter has a steep learning curve even for the experienced C++ programmers.

Ch 11 - Template Argument Deduction

Ch11 contains some contrived Template Argument Deduction examples that are necessary for understanding some of the equally contrived SFINAE applications.

Ch 12.4 onward - Partial class template specialization.

This covers the internal mechanics that is often called upon in an SFINAE application.

Part III (Ch 17 - Ch ???) Metaprogramming.

Ch 17 - Begins with introductory functional programming.

App. A.3 - One-Definition Rule (ODR) in detail.

ContentLicense: CC BY-SA 3.0


问:
If another team haven't done a requested task, are we supposed to mention it in every Daily Scrum as an Impediment until they do?
Is it really necessary to mention the same impediment (blocking issue) in every daily standup, if the whole Scrum team already know about it because it's been mentioned at previous daily standups?</p>

答:
I don't think so. First time need to discuss this blocking issue, but second time it doesn't necessary. But when there are new information about this topic, it need to discuss all story again.

I think If there aren't any new information, news about this impediment, it doesn't necessary to mention in every daily standups.

During the Daily Srum the team members explain:

What did I do yesterday that helped the Development Team
meet the Sprint Goal?

What will I do today to help the Development Team meet the Sprint Goal?

Do I see any impediment that prevents me or the Development Team from meeting the
Sprint Goal?

From Scrum Guide.


答:
Just the fact there is a dependency on task other team is doing right now seems weird to me. Usually, you don't want to add tasks into sprint if you are not even sure if you can finish it within a sprint, because you cannot know if the dependency will be completed. Usually, you want to postpone adding this task until it's dependency was finished.

On your comment of NEED to have this feature finished: You are not doing agile right. If it is so important, you should have added it into sprint (along with it's dependency) much earlier. And even if this requirement appeared suddenly, it is not a reason to add it into sprint right away. If your sprints are short, the wait of few weeks is not going to kill anyone. Of course the problem is different if bug in dependency exists for many sprints and still isn't fixed. In which case, there is some serious process problem and your product owner and scrum master should be looking into it ASAP. In general agile, bugs should have highest priority and should be fixed before any kind of features are added in sprint. I would send your scrum master to the other team and ask what kind of half-arsed agile are they doing.

Title: If another team haven't done a requested task, are we supposed to mention it in every Daily Scrum as an Impediment until they do?

Body: Is it really necessary to mention the same impediment (blocking issue) in every daily standup, if the whole Scrum team already know about it because it's been mentioned at previous daily standups?</p>


问:
Why is 80 characters the 'standard' limit for code width?
Why is 80 characters the "standard" limit for code width? Why 80 and not 79, 81 or 100? What is the origin of this particular value? </p>

答:
While probably not the original reason for the 80 character limit, a reason that it was accepted widely is simply reading ergonomics:

If lines are too short, text becomes hard to read because you must constantly jump from one line to the next while reading.

If lines are too long, the line jumping becomes too hard because you "lose the line" while going back to the start of the next line (this can be mitigated by having a bigger inter-line spacing, but this also wastes space).

This is widely known and accepted in typography. The standard recommendation (for text in books etc.) is to use something in the region of 40-90 characters per line, and ideally about 60 (see e.g. Wikipedia, Markus Itkonen: Typography and readability.

If you aim for 60 characters per line, your upper limit must obviously be a bit higher to accommodate the occasional long expression (and things like margins markers and line numbers), so having an upper limit of 70-80 makes sense.

This probably explains why the 80 character limit was taken over by many other systems.

ContentLicense: CC BY-SA 4.0


问:
Unit testing method name standard for overloaded methods
I have read several posts which discuss coding standard for naming the unit test methods for improving readability.

I follow this NameOfMethod_ExpectedBehavior_WhenSomeScenario, but now I am confused as to how should I continue with this in the face of overloaded methods. There can be several methods with same name but different signatures.

Can someone please suggest me how to incorporate overloading in method names?

For example: Java Code

```<code>class ClassUnderTest{
    public int method1(){
    }

    public int method1(int arg){
    }
}
</code>```

Now I need to test both the methods individually from my test case. I am thinking of some standard that is applicable for this scenario.

答:
Since your test methods typically don't have different signatures (I guess they will seldom have parameters), you need a different way to distinguish them. As long as the WhenSomeScenario part is different for different overloads, you don't have to provide any special measures:

```<code> MyMethod_Returns0_WhenCalledWith1     // testing MyMethod(int)
 MyMethod_Returns0_WhenCalledWith1_2   // testing MyMethod(int,int)
</code>```

does it.

If that does not work in specific cases, because you have a more abstract scenarios to test, where the names don't reflect the input parameters directly, you need something like

```<code>  NameOfMethodSignaturecode_ExpectedBehavior_WhenSomeScenario
</code>```

You still have to decide what you fill in for the Signaturecode, depends a little bit on your personal taste. When you are willing to use very long method names, you could use just add a concatenation of the typenames, like

```<code> MyMethodInt_Returns0_WhenCalledBeforeInitialization     // testing MyMethod(int)
 MyMethodIntInt_Returns0_WhenCalledBeforeInitialization // testing MyMethod(int,int)
</code>```

If you think the method names become too long that way, you have to use some kind of shortage for the typenames (for example, analogous to the shortages in Hungarian notation). What I would avoid is to use some kind of index 1,2,3,... to distinguish the test methods, this gives you no clue which test method is for which overload.

Body:
Since your test methods typically don't have different signatures (I guess they will seldom have parameters), you need a different way to distinguish them. As long as the WhenSomeScenario part is different for different overloads, you don't have to provide any special measures:

 MyMethod_Returns0_WhenCalledWith1     // testing MyMethod(int)
 MyMethod_Returns0_WhenCalledWith1_2   // testing MyMethod(int,int)

does it.

If that does not work in specific cases, because you have a more abstract scenarios to test, where the names don't reflect the input parameters directly, you need something like

  NameOfMethodSignaturecode_ExpectedBehavior_WhenSomeScenario

You still have to decide what you fill in for the Signaturecode, depends a little bit on your personal taste. When you are willing to use very long method names, you could use just add a concatenation of the typenames, like

 MyMethodInt_Returns0_WhenCalledBeforeInitialization     // testing MyMethod(int)
 MyMethodIntInt_Returns0_WhenCalledBeforeInitialization // testing MyMethod(int,int)

If you think the method names become too long that way, you have to use some kind of shortage for the typenames (for example, analogous to the shortages in Hungarian notation). What I would avoid is to use some kind of index 1,2,3,... to distinguish the test methods, this gives you no clue which test method is for which overload.


问:
Are there areas where TDD provides a high ROI and other areas where the ROI is so low that it is not worth following?
Test driven development. I get it, like it.

But writing tests does require overhead. So should TDD be used universally throughout the code base, or are there areas where TDD provides a high ROI and other areas where the ROI is so low that it is not worth following.

答:
I suggest writing a full test suite in areas where it's sensible and practical to do.  In less practical areas, write sanity checks.

In my experience, the overhead of a full set of test cases is certainly worth it in most cases, but realistically code coverage has diminishing returns. At some point, writing more tests just to increase code coverage just doesn't make sense.

For example, depending on your language/technology, testing the UI may not be practical or even feasible. A lot of tests will probably rely on what a user sees and can't be automated.  How would you test that a method for generating a captcha produces an image that is readable by a human for example?

If a complete set of tests is going to take you three days to write, the likelihood of a bug being introduced in that component down the track is very low, and the function itself only takes half an hour to write, you should probably think hard about whether that time is worth it.  Maybe just writing a basic sanity check for that function would provide value?

My general advice would be that you should test components fully where tests can be written relatively easily. However, if it's an area that's very hard to test, draw a line in the sand and write tests that will test the area at a higher level rather than test it fully.

In the previous captcha example, maybe write tests that check an image of the correct size and format is returned and that no exceptions are thrown.  That gives you some level of assurance without going overboard.

ContentLicense: CC BY-SA 2.5


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

Greatly decreased your productivity?

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

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

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

You had no idea why they were included?

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

Some examples here

答: The worst coding standard I've ever participated in is code bases which had none at all.  I'd rather follow a coding standard I completely disagree with than work in code bases where there is none at all.  It makes it that much harder to learn new parts of the code base.  </p>


问:
What does the Apache licensing mean by "Permitted: Commercial Use"
At choosealicense.com/licenses I am reading the Apache licensing, and see that under Permitted there stands Commercial Use:

This software and derivatives may be used for commercial purposes.

Meaning, they can use (and modify) my app, in a commercial environment (e.g. Microsoft, Apple). Or, they can commercialize my app? English is not my native language and I am wondering if I am misinterpreting something.

答:
Commercial use is any use that is a part of revenue generating activity, that is, making money. It includes all use by for-profit organizations (companies) and use by self-employed natural persons as part of their paid work.

It has nothing to do with the environment. Using Linux to run a web shop is a commercial use and using Windows at home for watching youtube videos is not commercial use.

This is in contrast with licenses that allow free use for some purposes, but require fee for commercial use. Such licenses are not considered open-source and note that the site does not list any license that would not permit "commercial use".

This does not imply that they can derive commercial software, i.e. one where fee is required for use, from your work. However the Apache license does permit that. It is the "sublicense" item, last one in the permitted list.

The "sublicense" in general means that the recipient of the work can further distribute it or derived version under different terms. Which specifically includes requiring fee for use. GPL prohibits this and requires that derived work may only be distributed under the same license while most other open-source licenses permit it.

Note that even GPL-licensed software can be sold, but it's the distribution itself that is paid (e.g. burned CD with Linux can be sold) while the recipient still gets the right to use it for any purpose and most importantly to further distribute it.


答:
Having a version parameter would be dirty.

It's a blatant mixing of concerns.  The first concern is what the method is expected to do.  The second concern how to manage multiple conflicting versions of a massive API.  The two are completely unrelated and should stay as separate as possible.

As a developer, I'm only interested in the first concern (what the method is expected to do).  If I try to call Math.Random and suddenly there's a parameter for version... well, I'll be confused.  What does versioning have to do with randomness?

In other words, adding a version parameter would force the developer to become aware of the implementation of Math.Random (and its history) instead of just knowing what it's expected to do.  In my opinion, that would make it a very bad API.

Title: Adding a new method to a class library for its new version and exposing a version option the users can select

Body:
Is it a bad idea to add a new method (that implements a new algorithm) to a class library for its new version and expose a version option the consumers can select?

It is  just for backward compatibility where an old application might need a constant sequence of random numbers for a certain seed number.

The following code might speak my idea much better. Hopefully you get the essence.

```<code>//Class Library:
namespace MyGenerator
{
    public sealed class MyRandom
    {
        public enum Version { One, Two }// add more options in the future
        private int current;
        private Version version;

        public MyRandom(int seed, Version version = Version.One)
        {
            current = seed;
            this.version = version;
        }

        public int Next()
        {
            switch (version)
            {
                case Version.One:
                    AlgorithmOne();
                    break;
                case Version.Two:
                    AlgorithmTwo();
                    break;
                // add more options in the future
            }
            return current;
        }

        private int AlgorithmOne()
        {
            current = (current * 1234567890 + 987654321) & 0x7FFFFFFF;
            return current;
        }

        private int AlgorithmTwo()
        {
            current = (current * current + current) & 0x7FFFFFFF;
            return current;
        }
        // add more algorithm in the future
    }
}
</code>```

and

```<code>//Console Application (for testing purposes):

using MyGenerator;
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            const int seed = 12345;
            MyRandom rnd = new MyRandom(seed, MyRandom.Version.Two);
            Console.WriteLine(rnd.Next());
            Console.ReadLine();
        }
    }
}
</code>```


问:
Grammar: start: (a b)? a c; Input: a d. Which error correct at position 2? 1. expected "b", "c". OR expected "c"
I am writing a parser (a parser generator for PEGs) and am trying to figure out how to report errors.

Grammar:

```<code>rule: (a b)? a c ;
</code>```

Input:

```<code>a d
</code>```

Question: Which error message correct at position 2 for given input?

expected "b", "c".

expected "c".

So should it be taken into account that "b" was also expected at position?

The 1st error (expected "b", "c") wants to say that the input a b was expected but because it optional it is only a possibility, not a requirement.

I don't know possible is the same as expected or not?

Which error message better and correct: The 1st or the 2nd version?

Thanks for answers.

Second Part

In first case I define marker of testing as limit of position.

```<code>if(_inputPos > testing) {
  _failure(_inputPos, _code[cp + {{OFFSET_RESULT}}]);
}
</code>```

Limit moved in optional expressions:

```<code>OPTIONAL_EXPRESSION:
testing = _inputPos;
</code>```

The "b" expression move _inputPos above the testing pos and add failure at _inputPos.

In second case I can define marker of testing as boolean flag.

```<code>if(!testing) {
  _failure(_inputPos, _code[cp + {{OFFSET_RESULT}}]);
}
</code>```

The "b" expression in this case not add failure because it tested (inner for optional expression).

What you think what is better and correct?

Testing defined as specific position and if expression above this position (_inputPos > testing) it add failure (even it inside optional expression).

Testing defined as flag and if this flag set that the failures not takes into account. After executing optional expression it restore (not reset!) previous value of testing (true or false).

Also failures not takes into account if rule not fails. They only reported if parsing fails.

Third Part

This question raised because it related to two different problems.

First problem:

A Parsing Expression Grammar (PEG) describes input in only three atomic items:

terminal symbol

nonterminal symbol

empty string

The grammar doesn't use a lexer, hence the concept of a “token” does not apply here.

Second problem:

What is a grammar? Can two grammars be considered equal if they accept the same input but produce different result?

Assume we have two grammars:

Grammar 1

```<code>rule <- type? identifier
</code>```

Grammar 2

```<code>rule <- type identifier / identifier
</code>```

They both accept the same input but produce (in PEG) different result.

Grammar 1 results:

{type: type, identifier: identifier}

{type: null, identifier: identifier}

Grammar 2 results:

{type: type, identifier: identifier}

{identifier: identifier}

Questions:

Are both grammars equal?

It is painless to do optimization of grammars?

My answer on both questions is negative. No equal, Not painless.

But you may ask. "But why this happens?".

I can answer to you. "Because this is not a problem. This is a feature".

In a PEG grammar each rule always consists from these parts:

ordered choice

sequence

expression

And this explanation is the my answer on question "But why this happens?".

Another problem.

As a PEG does not have tokens, whitespace cannot be silently ignored in the lexer between tokens. Therefore whitespace has to be considered inside the grammar. Now look at this grammar (in short):

```<code>program    <- WHITESPACE expr EOF
expr       <- ruleX
ruleX      <- 'X' WHITESPACE
WHITESPACE <- ' '?
EOF        <- ! .
</code>```

The first WHITESPACE is at the beginning, other `WHITESPACE (often) occurs at the end of a rule.

In this case in PEG optional WHITESPACE must be assumed as expected.

But WHITESPACE does not only mean space (\x20) but also other characters like [\t\n\r] and even comments.

But the main rule of error messages is the following.

If it is not possible to display all expected elements (or not possible to display at least one from all set of expected elements) then is more correct to not display anything.

More precisely required to display "unexpected" error mesage.

So how would I display in a PEG's error message that WHITESPACE was expected?

Parser error: expected WHITESPACE

Parser error: expected ' ', '\t', '\n' , 'r'

What about start characters of comments? They also may be part of WHITESPACE in some grammars.

In this case optional WHITESPACE will be reject all other potential expected elements because not possible correctly to display WHITESPACE in error message because WHITESPACE is too complex to display.

Is this good or bad?

I think this is not bad and required some tricks to hide this nature of PEG parsers.

And in my PEG parser I not assume that the inner expression at first position of optional (optional & zero_or_more) expression must be treated as expected. But all other inner (except at the first position) must treated as expected.

Example 1:

```<code>List<int list; // type? ident
</code>```

Here "List" is not at the first position in optional "type?".

This failure is taken into account and reported as "expected '>'". This is because we don't skip type but enter into type and after really optional "List" we move position from first to next real "expected" (that already outside of testing position) element.

"List" was in "testing" position.

If inner expression (inside optional expression) "fits in the limitation" not continue at next position then it not assumed as the expected input.

From this assumption has been asked main question.

You must just take into account that we are talking about PEG parsers and their error messages.

答:
In order to more easily work with the grammar, we will rewrite your rule from rule: (a b)? a c to

```<code>rule := "a" "b" "a" "c"
      | "a" "c"
</code>```

The common prefix can be factored out, so we get:

```<code>rule  := "a" rule2
rule2 := "b" "a" "c"
       | "c"
</code>```

(Grammar A)

However, we can also interpret the original rule as the equivalent of

```<code> rule  := rule2 "a" "c"
 rule2 := "a" "b"
        | SUCCEED
</code>```

(Grammar B)

where SUCCEED is a pseudo-rule that always succeeds and does not advance the position. Note that these three grammars are absolutely equivalent in terms of the languages which they can recognize.

I will assume that these transformations would be applied automatically. We can now watch how each desugared grammar matches the input a d.

Grammar A (recursive descent with backtracking):

Position: |a d, Stack: rule, Rule: "a" rule2.

Token "a" is recognized and the parser advances.

Position: a|d, Stack: rule, Rule: rule2.

Recurse into rule2.

Position: a|d, Stack: rule, rule2, Rule: "b" "a" "c".

This alternative fails because token "b" doesn't occur in the input.

Position: a|d, Stack: rule, rule2, Rule: "c".
This alternative fails because token "c" does not occur in the input.

Position: a|d, Stack: rule, rule2.

rule2 fails because neither "b" nor "c" occurs in the input

Position: a|d, Stack: rule.
rule fails because rule2 fails because neither "b" nor "c" occurs in the input.

Grammar B (recursive descent with backtracking):

Position: |a d, Stack: rule, Rule: rule2 "a" "c".

Recurse into rule2.

Position: |a d, Stack: rule, rule2, Rule: "a" "b".

Token "a" is recognized and the parser advances.

Position: a|d, Stack; rule, rule2, Rule: "b".

This alternative fails because token "b" doesn't occur in the input. Backtrack.

Position: |a d, Stack; rule, rule2, Rule: SUCCEED.

This alternative suceeds. Forget previous failure.

Position: |a d, Stack; rule, rule2.

rule2 suceeds

Position: |a d, Stack: rule, Rule: "a" "c".

Token "a" is recognized and the parser advances.

Position: a|d, Stack: rule, Rule: "c".
rule fails because token "c" does not occur in the input.

So depending on how you implement and simplify the grammar, and how your error reporting works, you end up with different reasons for failure, but both are equivalent (at the same input position) and correct.

Now if both are equivalent, we might want to pick the “better” one that provides more information. In this case, this would be a rule rewriting as in Grammar A, or a parsing algorithm other than recursive descent:

Earley parsing offers a lot more “situational awareness”.

An LR parser (bottom-up) would also work here and provide more useful error messages.

The drawback is that those are more difficult to do yourself, and rewriting to Grammar B (which is how a hand-written RecDesc usually works implicitly) is simpler to implement.

A note on rule rewriting: This assumes that the grammar is specified as some data structure, and not as hard-coded control flow. Rule rewriting is useful because it can eliminate certain undesirable features of a grammar (e.g. left recursion in top-down parsers).

Body:
In order to more easily work with the grammar, we will rewrite your rule from rule: (a b)? a c to

rule := "a" "b" "a" "c"
      | "a" "c"

The common prefix can be factored out, so we get:

rule  := "a" rule2
rule2 := "b" "a" "c"
       | "c"

(Grammar A)

However, we can also interpret the original rule as the equivalent of

 rule  := rule2 "a" "c"
 rule2 := "a" "b"
        | SUCCEED

(Grammar B)

where SUCCEED is a pseudo-rule that always succeeds and does not advance the position. Note that these three grammars are absolutely equivalent in terms of the languages which they can recognize.

I will assume that these transformations would be applied automatically. We can now watch how each desugared grammar matches the input a d.

Grammar A (recursive descent with backtracking):

Position: |a d, Stack: rule, Rule: "a" rule2.

Token "a" is recognized and the parser advances.

Position: a|d, Stack: rule, Rule: rule2.

Recurse into rule2.

Position: a|d, Stack: rule, rule2, Rule: "b" "a" "c".

This alternative fails because token "b" doesn't occur in the input.

Position: a|d, Stack: rule, rule2, Rule: "c".
This alternative fails because token "c" does not occur in the input.

Position: a|d, Stack: rule, rule2.

rule2 fails because neither "b" nor "c" occurs in the input

Position: a|d, Stack: rule.
rule fails because rule2 fails because neither "b" nor "c" occurs in the input.

Grammar B (recursive descent with backtracking):

Position: |a d, Stack: rule, Rule: rule2 "a" "c".

Recurse into rule2.

Position: |a d, Stack: rule, rule2, Rule: "a" "b".

Token "a" is recognized and the parser advances.

Position: a|d, Stack; rule, rule2, Rule: "b".

This alternative fails because token "b" doesn't occur in the input. Backtrack.

Position: |a d, Stack; rule, rule2, Rule: SUCCEED.

This alternative suceeds. Forget previous failure.

Position: |a d, Stack; rule, rule2.

rule2 suceeds

Position: |a d, Stack: rule, Rule: "a" "c".

Token "a" is recognized and the parser advances.

Position: a|d, Stack: rule, Rule: "c".
rule fails because token "c" does not occur in the input.

So depending on how you implement and simplify the grammar, and how your error reporting works, you end up with different reasons for failure, but both are equivalent (at the same input position) and correct.

Now if both are equivalent, we might want to pick the “better” one that provides more information. In this case, this would be a rule rewriting as in Grammar A, or a parsing algorithm other than recursive descent:

Earley parsing offers a lot more “situational awareness”.

An LR parser (bottom-up) would also work here and provide more useful error messages.

The drawback is that those are more difficult to do yourself, and rewriting to Grammar B (which is how a hand-written RecDesc usually works implicitly) is simpler to implement.

A note on rule rewriting: This assumes that the grammar is specified as some data structure, and not as hard-coded control flow. Rule rewriting is useful because it can eliminate certain undesirable features of a grammar (e.g. left recursion in top-down parsers).


问:
What's a similar functionality in JavaScript that insures the object has X data before any actions are taken?
If java/C#/etc one might do something like create a constructor with a parameter, the parameter being the thing the rest of the object may act upon. How is this done in JavaScript? I'm trying to figure out what the best practice is with JavaScript to do something similar to this C#/Java Object.

```<code>public class Blagh{

    public var ThingToActOn;  // Appropriate get & set methods here.

    public new Blagh(variable ThingForObjectToActOn) {
        this.ThingToActOn = ThingForObjectToActOn;
    }
}
</code>```

I was thinking something like this in JavaScript, but it seems maybe I'm missing something. I'm also aware that New in JavaScript is frowned upon for a number of reasons, but am not sure what the best solution is otherwise.

```<code>var Symphonize = function(generation_specification){
    this.gen_spec = generation_specification;
}

Symphonize.prototype.act_on_object = function () {

    // Do actions here on the generation_specification value.

    return this.gen_spec;
}

blu = new Symphonize({"gen":"stuff"});
</code>```

答:
Your solution works, but it breaks encapsulation. You can use the fact that your object is a function to work with local variables instead of properties.

Writing it this way allows you to keep the property private:

```<code>function Symphonize(generationSpecification){
    this.actOnObject = function(){
        // do stuff
        return generationSpecification;
    }
}

blu = new Symphonize({ gen: "stuff" });
</code>```

You have to keep in mind, however, that actOnObject will be redefined for every new Symphonize.

Body:
Your solution works, but it breaks encapsulation. You can use the fact that your object is a function to work with local variables instead of properties.

Writing it this way allows you to keep the property private:

function Symphonize(generationSpecification){
    this.actOnObject = function(){
        // do stuff
        return generationSpecification;
    }
}

blu = new Symphonize({ gen: "stuff" });

You have to keep in mind, however, that actOnObject will be redefined for every new Symphonize.


答:
The overload being tested doesn't really matter. The state really handles the decision of which overload to call.

So if you have a ToString method on a DateTime object with one that takes no arguments and one that takes a format string you would have.

```<code>ToString_1-3-2014T00:00:00_JanThirdDefaultFormat
</code>```

and

```<code>ToString_1-3-2014_JanThirdDateOnly
</code>```

Title: Unit testing method name standard for overloaded methods

Body:
I have read several posts which discuss coding standard for naming the unit test methods for improving readability.

I follow this NameOfMethod_ExpectedBehavior_WhenSomeScenario, but now I am confused as to how should I continue with this in the face of overloaded methods. There can be several methods with same name but different signatures.

Can someone please suggest me how to incorporate overloading in method names?

For example: Java Code

```<code>class ClassUnderTest{
    public int method1(){
    }

    public int method1(int arg){
    }
}
</code>```

Now I need to test both the methods individually from my test case. I am thinking of some standard that is applicable for this scenario.

Body:
The overload being tested doesn't really matter. The state really handles the decision of which overload to call.

So if you have a ToString method on a DateTime object with one that takes no arguments and one that takes a format string you would have.

ToString_1-3-2014T00:00:00_JanThirdDefaultFormat

and

ToString_1-3-2014_JanThirdDateOnly


问:
Write data to SQL Server directly from BizTalk or use external service?
An external source will be sending us XML data that BizTalk will pick up and transform into an internal schema.  We need this data to be loaded into a SQL Server database as we're going to expose some of the data to our web front-end via a custom WCF service.

The question is: what is the recommended approach for doing something like this?  Options we're considering are having BizTalk write to the database directly or having BizTalk call a custom WCF service which would handle the save operation.  Another briefly considered idea was having BizTalk write to an MSMQ and have a custom service pull from there and store it in the database.

What are some of the guidelines or questions that should be asked in assessing these options?   There are concerns related to overhead from calling the extra service, duplication of efforts if the schema is modified in the future (which it will be to some extent), and simply the best way to design within a service-oriented architecture that we're struggling with.

答:
I would adopt a pragmatic approach. If the current requirement is primarily just to get the xml data into a Sql database ETL style, there's no point over-engineering the solution at present.

Although it is tempting to make the loading process asynchronous via MSMQ:

BizTalk can be viewed as a kind of (Sql based) queueing mechanism in itself, by buffering messages in the messagebox (although I wouldn't recommend storing too much backlog in BizTalk, as performance degrades with #messages in the messagebox)

If the only reasons to use MSMQ during the load are to throttle the throughput and / or handle downtime of the Sql Database, there are a bunch of knobs in the WCF-Sql adapter, and the standard retries mechanism in the send port should cater for downstream Sql unavailability (and if all else fails, you can orchestrate load and reliability requirements, e.g. with a Singleton / Multiton orch)

IMO the option to move to a SOA service would be driven by questions like:

Are there additional systems (other than your BizTalk server) which need to push the same data to the Sql server?

If there are additional rules which need to be enforced with the data, which may require information from additional data / services.

If data enrichment or cleansing steps are required

Are there other SOA services needed elsewhere in your enterprise which may tip the scales toward a WCF loading layer?

If you do foresee change to the direct coupling of BizTalk to Destination Sql database in the future, you can use a canonical schema in Biztalk for your xml data, which is then mapped to the WCF-SQL send port as late as possible (i.e. so you are decoupled as far as possible from the generated Sql-WCF schema, which may be discarded).


问:
Best practice mapping an external id on my system
I've done some searches for "id mapping" and "external id mapping" and I can't find anything meaningful on the site or google, so, here's my question/scenario.

I'm developing an application which will match some records from our internal system with the "same" records from an external (outside the company) system. The data-exchange (receive the data from external system) is irrelevant (could be TXT, CSV, XML, Excel, etc...).

At some point I'll have to match our internal customer id with the external customer id. The thing is: I know my id is immutable, but I don't know id the external id is mutable. And there's no way to know, because the external system is out of my control and can be changed without my knowledge anytime.

So I have 2 scenarios:

Best case: the external ID is immutable;

Worst case: the external ID is mutable (within the constraints below);

So I'm developing a mapping table with the following attributes:

Internal System Customer ID;

External System Customer ID;

Pretty standard stuff.

The real question is: What should I add on this table in order to prepare for worst-case scenario ?

Constraints:

If the ID is mutable, it'll be on a daily basis, so there can't be a 1-to-many internal-to-external ID on the same day (this is a business rule that can be enforced);

The external ID can be anything from an integer to a GUID or a zip-code. But nothing bigger than a GUID;

答:
In order to do the mapping, you need something which uniquely identifies the object in the external system. This is exactly the purpose of an ID.

If the external system uses mutable IDs, the system is broken. This includes the case where an ID of a removed entity is reused for a new entity.

In order to have a hint that the system is broken, you can compare several properties of the entity stored locally with the information of the external system. For example, for a customer, one can match the first and last name, the e-mail address or the birth date. While a mismatch in one of those fields doesn't mean anything (for example, the customer may change his name, or the original birth date may be incorrect and corrected later), the fact that several of them changed is a good indication of the ID recycling.


问:
At what point is version control needed?
I work in embedded systems. Right now, my organization has two full-time programmers and two occasional programmers. It's rare that the same project is worked on by two programmers. All code is stored on a network drive. There are folders for the current production code, another folder for the source for every released version throughout history, and a third folder for active work. We have an automated system (Mercurial being abused) that makes backups of every changed code file in Working every fifteen minutes, so we can revert to previous states.

My question is this: is it worth the trouble to set up a formal versioning system in an environment like this? Why or why not?

答:
As you describe it, you already have some sort of version control, though currently there are some issues with it compared to a typical version control:

An intentional commit in version control indicates that the developer strongly believes that the current state of the system would build successfully.

(There are exceptions, as suggested by Jacobm001's comment. Indeed, several approaches are possible, and some teams would prefer not trying to make every commit possible to build. One approach is to have nightly builds, given that during the day, the system may receive several commits which don't build.)

Since you don't have commits, your system will often result in a state which doesn't build. This prevents you from setting Continuous Integration.

By the way, a distributed version control system has a benefit: one can do local commits as much as needed while bringing the system to a state where it cannot build, and then do a public commit when the system is able to build.

Version control lets you enforce some rules on commit. For example, for Python files, PEP 8 can be run, preventing the commit if the committed files are not compliant.

Blame is extremely hard to do with your approach.

Exploring what changes were made when, and by who is hard too. Version control logs, the list of changed files and a diff is an excellent way to find exactly what was done.

Any merge would be a pain (or maybe developers wouldn't even see that their colleagues were modifying the files before they save the changes). You stated that:

It's rare that the same project is worked on by two programmers

Rare doesn't mean never, so merges would occur sooner or later.

A backup every fifteen minutes means that developers may lose up to fifteen minutes of work. This is always problematic: it's hard to remember exactly what changes were done meanwhile.

With source control you can have meaningful commit messages. With backups all you know is that it was x minutes since last backup.

A real version control ensures that you can always revert to the previous commit; this is a huge advantage. Reverting a backup using your system would be slightly more difficult than doing a one-click rollback, which you can do in most version control systems. Also, in your system Branching is impossible.

There's a better way to do version control, and you should certainly consider changing the way you currently do it. Especially since, like Eric Lippert mentions, your current system is probably a lot more painful to maintain than any common version control system is. Having a Git or Mercurial repository on a network drive is pretty easy for example.

Note: Even if you switch to a common version control system, you should still have a daily/weekly backup of the repositories. If you're using a distributed system it's less important though, since then every developer's working copy is also a backup.


答:
Just my personal view: Version control is useful for anything that takes me more than half a day or that involves a lot of trial and error – or both, of course. If it involves two or more people who are not using the same keyboard and monitor all the time, it is essential.

The cost of using a formal versioning system, beyond the initial learning curve, is negligible. Initializing a repo? Two seconds. Adding files? One second. Being able to go back to what I tried this morning and discuss what I discarded with my colleague? Worth hours or days, easily.

Title: At what point is version control needed?

Body:
I work in embedded systems. Right now, my organization has two full-time programmers and two occasional programmers. It's rare that the same project is worked on by two programmers. All code is stored on a network drive. There are folders for the current production code, another folder for the source for every released version throughout history, and a third folder for active work. We have an automated system (Mercurial being abused) that makes backups of every changed code file in Working every fifteen minutes, so we can revert to previous states.

My question is this: is it worth the trouble to set up a formal versioning system in an environment like this? Why or why not?


答:
Version control was always needed, even before you hacked together your "but, we backup really often!" kludge.

Version control lets you publish those changes across files that belong to a logical function as a unit. If you need to review "what was necessary for case-insensitive sorting in that mask?", it tells you all relevant changes and suppresses the irrelevant ones.

Good version control keeps track of file names, metadata, and of the provenance of every individual line of code.

Version control lets you tag all changes with the reason you made them.

Version control is not about allowing more than one person to work together. It is about guaranteeing the historical record of your codebase. Secure in the knowledge that you cannot lose anything, or even forget when you did it and how, you are free to refactor, invent and create without fear. And you don't know what fearlessness is before you've experienced it.


答:
There is a great deal of value in using version control even as an individual developer and it could be quite a bit simpler than the backup/file copy based system you have now.

Right now, you have the ability to get to older version of the code, but how do you find the version you want?

Just the ability to do a diff between revisions will be very valuable.  Integration with development tools is another benefit you aren't getting from you current tools.

Another substantial benefit is the ability to branch, and experiment with new features or designs without having to worry about breaking anything.

As was mentioned in other responses, the ability to intentionally commit the code that you want to share with others is substantially different than just saving all versions of the code at 15 minute intervals.  You are no doubt saving off multiple non-working versions of code that you or others will later need to dig through to find the previous good version that you actually need.

It is pretty simple to get a version control system up and running,
particular in an environment as straightforward as this one.  So the investment required isn't very high.  As I mentioned, the backup based system you have now sounds like it could be needlessly complex and potentially fragile.  You should benefit from the years of investment the community has made in building tools like SVN, Git, or Mercurial to solve exactly the problem of maintaining multiple versions of the software and providing a good deal of additional capability that is directly useful to developers.

By setting up and using using formal version control, you will develop a valuable set of skills that will serve you well throughout your career. Almost every professional software development environment uses a version control system.  Knowing the ins and outs of how to set up and use a repository will help you over an over again.

I am not familiar with Mercurial, but from what I understand, it is a full blown revision control system.  If you already have some familiarity with it, it might be worth starting to experiment with it as a VCS.


问:
DAL vs BLL functions' return types
Here is how I see the main differences between the DAL and the BLL:

The DAL directly query the database.

The DAL doesn't create new information. It may execute complex sql requests, joining several tables, but the result of such a request never gives any information that wasn't already in the database.

The BLL applies a business logic on the DAL's informations to create new informations.

Now, I wonder what datatypes these layers' functions are supposed to return. For the moment, all my DAL's function return DataTable. But my BLL's functions return some class or list of class that I created.

For example:

dal.getAllPortfolios() returns a DataTable (I'm working with Visual Studio), result of a join on several tables.

bll.getAllPortfolios() calls dal.getAllPortfolios, but return a List of Portfolio. With my public Portfolio class being in the BLL's namespace.

Sometimes, the BLL function doesn't really apply any "business logic" but only map the DataTable from de DAL into a BLL's class.

I wonder if this is ok. Maybe all the mapping work should be done by the DAL?
If this is the case, where to put my personal mapping classes? In the BLL or DAL namespace (those classes being required in layers above the BLL)?

答:
There is no need to abstract getting data from one layer to another unless 1 or more transformations are going to occur to put it in a format the consumer expects.

Mapping of data tables to collections of objects before returning from the 'data access' is more prudent than having a separate class / function to do so unless you have consumers expecting different return types

Title: DAL vs BLL functions' return types


答:
It's an interesting idea. However, I would probably curse the library developer when I try to use a method like this. From user perspective, it makes the library much more complicated to understand.

In this specific case, I will go for the Template Method pattern. I will create an abstract class "Random" and make the existing "MyRandom" its subclass.

After this, I can implement algorithm B in another new subclass ("YourRandom", "HisRandom" :) ) The existing code will not break, new usage can select the algorithm for random.


答:
I would say that's perfectly acceptable - even desirable. The DAL should only be Data Access - that's why it's the Data Access Layer. The BL, on the other hand, should never interact directly with the database, but should take the data retrieved from the DAL and put it in a more consumer- or developer-friendly format to be leveraged in your code.

By maintaining this separation of concerns, if you ever changed databases (either database structure, or database type, or the physical server itself) you only need to make changes in the DAL. Generally speaking, the DAL will only have basic methods for executing stored procedures, queries, etc., and returning single values or data tables/data sets. It sends those back to the BLL, which then creates the necessary objects to be consumed. If you want an easy (if overly-simplified) way to visualize it, a Google Search popped up this image:

Title: DAL vs BLL functions' return types

Body:
Here is how I see the main differences between the DAL and the BLL:

The DAL directly query the database.

The DAL doesn't create new information. It may execute complex sql requests, joining several tables, but the result of such a request never gives any information that wasn't already in the database.

The BLL applies a business logic on the DAL's informations to create new informations.

Now, I wonder what datatypes these layers' functions are supposed to return. For the moment, all my DAL's function return DataTable. But my BLL's functions return some class or list of class that I created.

For example:

dal.getAllPortfolios() returns a DataTable (I'm working with Visual Studio), result of a join on several tables.

bll.getAllPortfolios() calls dal.getAllPortfolios, but return a List of Portfolio. With my public Portfolio class being in the BLL's namespace.

Sometimes, the BLL function doesn't really apply any "business logic" but only map the DataTable from de DAL into a BLL's class.

I wonder if this is ok. Maybe all the mapping work should be done by the DAL?
If this is the case, where to put my personal mapping classes? In the BLL or DAL namespace (those classes being required in layers above the BLL)?


答:
As other people have said, "now" is always a good time to start using version control. There's so many benefits to using a good version control system it's almost a no brainer. </p>

<p>You mention you use Mercurial. Like other distributed vcs, you can always initialize your own (private) repo and work there. Why not try that? If it starts working for you, it might work for your team. DVCS is all about building from the ground up. </p>

Body:
As other people have said, "now" is always a good time to start using version control. There's so many benefits to using a good version control system it's almost a no brainer.

You mention you use Mercurial. Like other distributed vcs, you can always initialize your own (private) repo and work there. Why not try that? If it starts working for you, it might work for your team. DVCS is all about building from the ground up.


问:
How large non-OO code bases are managed?
I always see abstraction is a very useful feature the OO provides for managing the code-base. But how are large non-OO code bases are managed? Or do those just become a "Big Ball of Mud" eventually?

Update:

It seemed everyone is thinking 'abstraction' is just modularization or data-hiding. But IMHO, it also means the use of 'Abstract Classes' or 'Interfaces' which is a must for dependency-injection and thus testing. How non-OO code bases manage this? And also, other than abstraction, the encapsulation also helps a lot to manage large code bases as it define and restrict the relation between data and functions.

With C, it is very much possible to write pseudo-OO code. I don't know much about other non-OO languages. So, is it THE way to manage large C code bases?

答:
Even without abstraction most programs are broken up into sections of some sort.  Those sections usually relate to specific tasks or activities and you work on those the same way you would work on the most specific bits of the abstracted programs.

In small to medium sized projects this is actually easier to do that with a purist OO implementation sometimes.


问:
How should dependencies be managed across a modular application?
Let's say that we have a structure like this:

```<code>Application
    -- Modules
        --Module1
            -- Controller
            -- PublicHelper

        --Module2
           -- Controller
           -- PublicHelper
</code>```

Whereby a module's Public Helper can provide helper functions.

In nearly every module helper, the helper needs to access another module's public helper methods.

Let's say for instance, in a PHP application:

Module1 provides functionality to create a sale, and as part of the

```<code>class Module1PublicHelper extends AbstractModuleHelper {

    public function createSale($customerId, $param, $param)
    {
         $userPublicHelper = // grab an instance of the user public helper
         $currentUser = $userPublicHelper->getCurrentUser();
    }
}

class Module2PublicHelper extends AbstractModuleHelper {

    public function getCurrentUser()
    {
         //do something
         return $user;
    }
}
</code>```

In this situation, the method needs to obtain an instance, either new or whatever of the user public helper.

Given that all of Module Public Helper classes are instantiated with a minimum set of constructor params, e.g. EntityManager, what would be the best way to get a copy of it?

Obviously, we can't really inject the user public helper class into the class containing createSale

One solution would be to use a service locator or registry, however, testing the application isn't exactly easy.

答:
In most cases, this could be just two layers of the same module. The difference between layers and modules are that as layers are on top of each other, the higher layers is allowed to ask for information from the lower layer.

If you really have two modules, Module1 can have it's own stripped down version of User which helps to just keep track of the identity of User, or any other information Module1 might need. This will be difficult if you have a data driven application.

Having Module1 depend on Module2 is bad design.

Now let me try to explain this further with your example.

You have a createSale method. The purpose of this method is to create a sale. What I would do in this case is assume that the $customerId that is send to the method is correct from which ever collaborator that called it.That is why you need to completely separate your Model layer from the Application layer.

Consider the following structure.

```<code>Application
    -- Modules
        --Module1
            -- Controller
            -- PublicHelper

        --Module2
           -- Controller
           -- PublicHelper
Model
    -- Sales
        -- SalesManager
        -- Sale
    -- Users
        -- UserManager
        -- User
</code>```

Now with the following Module1Controller I hope you can understand the setup.

```<code>class Module1Controller {
    public function createSalesAction() {
        $userId = $this->getPost('user-id');

        // UserManager is injected to application level
        $user = $this->userManager->getUser($userId);

        // SalesManager is injected to application level
        $this->salesManager->createSale($user->getId(), $param1, $param2);
    }

    public function giveCredit() {
        $userId = $this->getPost('user-id');
        $credit = $this->getPost('credit');

        $this->salesManager->setCredit($userId, $credit);
    }
}
</code>```

Then a sample Sales Manager might help

```<code>class SalesManager {
    public function setCredit($userId, $credit) {
        $credit = new Credit($userId, $credit);
        $this->creditRepo->save($credit);
    }

    public function createSale($userId, $amount, $param2) {
        if (!$this->hasCredit($userId, $amount)) {
            throw new CustomerDontHaveCredit($userId, $amount);
        }

        $sale = new Sale($userId, $amount, $param1);
        $this->salesRepo->save($sale);
    }

    private function hasCredit($userId, $amount) {
        // get the credit
        // get sales if need and check if he has credit

        return true;
    }
}
</code>```

Sales module is completely oblivious of User module and vice versa. Furthermore, the actual development of Sales and Users module can be completely separate from the actual application. Meaning you can mock the SalesManager and UserManager in the app for testing.

Body:
In most cases, this could be just two layers of the same module. The difference between layers and modules are that as layers are on top of each other, the higher layers is allowed to ask for information from the lower layer.

If you really have two modules, Module1 can have it's own stripped down version of User which helps to just keep track of the identity of User, or any other information Module1 might need. This will be difficult if you have a data driven application.

Having Module1 depend on Module2 is bad design.

Now let me try to explain this further with your example.

You have a createSale method. The purpose of this method is to create a sale. What I would do in this case is assume that the $customerId that is send to the method is correct from which ever collaborator that called it.That is why you need to completely separate your Model layer from the Application layer.

Consider the following structure.

Application
    -- Modules
        --Module1
            -- Controller
            -- PublicHelper

        --Module2
           -- Controller
           -- PublicHelper
Model
    -- Sales
        -- SalesManager
        -- Sale
    -- Users
        -- UserManager
        -- User

Now with the following Module1Controller I hope you can understand the setup.

class Module1Controller {
    public function createSalesAction() {
        $userId = $this->getPost('user-id');

        // UserManager is injected to application level
        $user = $this->userManager->getUser($userId);

        // SalesManager is injected to application level
        $this->salesManager->createSale($user->getId(), $param1, $param2);
    }

    public function giveCredit() {
        $userId = $this->getPost('user-id');
        $credit = $this->getPost('credit');

        $this->salesManager->setCredit($userId, $credit);
    }
}

Then a sample Sales Manager might help

class SalesManager {
    public function setCredit($userId, $credit) {
        $credit = new Credit($userId, $credit);
        $this->creditRepo->save($credit);
    }

    public function createSale($userId, $amount, $param2) {
        if (!$this->hasCredit($userId, $amount)) {
            throw new CustomerDontHaveCredit($userId, $amount);
        }

        $sale = new Sale($userId, $amount, $param1);
        $this->salesRepo->save($sale);
    }

    private function hasCredit($userId, $amount) {
        // get the credit
        // get sales if need and check if he has credit

        return true;
    }
}

Sales module is completely oblivious of User module and vice versa. Furthermore, the actual development of Sales and Users module can be completely separate from the actual application. Meaning you can mock the SalesManager and UserManager in the app for testing.


答:
In a professional environment where there is code written you should always have source control.

There is always the danger of an interview candidate asking what you use for version control and refusing the position because of the lack of a reasonable version control system.

Also... if you happen to be able to hire a professional they might also have a lot harder time understanding and using your current versioning environment.


答:
No, never do this. If you want to design for future versionability then use the object-oriented patterns specifically designed for that.  For example, here's how I would solve your problem:

```<code>abstract class MyRandom
{
    // Ensure that a third party cannot extend the base
    // class by making the ctor private.
    private MyRandom() {}

    public abstract int Next();

    private class First : MyRandom
    {
        // whatever
    }

    private class Second : MyRandom
    {
        // whatever
    }

    // Chef's choice:
    public static MyRandom MakeRandom() { return new Second(); }

    // Diner's choice:
    public static MyRandom MakeFirst() { return new First(); }
    public static MyRandom MakeSecond() { return new Second(); }
}
</code>```

When you want to add a new version, that's a private implementation detail of the class, and you then add a new static factory method.  If the caller wants you to choose the best version, they call the method that lets you decide. If they have a specific version they want, they call a method that gives them that.

Some more guidance:

If you believe you will be adding more members to an enum in the future then you are probably doing something wrong. The set of items in an enum should be identical forever.

If you are taking a non-flags enum with n options and doing n different things as a result then just write n methods.

Body:
No, never do this. If you want to design for future versionability then use the object-oriented patterns specifically designed for that.  For example, here's how I would solve your problem:

abstract class MyRandom
{
    // Ensure that a third party cannot extend the base
    // class by making the ctor private.
    private MyRandom() {}

    public abstract int Next();

    private class First : MyRandom
    {
        // whatever
    }

    private class Second : MyRandom
    {
        // whatever
    }

    // Chef's choice:
    public static MyRandom MakeRandom() { return new Second(); }

    // Diner's choice:
    public static MyRandom MakeFirst() { return new First(); }
    public static MyRandom MakeSecond() { return new Second(); }
}

When you want to add a new version, that's a private implementation detail of the class, and you then add a new static factory method.  If the caller wants you to choose the best version, they call the method that lets you decide. If they have a specific version they want, they call a method that gives them that.

Some more guidance:

If you believe you will be adding more members to an enum in the future then you are probably doing something wrong. The set of items in an enum should be identical forever.

If you are taking a non-flags enum with n options and doing n different things as a result then just write n methods.


问:
Do we have any special design considerations for maintaining anonymity in an application?
This is an open-ended question which I am analysing while doing some fun projects in leisure. Websites like Google, Facebook do store user activities and perhaps sell them or use them for advertisements. But I believe anonymity is maintained. For instance, I need to expose that there are 5 people between age 45-50 who are drug-addicts in a given area... but I don't want to offer the names of the people. In fact I want to be sure that noone can access their names, otherwise resulting in privacy violation (Sorry for the weird example !)

Is there some tool/standard which everyone(especially smaller organizations) follow to limit legal complications due to identity theft like this ?

I am tagging MongoDB and Java, as I am using these technologies and answers specific to them would be easier to implement.

答:
There is a company in my area (no I do not work for them or have any connection with them, although I did interview for a job there some time back) that does what they call "Anonymizing Health Data".  While they have various software solutions, the CEO and team have also produced a number of references that might be helpful in solving your problem.  The list of books on their website can be found at:

http://www.privacyanalytics.ca/resources/books/

I suggest starting with those references and then seeing if there are more specific questions as to functionality that we might help you with.


问:
Win loss code that does not make 1-0 record better than someone like 20-3
ok, am just looking for a win loss code example. This can be for any language, just wanting the outline. Fairly new to programming, so dummy it up for me :)

I can do (win-loss/total of win loss). Guessing that is a good standard win loss ratio, but I don't want a new person that has 1-0 to be ranked higher than someone that has 20-3.

Any help is appreciated and thank you.

EDIT:

The chess styles are a little more than needed. Just want a ranking system with win/loss. so lest say 20-3 is top in league right now. he is, say 23 weeks in so far. if one guy comes in and wins first match against anyone, I don't want him to take #1 spot over people thats been there longer and have a great winning record. To respond to ampt... maybe he will be best in league, but I don't want him instantly there cause he had one good match. Not sure if that clarify any more. Didn't really follow Doc all the way. Looks as if he is hindered in list up to his 11th game. Not sure if thats what you ment there. Thanks again for all reasponses.

答:
Just want a ranking system with win/loss. so lest say 20-3 is top in league right now. he is, say 23 weeks in so far. if one guy comes in and wins first match against anyone, I don't want him to take #1 spot over people thats been there longer and have a great winning record.

If you want to do it uniformly, temper the win fraction with the amount of participation.  The more games a player plays, the more his win fraction counts in the rankings.

An established player with a 20-3 (0.869) record who's played all 23 (1.000) of the possible games has a ranking of 0.869 x 1.000 = 0.869.  He loses nothing because of his high participation.

A new player plays one game and wins it (1.000) but is cut back by the fact that he's played only one of the 23 (0.043).  His ranking is 1.000 x 0.043 = 0.043.  This puts him at the same level as someone who's played all 23 and won only one.


答:
A very simple solution is to give points for any game played, lost or won.

Score = 3 * win + loss

A new player won't appear in the top ranks until he has a number of matches comparable with other players. This can be good, or bad - if your number of games isn't bound new players might have no practical chance to ever get to the top.

Title: Win loss code that does not make 1-0 record better than someone like 20-3

Body:
ok, am just looking for a win loss code example. This can be for any language, just wanting the outline. Fairly new to programming, so dummy it up for me :)

I can do (win-loss/total of win loss). Guessing that is a good standard win loss ratio, but I don't want a new person that has 1-0 to be ranked higher than someone that has 20-3.

Any help is appreciated and thank you.

EDIT:

The chess styles are a little more than needed. Just want a ranking system with win/loss. so lest say 20-3 is top in league right now. he is, say 23 weeks in so far. if one guy comes in and wins first match against anyone, I don't want him to take #1 spot over people thats been there longer and have a great winning record. To respond to ampt... maybe he will be best in league, but I don't want him instantly there cause he had one good match. Not sure if that clarify any more. Didn't really follow Doc all the way. Looks as if he is hindered in list up to his 11th game. Not sure if thats what you ment there. Thanks again for all reasponses.


问:
Can only integers be stored as register variables?
I am confused about this: what type of data can we store in register variables?
I guess logically we can store any kind of data as register variables because they are variables, but really I am confused.

I have tried to search on internet and in my book. I couldn't find the answer. By book I am referring to ANSI C's programming book.

答:
The answer is neither yes nor no. The answer is it depends.

The register keyword never required the compiler to store the variable in a register. It is just a hint to the optimizer to preferentially allocate a register for that variable.

With register colouring implementations of modern compilers it's extremely unlikely that such hint will improve the situation, but it can easily make it worse. Or the optimizer will just ignore it, because it actually does know better. So in modern code, the recommendation is forget the keyword ever existed.

If the compiler actually honours the hint, it still depends on whether there is a register that can hold the type and whether it is available. All platforms have registers that can hold pointers and registers that can hold int. They may or may not have registers that can hold long, long long, double or long double. The compiler also may store derived types in one or more registers if they fit. When appropriate register exists, it may still be better used by other values, possibly implicitly generated by precalculation, subexpression elimination and similar optimizations. The compiler can actually calculate the cost of instructions it is about to generate and make a well informed decision about the register allocation.

And more importantly there is absolutely no way for you to tell when writing the code where the hint might possibly be helpful. The only way to know is to profile the code. So don't bother with register keyword before you've debugged your code, optimized all algorithms and eliminated any unnecessary work. Don't forget, premature optimization is the root of all evil and register is only optimization of last resort.


答:
The register keyword in C can be used on any type of (local) variable and is only a hint to the compiler that you will be using that variable often, so the compiler should make accessing it as fast as possible. As keeping a variable in a processor register is often the fastest way to access it again, that was the name that got chosen for this hint.

Modern C compilers (less than about 20 years old) are good enough at determining which variables to keep in registers that they don't need hints like the register keyword, and it sometimes even causes a slowdown (when the compiler honors the hint and produces sub-optimal code as a result).

What types of values you can store in the physical registers of a processor depends on the processor architecture, but is typically limited to integer-like values (including pointers) and floating point values.

Title: Can only integers be stored as register variables?

Body:
I am confused about this: what type of data can we store in register variables?
I guess logically we can store any kind of data as register variables because they are variables, but really I am confused.

I have tried to search on internet and in my book. I couldn't find the answer. By book I am referring to ANSI C's programming book.


答:
Version control really is one of the most critical pieces of a functional development team. Aside from the standpoint that your code is always backed up, you are exposed to features such as commit messages that help you understand exactly what the person before you (or you yourself) did to a particular file. You can also diff files with previous versions and create tags for particular releases. Tags are a HUGE benefit in that you can basically create a snapshot of version x.x.x of your app's source code. This makes tracking down old bugs much much easier.

Start reading up on different platforms and see what suits your needs best. We used SVN because there were tools integrated into our IDE to leverage SVN. Ironically we do not even use these tools now, we just use Tortoise SVN to check in and check out code.

To answer your question, version control is needed from the moment you write your first line of code.


问:
How do you handle supporting Chrome versions?
I'm working on a site for my company which, up until a certain point, was an Internet Explorer-only site for various reasons, mainly that when the site was originally conceived IE had a 90%+ market share so the work to get it working in other browsers just didn't make sense.

Now that we live in a more diverse browser economy we're doing the work to get the site working everywhere, and as luck would have it a decent chunk of it just happens to already work.

However, one issue we're struggling with is the issue of what to support and what not to support. For starters, non-IE browsers release much more frequently than IE did, and you don't know which versions are still in the wild. There's been basically three versions of IE released in the last decade, and IE6 is still supported until 2014. But there's an update for Firefox every other day, Apple updates Safari more or less annually. And then there's Chrome.

Chrome has gone from 0.2 to 9.0 in a little over two years. 7.0.517 was released a month and a half after 6.0.472. There's three different versions out right now, a stable, a beta, and a dev. And the dev version of 9.0.587 was actually released before the latest beta version of 8.0.552.

With IE we've had the situation arise where we have to support an old version because the IT department of the company in question does not allow the employees to upgrade. With non-IE browsers I'm thinking we'll adopt the line of "update to the latest or we can't help you" but I'm not sure how effective that is.

Also, my company does some amount of artificial limitations. For example we have a product aimed at companies so we don't support "Home" versions of Windows (i.e., XP Home, 7 Home Premium) even though there's no technical reason we couldn't.

When my company starts asking "what version or versions of Chrome do we support", how should I answer?

答:
This is just my personal opinion as one who has been developing websites for some time, but I feel that the best you can reasonably hope to do (depending on time or budget constraints, of course) is aim to accommodate all of the most recent public browser builds. Despite Chrome's rapid update schedule, the rendering and interpretation stays pretty consistent thanks to the Webkit engine which powers by both Chrome and Safari.

Don't worry about supporting non-public releases of browsers, they aren't official for a reason and developing against them is likely to cause more pain than good in the long run.


问:
How to handle status integers from database in object oriented code?
Consider a database table of Items that have a status flag represented by an integer. A few of the status might be:

```
0 - Past Storage;
1 - Current Inventory;
5 - Scrap;
6 - Rework;
15 - Processing;
```

Now, I would like to avoid passing and querying for 'magic numbers' in my code, and in the past I have used a Dictionary to accomplish this, but this approach seems less elegant than what I hope to accomplish.

How are these types of status flags retrieved from a database handled in object oriented code? Is it with enums, and if so, how? Or is it better to create a separate table with the status flag as the primary key?

答: Where I work this is a common situation. What we do here is use enums AND a separate table with the status flag as the primary key. In our experience, things have been a lot easier when the primary key was not an identity field. The good thing about doing it this way is that the c# compiler has a list of valid values (the enum) and the DBAs and whoever else has to work with the data (report writers) also has a list of valid values (the table). The downside, of course, is that any additions or modifications have to be done in both places.</p>


问:
If another team haven't done a requested task, are we supposed to mention it in every Daily Scrum as an Impediment until they do?
Is it really necessary to mention the same impediment (blocking issue) in every daily standup, if the whole Scrum team already know about it because it's been mentioned at previous daily standups?</p>

答:
I do think it's worth mention every day; your CSM should be charged with removing roadblocks, but reality shows that they are often spread too thinly across an organization.

When an impediment is truly blocking progress on a task and there's no timeframe for a remedy, that can serve as an indicator for a PO to either re-evaluate priority of your blocked task or work with the other team to drag the blocked task into your team so that you can remove it yourself.

When it's time to retrospect the iteration/sprint, that blockage could be an example of things to improve at an organizational level.


答:
Usually integers can be represented by enums in code, as that will make it more readable for code blocks that use the integer.

Example:

```<code>        public enum StatusFlag
        {
            PastStorage = 0,
            CurrentInventory = 1,
            Scrap = 5,
            Rework = 6,
            Processing = 15,
            Unknown = 99 //Optional
        }
</code>```

I included an optional unknown, but you may not need it.  Also, this is not really necessary, you could use integers as is with something like this:

```<code>if (statusflag == 15) //processing
</code>```

But this introduces some magic number like scenarios.

Although not mandatory, there should be a table in the database that has the integer as the PK and probably a description field.

Any reference tables should have  FK to the status flag lookup table.  That way, one cannot insert a status flag that is not in the table.

If this is not there, there is a potential for any integer to be inserted, so there is less referential integrity to the data.  The downside of this is that every new integer will have to be added to the DB and code.  If you leave it as an INT with no PK/FK relationships, you can add integers ad hoc.  Code changes may need to be done if you wish to incorprate the new INT with newer logic.

I tend to advocate the enum/PK-FK style as making additions should be relatively straight forward.  This also ensure data integrity which is a good thing.

Title: How to handle status integers from database in object oriented code?

Body:
Consider a database table of Items that have a status flag represented by an integer. A few of the status might be:

```
0 - Past Storage;
1 - Current Inventory;
5 - Scrap;
6 - Rework;
15 - Processing;
```

Now, I would like to avoid passing and querying for 'magic numbers' in my code, and in the past I have used a Dictionary to accomplish this, but this approach seems less elegant than what I hope to accomplish.

How are these types of status flags retrieved from a database handled in object oriented code? Is it with enums, and if so, how? Or is it better to create a separate table with the status flag as the primary key?

Body:
Usually integers can be represented by enums in code, as that will make it more readable for code blocks that use the integer.

Example:

        public enum StatusFlag
        {
            PastStorage = 0,
            CurrentInventory = 1,
            Scrap = 5,
            Rework = 6,
            Processing = 15,
            Unknown = 99 //Optional
        }

I included an optional unknown, but you may not need it.  Also, this is not really necessary, you could use integers as is with something like this:

if (statusflag == 15) //processing

But this introduces some magic number like scenarios.

Although not mandatory, there should be a table in the database that has the integer as the PK and probably a description field.

Any reference tables should have  FK to the status flag lookup table.  That way, one cannot insert a status flag that is not in the table.

If this is not there, there is a potential for any integer to be inserted, so there is less referential integrity to the data.  The downside of this is that every new integer will have to be added to the DB and code.  If you leave it as an INT with no PK/FK relationships, you can add integers ad hoc.  Code changes may need to be done if you wish to incorprate the new INT with newer logic.

I tend to advocate the enum/PK-FK style as making additions should be relatively straight forward.  This also ensure data integrity which is a good thing.


问:
Deploying v Releasing
So there's this desktop application.

And I am wanting to inform it's users that a new version has been released.

Is it more correct to say that a new version of a desktop application has been 'released' or 'deployed' (as with a web app)?

答: Deployed means that it's been shoved onto and works on a server or other machine (say an embedded chipset) somewhere. Released means that that machine and the application(s) on it has been made available to the public. So "release" would be the better term. </p>

Title: Deploying v Releasing


答:
Chrome's new version adoption rate is really fast because of their automatic upgrade. Way faster than IE and even quite a bit faster than Firefox. Generally, if you are supporting the latest stable build of Chrome, you should be fine. It is literally only a matter of days or weeks before a new stable version almost totally replaces the old.

Edit: Graph from How Google Keeps Chrome Fresh

Title: How do you handle supporting Chrome versions?

Body:
I'm working on a site for my company which, up until a certain point, was an Internet Explorer-only site for various reasons, mainly that when the site was originally conceived IE had a 90%+ market share so the work to get it working in other browsers just didn't make sense.

Now that we live in a more diverse browser economy we're doing the work to get the site working everywhere, and as luck would have it a decent chunk of it just happens to already work.

However, one issue we're struggling with is the issue of what to support and what not to support. For starters, non-IE browsers release much more frequently than IE did, and you don't know which versions are still in the wild. There's been basically three versions of IE released in the last decade, and IE6 is still supported until 2014. But there's an update for Firefox every other day, Apple updates Safari more or less annually. And then there's Chrome.

Chrome has gone from 0.2 to 9.0 in a little over two years. 7.0.517 was released a month and a half after 6.0.472. There's three different versions out right now, a stable, a beta, and a dev. And the dev version of 9.0.587 was actually released before the latest beta version of 8.0.552.

With IE we've had the situation arise where we have to support an old version because the IT department of the company in question does not allow the employees to upgrade. With non-IE browsers I'm thinking we'll adopt the line of "update to the latest or we can't help you" but I'm not sure how effective that is.

Also, my company does some amount of artificial limitations. For example we have a product aimed at companies so we don't support "Home" versions of Windows (i.e., XP Home, 7 Home Premium) even though there's no technical reason we couldn't.

When my company starts asking "what version or versions of Chrome do we support", how should I answer?


问:
Best way to notify the client in real time that their queue (e.g. SQS) job has finished?
Current Scenario

Our application allows users to upload (Amazon S3) and manage their files through our interface. Currently those users can download the files directly from S3/Cloudfront through our application.

Adding a Zip feature

We would like to add a feature to the system that allows users to select multiple files at once and download them as a zip file.

We would like the process to work in real time, so that when the user clicks the button to download a zip file, the system processes the request, compiles the zip, and returns the zip to the end user.   While the process is running, the front-end will tell the user their request is processing, and when it is complete, it will prompt them to download the file.

Proposed Strategy

Our application is AWS cloud based, so my first instinct is to use Amazon SQS (but am open to other suggestions) to build a queue system to handle these requests.  The flow would work like this:

User selects files and requests a zip file to be created.

Front-end sends a request to SQS with the files to be zipped, and the destination (on S3) where the final zip file will be stored.

The queue worker uses long polling to check for new SQS jobs. When a job is found, the worker downloads the files from S3, zips them up, and returns the finished zip file to the specified location on S3.

Now that the queue has finished processing, alert the client that their job is done and their file is ready for download.

Best Way to Handle Step 4?

This process appears to be a solid approach, and everything makes sense up until step 4.  We are struggling with the best way to notify the end user in real-time that their job has finished and their file is ready for download.

From my research I have seen three ways that people suggest:

Use pub/sub to create a socket for the job, and return the response when complete.

From everything I have read, it is not best practice (and sometimes not possible) to create a large number of open pub/sub sockets/channels. In addition, how does SQS notify the open socket that the job is complete?  This article regarding Amazon SNS looked promising at first, but they seem to infer that it is best practice to use a single SNS topic for the entire queue, not an SNS topic per job.  This seems like a great approach if we were simply wanting to send an email to the user, letting them know their job has finished.  However, I want to be able to update the user interface inside the web browser.

Continuous polling by the front-end server for the finished zip file on S3.

If there are thousands of simultaneous jobs, this would create thousands of requests.  This approach doesn't seem very scaleable, and could potentially cost money by extra S3 api calls.

Leave an open long-running request

Due to the fact that if there are many jobs in the queue, the time taken to deliver the response could cause the request to time out.  In addition this creates a lot of strain/wasted resources on the front-end web server.  Again, not very scaleable.

My Question

Taking into account the points that I mentioned above, what is the best way to notify the front-end client that their job queue has finished and their file is ready to download?

A great example of what I am trying to do is YouTube.  When you upload a video to YouTube, their queue processes your video, and when it is complete, it notifies you that the video processing has finished.  I am trying to replicate the same concept, except that in my scenario, I just want to the client to know when the zip file has been prepared and uploaded to S3.

I'm aware of theoretical solutions, so please be specific.  I am open to any suggestions, regardless if they use SQS or any of the technologies/methodologies I have listed. Pointing to any real-world code examples of this sort of thing would be a big bonus.

Thank you in advance for your great help!

答:
My thinking is your front-end establishes a server sent event (https://developer.mozilla.org/en-US/docs/Server-sent_events/Using_server-sent_events) with a web server which issues the do job message via SQS to the worker. When the worker completes it adds a message back to the web server on a separate queue which is being polled for batches of messages at a time, for each one sending the event back down to the client.

You do not need to use web sockets as your client and server will not be chatting back and forth.


问:
Release as open source after granting usage rights?
I have written software and have granted usage rights to different companies per contract. Is it possible to change the software licence to an open source licence afterwards?

At what circumstances is this impossible and how will this affect the current contracts?

Like one of the companies is allowed to modify and resale the software. If I change to GPL are they forced to change to GPL, too?

答:
I am not a lawyer.  Do not take this as legal advice.  Much of this really depends on the exact wording of the license that you initially released your software to the companies under.

You wrote the code.  You can do what you want with it.  This is the primary thing that you, as the copyright holder of the source have the rights to do.

You can release the source under any number of licenses you wish.

The one thing you do have to watch out for (I doubt this is the case, just mentioning it) is make sure you don't re-release it in a time frame where you have given exclusive rights to the source to some other entity for some period of time.  This is more seen in other copyrights such as photographs and music than software, but it is a possibility so mentioning it.

Realize though, that the licenses that you released your software to those companies are the licenses that they will continue to operate under.

If you released the software to them under a "pay me money, do what you want" license and then later release your software under the GPL, they are not bound by the GPL because that is not the license that they received the software under (note: some companies intentionally do this - "here's GPL" and "here's pay me money, not GPL").

If you gave the company the license to modify and resell the software, then thats what you gave them - not the GPL.


问:
Service Design approach - one generic operation, and its implications
The hot topic in our organization is Service Design Approach.

First Approach - The team wants to design services which essentially have one operation, can take any XML and return response XML message. The operation and the parameters are in the request XML message.  Once the message is received the service determines the action/method that is requested. Reasons cited are ease of deployment and flexibility of introducing future operations.

Second Approach - The second group is adamant about well defined service contracts and specific messages.   Reasons cited are better performance, message validation and versioning.  This is my preferred approach as well.

What are the Pros and Cons?  Can there be challenges introducing an ESB later in the architecture if we have chosen the first approach?

答:
Design services that are logically required by the application domain, not artificially designated by abstract a priori architecture.

Some will have one simple operation and be stateless, others may be more complex.

As far as choosing an interface mechanism goes, separate the message format from the services and clients using the Adapter pattern, so you don't knit yourself a straightjacket from the start ;)


答:
The best practice is the external ID must be immutable.

Let's say your matching on employee ID only.  Certainly taking just the employee ID may not be enough as different companies may use the same type of ID assignment.  For example employee ID of company X is 1234 and employee ID of company Y is 1234.   The system is now broken if your just using employee ID in this case.

In these cases, more design is required to come up with an immutable ID.  In this case, perhaps the ID is a combination of employee ID and company ID, or maybe employee ID, company ID, and conmpany name, whatever combo it is, it must be immutable.

This will require some forethought to ensure that external IDs can be found and matched to your internal IDs.

Now if the company is sending newer IDs to replace older ones, they have to send the previous one, or else how are you going to find the previous and match and update data on your end.  You have to treat any ID not found as a new one.

You could use techniques as @MainMa suggests to do property/fuzzy logic type matching, but these are always flawed and tend to become very complex quickly.

Consider this case:

123 South Main Street Apt 1

123 S. Main St. Plaza Building Apt 1

Are these addresses the same?  Maybe.  The water is deep and murky in this pool.

Use immutable external IDs.

Title: Best practice mapping an external id on my system

Body:
I've done some searches for "id mapping" and "external id mapping" and I can't find anything meaningful on the site or google, so, here's my question/scenario.

I'm developing an application which will match some records from our internal system with the "same" records from an external (outside the company) system. The data-exchange (receive the data from external system) is irrelevant (could be TXT, CSV, XML, Excel, etc...).

At some point I'll have to match our internal customer id with the external customer id. The thing is: I know my id is immutable, but I don't know id the external id is mutable. And there's no way to know, because the external system is out of my control and can be changed without my knowledge anytime.

So I have 2 scenarios:

Best case: the external ID is immutable;

Worst case: the external ID is mutable (within the constraints below);

So I'm developing a mapping table with the following attributes:

Internal System Customer ID;

External System Customer ID;

Pretty standard stuff.

The real question is: What should I add on this table in order to prepare for worst-case scenario ?

Constraints:

If the ID is mutable, it'll be on a daily basis, so there can't be a 1-to-many internal-to-external ID on the same day (this is a business rule that can be enforced);

The external ID can be anything from an integer to a GUID or a zip-code. But nothing bigger than a GUID;