问:
Is this database design good? What JPA Entities should I create for this design?
I am trying my hands on JPA. For this I am thinking of using the example of a student admission process as shown in the diagram below.

Is this design good ?

Any suggestions for improvement are more than welcome.

I am also confused about what Entity classes should I create for this.
Especially for College_Major, should there be an Entity class for this or it should only be a mapping table created for many-to-many mapping between College and Major?

If the latter is a better case, how can the Admission_Form table refer to a Major in a College?

In either case, what should Entity classes (if good to have) for College_Major and Admission_Form look like?

答:
Looks a fairly solid design apart from the college_major area which seems to be giving you problems as well :)

Personally, I would split this table into two:

Change the College_Major table to be a true many to many resolver (i.e. no intake int). This would become a reference table which is only changed when a college establishes a new major.

Intake, which links to College_Major and has the 1:* relationship to admission. I suspect that the intake date should be added, since it should not be possible to enrol a student for a non-existing course.

I like your use of id fields (aka business neutral primary keys). For consistency, the Student table primary key should probably be named student_id rather than just id.

You might like to give some thought to the name Admission_Form. It looks like the database is recording a successful admission, which may not always come from a form, and some forms may never result in an admission.

You will need a an entity class for each table except possibly College_Major. If I remember correctly, Hibernate can handle many to many relationship using collections (e.g College will have a list of majors, and major will have a list of colleges).

OwnerDisplayName: Nils


问:
Is there still a need for writing SQL?
With so many ORM tools for most modern languages, is there still a use case for writing and executing SQL in a program, in a language/environment that supports them?  If so why?

For clarity: I'm not asking about if programmers need to know SQL, or if I should have a SQL tool on my desktop.  I'm asking specifically why I might have it in code (or config, or whatever) as opposed to an ORM.

答:
Views

Triggers

Constraints

Packages (SSIS, DTS, etc)

Anytime you need to control execution flow precisely

ORM does not help you build, tune or automate the database.  It just gives you an alternative way to interact with the database once you have done all that stuff.

ContentLicense: CC BY-SA 2.5

Title: Is there still a need for writing SQL?


问:
Bitwise operation on uppercase ASCII character turns to lowercase. Why?
I came across this in the http_parser library of node.js implementation. When I bitwise-OR an ASCII capitalized character code, it converts into its lowercase version. The lowercase version remains as it is.

Why is a bitwise OR causing the ASCII code to change to the lowercase letter?

答:
ASCII has several interesting properties in addition to the one you pointed out. It is relatively simply to ascertain properties about a character. For example, all printable characters are greater than or equal to 32 (010 0000), so if you AND a character with 96 (110 0000) and get zero, it must be nonprintable. Uppercase and lowercase letters differ by a single bit as you noticed:

A = 100 0001, OR with 010 0000 gives a = 110 0001. Same is true for all other letters.

a = 110 0001, AND with 101 1111 gives A = 100 0001. Same is true for all other letters.

This makes it trivial to perform case-insensitive searches via simple bit mask logic. Certainly it is much easier than with some Unicode-encoded characters that need to be decoded into their code points first (7-bit ASCII is also valid UTF-8, good luck other encodings).

Another cool property is the numbers all start with the high-order bits 011. If you see that, and the next bits are 0-9 (0000 - 1001) you can grab those bits and interpret them directly as an integer.

I cannot provide any specific quotes from decades ago back when EBCDIC and ASCII were competing standards, but it is common knowledge in the CS community that ASCII was designed with those specific properties in mind. The idea was to be able to use bit masking and arithmetic an easy way to detect and manipulate human-readable attributes of ASCII characters.

Many devices from ages ago were character-based, such as printers and terminals. Having an easy way for the low-tech devices of the day to be able to decode and use a character without a CPU was a bit deal.

ContentLicense: CC BY-SA 3.0


问:
How do deal with angle wraparounds when comparing them?
Angle A is a degree angle that keeps increasing by increments and Angle B is the stopping point of Angle A (think 'Spin-the-bottle' where Angle A is the current angle of the bottle Angle B is the angle needed to point to your crush and the bottle spins at a fixed rate clock-wise).

To do this, I've been trying to compare Angle A and Angle B with inequalities. If Angle A is 60 degrees and Angle B is 80 degrees, this is no problem. If Angle A is 350 degrees and Angle B is 10 degrees however, the inequality thinks that Angle A has crossed Angle B even though it hasn't.

How do I compare angles when they wraparound at 360 degrees?

This is some pseudo-code for what I have so far:

int AngleB = 30;
int AngleA = 300;

void Update() {
    AngleA += 13;
    if (AngleA > AngleB) {
        AngleA = AngleB;
    }
}
```

<p>Update: Here's my new method that wraps Angle A relative to Angle B:</p>

<pre class="lang-java prettyprint-override"><code>double GetAngleDifference(double from, double to)
{
    double difference = to - from;
    while (difference < -180) double += 360;
    while (difference > 180) double-= 360;
    return difference;
}
</code>```

答:
If the question is How do I detect whether A has crossed B? you might use the following logic:

```<code>    a := A mod 360.
    b := B mod 360.
    prev := a > b.
    A := A + 13.
    a := A mod 360.
    current := a > b.
    Return: current not = prev
</code>```

The pseudo-code above returns with TRUE if, and only if, A has crossed B. This means that you should update the position of A and, at the same time, find out whether the cross just happened.

Body:
If the question is How do I detect whether A has crossed B? you might use the following logic:

    a := A mod 360.
    b := B mod 360.
    prev := a > b.
    A := A + 13.
    a := A mod 360.
    current := a > b.
    Return: current not = prev

The pseudo-code above returns with TRUE if, and only if, A has crossed B. This means that you should update the position of A and, at the same time, find out whether the cross just happened.


问:
Should I use foreign keys in my database if I use laravel?
I'm creating a website with Laravel for the first time. I checked relationships documentation today and it seems that Laravel just uses simple SQL queries.

```<code>class User extends Eloquent {

    public function phone()
    {
        return $this->hasOne('Phone');
    }

}

$phone = User::find(1)->phone;
</code>```

And it's basically a select * from phones where user_id = 1 query. So the question is, should I use foreign keys anyway in my database to create relationships?

答:
Using the exact same words from @JeffO:

Isn't user_id a foreign key?

I think the problem is not necessarily setting a foreign key or not. The problem is how much do you need to depend on the database features.

In Laravel you will set your foreign keys while adding your migrations.

But if you for any reason/error have a user having direct access to the database or using PHP features without the framework or whatever other issue the might not only rely on the framework, it is best practice to add foreign keys to your database.

Finally, I already worked on projects where they decided not to have foreign keys and rely only on the frameworks validations for maintenance reasons.

ContentLicense: CC BY-SA 4.0


答:
I don't completely understand the problem being posed, but I suspect that it would be useful to find the smallest angle between AngleA and AngleB, where the smallest angle is in the range -180 to 180.  This can be done with modulo arithmetic.

Most programming languages have some form of a modulo function, but their behavior varies, see wikipedia page.  In order to find the smallest angle, you actually want to use a modulo function that rounds to the nearest integer.  It turns out this isn't very common.  However, it is rather simple to implement (as described at link):

```<code>double ModNearestInt(double a, double b) {
    return a - b * round(a / b);
}
</code>```

The has the nice property that the remainder returned is

always in the interval [-b/2, +b/2]

always the shortest distance to zero

So, to find the smallest angle between AngleA and AngleB, you could do:

```<code>double smallestAngle = ModNearestInt(AngleA - AngleB, 360.0);
</code>```

To detect A crossing B in the positive direction if it is known that AngleA is increasing, it is sufficient to check to see that smallestAngle changes sign from negative to positive.  When the sign of smallestAngle changes from positive to negative and AngleA is increasing, this corresponds to A crossing (B + 180).  Similarly, if it is known that AngleA is decreasing, then A crosses B when the sign of smallestAngle changes from positive to negative.

Title: How do deal with angle wraparounds when comparing them?

Body:
Angle A is a degree angle that keeps increasing by increments and Angle B is the stopping point of Angle A (think 'Spin-the-bottle' where Angle A is the current angle of the bottle Angle B is the angle needed to point to your crush and the bottle spins at a fixed rate clock-wise).

To do this, I've been trying to compare Angle A and Angle B with inequalities. If Angle A is 60 degrees and Angle B is 80 degrees, this is no problem. If Angle A is 350 degrees and Angle B is 10 degrees however, the inequality thinks that Angle A has crossed Angle B even though it hasn't.

How do I compare angles when they wraparound at 360 degrees?

This is some pseudo-code for what I have so far:

int AngleB = 30;
int AngleA = 300;

void Update() {
    AngleA += 13;
    if (AngleA > AngleB) {
        AngleA = AngleB;
    }
}
```

<p>Update: Here's my new method that wraps Angle A relative to Angle B:</p>

<pre class="lang-java prettyprint-override"><code>double GetAngleDifference(double from, double to)
{
    double difference = to - from;
    while (difference < -180) double += 360;
    while (difference > 180) double-= 360;
    return difference;
}
</code>```

Body:
I don't completely understand the problem being posed, but I suspect that it would be useful to find the smallest angle between AngleA and AngleB, where the smallest angle is in the range -180 to 180.  This can be done with modulo arithmetic.

Most programming languages have some form of a modulo function, but their behavior varies, see wikipedia page.  In order to find the smallest angle, you actually want to use a modulo function that rounds to the nearest integer.  It turns out this isn't very common.  However, it is rather simple to implement (as described at link):

double ModNearestInt(double a, double b) {
    return a - b * round(a / b);
}

The has the nice property that the remainder returned is

always in the interval [-b/2, +b/2]

always the shortest distance to zero

So, to find the smallest angle between AngleA and AngleB, you could do:

double smallestAngle = ModNearestInt(AngleA - AngleB, 360.0);

To detect A crossing B in the positive direction if it is known that AngleA is increasing, it is sufficient to check to see that smallestAngle changes sign from negative to positive.  When the sign of smallestAngle changes from positive to negative and AngleA is increasing, this corresponds to A crossing (B + 180).  Similarly, if it is known that AngleA is decreasing, then A crosses B when the sign of smallestAngle changes from positive to negative.


答:
Any angle is equivalent to the angle + 360 degrees.

So if you are increasing a, but a > b (numerically), then add 360 to b at the start. Now a < b works for your loop.

e.g.

```<code>a = 270
b = 45
b += 360 // = 405
while (a < b)
  a += ... // 270 up to 405
</code>```

If you are decreasing a but b > a (numerically), then add 360 to a at the start. Now a > b works for your loop.

e.g.

```<code>a = 10
b = 310
a += 360 // = 370
while (a > b)
  a -= ...  // 370 down to 310
</code>```

That's not the full pseudocode, but illustrates the two cases where you need to worry about "crossing" the 360 mark.

Body:
Any angle is equivalent to the angle + 360 degrees.

So if you are increasing a, but a > b (numerically), then add 360 to b at the start. Now a < b works for your loop.

e.g.

a = 270
b = 45
b += 360 // = 405
while (a < b)
  a += ... // 270 up to 405

If you are decreasing a but b > a (numerically), then add 360 to a at the start. Now a > b works for your loop.

e.g.

a = 10
b = 310
a += 360 // = 370
while (a > b)
  a -= ...  // 370 down to 310

That's not the full pseudocode, but illustrates the two cases where you need to worry about "crossing" the 360 mark.


问:
Are there real-life usage and applications for "do while" loops?
When I see for and while loops all over production codes and mammoth projects, the last time I saw a do while loop is for a university assignment involving menu-based console input program. About 50 lines long, at most.

Have you seen real-world applications of the do while loop construct? In what way is such a construct, in your example, advantageous over for or while loops, or any other constructs?

Note: I am not looking for hypothetical scenarios, but actual usage applied in the commercial industry.

答:
You use do while any time you want the loop to always execute at least once.

A typical example of such usage is a command-line interpreter; the command line prompt will always be displayed at least once.


答:
@RobertHarvey's answer is gold, but I'll throw in a fun twist on "do...while" and "while...do"

In the Forth programming language, the looping was actually split up this way (conjuring up pseudocode based on Forth code from years, dare I say decades, ago)

```<code>{
  a()
  }
 loop (expr())
{
  b()
  }
</code>```

... so that a() was guaranteed to execute at least once, then the expression was tested, and if it was true, execute b() and then back to a().

The upshot is, if you don't have the information you need to decide whether to loop, then do...while can be really handy.

The (clunky) work-around is something like

```<code>a = null
while (a == null)
  a = something()
</code>```

...does the same thing, but that initial a = null always leaves a sour taste in my mouth.

Title: Are there real-life usage and applications for "do while" loops?

Body:
When I see for and while loops all over production codes and mammoth projects, the last time I saw a do while loop is for a university assignment involving menu-based console input program. About 50 lines long, at most.

Have you seen real-world applications of the do while loop construct? In what way is such a construct, in your example, advantageous over for or while loops, or any other constructs?

Note: I am not looking for hypothetical scenarios, but actual usage applied in the commercial industry.

Body:
@RobertHarvey's answer is gold, but I'll throw in a fun twist on "do...while" and "while...do"

In the Forth programming language, the looping was actually split up this way (conjuring up pseudocode based on Forth code from years, dare I say decades, ago)

{
  a()
  }
 loop (expr())
{
  b()
  }

... so that a() was guaranteed to execute at least once, then the expression was tested, and if it was true, execute b() and then back to a().

The upshot is, if you don't have the information you need to decide whether to loop, then do...while can be really handy.

The (clunky) work-around is something like

a = null
while (a == null)
  a = something()

...does the same thing, but that initial a = null always leaves a sour taste in my mouth.


答:
Real-world application, reading data from a file in blocks until end of file:

```<code>do
    result = readData(buffer)
while result != EOF
</code>```

Without do-while you have to do something like

```<code>result = 0   # magic value that must not be EOF
while result != EOF
    result = readData(buffer)
</code>```

or

```<code>while true
    result = readData(buffer)
    if result == EOF
        break
</code>```

Both of which are uglier in my opinion.

When I mostly did C++ programming, I used the do-while all the time, in real, shipping applications.

Body:
Real-world application, reading data from a file in blocks until end of file:

do
    result = readData(buffer)
while result != EOF

Without do-while you have to do something like

result = 0   # magic value that must not be EOF
while result != EOF
    result = readData(buffer)

or

while true
    result = readData(buffer)
    if result == EOF
        break

Both of which are uglier in my opinion.

When I mostly did C++ programming, I used the do-while all the time, in real, shipping applications.


问:
What is the difference between "data hiding" and "encapsulation"?
I'm reading "Java concurrency in practice" and there is said: "Fortunately, the same object-oriented techniques that help you write well-organized, maintainable classes - such as encapsulation and data hiding -can also help you create thread-safe classes."

The problem #1 - I never heard about data hiding and don't know what it is.

The problem #2 - I always thought that encapsulation is using private vs public, and is actually the data hiding.

Can you please explain what data hiding is and how it differs from encapsulation?

答:
They are often, maybe usually, used interchangeably. But note the Booch quote above says, "Encapsulation is most often achieved through information hiding..." i.e. most often, but not always in every case.

Note that Python allows rolling data up in classes, but does not allow private variables. So it could be said that Python provides encapsulation without data hiding.

You could do the same thing in Java by making all your member variables public, but aside from giving everyone a heart attack, you'd loose the benefit of data hiding ... i.e. preserving the semantics of an object by restricting access to its state.


答:
In O-O, Encapsulation is where information is held within an Object.  For example, a Person has a name and clients of Person (i.e. you) know that Person holds a name, either via public fields or accessor methods.  And, hopefully, you don't need to also hold the names in some global array of names, etc.  So this is a big step to avoid unmanageable spaghetti code.  But the client still needs to know something about how Person handles names: e.g. space or comma delimited?

Data Hiding is where Person has a name field, but, at least in theory, nobody knows.  The field is private with no public accessor methods.  Clients may pass a name from a database record, XML, HTTP POST, whatever, but the internal working of how Person handles the name are a "black box".  Future implementations of Person are free to change, for example, to switch to having a firstName and a lastName.

In an ideal world Data Hiding is superior to Encapsulation, but not all worlds are ideal.  :-)

Title: What is the difference between "data hiding" and "encapsulation"?

Body:
I'm reading "Java concurrency in practice" and there is said: "Fortunately, the same object-oriented techniques that help you write well-organized, maintainable classes - such as encapsulation and data hiding -can also help you create thread-safe classes."

The problem #1 - I never heard about data hiding and don't know what it is.

The problem #2 - I always thought that encapsulation is using private vs public, and is actually the data hiding.

Can you please explain what data hiding is and how it differs from encapsulation?


问:
Big O of 2 interesting Algorithmic functions
This is my homework(I have attempted it, and there are no references for  questions like these)

Determine whether or not these functions are polynomial run time and determine the constant c for O(n^c) based on these functions:

```<code>3^(log base2 (n))

(log base2 (n))!
</code>```

My intuition tells me yes for both.

Case 1: The exponential will always dominate, regardless of what number is put as n. since its log base 2, it will grow "exponentially" as n is increased.. however I do not know how to prove it

Case 2: Using n! as a reference, since n! is equivalent 2^n, then (log base2 (n))! must be equivalent to 2^(log base 2 (n))

答:
Calculate log(3^(log_2(n)))

n! is not equivalent to 2^n.  See Stirling's approximation for the factorial.


答:
Since this is clearly homework I am not going to throw the answers out there, but I will give you some tips for approaching them.

For your first problem, you need to think back to the definition of a logarithm. What would the answer be if it were this?

2^(log base2 (n))

If I plug four in for n, the log would evaluate to two. The power would then evaluate to four. If I plug 8 in, I get 8. In other words, any base b raised to the log base b of any value n gives n. The exponentiation and the log cancel each other out with the same base.

What happens if the exponentiation has a larger base than the logarithm? Smaller base? How fast do polynomials grow compared to exponentiation and logs regardless of base?

For the second problem, what happens when you apply any exponentiation or factorial to a function that is polynomial or lower? What dominates in the long run, assuming you are not doing 2^(log2(n)) or something else that cancels out?

Remember, with Big-Oh you need to think about arbitrarily large trends. Not specific numbers, just think if you looked down the n axis trillions of values out, what is the dominating factor? I could plot 1.00000000000000000000000001n and it will stay very small for a long time but eventually it will grow faster than n10000000000000000. Granted in practice the first is preferable to the second, but we are talking theory here, not production-quality algorithms.

Title: Big O of 2 interesting Algorithmic functions

Body:
This is my homework(I have attempted it, and there are no references for  questions like these)

Determine whether or not these functions are polynomial run time and determine the constant c for O(n^c) based on these functions:

```<code>3^(log base2 (n))

(log base2 (n))!
</code>```

My intuition tells me yes for both.

Case 1: The exponential will always dominate, regardless of what number is put as n. since its log base 2, it will grow "exponentially" as n is increased.. however I do not know how to prove it

Case 2: Using n! as a reference, since n! is equivalent 2^n, then (log base2 (n))! must be equivalent to 2^(log base 2 (n))


问:
Does using == in JavaScript ever make sense?
In JavaScript, the Good Parts, Douglas Crockford wrote:

JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=.  The good ones work the way you would expect.  If the two operands are of the same type and have the same value, then === produces true and !== produces false.  The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values.  The rules by which they do that are complicated and unmemorable.  These are some of the interesting cases:

```<code>'' == '0'           // false
0 == ''             // true
0 == '0'            // true

false == 'false'    // false
false == '0'        // true

false == undefined  // false
false == null       // false
null == undefined   // true

' \t\r\n ' == 0     // true
</code>```

The lack of transitivity is alarming.  My advice is to never use the evil twins.  Instead, always use === and !==.  All of the comparisons just shown produce false with the === operator.

Given this unequivocal observation, is there ever a time when using == might actually be appropriate?

答:
I'm going to make an argument for ==

Douglas Crockford which you cited is known for his many and often very useful opinions. While I'm with Crockford in this particular case it's worth mentioning it is not the only opinion. There are others like language creator Brendan Eich who don't see the big problem with ==. The argument goes a little like the following:

JavaScript is a behaviorally* typed language. Things are treated based on what they can do and not their actual type. This is why you can call an array's .map method on a NodeList or on a jQuery selection set. It's also why you can do 3 - "5" and get something meaningful back - because "5" can act like a number.

When you perform a == equality you are comparing the contents of a variable rather than its type. Here are some cases where this is useful:

Reading a number from the user  - read the .value of an input element in the DOM? No problem! You don't have to start casting it or worrying about its type - you can == it right away to numbers and get something meaningful back.

Need to check for the "existence" of a declared variable? - you can == null it since behaviorally null represents there is nothing there and undefined doesn't have anything there either.

Need to check if you got meaningful input from a user? - check if the input is false with the == argument, it will treat cases the user has entered nothing or just white-space for you which is probably what you need.

Let's look at Crockford's examples and explain them behaviorally:

```<code>'' == '0'           // got input from user vs. didn't get input - so false
0 == ''             // number representing empty and string representing empty - so true
0 == '0'            // these both behave as the number 0 when added to numbers - so true
false == 'false'    // false vs got input from user which is truthy - so false
false == '0'        // both can substitute for 0 as numbers - so again true

false == undefined  // having nothing is not the same as having a false value - so false
false == null       // having empty is not the same as having a false value - so false
null == undefined   // both don't represent a value - so true

' \t\r\n ' == 0     // didn't get meaningful input from user vs falsey number - true
</code>```

Basically, == is designed to work based on how primitives behave in JavaScript, not based on what they are.  While I don't personally agree with this point of view there is definitely merit in doing it - especially if you take this paradigm of treating types based on behavior language-wide.

* some might prefer the name structural typing which is more common but there is a difference - not really interested in discussing the difference here.

Body:
I'm going to make an argument for ==

Douglas Crockford which you cited is known for his many and often very useful opinions. While I'm with Crockford in this particular case it's worth mentioning it is not the only opinion. There are others like language creator Brendan Eich who don't see the big problem with ==. The argument goes a little like the following:

JavaScript is a behaviorally* typed language. Things are treated based on what they can do and not their actual type. This is why you can call an array's .map method on a NodeList or on a jQuery selection set. It's also why you can do 3 - "5" and get something meaningful back - because "5" can act like a number.

When you perform a == equality you are comparing the contents of a variable rather than its type. Here are some cases where this is useful:

Reading a number from the user  - read the .value of an input element in the DOM? No problem! You don't have to start casting it or worrying about its type - you can == it right away to numbers and get something meaningful back.

Need to check for the "existence" of a declared variable? - you can == null it since behaviorally null represents there is nothing there and undefined doesn't have anything there either.

Need to check if you got meaningful input from a user? - check if the input is false with the == argument, it will treat cases the user has entered nothing or just white-space for you which is probably what you need.

Let's look at Crockford's examples and explain them behaviorally:

'' == '0'           // got input from user vs. didn't get input - so false
0 == ''             // number representing empty and string representing empty - so true
0 == '0'            // these both behave as the number 0 when added to numbers - so true
false == 'false'    // false vs got input from user which is truthy - so false
false == '0'        // both can substitute for 0 as numbers - so again true

false == undefined  // having nothing is not the same as having a false value - so false
false == null       // having empty is not the same as having a false value - so false
null == undefined   // both don't represent a value - so true

' \t\r\n ' == 0     // didn't get meaningful input from user vs falsey number - true

Basically, == is designed to work based on how primitives behave in JavaScript, not based on what they are.  While I don't personally agree with this point of view there is definitely merit in doing it - especially if you take this paradigm of treating types based on behavior language-wide.

* some might prefer the name structural typing which is more common but there is a difference - not really interested in discussing the difference here.


答:
```<code>    int counter = 0;
    do {
        s = Formatter.formatWorkerId(counter++);
    } while(all.contains(s));
</code>```

Finds the smallest syntactically correct worker ID that isn't already present in a set. (My uses of do tend to be confined to that kind of problem, where you definitely have to generate a value, but the very first test might already succeed.)

Body:
    int counter = 0;
    do {
        s = Formatter.formatWorkerId(counter++);
    } while(all.contains(s));

Finds the smallest syntactically correct worker ID that isn't already present in a set. (My uses of do tend to be confined to that kind of problem, where you definitely have to generate a value, but the very first test might already succeed.)


问:
PHP MVC as backend for iOS app
So, essentially, the question is, to develop a PHP back-end to an iOS application, would you implement an MVC architecture on the PHP side? Or no, since the client side (iOS) already has an MVC architecture?

Or, since we're just passing happy little JSON packets in between front / back end, both server and client should employ MVC architecture? Thus we can implement "private api key" authentication and other security measures at the device level?

Any ideas suggestions welcomed.

答:
Using a PHP MVC framework for ios development is a good idea but you should definitely take a look at these Moblile App development frameworks.They additionally provide access to back-end API's & you can run tests in php,python,ruby etc.(Mostly they work both for ios & android apps).
And if its only that you want to use a php framework then take a look at dolphinphp framework.It is the first php framework for native cross-platform mobile app development.</p>

Title: PHP MVC as backend for iOS app


问:
How do you respond to a request for 'emergency contact information' for when you are on vacation?
I want to go on vacation and not think about work at all but they want me to provide them a contact number in the event of an emergency (server goes down, web service malfunctions, etc). I am afraid that it will be abused (they will contact me before trying everything for example) but I also think that if I am on vacation I should not be bothered even if there is an outage. Does anyone have experience with situations like this? What's the tactful approach? Any creative solutions?</p>

答:
IMO that depends (among many other things) on how much vacation you have per year. Living in Europe I have more than one month of vacation each year. If I was in the US, with, say, two weeks vacation per year, I'd be much less willing to be reachable in those two weeks.

What I usually do is to leave a mobile phone number, indicating that I might not be reachable, but will try to get back ASAP.

However, I'm not sure they're realizing that, if we were sharing a meal in front of the tent after a long day of hiking, I'd consider it impossible to get back right away. Likewise if I spent the day in the natural history museum with the kids.

Taking 10mins to log in per VPN from home and have a look at something to make a guess at what it would take to fix it is different.


问:
Is it OK to credit (CC BY 3.0) icons in my (GPLv2) Github project with a CREDITS.txt file?
I'm in the middle of uploading a project to github. My software uses some icons which are licensed: "Creative Commons (CC BY 3.0 US)"

Should I hardcode the credits in a... let's say "Help->About" dialog for the software or can I ship a CREDITS.txt file inside the source code tree on github. For example inside icons folder with credit to the authors and links?

Also can I use a MIT license for this case?

答:
A software program and the icons it uses are generally not considered derived works of each other under copyright law. This means that there is no interaction between the license used for the icons and the license used for the software. The licenses do not even have to be compatible with each other.

That said, the CC-BY license of the icons does place some requirements on you, and the proposed CREDITS.txt file might not fulfill them.

One of the requirements is that the attribution given to the author of the icons must be in the same place and equally prominent as other attributions you give. Those other attributions would also include third-party libraries.

If you already have a Help->About box and/or a LICENSES.txt or README.txt file where you mention the third-party libraries you use, then you must put the attribution for the icons there as well.

If you don't have any source/library credits yet, then collecting all credits in a CREDITS.txt file is ok, provided that the file is distributed with all copies of your program (also the binary-only distributions).

tl;dr: Every distribution of your program with the icons must contain an attribution to the icon's author in some way. This can be a Help->About screen or a separate file. If you also attribute authors of other works (such as libraries), all attributions must be collected together.


问:
java add new modules to an existing app
I have an app build with JSF2.x Spring IoC,transactions and JPA over Hibernate. This is a fully functional call center app.

The challenge is that now I want to add some HR functionality where the HR team would perform various tasks. My initial thought was to create this as an module in order to be able to deploy/undeploy independently from the mother app. The communication between main app and HR module will be implemented via REST/SOAP WS or any other async communication technology (JMS).

With this in my mind I already see one problem: database replication. Because the HR module will work with user or user profile objects from my main app. So in this scenario I would send this objects to HR module and probably there I would have a local database where this info will be duplicated and hard to maintain in sync.

The other approach would be to have 2 apps that share the same database, and I guess that this will eliminate the need for a communication layer (WS/JMS...), because the both apps read/write to same database. but as it was expected this also have some drawbacks:

performing operations from HR module to a user entity will break the cache layer that it is used by the main app;

sharing the same database will arise some scenarios where for some HR functionality to be forced to alter DB schema, and the to redeploy the main app.

How should I proceed in order to obtain a high level of independence between main app and various modules and without replicate some data for each module?

答:
Determine a master responsible for each piece of data

It seems very odd that both applications would need to change the same data. Instead, can you divide the data between the two applications so only one of the applications has the responsibility to change a specific piece of data? For example, the call center application itself could handle changes to the contact information for a client (telephone, e-mail) as they are dealing with it directly. The HR application could be responsible for all changes to the financial data for the client (what percentage they get off the total for ordering).

Avoid reading each other's database

Two applications reading on a single database makes for a big headache. Updates to the application become more difficult because they impact both applications, testing involves both applications and you have to keep development in sync to avoid breaking changes. Instead, opt to have the database belong to a single application that exposes a contract to access or expose and - if need be - change the data. If you can clearly determine who is responsible for what pieces of data you can even have the master send its data over to the slave. The HR application could receive data from the call center application and keep it read-only in its own database, stored in a table structure that makes sense to the HR application.

Determine how stale your data can be

Do both applications need access to the data real-time? Let's assume the HR app updates a typo in the name of the company the client works for, how bad would it be to have this information only show up the next day? This will determine your data acess strategy. If it needs to be real-time, use a webservice for data access or send messages between your applications to alter the data real-time. If the data can be more stale you can use a scheduled task to sync the data, for example once a night. The more you couple your applications (through webservices or shared databases), the more dependant they become. If your HR and call center app use webservices, having one of the applications go down (for updates or due to a crash) effectively brings both down. Synchronising data that is stored in their own databases avoids having this kind of interdependency. If you NEED that kind of reliability is another question.

Title: java add new modules to an existing app


问:
Why does PHP allow sending mail from any address
I'm sorry if this has been asked but I'm not quite sure how to search for it. I'm having a bit of trouble understanding how mail() works in PHP. The way I see it, using that function, I can send e-mails from any user on my mail server - existent or not, without needing any  credentials or anything. I doubt the guys from PHP would let this be the way I think it is and I also suspect that this has something to do with the fact that e-mails I send from my mail server go straight into the spam folders on other mailing services (gmail, yahoo etc.)

Can somebody shed some light on me and fill the missing link. Thanks!

答:
Unfortunately, this is just how email works. There is no way for PHP to validate whether you are allowed to send mail from a particular address, so it will let you specify any address you want. Your mail server may be configured to reject email from invalid mailboxes, or if you do not have the correct authentication details for a valid mailbox, but most servers are not set up to do this.

As to why your email is being rejected by the large service providers, the most likely cause is that either you are on a blacklist somewhere, you're sending email directly from an end-user ip address without using a relay server, or have not correctly implemented sender address verification for your domain.


问:
How do I recreate this Access Control/Group/ whatever methodology in OO/MVC
I am looking at trying to rewrite an application that is mostly procedural to an MVC/OO approach in order to teach myself a deeper understanding of both.

BUT, I am having some conceptual issues with the current group/access control that is used.

We have Groups (Businesses) that have role based users (Manager, salespersons, customers).
They can have customers either assigned to a salesperson, or not. The manager sees everything, the salesperson only those customers assigned to him.

```<code>Business
  |
  ---Manager
       |
       ---Salespersons
            |
            ---Customers
  |
  ---Customers
</code>```

The table structure for this currently is something like this:

```<code>users (userID [demographic info])
business (businessID, userID, et al [demographic info])
salespeople (salesID, businessID, userID [just foreign keys])
customers (customerID, businessID, userID, et al [demographic info])
salesAssignments (salesID, customerID [just foreign keys])
</code>```

The Manager can affect everyone within that businesses group (everyone has a businessID that links them to that business and no other). The customers can login and make minor changes to their profiles or interact via messaging to their salesperson or the businesses manager.

Added Spice to the mix: (comment on any of these if they apply to your insights to the above question) Is there a better way to have similar user access and control?
I want to rebuild the site with an API that can be used by both the web app and mobile apps.

EDIT
My main conceptual hangup at the moment relates to how to recreate this structure in a user object for the OO part of the application. Now everything is accessible via session variables, or queried from the DB via procedural functions.
Again my understanding of OO is limited, and this is an attempt to figure it out.

答:
You could implement permissions using the type object pattern http://gameprogrammingpatterns.com/type-object.html

So each of your users would have a type property that defines their type in 1 of 2 ways.

differing type object properties eg. typeName

type object inheritance hierarchy

1 has the advantage that all type objects are of the same class and thus can always be treated identically and it is quite simple to interrogate an object's type.

2 has the advantage of specifying differing type properties that apply only to that type (and it's subtypes), eg. the Manager type may have the property groupSalesTarget which might not make sense for a customer

One of the big advantages of this pattern in general is the ease of upgrading and downgrading the permissions of individual users.


答:
Writing complex SQL

ORM are great for basic things. However for complex situations you will have to write SQL.

So in short, there most certainly is a need for SQL and it will always remain so.

Title: Is there still a need for writing SQL?

Body:
With so many ORM tools for most modern languages, is there still a use case for writing and executing SQL in a program, in a language/environment that supports them?  If so why?

For clarity: I'm not asking about if programmers need to know SQL, or if I should have a SQL tool on my desktop.  I'm asking specifically why I might have it in code (or config, or whatever) as opposed to an ORM.


问:
Is Unit Testing the primary objective of MVC Pattern?
Recently in an interview, one of the questions was 'Why do we use MVC?’
I just answered that it is much closer to how, many of the real world systems are! Explained the benefits it has when it comes to Maintainability, Scalability etc. But they were not convinced and finally told me that MVC is used mainly as it 'enables easy Unit Testing'.

While I know theirs is a valid point, I still doubt if it is the major reason because (i) even if I decide not to write Unit Testcases, MVC is a probable choice (ii) Many GUI systems where Unit Testcases are there does not follow MVC.

So the question is 'Is Unit Testing the primary objective of MVC Pattern?'

EDIT: I assume that they might be mentioning ease of Test Driven Development/writing NUnit Testcases. This is because we canwrite testcases for the Model (Provided the View is exactly reflecting Model's state changes)-please correct me if I am wrong.

答:
In the ASP.NET MVC world, many improvements to ASP.NET have been included in the framework itself. The main purpose of this design pattern is to isolate business logic from the user interface in order to focus on better maintainability, improved testability, and a cleaner structure to the application.

ASP.NET MVC has certain capabilities that make it the best option to choose if you need one or more of the following:

•A high level of control over the generated HTML: Unlike Web Forms, Views in ASP.NET MVC render HTML exactly as you tell them to. Recently, Web Forms have been improved in this area but still don’t have the level of control MVC has.

•Easier unit testing: With ASP.NET MVC, it is very easy to follow testing patterns such as test-driven development (TDD). Because of the complex event lifecycle in Web Forms, on top of a control-based framework, TDD is a lot easier with MVC.

•Separation of concerns: This refers to having all aspects of the system clearly separated from one another. Because of the pattern it implements, an MVC application is divided into discrete and loosely bound parts (model, views, and controllers), which makes it easy to maintain.

Some of the other benefits are:

•The MVC pattern itself makes it easier to manage complexity by clearly separating the functionality of the application into three core parts, the model, the view, and the controller.

•ASP.NET MVC web applications do not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application. View state can become very large, which is a problem for devices like smartphones running over slow networks (transmitting all that information can be very slow). In a Web Forms page, you could only have one  per page. This is quite a major restriction. In MVC, there is no such restriction—that is, you can have as many elements as you like.

•ASP.NET MVC provides better support for test-driven development (TDD).

•ASP.NET MVC works well for web applications that are supported by large teams of developers and for web designers who need a high degree of control over the HTML.
ASP.NET MVC Request Processing


问:
Recovering a process after illegal instruction exception
Is it possible in theory to recover after a process is mistakenly pointed-out to read from a wrong memory address, rather than terminating it?

Let say an error while working with registers lead the processor to read a random place on memory and therefore throwing an illegal instruction exception. At this point, are there any ways to recover to a stable state rather terminating the process?

Are there any processor architecture (specially for Embedded systems), with some extra features to deal with these issue?

Also are there any research papers trying to figure out what are valid return addresses for a function? For example if my function is trying to return to an address that is (virtually) invalid for my program to do its job, have been there any efforts to detect such a violation? Either on the programming language level or on the operating system and memory management?

Note: Illegal Instruction is an exception thrown by the processor.

Update

Would saving last known valid Instruction Pointer somewhere manually help? Maybe in an unused or reserved register, but it should be somehow guaranteed to stay untouched by the rest of the program.

答:
When the processor throws up an illegal instruction error, there are usually so many unknowns about the program state that the easiest way to get into a known-good state is to let the process crash and to let the fail-safe mechanisms restart the it or to let a fall-back system take over. This might go as far as restarting the embedded device.

All processors that I know of signal errors like illegal instruction through interrupts. This is how an OS like Windows can inform the user that an application did something terribly wrong. In the firmware for embedded devices, you have enough control over the OS to hook up a different handler to that interrupt. This alternative handler might try to recover the situation, but in my experience, the only recovery used in practice is "terminate and restart".


问:
What are Web CMSs and how they work?
I have heard about many content management systems (CMSs) such as Drupal, Wordpress, Joomla, etc. Many sites are built using these CMSs, but what are CMSs and how do they work? Is a CMS a normal blog-like site which has extended functionality, or can you do more with it?</p>

答:
A CMS - Content Management System - is basically any website or application that lets the end-user create and manage content without specialized help from a programmer.

CMS applications can be blogs, eCommerce applications, presentation / portfolio / gallery websites, official websites - anything you can think of that allows a user to manage the content without any specific programming skills.

Many content management systems have evolved well beyond just simple content management and allow users to visually manage anything that is related to the application - layout, design elements, colors and themes, various page templates that can be used to create a specific type of content, menus and the overall application structure, plugins and widgets which can offer specific functionalities tailored to the end-user's preferences etc..

Title: What are Web CMSs and how they work?


答:
I like to use do while loops for pre-processor macros in C/C++ without the trailing ;. If I forget the ;, the compiler will stop with an error.

Example:

```<code>#define expr(a) do { /* do something with a */ } while(false)
</code>```

Notice the missing ; at the end of the line. In your code, you have to write

```<code>expr(a);
</code>```

with a semicolon. Otherwise compilation will fail.

Body:
I like to use do while loops for pre-processor macros in C/C++ without the trailing ;. If I forget the ;, the compiler will stop with an error.

Example:

#define expr(a) do { /* do something with a */ } while(false)

Notice the missing ; at the end of the line. In your code, you have to write

expr(a);

with a semicolon. Otherwise compilation will fail.


问:
Is there still a need for writing SQL?
With so many ORM tools for most modern languages, is there still a use case for writing and executing SQL in a program, in a language/environment that supports them?  If so why?

For clarity: I'm not asking about if programmers need to know SQL, or if I should have a SQL tool on my desktop.  I'm asking specifically why I might have it in code (or config, or whatever) as opposed to an ORM.

答:
Even if you didn't need to write it in your code, it's pretty handy to be able to use it when you have terminal access to a database server.

Also, most of what makes programming a challenge is working within the restrictions that life sets us- often we are working with old code, or old versions of databases and don't have the opportunity to install the latest ORM library for whatever language we are working with. In that situation you will need any tool at your disposal.

The rest of the time you may not need SQL for your CRUD stuff, but there is a lot more to SQL than simple SELECT, INSERT, UPDATE and basic JOIN queries. You can do very clever things with it and although you may not use them often, it's useful to know what they are.

Increasingly, I think we will find ourselves in a post SQL world, however- most of the Cloud services use non-sql table storage and for simple CRUD type work the full power of SQL is unnecessary. But that doesn't mean there will be no value in understanding it.

Also, of course, someone has to know enough to write a better ORM system if the current ones aren't up to much. It would help them if they knew SQL...

Title: Is there still a need for writing SQL?


问:
Is it feasible and useful to auto-generate some code of unit tests?
Earlier today I have come up with an idea, based upon a particular real use case, which I would want to have checked for feasability and usefulness. This question will feature a fair chunk of Java code, but can be applied to all languages running inside a VM, and maybe even outside. While there is real code, it uses nothing language-specific, so please read it mostly as pseudo code.

The idea

Make unit testing less cumbersome by adding in some ways to autogenerate code based on human interaction with the codebase. I understand this goes against the principle of TDD, but I don't think anyone ever proved that doing TDD is better over first creating code and then immediatly therafter the tests. This may even be adapted to be fit into TDD, but that is not my current goal.

To show how it is intended to be used, I'll copy one of my classes here, for which I need to make unit tests.

```<code>public class PutMonsterOnFieldAction implements PlayerAction {
    private final int handCardIndex;
    private final int fieldMonsterIndex;

    public PutMonsterOnFieldAction(final int handCardIndex, final int fieldMonsterIndex) {
        this.handCardIndex = Arguments.requirePositiveOrZero(handCardIndex, "handCardIndex");
        this.fieldMonsterIndex = Arguments.requirePositiveOrZero(fieldMonsterIndex, "fieldCardIndex");
    }

    @Override
    public boolean isActionAllowed(final Player player) {
        Objects.requireNonNull(player, "player");
        Hand hand = player.getHand();
        Field field = player.getField();
        if (handCardIndex >= hand.getCapacity()) {
            return false;
        }
        if (fieldMonsterIndex >= field.getMonsterCapacity()) {
            return false;
        }
        if (field.hasMonster(fieldMonsterIndex)) {
            return false;
        }
        if (!(hand.get(handCardIndex) instanceof MonsterCard)) {
            return false;
        }
        return true;
    }

    @Override
    public void performAction(final Player player) {
        Objects.requireNonNull(player);
        if (!isActionAllowed(player)) {
            throw new PlayerActionNotAllowedException();
        }
        Hand hand = player.getHand();
        Field field = player.getField();
        field.setMonster(fieldMonsterIndex, (MonsterCard)hand.play(handCardIndex));
    }
}
</code>```

We can observe the need for the following tests:

Constructor test with valid input

Constructor test with invalid inputs

isActionAllowed test with valid input

isActionAllowed test with invalid inputs

performAction test with valid input

performAction test with invalid inputs

My idea mainly focuses on the isActionAllowed test with invalid inputs. Writing these tests is not fun, you need to ensure a number of conditions and you check whether it really returns false, this can be extended to performAction, where an exception needs to be thrown in that case.

The goal of my idea is to generate those tests, by indicating (through GUI of IDE hopefully) that you want to generate tests based on a specific branch.

The implementation by example

User clicks on "Generate code for branch if (handCardIndex >= hand.getCapacity())".

Now the tool needs to find a case where that holds.

(I haven't added the relevant code as that may clutter the post ultimately)

To invalidate the branch, the tool needs to find a handCardIndex and hand.getCapacity() such that the condition >= holds.

It needs to construct a Player with a Hand that has a capacity of at least 1.

It notices that the capacity private int of Hand needs to be at least 1.

It searches for ways to set it to 1. Fortunately it finds a constructor that takes the capacity as an argument. It uses 1 for this.

Some more work needs to be done to succesfully construct a Player instance, involving the creation of objects that have constraints that can be seen by inspecting the source code.

It has found the hand with the least capacity possible and is able to construct it.

Now to invalidate the test it will need to set handCardIndex = 1.

It constructs the test and asserts it to be false (the returned value of the branch)

What does the tool need to work?

In order to function properly, it will need the ability to scan through all source code (including JDK code) to figure out all constraints. Optionally this could be done through the javadoc, but that is not always used to indicate all constraints. It could also do some trial and error, but it pretty much stops if you cannot attach source code to compiled classes.

Then it needs some basic knowledge of what the primitive types are, including arrays. And it needs to be able to construct some form of "modification trees". The tool knows that it needs to change a certain variable to a different value in order to get the correct testcase. Hence it will need to list all possible ways to change it, without using reflection obviously.

What this tool will not replace is the need to create tailored unit tests that tests all kinds of conditions when a certain method actually works. It is purely to be used to test methods when they invalidate constraints.

My questions:

Is creating such a tool feasible? Would it ever work, or are there some obvious problems?

Would such a tool be useful? Is it even useful to automatically generate these testcases at all? Could it be extended to do even more useful things?

Does, by chance, such a project already exist and would I be reinventing the wheel?

If not proven useful, but still possible to make such thing, I will still consider it for fun. If it's considered useful, then I might make an open source project for it depending on the time.

For people searching more background information about the used Player and Hand classes in my example, please refer to this repository. At the time of writing the PutMonsterOnFieldAction has not been uploaded to the repo yet, but this will be done once I'm done with the unit tests.

答:
With these main questions:

Is it even useful to automatically generate these testcases at all?
  Could it be extended to do even more useful things? Does, by chance,
  such a project already exist and would I be reinventing the wheel?

I will boldly claim that yes, generating testcases can be useful and yes, such projects already exist and are used. However, it is not that useful in the way asked in the question, namely as a TDD replacement. That it is not.

This was said in one of the other answers:

A correct unit test should test that a unit of your code does what it
  is supposed to do, in a situation. A test generated like you mention,
  would test that the code does what it is implemented to do (and maybe
  that your code is reachable). This in no way relates to your specs.

Which I mostly agree with. This is how unit tests are generally used, and how they are used in TDD. However, this is not all tests are used for.

Assume a situation where you have inherited a large codebase with no existing unit tests. You don't know about its behaviour, and you certainly don't know if any change you're about to introduce will break any existing behaviour. Wouldn't it be great to have tests generated that would capture the current behaviour of the existing codebase?

It sure would. Those kinds of tests are called regression tests, and in this case I do see generating test cases as useful. Tools actually do exist that do this already: maybe the most popular one is a commercial tool AgitarOne with its regression test generating capabilities. There are other alternatives as well.

Another use case where this would be useful is to check if some common contracts are not violated. Common contracts could be that a) your code should never throw a null pointer exception if you didn't give it any null parameters, and b) your code, if it implements the equals method, should follow the rules required by the equals method contract. There exists tools for this as well, such as the free tool Randoop, that uses feedback-assisted random test generation to catch such issues.

These are some examples where I see usefulness in generated test cases. However, like pointed out in the previous answers, it is not the same benefit someone gets from tests in TDD, for example, or a good test suite in general. These are somewhat corner cases: in the general case, you should still write the tests yourself.


问:
Using struct to enforce validation of built-in type
Commonly domain objects have properties which can be represented by a built-in type but whose valid values are a subset of the values which may be represented by that type.

In these cases, the value can be stored using the built-in type but it is necessary to ensure values are always validated at the point of entry, otherwise we might end up working with an invalid value.

One way to solve this is to store the value as a custom struct which has a single private readonly backing field of the built-in type and whose constructor validates the provided value. We can then always be sure of only using validated values by using this struct type.

We can also provide cast operators from and to the underlying built-in type so that values can seamlessly enter and exit as the underlying type.

Take as an example a situation where we need to represent the name of a domain object, and valid values are any string which is between 1 and 255 characters in length inclusive. We could represent this using the following struct:

```<code>public struct ValidatedName : IEquatable<ValidatedName>
{
    private readonly string _value;

    private ValidatedName(string name)
    {
        _value = name;
    }

    public static bool IsValid(string name)
    {
        return !String.IsNullOrEmpty(name) && name.Length <= 255;
    }

    public bool Equals(ValidatedName other)
    {
        return _value == other._value;
    }

    public override bool Equals(object obj)
    {
        if (obj is ValidatedName)
        {
            return Equals((ValidatedName)obj);
        }
        return false;
    }

    public static implicit operator string(ValidatedName x)
    {
        return x.ToString();
    }

    public static explicit operator ValidatedName(string x)
    {
        if (IsValid(x))
        {
            return new ValidatedName(x);
        }
        throw new InvalidCastException();
    }

    public static bool operator ==(ValidatedName x, ValidatedName y)
    {
        return x.Equals(y);
    }

    public static bool operator !=(ValidatedName x, ValidatedName y)
    {
        return !x.Equals(y);
    }

    public override int GetHashCode()
    {
        return _value.GetHashCode();
    }

    public override string ToString()
    {
        return _value;
    }
}
</code>```

The example shows the to-string cast as implicit as this can never fail but the from-string cast as explicit as this will throw for invalid values, but of course these could both be either implicit or explicit.

Note also that one can only initialize this struct by way of a cast from string, but one can test whether such a cast will fail in advance using the IsValid static method.

This would seem to be a good pattern to enforce validation of domain values which can be represented by simple types, but I don't see it used often or suggested and I'm interested as to why.

So my question is: what do you see as being the advantages and disadvantages of using this pattern, and why?

If you feel that this is a bad pattern, I would like to understand why and also what you feel is the best alternative.

NB I originally asked this question on Stack Overflow but it was put on hold as primarily opinion-based (ironically subjective in itself) - hopefully it can enjoy more success here.

Above is the original text, below a couple more thoughts, partly in response to the answers received there before it went on hold:

One of the major points made by the answers was around the amount of boiler plate code necessary for the above pattern, especially when many such types are required. However in defence of the pattern, this could be largely automated using templates and actually to me it doesn't seem too bad anyway, but that is just my opinion.

From a conceptual point of view, does it not seem strange when working with a strongly-typed language such as C# to only apply the strongly-typed principle to composite values, rather than extending it to values which can be represented by an instance of a built-in type?

答:
what do you see as being the advantages and disadvantages of using this pattern, and why?

Good:

It is self contained. Too many validation bits have tendrils reaching into different places.

It helps self-documentation. Seeing a method take a ValidatedString makes it much clearer about the semantics of the call.

It helps limit validation to one spot rather than needing to be duplicated across public methods.

Bad:

The casting trickery is hidden. It's not idiomatic C#, so can cause confusion when reading the code.

It throws. Having strings that don't meet validation isn't an exceptional scenario. Doing IsValid before the cast is a little unweildy.

It can't tell you why something is invalid.

The default ValidatedString is not valid/validated.

I've seen this sort of thing more often with User and AuthenticatedUser sort of things, where the object actually changes. It can be a fine approach, though it seems out of place in C#.


问:
Use of raw pointer of std::vector
I am currently maintaining a code that makes liberal use of raw pointers where std::vector would be a better option. Worse, these pointers are not always properly handled (when run using Intel Inspector, I get the warning message "Warning: Only the first 100,000 memory issues are reported"). As such, I have been slowly changing all instances of raw pointers to std::vector. However, there are several functions that expect a raw pointer as input, and instead of changing all of the function declarations and definitions, I have simply been accessing the raw pointer associated with the std::vector. I.e., code that was:

```<code>double *doubleVec = new double[size];
//code that puts values in doubleVec
someFunc(doubleVec);
</code>```

becomes

```<code>std::vector<double> doubleVec(size);
//code that puts values in doubleVec
someFunc(&doubleVec.front());
</code>```

Is this considered bad practice? On the one hand, I am using a wrapper class and then completely ignoring the wrapper in the function calls, which doesn't really make sense. On the other hand, the point of the wrapper class is to take care of memory management, and since the function calls do not mess with the memory in any way, it's doing it's job.

答: There's now a vector.data() method which explicitly blesses the practice

Title: Use of raw pointer of std::vector


答:
This is fairly common in ML-style languages like Standard ML/OCaml/F#/Haskell where it's much easier to create the wrapper types. It provides you with two benefits:

It allows a piece of code to enforce that a string has undergone validation, without having to take care of that validation itself.

It allows you to localize the validation code in one place. If a ValidatedName ever contains an invalid value, you know the error is in the IsValid method.

If you get the IsValid method right, you have a guarantee that any function that receives a ValidatedName is in fact receiving a validated name.

If you need to do string manipulations you can add a public method that accepts a function that takes a String (the value of the ValidatedName) and returns a String (the new value) and validates the result of applying the function. That eliminates the boilerplate of getting the underlying String value and re-wrapping it.

A related use for wrapping values is to track their provenance. E.g. C-based OS APIs sometimes give handles for resources as integers. You can wrap the OS APIs to instead use a Handle structure and only provide access to the constructor to that part of the code. If the code that produces the Handles is correct, then only valid handles will ever be used.

Title: Using struct to enforce validation of built-in type

Body:
Commonly domain objects have properties which can be represented by a built-in type but whose valid values are a subset of the values which may be represented by that type.

In these cases, the value can be stored using the built-in type but it is necessary to ensure values are always validated at the point of entry, otherwise we might end up working with an invalid value.

One way to solve this is to store the value as a custom struct which has a single private readonly backing field of the built-in type and whose constructor validates the provided value. We can then always be sure of only using validated values by using this struct type.

We can also provide cast operators from and to the underlying built-in type so that values can seamlessly enter and exit as the underlying type.

Take as an example a situation where we need to represent the name of a domain object, and valid values are any string which is between 1 and 255 characters in length inclusive. We could represent this using the following struct:

```<code>public struct ValidatedName : IEquatable<ValidatedName>
{
    private readonly string _value;

    private ValidatedName(string name)
    {
        _value = name;
    }

    public static bool IsValid(string name)
    {
        return !String.IsNullOrEmpty(name) && name.Length <= 255;
    }

    public bool Equals(ValidatedName other)
    {
        return _value == other._value;
    }

    public override bool Equals(object obj)
    {
        if (obj is ValidatedName)
        {
            return Equals((ValidatedName)obj);
        }
        return false;
    }

    public static implicit operator string(ValidatedName x)
    {
        return x.ToString();
    }

    public static explicit operator ValidatedName(string x)
    {
        if (IsValid(x))
        {
            return new ValidatedName(x);
        }
        throw new InvalidCastException();
    }

    public static bool operator ==(ValidatedName x, ValidatedName y)
    {
        return x.Equals(y);
    }

    public static bool operator !=(ValidatedName x, ValidatedName y)
    {
        return !x.Equals(y);
    }

    public override int GetHashCode()
    {
        return _value.GetHashCode();
    }

    public override string ToString()
    {
        return _value;
    }
}
</code>```

The example shows the to-string cast as implicit as this can never fail but the from-string cast as explicit as this will throw for invalid values, but of course these could both be either implicit or explicit.

Note also that one can only initialize this struct by way of a cast from string, but one can test whether such a cast will fail in advance using the IsValid static method.

This would seem to be a good pattern to enforce validation of domain values which can be represented by simple types, but I don't see it used often or suggested and I'm interested as to why.

So my question is: what do you see as being the advantages and disadvantages of using this pattern, and why?

If you feel that this is a bad pattern, I would like to understand why and also what you feel is the best alternative.

NB I originally asked this question on Stack Overflow but it was put on hold as primarily opinion-based (ironically subjective in itself) - hopefully it can enjoy more success here.

Above is the original text, below a couple more thoughts, partly in response to the answers received there before it went on hold:

One of the major points made by the answers was around the amount of boiler plate code necessary for the above pattern, especially when many such types are required. However in defence of the pattern, this could be largely automated using templates and actually to me it doesn't seem too bad anyway, but that is just my opinion.

From a conceptual point of view, does it not seem strange when working with a strongly-typed language such as C# to only apply the strongly-typed principle to composite values, rather than extending it to values which can be represented by an instance of a built-in type?


问:
Nullable enumeration values vs. "NoValue" or "Undefined", etc
I often write code which translates entities in the database to domain objects.  These entities often have fields which are constrained and translate to enumerations in the domain objects.  In some cases, though, the fields can be null.

For example, imagine I have a PrintJob entity with a Status field that can be New, Submitted, or Completed and a Result field that can be Succeeded, FailedNoPaper, or FailedNoToner but it can also be NULL if the Status is not Completed.

On the one hand, I like having a one-to-one mapping of entity field values to domain object enum values, but on the other hand, it somehow feels "better" to always have values for properties with enumeration types.

My question is: is it better to represent the value of the Result field in my domain object as a nullable value (e.g. MyStatus? in C# or VB.NET) having essentially no value when the corresponding entity field is NULL, or should I create a special enum value along with the others, e.g. NoValue or Undefined?

答:
If a field value is one of a list of predefined values, your domain will have a real-world value that you can correspond to NULL. All you have to do is look for it. If the Status is not completed its result could be 'NotFinished', 'Unavailable', 'DoesNotExist' or 'Unknown'.

Think about this in a non-code way. If you print something and ask a colleague to bring over the stack of papers from the printer, how would he let you know that there is no printout on the printer? He might say it isn't finished yet, it wasn't available yet, there was nothing on the printer...

As far as enums go, I'm not a big fan of nullable enums. Add a single, default field such as 'Unknown' and you NEVER EVER have to worry about it being NULL. Otherwise, you will spend reams of code in your application to first check for NULL before doing anything sensible... Enums, like booleans, should shy away from being NULL.


答:
On embedded systems, where you can't always just exit the process and let the OS clean up (what if there's no OS?), an alternative method is to jump to a reinit() handler which reinitializes RAM and jumps to the program's entry point.

This is a reasonable technique if the CPU doesn't need complex reinitialization after such an error. But you probably should have a fallback technique to reset the actual CPU if the simple reinit() fails. Sometimes a full clean restart may be needed.

Title: Recovering a process after illegal instruction exception

Body:
Is it possible in theory to recover after a process is mistakenly pointed-out to read from a wrong memory address, rather than terminating it?

Let say an error while working with registers lead the processor to read a random place on memory and therefore throwing an illegal instruction exception. At this point, are there any ways to recover to a stable state rather terminating the process?

Are there any processor architecture (specially for Embedded systems), with some extra features to deal with these issue?

Also are there any research papers trying to figure out what are valid return addresses for a function? For example if my function is trying to return to an address that is (virtually) invalid for my program to do its job, have been there any efforts to detect such a violation? Either on the programming language level or on the operating system and memory management?

Note: Illegal Instruction is an exception thrown by the processor.

Update

Would saving last known valid Instruction Pointer somewhere manually help? Maybe in an unused or reserved register, but it should be somehow guaranteed to stay untouched by the rest of the program.


答:
What you should worry about is ownership of the data and how long the pointers should/will be valid.

Using std::vector will allow you to be more relaxed about validity though you should still be careful as a reallocation will invalidate the pointer.

However much C++ code is littered with &vector[0] to get the pointer to the first element so it's very much accepted to grab a raw pointer to fill in data using a third party library.

Title: Use of raw pointer of std::vector

Body:
I am currently maintaining a code that makes liberal use of raw pointers where std::vector would be a better option. Worse, these pointers are not always properly handled (when run using Intel Inspector, I get the warning message "Warning: Only the first 100,000 memory issues are reported"). As such, I have been slowly changing all instances of raw pointers to std::vector. However, there are several functions that expect a raw pointer as input, and instead of changing all of the function declarations and definitions, I have simply been accessing the raw pointer associated with the std::vector. I.e., code that was:

```<code>double *doubleVec = new double[size];
//code that puts values in doubleVec
someFunc(doubleVec);
</code>```

becomes

```<code>std::vector<double> doubleVec(size);
//code that puts values in doubleVec
someFunc(&doubleVec.front());
</code>```

Is this considered bad practice? On the one hand, I am using a wrapper class and then completely ignoring the wrapper in the function calls, which doesn't really make sense. On the other hand, the point of the wrapper class is to take care of memory management, and since the function calls do not mess with the memory in any way, it's doing it's job.


答:
Looking at this as a state machine problem, where each state was represented by an enum, it would be reasonable to provide an enum for all states, including the "not yet" state. I'd be tempted to name it something meaningful, though, like "PROCESSING" rather than a synonym for "NULL".

Setting aside the programmatic problems with NULL, representing the state as NULL would be a valid way to say "no state at all". But putting the second value into some known initial state is more definitive.

Title: Nullable enumeration values vs. "NoValue" or "Undefined", etc

Body:
I often write code which translates entities in the database to domain objects.  These entities often have fields which are constrained and translate to enumerations in the domain objects.  In some cases, though, the fields can be null.

For example, imagine I have a PrintJob entity with a Status field that can be New, Submitted, or Completed and a Result field that can be Succeeded, FailedNoPaper, or FailedNoToner but it can also be NULL if the Status is not Completed.

On the one hand, I like having a one-to-one mapping of entity field values to domain object enum values, but on the other hand, it somehow feels "better" to always have values for properties with enumeration types.

My question is: is it better to represent the value of the Result field in my domain object as a nullable value (e.g. MyStatus? in C# or VB.NET) having essentially no value when the corresponding entity field is NULL, or should I create a special enum value along with the others, e.g. NoValue or Undefined?


答:
Checking values for null or undefined is one thing, as has been explained abundantly.

There's another thing, where == shines:

You can define comparison from >= like so (people usually start from > but I find this more elegant):

a > b <=> a >= b && !(b >= a)

a == b <=> a >= b && b >= a

a < b and a <= b are left as an exercise to the reader.

As we know, in JavaScript "3" >= 3 and "3" <= 3, from which you get 3 == "3". You can make a point that it's a horrible idea to allow implementing comparison between strings and numbers by parsing the string. But given that this is the way it works, == is absolutely the correct way to implement that relationship operator.

So the really good thing about == is that it is consistent with all other relationships. To put it differently, if you write this:

```<code>function compare(a, b) {
  if (a > b) return 1;
  if (a < b) return -1;
  return 0;
}
</code>```

You are implicitly using == already.

Now to the quite related question of: Was it a bad choice to implement number and string comparison the way it is implemented? Seen in isolation, it seems a rather stupid thing to do. But in the context of other parts of JavaScript and the DOM, it's relatively pragmatic, considering that:

attributes are always strings

keys are always strings (the use case being that you use an Object to have a sparse map from ints to values)

user input and form control values are always strings (even if the source matches input[type=number])

For a whole number of reasons it made sense to make strings behave like numbers when needed. And assuming that string comparison and string concatenation had different operators (e.g. :: for concating and a method for comparing (where you can use all kinds of parameters regarding case sensitivity and what not)), this would in fact be less of a mess. But this operator overloading is probably in fact where the "Java" in "JavaScript" comes from ;)

Title: Does using == in JavaScript ever make sense?

Body:
In JavaScript, the Good Parts, Douglas Crockford wrote:

JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=.  The good ones work the way you would expect.  If the two operands are of the same type and have the same value, then === produces true and !== produces false.  The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values.  The rules by which they do that are complicated and unmemorable.  These are some of the interesting cases:

```<code>'' == '0'           // false
0 == ''             // true
0 == '0'            // true

false == 'false'    // false
false == '0'        // true

false == undefined  // false
false == null       // false
null == undefined   // true

' \t\r\n ' == 0     // true
</code>```

The lack of transitivity is alarming.  My advice is to never use the evil twins.  Instead, always use === and !==.  All of the comparisons just shown produce false with the === operator.

Given this unequivocal observation, is there ever a time when using == might actually be appropriate?

Body:
Checking values for null or undefined is one thing, as has been explained abundantly.

There's another thing, where == shines:

You can define comparison from >= like so (people usually start from > but I find this more elegant):

a > b <=> a >= b && !(b >= a)

a == b <=> a >= b && b >= a

a < b and a <= b are left as an exercise to the reader.

As we know, in JavaScript "3" >= 3 and "3" <= 3, from which you get 3 == "3". You can make a point that it's a horrible idea to allow implementing comparison between strings and numbers by parsing the string. But given that this is the way it works, == is absolutely the correct way to implement that relationship operator.

So the really good thing about == is that it is consistent with all other relationships. To put it differently, if you write this:

function compare(a, b) {
  if (a > b) return 1;
  if (a < b) return -1;
  return 0;
}

You are implicitly using == already.

Now to the quite related question of: Was it a bad choice to implement number and string comparison the way it is implemented? Seen in isolation, it seems a rather stupid thing to do. But in the context of other parts of JavaScript and the DOM, it's relatively pragmatic, considering that:

attributes are always strings

keys are always strings (the use case being that you use an Object to have a sparse map from ints to values)

user input and form control values are always strings (even if the source matches input[type=number])

For a whole number of reasons it made sense to make strings behave like numbers when needed. And assuming that string comparison and string concatenation had different operators (e.g. :: for concating and a method for comparing (where you can use all kinds of parameters regarding case sensitivity and what not)), this would in fact be less of a mess. But this operator overloading is probably in fact where the "Java" in "JavaScript" comes from ;)


问:
Using macros to protect assignment to global variables
Because there is no language feature in C to protect assignment to global variables would you recommend doing something like this?

Take this example:

We have a module with the header file called module.h and
  implementation file module.c. The module contains a global variable
  called global_variable. global_variable will be updated by other functions
  in the implementation but we do not want users of module to be able
  to assign to it.

module.h:

```<code>#ifndef MODULE_H_
#define MODULE_H_

extern int global_variable;
#define global_variable (int)global_variable
/* Because the macro expansion is not an "lvalue" it cannot be assigned to. */

/* ... */

#endif
</code>```

In the implementation you just #undef the macro to get full read/write access to it.

module.c:

```<code>#include "module.h"
#undef global_variable /* Make `global_variable` mutable again. */

int global_variable = 17;

/* ... */
</code>```

This method obviously has the disadvantage that you cannot create a local variable with the identifier global_variable without #undefing the macro.

```<code>#include "module.h"

int f(void)
{
    int global_variable; /* This doesn't work. */
    /* ... */
}
</code>```

But if you manage to come up with a naming convention that separates the identifiers this will not be a problem. Something like prefixing global variables with glbl_ or GLBL_. GLBL_ seems like a good choice since that also gives you a hint that it can be defined as a macro.

Another technique I have figured out is this:

module.h:

```<code>#ifndef MODULE_H_
#define MODULE_H_

#ifdef MODULE_IMPL_
extern int global_variable; /* Writable for the implementation. */
#else
extern const int global_variable; /* `readonly` for everyone else. */
#endif

/* ... */

#endif
</code>```

module.c:

```<code>#define MODULE_IMPL_ /* I am the implementation. I want global_variable to be mutable. */
#include "module.h"

int global_variable = 17;

/* ... */
</code>```

I know that the simplest and most flexible approach is to create get functions to retrieve the value of the variable at the cost of a function call. But that does not stop me from finding other hacks to solve the problem.

Are these evil things to do? I am not going to lie, I like to play with macros. But I want to know if this is something that can be applied to a serious project. :)

答:
Using macros to create code that's syntactically identical to C but semantically different is almost always evil, especially in an unsafe language like C where the fact that something compiles in no way guarantees it actually has defined behavior at run time. If you must use a macro for something, you generally want to make it clear that a macro is being used.

For this particular case you can achieve your goal better by not exposing the variable at all (i.e. make it static) and providing a function to read its value. You get the same end result (the value is read-only from outside the implementation file) but avoid using macros and their associated pitfalls altogether. Even better, don't use a global variable at all if you can; pass the value to the functions that need it.


问:
How to deal with historic exception specifications in maintained C++ code
Today, I discovered a few exception specifications in legacy code I've to maintain, when Cppcheck 1.68 ([Inconclusive] but correctly) pointed out that the specified exceptions are not handled in specific portions of the code.

[Inconclusive] Unhandled exception specification when calling function [...]. Either use a try/catch around the function call, or add a exception specification for [...] also.

But the occurrence of any of them would be catastrophic for the program, so it's a good idea not to handle them locally, and copying the specification over and over the code would be nonsense. And furthermore, exception specifications got deprecated in C++11 (for good reasons).

So, generally spoken: Is the best I can do with exception specifications, removing them?

答: Pretty much. There's no reason to keep them. I would strip them all out.</p>


问:
Why is there little use of filesharing as compression (outside of libraries)?
Recently I was looking for a program that will run as a daemon and find files that have the same size/type, check if they're the same, then make both a hard link to a single copy if they are. And I started wondering why Operating Systems don't do this automatically.

I thought maybe because it would be time consuming, but it wouldn't need to check if no new files were added outside of the cache directory, and checking the size would rapidly cut the search space. Then I thought maybe because it doesn't come up very often; but if that were the case then I would expect game consoles to do this, because most games will use the same stock sound effects package for instance, but they don't. Having two games from one series takes the same amount of space as just summing the two sizes, even though tons of assets would be reused.

Or in a system like youtube, they check videos against other videos when checking for copyright violations, but they don't seem to cause two identical videos to be stored only once, considering how mirroring a video can prevent it being taken off the site, (e.g. when 'youtube vs the users' kept being mirrored they took it out of the search results rather than continuing to take them off the site).

So, what's the reason the system doesn't compress things this way?

答:
I'm going to assume you mean resource type files here e.g. images, songs, sounds etc. If you're on about sharing executable code, this path has already been well trodden: windows has had its DLL Hell whilst Unix gets round this by compiling an all singing, all dancing executable.

The main problem with resource type files to my mind comes with editing. Say you have a photo and you want to make a copy to clip it, correct it, enhance it etc. Clearly you wouldn't want the edit to also update the source as the raw information would be lost.

There is some mileage in applications that would do such a job - to control photo libraries & music collections etc. But I don't see the value in building this into the OS as standard.

Bear in mind also that some operating systems don't have the facility to create linked files as elegantly as Unix does.


问:
How to organize points on a sphere in bins and navigate between bins?
I'm having trouble coming up with a suitable way to navigate through a set of star coordinates in the Equatorial Coordinate System. My goal is to display those which are within a given range of horizontal coordinates. The display is square with about 10 degrees "length" in each direction.

I thought about binning the stars in clusters of sufficiently large (but small enough) equal right ascension and declination, so I can display one or more bins at a time on the display (one if the display is showing the center of a bin, four if the display is showing the point connecting adjacent bins). The binning is simple, but how can I navigate between bins in order to select the right ones for the display? This appears to be a problem around the poles, where many bins touch each other.

The application is being written in C++ and will have to run on a microcontroller, so resources (memory and CPU time) are very limited. Coordinates can be read from an SD card and the format may be custom, so if the algorithm imposes any constraints on that, that's fine.

Additional thoughts:

The tiles that divide the celestial sphere into bins also have constant (not necessarily equal) size and are generated together with the lookup structure.

insertion time is not important. The structure used for finding the right bin does not change during runtime and can be loaded from the SD card to RAM at startup.

The word I was missing was "tiles". Gamedev SX has a [tiles] tag and there are some questions and answers there; I'll have a look at those.

And another one:

Digging through the Gamedev [tiles] tag didn't reveal a lot that I could use for spherical coordinates. It also looks like I'm not familiar enough with the underlying theory to come up with a suitable solution. Another idea I had was to add information about all adjacent bins to each bin, so that when the display's view is moved I can just scan through all neighbours to find the next one that the display is "centered" on. I think this is similar to a graph, but decentralized.

答: Map the stars onto an Isocahedron(https://en.wikipedia.org/wiki/Icosahedron) and if you need more fine binning, then just subdivide the triangles.</p>


问:
Unit testing a template class after refactoring
I am cleaning up my code by way of removing duplicates, and found two classes that were almost identical, out of 55 lines, only a single predicate in an if statement differed between them.

Both classes also had a suite of tests, which were almost identical copies as well.

The two original classes were FooApiAuthenticationProvider and BarApiAuthenticationProvider.

Below is my current refactored code using a template-pattern refactoring.

Template

```<code>public abstract class ApiAuthenticationProviderTemplate : IApiAuthenticationProvider
{
    private readonly IClientRepository _clientRepository;

    protected ApiAuthenticationProviderTemplate(IClientRepository clientRepository)
    {
        if (clientRepository == null)
        {
            throw new ArgumentNullException("clientRepository");
        }

        _clientRepository = clientRepository;
    }

    public GenericPrincipal GetPrincipal(string username, string password)
    {
        if (string.IsNullOrWhiteSpace(username))
        {
            throw new ArgumentNullException("username");
        }

        if (string.IsNullOrWhiteSpace(password))
        {
            throw new ArgumentNullException("password");
        }

        var client = clientRepository.GetByUsername(username);

        if (client == null && !DoesPasswordMatch(password, client))
        {
            return null;
        }

        return PrincipalBuilder.BuildPrinciple(client.LoginIdentifier, client.ID);
    }

    protected abstract bool DoesPasswordMatch(string password, Client client);
}
</code>```

FooApiAuthenticationProvider

```<code>public sealed class FooApiAuthenticationProvider : ApiAuthenticationProviderTemplate
{
    public FooApiAuthenticationProvider(IClientRepository clientRepository)
        : base(clientRepostitory)
    {
    }

    protected override bool DoesPasswordMatch(string password, Client client)
    {
        return client.FooApiPassword == password;
    }
}
</code>```

BarApiAuthenticationProvider

```<code>public sealed class BarApiAuthenticationProvider : ApiAuthenticationProviderTemplate
{
    public BarApiAuthenticationProvider(IClientRepository clientRepository)
        : base(clientRepostitory)
    {
    }

    protected override bool DoesPasswordMatch(string password, Client client)
    {
        return client.DoesBarServicePasswordMatch(password);
    }
}
</code>```

Both unit test fixtures for each specific class pass, and normally that would be the end of the thought, however, I have to extend the functionality that's common to both authentication providers (so I would obviously implement in the template base class).

My questions are:

Should I refactor the test code to remove test duplication?  To test the abstract class somehow, and write specific tests for the DoesPasswordMatch method

Should I add new tests to both fixtures to ensure the actual types both work properly?  Meaning the tests should have no idea the underlying class is a template, that way if both providers become significantly different where the template no longer makes sense, it could be refactored away without losing code coverage.

Should I leave both test fixtures the same, and just write a new fixture with tests against the template for the new functionality?

Is there something else I am not considering?

答:
Remove the duplicate test code

Having tests on your child-classes for code that is in the parent class means twice the maintenance if the parent class changes. The reason you move to a parent class is specifically to avoid duplicating code, actual code as well as tests. (And if you ever end up creating a third child you might end up thinking that all tests on the parent class need to be duplicated AGAIN. So you can see where that leads you)

Test the parent class logic on the parent class, not through the children

Depending on the language you can use mocks, or write a specific implementation of the parent class that allows you to test the parent class methods (a TestableApiAuthenticationProviderTemplate). This would also test that when the preconditions for GetPrincipal are valid the DoesPasswordMatch-method is called.

Test your child classes independently

Each child class can have its own test class that only tests the code in the child. Note that you might have to change the signature for the DoesPasswordMatch to become public in order to facilitate testing. You could go through the parent method and test by calling GetPrincipal but you could end up doing a lot of setting up code so that it can reach the actual code you are testing. And again, when changing the code of the parent (because you want to check an additional parameter) you would have to change all the tests of the child classes.