答:
It sounds like you're already doing due diligence. But ...

At the most practical level, always include a good handful of both "full-loop" integration tests in your suite for your own code, and write more assertions than you think you need. In particular, you should have a handful of tests that perform a full create-read-[do_stuff]-validate cycle.

```<code>[TestMethod]
public void MyFormatter_FormatsTimesCorrectly() {

  // this test isn't necessarily about the stream or the external interpreter.
  // but ... we depend on them working how we think they work:
  var stream = new StreamThingy();
  var interpreter = new InterpreterThingy(stream);
  stream.Write("id-123, some description, 12345");

  // this is what you're actually testing. but, it'll also hiccup
  // if your 3rd party dependencies introduce a breaking change.
  var formatter = new MyFormatter(interpreter);
  var line = formatter.getLine();
  Assert.equal(
    "some description took 123.45 seconds to complete (id-123)", line
  );
}
</code>```

And it sounds like you're already doing this sort of thing. You're just dealing with a flaky and/or complicated library. And in that case, it's good to throw in a few "this is how the library works" types of tests that both verify your understanding of the library and serve as examples of how to use the library.

Suppose you need to understand and depend on how a JSON parser interprets each "type" in a JSON string. It's helpful and trivial to include something like this in your suite:

```<code>[TestMethod]
public void JSONParser_InterpretsTypesAsExpected() {
  String datastream = "{nbr:11,str:"22",nll:null,udf:undefined}";
  var o = (new JSONParser()).parse(datastream);

  Assert.equal(11, o.nbr);
  Assert.equal(Int32.getType(), o.nbr.getType());
  Assert.equal("22", o.str);
  Assert.equal(null, o.nll);
  Assert.equal(Object.getType(), o.nll.getType());
  Assert.isFalse(o.KeyExists(udf));
}
</code>```

But secondly, remember that automated testing of any kind, and at almost any level of rigor, will still fail to protect you against all bugs. It's perfectly common to add tests as you discover problems. Not having a QA department, this means a lot of those problems will be discovered by end-users.

And to a significant degree, that's just normal.

And thirdly, when a library changes the meaning of a return-value or field without renaming the field or method or otherwise "breaking" dependent code (maybe by changing its type), I'd be pretty damn unhappy with that publisher. And I'd argue that, even though you should probably have read the changelog if there is one, you should probably also pass some of your stress onto the publisher. I'd argue they need the hopefully-constructive criticism ...

Body:
It sounds like you're already doing due diligence. But ...

At the most practical level, always include a good handful of both "full-loop" integration tests in your suite for your own code, and write more assertions than you think you need. In particular, you should have a handful of tests that perform a full create-read-[do_stuff]-validate cycle.

[TestMethod]
public void MyFormatter_FormatsTimesCorrectly() {

  // this test isn't necessarily about the stream or the external interpreter.
  // but ... we depend on them working how we think they work:
  var stream = new StreamThingy();
  var interpreter = new InterpreterThingy(stream);
  stream.Write("id-123, some description, 12345");

  // this is what you're actually testing. but, it'll also hiccup
  // if your 3rd party dependencies introduce a breaking change.
  var formatter = new MyFormatter(interpreter);
  var line = formatter.getLine();
  Assert.equal(
    "some description took 123.45 seconds to complete (id-123)", line
  );
}

And it sounds like you're already doing this sort of thing. You're just dealing with a flaky and/or complicated library. And in that case, it's good to throw in a few "this is how the library works" types of tests that both verify your understanding of the library and serve as examples of how to use the library.

Suppose you need to understand and depend on how a JSON parser interprets each "type" in a JSON string. It's helpful and trivial to include something like this in your suite:

[TestMethod]
public void JSONParser_InterpretsTypesAsExpected() {
  String datastream = "{nbr:11,str:"22",nll:null,udf:undefined}";
  var o = (new JSONParser()).parse(datastream);

  Assert.equal(11, o.nbr);
  Assert.equal(Int32.getType(), o.nbr.getType());
  Assert.equal("22", o.str);
  Assert.equal(null, o.nll);
  Assert.equal(Object.getType(), o.nll.getType());
  Assert.isFalse(o.KeyExists(udf));
}

But secondly, remember that automated testing of any kind, and at almost any level of rigor, will still fail to protect you against all bugs. It's perfectly common to add tests as you discover problems. Not having a QA department, this means a lot of those problems will be discovered by end-users.

And to a significant degree, that's just normal.

And thirdly, when a library changes the meaning of a return-value or field without renaming the field or method or otherwise "breaking" dependent code (maybe by changing its type), I'd be pretty damn unhappy with that publisher. And I'd argue that, even though you should probably have read the changelog if there is one, you should probably also pass some of your stress onto the publisher. I'd argue they need the hopefully-constructive criticism ...


问:
How do I test a system where the objects are difficult to mock?
I am working with the following system:

```<code>Network Data Feed -> Third Party Nio Library -> My Objects via adapter pattern
</code>```

We recently had an issue where I updated the version of the library I was using, which, among other things, caused timestamps (which the third party library returns as long), to be changed from milliseconds after the epoch to nanoseconds after the epoch.

The Problem:

If I write tests that mock the third party library's objects, my test will be wrong if I have made a mistake about the third party library's objects. For example, I didn't realize that the timestamps changed precision, which resulted in a need for change in the unit test, because my mock returned the wrong data. This is not a bug in the library, it happened because I missed something in the documentation.

The problem is, I cannot be sure about the data contained in these data structures because I cannot generate real ones without a real data feed. These objects are big and complicated and have a lot of different pieces of data in them. The documentation for the third party library is poor.

The Question:

How can I set up my tests to test this behavior? I'm not sure I can solve this issue in a unit test, because the test itself can easily be wrong. Additionally, the integrated system is large and complicated and it's easy to miss something. For example, in the situation above, I had correctly adjusted the timestamp handling in several places, but I missed one of them. The system seemed to be doing mostly the right things in my integration test, but when I deployed it to production (which has a lot more data), the problem became obvious.

I do not have a process for my integration tests right now. Testing is essentially: try to keep the unit tests good, add more tests when things break, then deploy to my test server and make sure things seem sane, then deploy to production. This timestamp issue passed the unit tests because the mocks were created wrong, then it passed the integration test because it didn't cause any immediate, obvious problems. I do not have a QA department.

答:
Short answer: It's hard. You're probably feeling like there are no good answers, and that's because there are no easy answers.

Long answer: Like @ptyx says, you need system tests and integration tests as well as unit tests:

Unit tests are fast and easy to run. They catch bugs in individual sections of code and use mocks to make running them possible. By necessity, they can't catch mismatches between pieces of code (like milliseconds versus nanoseconds).

Integration tests and system tests are slow(er) and hard(er) to run but catch more errors.

Some specific suggestions:

There's some benefit to simply getting a system test to run as much of the system as possible. Even if it can't validate very much of the behavior or do very well at pinpointing the problem. (Micheal Feathers discusses this more in Working Effectively with Legacy Code.)

Investing in testability helps. There are a huge number of techniques you can use here: continuous integration, scripts, VMs, tools to play back, proxy, or redirect network traffic.

One of the advantages (for me, at least) of investing in testability may be non-obvious: if tests are tedious, annoying, or cumbersome to write or run, then it's too easy for me to simply skip them if I'm pressured or tired. Keeping your tests below the "It's so easy that there's no excuse to not do this" threshold is important.

Perfect software is not feasible. Like everything else, effort spent on testing is a tradeoff, and sometimes it's not worth the effort. Constraints (such as your lack of a QA department) exist. Accept that bugs will happen, recover, and learn.

I've seen programming described as the activity of learning about a problem and solution space. Getting everything perfect ahead of time may not be feasible, but you can learn after the fact. ("I fixed timestamp handling in several places but missed one. Can I change my data types or classes to make timestamp handling more explicit and harder to miss, or to make it more centralized so I only have one place to change? Can I modify my tests to verify more aspects of the timestamp handling? Can I simplify my test environment to make this easier in the future? Can I imagine some tool that would have made this easier, and if so, can I find such a tool on Google?" Etc.)

ContentLicense: CC BY-SA 3.0


答:
I updated the version of the library … which … caused timestamps (which the third party library returns as long), to be changed from milliseconds after the epoch to nanoseconds after the epoch.

…

This is not a bug in the library

I strongly disagree with you here. It is a bug in the library, a rather insidious one in fact. They have changed the semantic type of the return value, but did not change the programmatic type of the return value. This can wreak all kinds of havoc, especially if this was a minor version bump, but even also if it was a major one.

Let's say instead the library returned a type of MillisecondsSinceEpoch, a simple wrapper that holds a long. When they changed it to a NanosecondsSinceEpoch value, your code would have failed to compile, and would have obviously pointed you to the places where you need to make changes. The change couldn't silently corrupt your program.

Better yet would be a TimeSinceEpoch object that could adapt it's interface as more precision was added, such as adding a #toLongNanoseconds method along side the #toLongMilliseconds method, requiring no change to your code whatsoever.

The next problem is that you don't have a reliable set of integration tests to the library. You should write those. Better would be to create an interface around that library to encapsulate it away from the rest of your application. Several other answers address this (and more keep popping up as I type). Integration tests should be run less frequently than your unit tests. That is why having a buffer layer helps. Segregate your integration tests into a separate area (or name them differently) so you can run them as needed, but not every time that you run your unit test.

Title: How do I test a system where the objects are difficult to mock?

Body:
I am working with the following system:

```<code>Network Data Feed -> Third Party Nio Library -> My Objects via adapter pattern
</code>```

We recently had an issue where I updated the version of the library I was using, which, among other things, caused timestamps (which the third party library returns as long), to be changed from milliseconds after the epoch to nanoseconds after the epoch.

The Problem:

If I write tests that mock the third party library's objects, my test will be wrong if I have made a mistake about the third party library's objects. For example, I didn't realize that the timestamps changed precision, which resulted in a need for change in the unit test, because my mock returned the wrong data. This is not a bug in the library, it happened because I missed something in the documentation.

The problem is, I cannot be sure about the data contained in these data structures because I cannot generate real ones without a real data feed. These objects are big and complicated and have a lot of different pieces of data in them. The documentation for the third party library is poor.

The Question:

How can I set up my tests to test this behavior? I'm not sure I can solve this issue in a unit test, because the test itself can easily be wrong. Additionally, the integrated system is large and complicated and it's easy to miss something. For example, in the situation above, I had correctly adjusted the timestamp handling in several places, but I missed one of them. The system seemed to be doing mostly the right things in my integration test, but when I deployed it to production (which has a lot more data), the problem became obvious.

I do not have a process for my integration tests right now. Testing is essentially: try to keep the unit tests good, add more tests when things break, then deploy to my test server and make sure things seem sane, then deploy to production. This timestamp issue passed the unit tests because the mocks were created wrong, then it passed the integration test because it didn't cause any immediate, obvious problems. I do not have a QA department.


问:
Can a DI object be both a client and a service simultaneously?
In my reasearch of Dependendcy Injection so far I haven't seen an example object being treated as both a client and a service (meaning a service [value, factory, etc] which has its own dependencies).

Can a component be both a client and a service without breaking some fundamental aspect of DI? Is this normal to do in DI?

For clarification, I'm asking if a component can both be a dependency, and have dependencies, making it both a client and a service in Dependency Injection.

答: Yes.  Think of the classic DI example - a Logger - which itself might take dependencies on a FileSystemWriter and a DatabaseWriter.</p>


问:
How long should a code review be?
Where I work, we are eight software developers and every task done must be reviewed by another developer. Often, I feel like the code reviews are done too quickly (example: a task completed in five hours gets reviewed in 15 minutes). I know I can easily spend an hour reviewing a task that took five hours to complete.

Here is what we agreed, as a team, to verify when we do a code review:

The code written/changed solves the problem (bug fix, new feature,
etc.)

Code is clean and well structure (to our standards)

Code style is correct (to our standards)

Documentation, if any, is up to date

Unit tests cover all the possible cases and do not fail

I was wondering if it's my code reviews that are too long or if it's the code reviews of the others that are too short. Or maybe both?

Edit 2015-10-06 15:55 EST : I agree that there is no one-size fits all answer to the question as mentioned by Thomas Owens♦. I guess I was more looking to what should trigger a flag for a code review too short or too long. Or should I simply don't care and let the code fail in production because someone botched a code review (because it does happen)? Remember, we did, as a team, agree to verify that the code solves the problem. We have no QA team.

I ask because it happens that code pushed into production fail. While I agree it can happen, it happens too often in our team. When we talk with the developers to learn what happened, we learn that the code review simply didn't happen (this is more a process problem than a code review problem) or the code review was deficient / not tested enough.

答:
There's no one-size fits all answer to this question. The amount of effort for a peer review will change depending on the objectives of the review, the complexity of the change, and the level of formality. There is some guidance that you can apply.

The first thing to do is to understand why you are doing code reviews. Specifically, I'd argue that ensuring that the code solves the problem isn't part of a code review. For a defect, the person fixing it should have enough information to reproduce the issue. With sufficient acceptance criteria and test cases, they can not only ensure that the fix is appropriate, but also perform some level of regression testing. I'd also argue that ensuring compliance to code style and standards is something that large portions of can be automated.

The biggest thing that I would recommend is a divide-and-conquer approach.

Prior to code review, use automated tools as much as possible for analysis and style checking. Use static analysis to find issues before it is submitted to humans. Use tools to reformat the code per your team's style guidelines. Try to minimize the work that needs to be done by human reviewers.

Once you are focusing your human reviewers on things that tools can't catch, consider having more than one person participate in the review and divide the work up into two blocks. It's easier to get someone to spend an hour than it is to get them to spent 2 hours, so maybe have 2 people each spend an hour looking at different things. Depending on your team organization, there may be different ways to divide up the review.

Title: How long should a code review be?


问:
How can I roll-back the execution of a constructor while building a complex data structure?
I'm building a complex tree of objects. There are a total of five types, A, B, C, D, and E. There is a single instance of A, which is the root node. A has one or more Bs as children, each B has one or more Cs as children, and so on. The original data format is a stream that consists of 5 numbers (numerical IDs for A, B, C, D, and E) plus metadata that may be associated with each one.

I'm attempting to add some level of filtering to my tree. My current approach is to take the input and pass it into the constructor for A and then flow it down to the Bs that A construct and the Cs that B construct and so on. However, the filtering ultimately happens at the level of E. If all of the Es for a given D don't exist, I don't want to create that D. If C doesn't have any Ds, I don't want that C to exist.

My initial thought is to throw an exception, but that seems like using exceptions for flow control. Although some languages favor exceptions, I'm currently working in Java, where the tendency is for exceptions to be for exceptional conditions. I don't think that not matching a filter is an exceptional case.

What are my options for ensuring that my final tree only contains nodes with children and the filter is applied?

答:
I'll start by pointing out that building complex objects in a constructor is not always a good idea.

That said, if it's the way your code currently behaves, and you don't want to change that, you should probably be able to trade your constructors for lightweight factories.

Instead of A() doing new C() and then deciding it didn't really need it, you could do (with a factory or a static method, depending of your language): A() calling C#get() that returns a C or null if it's filtered out.


答:
I would do this by using a Map<Id, Container> at each level of the data structure. Write a private helper method that will return the container if it already exists, or creates a new Container if it does not yet exist. This is method is commonly called getOrAdd.

As usual, making sure that the the underlying container still exists is a bunch of boilerplate code which you are in danger of copy-pasting repeatedly if you do this wrong. Instead, you should create your own data structure to do this, or you could use Guava to help out which provides a number of useful tools including Multimap (which you can use if the data structures are pretty dumb) and ForwardingMap (which will make it easier to write your own Map implementations if you have metadata at every level). Then, just write get to use a Supplier / Factory (if not using Guava) if the container doesn't yet exist, or return the existing one if it does.

Title: How can I roll-back the execution of a constructor while building a complex data structure?

Body:
I'm building a complex tree of objects. There are a total of five types, A, B, C, D, and E. There is a single instance of A, which is the root node. A has one or more Bs as children, each B has one or more Cs as children, and so on. The original data format is a stream that consists of 5 numbers (numerical IDs for A, B, C, D, and E) plus metadata that may be associated with each one.

I'm attempting to add some level of filtering to my tree. My current approach is to take the input and pass it into the constructor for A and then flow it down to the Bs that A construct and the Cs that B construct and so on. However, the filtering ultimately happens at the level of E. If all of the Es for a given D don't exist, I don't want to create that D. If C doesn't have any Ds, I don't want that C to exist.

My initial thought is to throw an exception, but that seems like using exceptions for flow control. Although some languages favor exceptions, I'm currently working in Java, where the tendency is for exceptions to be for exceptional conditions. I don't think that not matching a filter is an exceptional case.

What are my options for ensuring that my final tree only contains nodes with children and the filter is applied?


问:
Data structure to use for time-optimized line-vs-grid check?
I am asking here because I feel that this question can be filed under the "algorithm and data structure concepts" category.

Background: I have been recently assigned the task to design and develop a new program. Specs are still in the discussion phase and I can have my say, given my experience I will go for either for C++ or C, also depending on hardware and legal (certification) requirements.

One of the main problems that I have to solve in this program is to check collisions between a (2D or 3D) line and a (2D or 3D again) grid. I am looking for suggestions about which kind of data structures would be optimal (runtime wise) to perform such checks and/or if there is an overview of possible algorithms with a comparison of the various costs and benefits connected to them?

EDIT
To address Useless' comment, the grid is a regular square one (x % 0.5 == 0, same for y) and the segments are straight between two known points (x_0, y_0) and (x_1,y_1). In the 3D case I should add the z coordinate, but these properties would remain unchanged. The result of the algorthm would be the list of grid squares crossed by the line.

Since the time I asked this question, I found out about Bresenham's algorithm. The output would be the one I look for, but is it optimal or are there better approaches?

答:
The standard algorithm is 2D-DDA and 3D-DDA. This returns every intersected cell in a 2D or 3D grid. Bresenham's algorithm is more for line rendering.

Rough pseudo-code for a ray (for a line just stop at the end by setting minBoundary and maxBoundary to be the bounding box of the line. This will stop it from both leaving the grid and going past the end):

```<code>var rayPosition = { x: 25, y: 25 };
var rayDirection = { x: 1, y: 1 };

var cellSize = 50;

var cell = { x: Math.floor(rayPosition.x / cellSize), y: Math.floor(rayPosition.y / cellSize) };

var step = { x: Math.sign(rayDirection.x), y: Math.sign(rayDirection.y) }; // sign returns -1, 0, or 1

var offsetFromAxis =
{
    x: step.x > 0 ? cellSize - (rayPosition.x - Math.floor(rayPosition.x / cellSize) * cellSize) : (rayPosition.x - Math.floor(rayPosition.x / cellSize) * cellSize),
    y: step.y > 0 ? cellSize - (rayPosition.y - Math.floor(rayPosition.y / cellSize) * cellSize) : (rayPosition.y - Math.floor(rayPosition.y / cellSize) * cellSize)
};
var tMax = { x: offsetFromAxis.x / Math.abs(rayDirection.x), y: offsetFromAxis.y / Math.abs(rayDirection.y) };
var tDelta = { x: cellSize / Math.abs(rayDirection.x), y: cellSize / Math.abs(rayDirection.y) };
var minBoundary = { x: -1, y: -1 }; // for a line just do something like (might be off by one):
/* var minBoundary =
{
    x: Math.max(0, Math.min(Math.floor(lineStart.x / cellSize), Math.floor(lineEnd.x / cellSize)) - 1,
    y: Math.max(0, Math.min(Math.floor(lineStart.y / cellSize), Math.floor(lineEnd.y / cellSize)) - 1
}
*/
var maxBoundary = { x: width + 1, y: height + 1 }; // for a line just do something like (might be off by one):
/* var maxBoundary =
{
    x: Math.min(width, Math.max(Math.floor(lineStart.x / cellSize), Math.floor(lineEnd.x / cellSize)) + 1,
    y: Math.min(height, Math.max(Math.floor(lineStart.y / cellSize), Math.floor(lineEnd.y / cellSize)) + 1
}
*/
var boundary = { x: step.x > 0 ? maxBoundary.x : minBoundary.x, y: step.y > 0 ? maxBoundary.y : minBoundary.y };
var cells = [];
do
{
    cells.push({ x: cell.x, y: cell.y });
    if (tMax.x < tMax.y)
    {
        cell.x += step.x;
        if (cell.x == boundary.x)
        {
            break;
        }
        tMax.x += tDelta.x;
    }
    else
    {
        cell.y += step.y;
        if (cell.y == boundary.y)
        {
            break;
        }
        tMax.y += tDelta.y;
    }
} while (true);
</code>```

The 3D-DDA is nearly identical adding a z-axis. (You can find examples though online). The only big change is the if statement:

```<code>if (tMax.x < tMax.y)
{
    if (tMax.x < tMax.z)
    {
        // x
    }
    else
    {
        // z
    }
}
else
{
    if (tMax.y < tMax.z)
    {
        // y
    }
    else
    {
        // z
    }
}
</code>```

Regarding data structures you can just use a 1D array and index it with something like:

index = z * xDimension * yDimension + y * xDimension + x;

Not sure what your exact application is though, but that should suffice.

Body:
The standard algorithm is 2D-DDA and 3D-DDA. This returns every intersected cell in a 2D or 3D grid. Bresenham's algorithm is more for line rendering.

Rough pseudo-code for a ray (for a line just stop at the end by setting minBoundary and maxBoundary to be the bounding box of the line. This will stop it from both leaving the grid and going past the end):

var rayPosition = { x: 25, y: 25 };
var rayDirection = { x: 1, y: 1 };

var cellSize = 50;

var cell = { x: Math.floor(rayPosition.x / cellSize), y: Math.floor(rayPosition.y / cellSize) };

var step = { x: Math.sign(rayDirection.x), y: Math.sign(rayDirection.y) }; // sign returns -1, 0, or 1

var offsetFromAxis =
{
    x: step.x > 0 ? cellSize - (rayPosition.x - Math.floor(rayPosition.x / cellSize) * cellSize) : (rayPosition.x - Math.floor(rayPosition.x / cellSize) * cellSize),
    y: step.y > 0 ? cellSize - (rayPosition.y - Math.floor(rayPosition.y / cellSize) * cellSize) : (rayPosition.y - Math.floor(rayPosition.y / cellSize) * cellSize)
};
var tMax = { x: offsetFromAxis.x / Math.abs(rayDirection.x), y: offsetFromAxis.y / Math.abs(rayDirection.y) };
var tDelta = { x: cellSize / Math.abs(rayDirection.x), y: cellSize / Math.abs(rayDirection.y) };
var minBoundary = { x: -1, y: -1 }; // for a line just do something like (might be off by one):
/* var minBoundary =
{
    x: Math.max(0, Math.min(Math.floor(lineStart.x / cellSize), Math.floor(lineEnd.x / cellSize)) - 1,
    y: Math.max(0, Math.min(Math.floor(lineStart.y / cellSize), Math.floor(lineEnd.y / cellSize)) - 1
}
*/
var maxBoundary = { x: width + 1, y: height + 1 }; // for a line just do something like (might be off by one):
/* var maxBoundary =
{
    x: Math.min(width, Math.max(Math.floor(lineStart.x / cellSize), Math.floor(lineEnd.x / cellSize)) + 1,
    y: Math.min(height, Math.max(Math.floor(lineStart.y / cellSize), Math.floor(lineEnd.y / cellSize)) + 1
}
*/
var boundary = { x: step.x > 0 ? maxBoundary.x : minBoundary.x, y: step.y > 0 ? maxBoundary.y : minBoundary.y };
var cells = [];
do
{
    cells.push({ x: cell.x, y: cell.y });
    if (tMax.x < tMax.y)
    {
        cell.x += step.x;
        if (cell.x == boundary.x)
        {
            break;
        }
        tMax.x += tDelta.x;
    }
    else
    {
        cell.y += step.y;
        if (cell.y == boundary.y)
        {
            break;
        }
        tMax.y += tDelta.y;
    }
} while (true);

The 3D-DDA is nearly identical adding a z-axis. (You can find examples though online). The only big change is the if statement:

if (tMax.x < tMax.y)
{
    if (tMax.x < tMax.z)
    {
        // x
    }
    else
    {
        // z
    }
}
else
{
    if (tMax.y < tMax.z)
    {
        // y
    }
    else
    {
        // z
    }
}

Regarding data structures you can just use a 1D array and index it with something like:

index = z * xDimension * yDimension + y * xDimension + x;

Not sure what your exact application is though, but that should suffice.


问:
Using a private auto-implemented property vs. a private field
If I have a need for simple, private fields, is there any reason I shouldn't just make it a convention to use private, auto-implemented properties instead?

For instance, I could do this:

```<code>private MyClass _foo;
</code>```

or I could do this:

```<code>private MyClass Foo { get; set; }
</code>```

It seems like the only time I need actual fields is when I'm doing something like lazy loading:

```<code>private MyClass Foo
{
    get
    {
        if (_foo == null) _foo = new MyClass();
        return _foo;
    }
}
</code>```

答:
The two features of fields that I feel you might run into more commonly that you would lose by converting them to properties are the following:

You can't modify members of a property value if it's a value type.

```<code>// Rectangle is a value type:
struct Rectangle { int X, Y, Width, Height; }

Rectangle rect;
Rectangle RectProperty { get; set; }

void Test()
{
    // This works with a field:
    rect.X = 45;

    // but fails with a property:
    RectProperty.X = 45; // compiler error

    // The only way to update a value-type property
    // is to construct & assign a completely new value:
    RectProperty = new Rectangle(45, RectProperty.Y, RectProperty.Width, RectProperty.Height);
}
</code>```

You can't pass a property as an out or ref parameter

```<code>int field;
int SomeProperty { get; set; }

void Test()
{
    // Works with a field:
    int.TryParse("some text", out field);

    // but fails with a property:
    int.TryParse("some text", out SomeProperty); // compiler error.

    // you need to create temporary storage instead:
    int x;
    if (int.TryParse("some text", out x)) { SomeProperty = x; }
}
</code>```

If neither of these is an issue for you, then you probably won't notice the difference. There are of course other differences if you're reflecting over your type, or using libraries that reflect over your type and expect things to be properties or fields, etc.

Body:
The two features of fields that I feel you might run into more commonly that you would lose by converting them to properties are the following:

You can't modify members of a property value if it's a value type.

// Rectangle is a value type:
struct Rectangle { int X, Y, Width, Height; }

Rectangle rect;
Rectangle RectProperty { get; set; }

void Test()
{
    // This works with a field:
    rect.X = 45;

    // but fails with a property:
    RectProperty.X = 45; // compiler error

    // The only way to update a value-type property
    // is to construct & assign a completely new value:
    RectProperty = new Rectangle(45, RectProperty.Y, RectProperty.Width, RectProperty.Height);
}

You can't pass a property as an out or ref parameter

int field;
int SomeProperty { get; set; }

void Test()
{
    // Works with a field:
    int.TryParse("some text", out field);

    // but fails with a property:
    int.TryParse("some text", out SomeProperty); // compiler error.

    // you need to create temporary storage instead:
    int x;
    if (int.TryParse("some text", out x)) { SomeProperty = x; }
}

If neither of these is an issue for you, then you probably won't notice the difference. There are of course other differences if you're reflecting over your type, or using libraries that reflect over your type and expect things to be properties or fields, etc.


问:
How do you calculate affinity in Edge Rank/Activity Streams
I have been researching how to build a newsfeed that sorts the order by relevancy.

I have been following along Facebook's Edge Rank and Etsy's Activity Feed Architecture and I can't figure out how these companies calculate Affinity.

The database stores a percentage value for example 0.75

Given I have a set of activity items created.

User X commented on User Y
User X liked User Y

How would you get an affinity percentage out of this?

答:
As I understand your question, you are specifically asking why / how do we need to calculate percentage and not absolute affinity scores?

The EdgeRank algorithm for choosing the priority of Social Stories is the same problem (theoretically) as choosing a page for a Search Result in PageRank which is the same as choosing an Ad out of many for a particular search query.

Take the case of PageRank. According to Wikipedia:

  Mathematical PageRanks for a simple network, expressed as percentages. (Google uses a logarithmic scale.) Page C has a higher PageRank than Page E ...

Also see this -> http://www2007.org/posters/poster893.pdf

Similarly, I suspect the real reason for using percentages is to normalize the EdgeRank so that all news Feed stories are brought to the same scale.

Taking your example lets say there are 2 pages P1 and P2 our User called A has liked. Now there are Updates from both. If Facebook's affinity formula for pages is (hypothetically) this ->

```<code>popularity of page * frequency of user interaction
</code>```

Or

```<code>number of page likes / time since last interaction from user A.
</code>```

Say for Page P1 this is 100000 / 20 = 50000 and for Page P2 it is 2000 / 10 = 200.

So Page P1's news story wins because it is a more popular page and its story will be shown before P2.

But this also has to compete with stories from users where the formula can be totally different say

```<code>Number of Mutual Friends * Number of Posts shared on their Wall
</code>```

For a post from another user B this can be 1000 * 10 = 10000 but when this value competes with P1 it loses in absolute number. But having 1000 mutual friends is a really big thing! Technically B's story should appear before P1's.

A solution to this would be to normalize all affinity scores between 0 to 1 so that the competition is fair and relative.

Now the 2nd part of the EdgeRank formula has Edge Weight which is simlar to the above concept. But Edge Weight specifically focusses on the type of interaction, like , comment, share etc.

All these "Competition Algorithms" EdgeRank, PageRank etc. are called Recommendation Systems. These algorithms must normalize scores to scale in order to show relevant order of results!

I'll keep adding to the question if I find something more!

Body:
As I understand your question, you are specifically asking why / how do we need to calculate percentage and not absolute affinity scores?

The EdgeRank algorithm for choosing the priority of Social Stories is the same problem (theoretically) as choosing a page for a Search Result in PageRank which is the same as choosing an Ad out of many for a particular search query.

Take the case of PageRank. According to Wikipedia:

  Mathematical PageRanks for a simple network, expressed as percentages. (Google uses a logarithmic scale.) Page C has a higher PageRank than Page E ...

Also see this -> http://www2007.org/posters/poster893.pdf

Similarly, I suspect the real reason for using percentages is to normalize the EdgeRank so that all news Feed stories are brought to the same scale.

Taking your example lets say there are 2 pages P1 and P2 our User called A has liked. Now there are Updates from both. If Facebook's affinity formula for pages is (hypothetically) this ->

popularity of page * frequency of user interaction

Or

number of page likes / time since last interaction from user A.

Say for Page P1 this is 100000 / 20 = 50000 and for Page P2 it is 2000 / 10 = 200.

So Page P1's news story wins because it is a more popular page and its story will be shown before P2.

But this also has to compete with stories from users where the formula can be totally different say

Number of Mutual Friends * Number of Posts shared on their Wall

For a post from another user B this can be 1000 * 10 = 10000 but when this value competes with P1 it loses in absolute number. But having 1000 mutual friends is a really big thing! Technically B's story should appear before P1's.

A solution to this would be to normalize all affinity scores between 0 to 1 so that the competition is fair and relative.

Now the 2nd part of the EdgeRank formula has Edge Weight which is simlar to the above concept. But Edge Weight specifically focusses on the type of interaction, like , comment, share etc.

All these "Competition Algorithms" EdgeRank, PageRank etc. are called Recommendation Systems. These algorithms must normalize scores to scale in order to show relevant order of results!

I'll keep adding to the question if I find something more!


问:
Unit Testing a Function which produces "limit less" results
I am pretty new-ish to unit testing in a more nuanced sense. If have an application function which based on users given input could produce an seeming "limit-less"combination of output, whats the proper way to unit test this and how far might testing go?

I am thinking of something like building an XML file which given input you can create an unlimited combination of files. Producing the individual functions for things like root nodes, child nodes, etc, and testing them is pretty straight forward to me, but if you wanted to take all those functions and build the file, how might one test those combinations?

答:
There are two types of testing: black box testing and white box testing.

When you do black box testing, you don't know the internals of the code you test: the only thing you know is the interface and what the code is expected to do.

In white box testing, you can see how the code actually performs the task you are about to test.

Unit testing is white box testing. This means that you are doing unit testing based not on the eventually unlimited number of inputs and outputs, but on the branches, that is the possible ways to execute code.

Let's take the following code as an example:

string sayHello(string name) {
    if (name == null) {
        return "Hello!";
    }

    return "Hello, {0}!".format(name);
}
```

It does take a parameter which accepts a nearly unlimited number of values and leads to a nearly unlimited number of results, and it would be probably quite problematic to test every combination. Instead, you can explore the code and test it based on the logic of the code itself:

Is the result of sayHello("Jeff") actually "Hello, Jeff!"?

What about sayHello(null)? Is it "Hello!"?

Once you tested those cases, you are quite sure, by looking at the code, that it will work as well if we pass to it "Mary" or "Stephen". Thus, no need to test all the names you can imagine.

Another things you should take in account are:

The requirements. For instance, you may wonder what would be the output of the method for an empty string. Does it make sense to display "Hello, !" to the user?

The language, framework and system constraints. What if my name is actually 2^31 - 1 characters long? What would happen when the method will call format, attempting to produce a string which is 2^31 + 7 characters long?

Body:
There are two types of testing: black box testing and white box testing.

When you do black box testing, you don't know the internals of the code you test: the only thing you know is the interface and what the code is expected to do.

In white box testing, you can see how the code actually performs the task you are about to test.

Unit testing is white box testing. This means that you are doing unit testing based not on the eventually unlimited number of inputs and outputs, but on the branches, that is the possible ways to execute code.

Let's take the following code as an example:

string sayHello(string name) {
    if (name == null) {
        return "Hello!";
    }

    return "Hello, {0}!".format(name);
}

It does take a parameter which accepts a nearly unlimited number of values and leads to a nearly unlimited number of results, and it would be probably quite problematic to test every combination. Instead, you can explore the code and test it based on the logic of the code itself:

Is the result of sayHello("Jeff") actually "Hello, Jeff!"?

What about sayHello(null)? Is it "Hello!"?

Once you tested those cases, you are quite sure, by looking at the code, that it will work as well if we pass to it "Mary" or "Stephen". Thus, no need to test all the names you can imagine.

Another things you should take in account are:

The requirements. For instance, you may wonder what would be the output of the method for an empty string. Does it make sense to display "Hello, !" to the user?

The language, framework and system constraints. What if my name is actually 2^31 - 1 characters long? What would happen when the method will call format, attempting to produce a string which is 2^31 + 7 characters long?


答:
The goal of unit testing is not to test all possibilities of input versus output.

The goal of unit testing is to test each and every business rule, and within the scope of each business rule, all the potentially problematic cases. (Also known as "edge cases".)

So, basically, if your user gives a specific, known-in-advance piece of input, (which has been hard-coded into the test,) does your code yield a specific, known-in-advance piece of output (also hard-coded into the test) ?

And, if your user gives an empty string, does your code behave?

And, if your requirements say that your user must be able to type up to 10,000 characters, does your code in fact handle 10,000 characters?  And does it fail gracefully (with a proper exception, which would later be translated to an error message to the user) if the user supplies 10,001 characters?

Also, code coverage is a measurement of how good your unit testing is, not in the sense that if you have 100% code coverage then you are good to go, but in the sense that if you have significantly less than 100% code coverage then it is possible that you have missed something.  So, use a code coverage tool to see what parts of your code are not covered by your tests, and if any of them is crucial, then construct a test case in such a way that this piece of code will be covered.

Title: Unit Testing a Function which produces "limit less" results

Body:
I am pretty new-ish to unit testing in a more nuanced sense. If have an application function which based on users given input could produce an seeming "limit-less"combination of output, whats the proper way to unit test this and how far might testing go?

I am thinking of something like building an XML file which given input you can create an unlimited combination of files. Producing the individual functions for things like root nodes, child nodes, etc, and testing them is pretty straight forward to me, but if you wanted to take all those functions and build the file, how might one test those combinations?


问:
Passing Anonymous Type to a Bound Control
Generally speaking, I'm fairly opposed to the use of anonymous types in real-world code (except in LINQ and some other specific scenarios), but I'm looking right now at a situation where I need to bind an ASP GridView control with a collection of tuple values and they're looking pretty tempting.

Basically, I need to show a list of proprietary accounts that are associated with different computer names. I don't currently have a type that contains those two properties because I don't use them together like this anywhere else.

What I would normally do in a situation like this is just create a new class that has the properties, set the ItemType on the GridView to reference that type, then build objects of that type in my Select method (I use ObjectDataSource much of the time). But I'm thinking now that there's really no benefit to throwing in that extra class, since no matter what it's getting bound via reflection.

Is there any reason to shy away from using anonymous types in data-binding situations like this?

I'd accept anything: performance, readability, maintainability, principle, or whatever else you can throw at me. But the only disadvantage I can think of is if I wanted to use the Item property to use Intellisense for my data-binding, but in this particular case I have no use for anything more than BoundFields. Of course, this is all based on the assumption that it even works, admittedly I haven't tried it yet with anonymous types, so it might just not be supported for one reason or another.

答:
No

And your assumption about it not being statically typed is wrong too.

From the documentation:

Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object. The compiler provides a name for each anonymous type, although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type.

OwnerDisplayName: Matthew Haugen


答:
The general term for this type of testing is combinatorial testing.

One commonly used technique for combinatorial testing is all-pairs or pairwise testing, which cuts down on the combinatorial explosion of test cases by trying to find a smaller 'interesting' set of cases. With the example of generating XML files with a typical schema, a naive 'try every option in combination' approach would leads to literally millions or billions of cases. Pairwise testing can probably identify a few tens of XML files that exercise each combination of schema features.

Another is purely random or generative testing, which avoids the effort required to boil the test cases down to a minimum set by simply generating a few thousand at random and relying on the law of large numbers.

Testing of this kind might well be considered not to be unit testing. In fact, it is commonly done at a higher level, perhaps by an external test team. However, if it is done by the author of the code and at a detailed technical level, then in practice there is not much distinction.

Some (Java-based) tools for this low-level approach to combinatorial testing are jcunit, junit-quickcheck, and junit-theory-suite. Most other languages have similar tools available.


问:
What are potential problems when write business logic code in GUI as MVVM pattern
Currently, I'm implementing MVVM pattern for a WPF application but not 100% no code behind, sometimes I put some business logic code into GUI and so what are potential problems for this? Thanks</p>

答:
The whole point of MVVM is to abstract as much logic as possible away from the View, the surface that the user sees.  If you're using CodeBehind to implement business logic, you're probably not practicing MVVM.

This has several benefits:

It makes the code more testable.  UI is difficult to test, especially UI that has CodeBehind.

If the business logic is somewhere else besides the UI, you can swap out the UI for another UI (such as a mobile device or web page), and the business logic will still work.

Of course, if this is a very small application and you never intend to talk to a database on a server (a rarity these days), you may not need all this ceremony; CodeBehind might be perfectly adequate.


问:
Performance: recursion vs. iteration in Javascript
I have read recently some articles (e.g. http://dailyjs.com/2012/09/14/functional-programming/) about the functional aspects of Javascript and the relationship between Scheme and Javascript (the latter was influenced by the first, which is a functional language, while the O-O aspects are inherited from Self which is a prototyping-based language).

However my question is more specific: I was wondering if there are metrics about the performance of recursion vs. iteration in Javascript.

I know that in some languages (where by design iteration performs better) the difference is minimal because the interpreter / compiler converts recursion into iteration, however I guess that probably this is not the case of Javascript since it is, at least partially, a functional language.

答:
Without strict mode, Iteration performance is usually slightly faster then recursion (in addition to making the JIT do more work). Tail recursion optimization essentially eliminates any noticeable difference because it turns the whole call sequence to a jump.

Example: Jsperf

I would suggest worrying much more about code clarity and simplicity when it comes to choosing between recursion and iteration.


问:
How does the communication between a chat server and client work?
(Socket programming newbie here...)

So, for learning purposes I've just started developing a chat server and client in Python, and I was wondering how it is usually implemented.

When someone connects to the server, does the socket stay alive until the whole client is closed (All messages are sent through it), or is a new socket created for each new message?

If the second case is true, then what I've imagined by "connection" was always wrong (Since by each message a new connection is made). How does it work?

答:
I don't know how they usually work, but when I implemented one, I chose your first approach and it worked ok. That's also how IRC works, so it can clearly scale to a reasonable number of users.

If you're opening a new socket for each message, there would be a problem in terms of how the server sends messages to the clients, who may be behind firewalls and unable to accept incoming confections. Polling is possible, and I know some early web chat clients did this, but I believe this approach is now very rare.

A third option is using UDP, where the cost of maintaining an open socket is lower (because there's no connection whose state must be maintained). I don't know if any popular chat systems do this, however.


答:
An image from IBM, where you can also find useful information:

Below is a simple explanation of how sockets work (thus a lot more is happening during but I only figure out the basic parts)

A server defines a socket and binds an IP address and port to it. If binding is successful, then it starts to listen to that socket for incoming connections. A client sends a connection request to related IP and port and the socket server listening to that port accepts it. After the server accepts a client request, a connection is established.

You can send and receive data through that connection (step 5, 6) while the connection is active. If the client connection is closed, the Server should accept it again (step 4). accept step is done once for each new connection and that connection do not needed to be accepted again while it was active.

A server should have a specific IP and port so the client can connect it. A server could not connect to a client since client does not have any socket bound to a specific IP and port for listening incoming connections.

```<code>------------        ----------       ------------
| Client 1 | -----> | Server | <---  | Client 2 |
------------        ----------       ------------
</code>```

Client 1 sends a message, the message should be received by the server since only servers can accept connections (thus, a client can not establish a connection to another client since another client can not accept any incoming connection). Server receives the message and sent it to client 2
Since a server could not establish a connection to a client, Client 2 should be already connected. Otherwise the server should wait for the client 2 to establish a connection so it can send data.

From that point of view, all clients should be connected to the server and keep those connections alive. A Client may have an active connection while it was communicating, and close that connection a while after it was idle for a specific time. But the client should establish connections to server and checks if it has any data waiting to be transferred to himself. So keeping the connection alive looks like a better approach.

There are protocols like TCP and UDP and you define the socket as a TCP socket or a UDP socket. But these protocols have many details and for simplicity, I can mention that TCP protocol is error-checked and controls if sent data is received by the receiver application (Instant messaging services told you whether your message sent is successful or not, so this is TCP). UDP have no error-check mechanism (So you just send the package but do not be confirmed whether it is delivered or not).

Title: How does the communication between a chat server and client work?

Body:
(Socket programming newbie here...)

So, for learning purposes I've just started developing a chat server and client in Python, and I was wondering how it is usually implemented.

When someone connects to the server, does the socket stay alive until the whole client is closed (All messages are sent through it), or is a new socket created for each new message?

If the second case is true, then what I've imagined by "connection" was always wrong (Since by each message a new connection is made). How does it work?

Body:
An image from IBM, where you can also find useful information:

Below is a simple explanation of how sockets work (thus a lot more is happening during but I only figure out the basic parts)

A server defines a socket and binds an IP address and port to it. If binding is successful, then it starts to listen to that socket for incoming connections. A client sends a connection request to related IP and port and the socket server listening to that port accepts it. After the server accepts a client request, a connection is established.

You can send and receive data through that connection (step 5, 6) while the connection is active. If the client connection is closed, the Server should accept it again (step 4). accept step is done once for each new connection and that connection do not needed to be accepted again while it was active.

A server should have a specific IP and port so the client can connect it. A server could not connect to a client since client does not have any socket bound to a specific IP and port for listening incoming connections.

------------        ----------       ------------
| Client 1 | -----> | Server | <---  | Client 2 |
------------        ----------       ------------

Client 1 sends a message, the message should be received by the server since only servers can accept connections (thus, a client can not establish a connection to another client since another client can not accept any incoming connection). Server receives the message and sent it to client 2
Since a server could not establish a connection to a client, Client 2 should be already connected. Otherwise the server should wait for the client 2 to establish a connection so it can send data.

From that point of view, all clients should be connected to the server and keep those connections alive. A Client may have an active connection while it was communicating, and close that connection a while after it was idle for a specific time. But the client should establish connections to server and checks if it has any data waiting to be transferred to himself. So keeping the connection alive looks like a better approach.

There are protocols like TCP and UDP and you define the socket as a TCP socket or a UDP socket. But these protocols have many details and for simplicity, I can mention that TCP protocol is error-checked and controls if sent data is received by the receiver application (Instant messaging services told you whether your message sent is successful or not, so this is TCP). UDP have no error-check mechanism (So you just send the package but do not be confirmed whether it is delivered or not).


问:
UML modeling angular controllers / factories and services
I have to create UML documentation for my upcoming project. Now I have previously worked with Java which as an object orientated language is relativly easy to design UML class diagrams for. For my next project I will have to design an AngularJs Application.

As some of you might know an Angular application consists of many things including Controllers Factories Services and many more.

My question is when designing these using UML should Controllers / Factories / Services be seen as classes in a class diagram even though they are never defined as classes nor have any constructor but merely consists of variables and functions?

答:
UML models are intended to be useful, so the answer will depend largely on the question 'what would be the most useful description of my system to the person reading this'. You might want to consider object interaction diagrams, component diagrams and sequence diagrams instead of class diagrams.

Depending what you are trying to communicate, you could define a controller stereotype and declare classes for the fields you are binding.

Ultimately though, talk to the person who will be using the documentation and find out what they would find useful.


问:
Can JIT compilation be non-deterministic?
I have been profiling a lot of javascript today in writing a firefox js engine bug report, and started really noticing the slight differences between JIT compilations.

While there are some obvious things that could cause non-deterministic flagging of "hot" sections of code (for example, inlining or not inlining a function that is called a random number of times), I was wondering if external fluctuations of execution speed (like CPU throttling) could cause non-deterministic JIT compilation?

答:
There are many ways in which JIT compilation can be non-deterministic. For example:

if the JIT runs on a separate thread, depending on OS scheduling, during one run, the JIT may be scheduled first, and compile a certain function before it runs, whereas on a different run, the interpreter may be scheduled first, and run the function before it is compiled

if the JIT uses dynamic profiling information for optimization, and the profiler is a sampling profiler, then even tiniest fluctuations in timing, memory layout, etc. may cause the sampling to occur at different points of the execution, possibly leading to different results

the more aggressive the optimizations, the more CPU time and memory the JIT compiler needs. If the system is low on memory, for example, a JIT compiler may decide to disable some optimizations, or only enable them for a few very high value targets (i.e. very hot spots)


问:
How to store (and find) updated values in a Distributed Hash Table?
Distributed Hash Tables are a great way to store immutable data in a resilient way.

However, I am wondering about how it would be possible to store new versions of old data in this system.

Because it is impossible in a distributed network to unconditionally trust the other party, a way is needed to ensure that another party does not manipulate stored data. The easiest way to do this is to store data values under keys that are generated from these values using a one-way hash function. This means that when someone wants to change data, they invalidate the key->value relation of that data, which is easy to check against.

Say, someone stores a document in the DHT, but later made some changes and wants to store that new version. How can other people connected to the DHT find out that there is a new version of this document?
The only information that I found about this said that an idea would be to store versioned data like this:

```<code>v1: hash(random_number) -> document1
v2: hash(key(v1)) -> document2
v3: hash(key(v2)) -> document3
...etc.
</code>```

Then, to check if there is a new version, all a client would need to do is to apply the hashing algorithm one more time to the hash of the current value.

Drawback: This approach does not have the relation between key and value, meaning that a value might be changed (by a malicious server or a man-in-the-middle) without invalidating the key.

How can these two approaches be combined? Or is there a different, better way to manage this?

答:
You want

A client connected to any number of (malicious) servers.

An authorized person to create new values, connected to (malicious) servers.

Your assumptions are (correct me if I a wrong):

The values are so big that they need identifiers (hashes).

The client and the person can not communicate directly.

Without any further assumptions the client can not be sure of any value of the person.
Possible new assumptions are:

The person signs the values

New values can be created by anyone

The person is not malicious

The person can reach the client

The person and the client have synchronous clocks

The client can identify the person's messages

A message from the person to the client can reach the client within some known time

The client does not need to reach the person

The client can not reach the person

Values have relation to the time of the client

A new value makes previous values invalid

A client must know all values of a person

The client can know that a value is invalid without having a new value

Values are only valid over a time span

Please tell me which assumptions you exclude.
Please tell me which assumptions you make.
Please tell me which assumptions you do not care about.
There might be even more.


问:
REST API and user rights
I am developing an application using Angular and REST API and I'm facing a problem concerning user access right.

The application runs this way:

A user signup

The same user creates his organization

He invites people to join the organization

Every users of the organization are able to manage many different things, like tasks, agenda, etc...

This flow can appear many, many, many times.

Question 1

Concerning the global rights, I m mean there, the fact that a user of an organization A cant access the task of an organization B etc...

Does it exist a pattern to avoid me, in each of my API methods, to check the organization ID, meaning that sometime, I have to work through multiple other objects and tables or collections, implying many databases requests (and more with reflexive classes)?

Question 2

Concerning the roles, should I test the role each time a user sends a request (meaning, that I have to request the role table and check if he can access this API endpoint)? Or does it exist another pattern there too?

答:
No, basically you can't avoid this. Only way could be to have a independent database for each organization, otherwise every single request you make would have to include organization id to make sure users get only data they are allowed to see or modify.

This even if a request directly includes a specific resource id. Say you have a resource order. Now you have a user logged in who has full permission to see and modify orders of his organization. In the first step he retrieves a order form with id 123. He modifies the order and posts the result. You have a RESTful URL like /order/123 for the POST request.

Now in your controller you could be tempted to load this order. Say your framework puts the ID from the url in a variable orders_id. You simply load the order with SQL like this (very simplified):

```<code>SELECT * FROM orders where id = 123;
</code>```

But what, if the user changes the ID and sends it to URL /order/456? Without checking user and organization this POST request would simply pass. So at a minimum you would have to first load the user and then get the organization and the (still simplified) SQL would have to do something like this:

```<code>SELECT * FROM orders where id = 123 AND organization_id = 456;
</code>```

So even if a single resource could be identified by its ID, you can't rely on this. The same for everything else you ask.

Similar for roles, while it would be possible to include the role as an attribute to the URL or payload this would not be safe.

Even if you have different databases you would have to load the user data and ensure that the right database is used. Otherwise you get similar problems.

Also the users id should of course be stored encrypted in the session data so a user can't change it like other data and act as a different user.

Title: REST API and user rights

Body:
No, basically you can't avoid this. Only way could be to have a independent database for each organization, otherwise every single request you make would have to include organization id to make sure users get only data they are allowed to see or modify.

This even if a request directly includes a specific resource id. Say you have a resource order. Now you have a user logged in who has full permission to see and modify orders of his organization. In the first step he retrieves a order form with id 123. He modifies the order and posts the result. You have a RESTful URL like /order/123 for the POST request.

Now in your controller you could be tempted to load this order. Say your framework puts the ID from the url in a variable orders_id. You simply load the order with SQL like this (very simplified):

SELECT * FROM orders where id = 123;

But what, if the user changes the ID and sends it to URL /order/456? Without checking user and organization this POST request would simply pass. So at a minimum you would have to first load the user and then get the organization and the (still simplified) SQL would have to do something like this:

SELECT * FROM orders where id = 123 AND organization_id = 456;

So even if a single resource could be identified by its ID, you can't rely on this. The same for everything else you ask.

Similar for roles, while it would be possible to include the role as an attribute to the URL or payload this would not be safe.

Even if you have different databases you would have to load the user data and ensure that the right database is used. Otherwise you get similar problems.

Also the users id should of course be stored encrypted in the session data so a user can't change it like other data and act as a different user.


问:
PHPDoc Comment, Class vs File
I am trying to standardise my code as much as possible, including DocComments, using PHPCS.

It seems that the PEAR standards contain two sniffs that require almost exactly the same tags appear in the Class and File DocBlocks:

```<code>PEAR.Commenting.ClassComment
PEAR.Commenting.FileComment
</code>```

Both of these want to see these tags: @category, @package, @author, @license, @link.

```<code>----------------------------------------------------------------------
FOUND 10 ERRORS AFFECTING 2 LINES
----------------------------------------------------------------------
  6 | ERROR | Missing @category tag in file comment
  6 | ERROR | Missing @package tag in file comment
  6 | ERROR | Missing @author tag in file comment
  6 | ERROR | Missing @license tag in file comment
  6 | ERROR | Missing @link tag in file comment
 13 | ERROR | Missing @category tag in class comment
 13 | ERROR | Missing @package tag in class comment
 13 | ERROR | Missing @author tag in class comment
 13 | ERROR | Missing @license tag in class comment
 13 | ERROR | Missing @link tag in class comment
----------------------------------------------------------------------
</code>```

It would be silly to repeat these because all my source files contain just a single class (or interface or trait).

My question is, which tags should go where. Should they all go in the file comment, all in the class comment, or should they be split between the two.

答:
Based on what I can find, this is my own opinion which I pose as an answer. I would really like feedback on this. This answer is based on a proposed (not-accepted) standard.

Breakdown:

Looking through the proposed PSR-5 standard, particularly the description of each tag helped a bit.

@category

Deprecated in favour of @package which does essentially the same thing, so can be removed from the sniff.

@package

Can be used in either, however in the file block it applies to: global functions, global constants, global variables, requires and includes. In the class it applies to the class and all containing elements. Assuming that your file only contains a class, the @package tag would be meaningless in the file block.

@author

This can apply to any structural element. The documentation doesn't specifically help answer the question of which, however since the file contains the class, I would say this should appear in the most encompassing element (the file comment), with other authors adding an @author tag to any sub elements they write.

@license

Again, this can be applied to any structural element, but is applied to all sub elements, therefore the file seems most appropriate.

@link

Link is also deprecated in favour of @see

So:

@see

@see is looser than @link, and could happily be applied to both the file and the class. For example the file could reference the project website, the file could reference the documentation for the class.

Summary:

So this is what I think the file should roughly look like

```<code><?php
/**
 * FileName.php
 * @author    My Name <email@example.com>
 * @copyright 2015 My Company
 * @license   Licence Name
 * @see       Link to project website
 */

namespace My/Namespace;

use Another/Namespace/Class;

/**
 * Class summary
 * A longer class description
 * @package Vendor/Project
 * @see     Link to class documentation
 */
class MyClass {
    ...
}
</code>```

Title: PHPDoc Comment, Class vs File

Body:
Based on what I can find, this is my own opinion which I pose as an answer. I would really like feedback on this. This answer is based on a proposed (not-accepted) standard.

Breakdown:

Looking through the proposed PSR-5 standard, particularly the description of each tag helped a bit.

@category

Deprecated in favour of @package which does essentially the same thing, so can be removed from the sniff.

@package

Can be used in either, however in the file block it applies to: global functions, global constants, global variables, requires and includes. In the class it applies to the class and all containing elements. Assuming that your file only contains a class, the @package tag would be meaningless in the file block.

@author

This can apply to any structural element. The documentation doesn't specifically help answer the question of which, however since the file contains the class, I would say this should appear in the most encompassing element (the file comment), with other authors adding an @author tag to any sub elements they write.

@license

Again, this can be applied to any structural element, but is applied to all sub elements, therefore the file seems most appropriate.

@link

Link is also deprecated in favour of @see

So:

@see

@see is looser than @link, and could happily be applied to both the file and the class. For example the file could reference the project website, the file could reference the documentation for the class.

Summary:

So this is what I think the file should roughly look like

<?php
/**
 * FileName.php
 * @author    My Name <email@example.com>
 * @copyright 2015 My Company
 * @license   Licence Name
 * @see       Link to project website
 */

namespace My/Namespace;

use Another/Namespace/Class;

/**
 * Class summary
 * A longer class description
 * @package Vendor/Project
 * @see     Link to class documentation
 */
class MyClass {
    ...
}


问:
Algorithm to determine best combination of keeping students together in their camp rooms
I have a problem I'd like to solve and am not sure whether there is a known algorithm or how the best way to approach it would be.

Say for example there is a class of 30 students who are going on a school camp. They will each share a room with other students. Each student can provide a list of 3 friends that they ideally want to share a room with.

I'd like to know if there is a programmatic way to determine the best outcome for keeping students together with who they requested to go with?

There is also another complication here, being that there are x amount of rooms, each room allowing a varying amount of students per room (up to 7).

答:
This solution isn't very fast and I am not sure that it will always finds the best solution, but I think it should be a viable strategy to find a good enough solution.

What you need first is a function to calculate the score of a room. The score is simply the sum of the number of fulfilled wishes of all its current inhabitants.

First distribute all students randomly on all beds in the camp (beds can be empty). Then look for beds in two different rooms where swapping the occupants (or moving the one occupant when one bed is empty) would improve the sum of the scores of both rooms:

```<code>for each bed as bed1
    for each bed as bed2 which comes after bed1
        if swapping the occupants of bed1 and bed2 improves the total score
           swap occupants of bed1 and bed2
</code>```

Repeat this until no swaps are found.

Possible flaw: This method will not find an improvement which requires to move more than two people to reach a positive change in score. I am not sure if such situations are possible, though.

Body:
This solution isn't very fast and I am not sure that it will always finds the best solution, but I think it should be a viable strategy to find a good enough solution.

What you need first is a function to calculate the score of a room. The score is simply the sum of the number of fulfilled wishes of all its current inhabitants.

First distribute all students randomly on all beds in the camp (beds can be empty). Then look for beds in two different rooms where swapping the occupants (or moving the one occupant when one bed is empty) would improve the sum of the scores of both rooms:

for each bed as bed1
    for each bed as bed2 which comes after bed1
        if swapping the occupants of bed1 and bed2 improves the total score
           swap occupants of bed1 and bed2

Repeat this until no swaps are found.

Possible flaw: This method will not find an improvement which requires to move more than two people to reach a positive change in score. I am not sure if such situations are possible, though.


问:
What is the use-case to use C++ friend class?
I am trying to understand C++ friend. When is the good use case to use friend? I suppose if we want to let another class have access to another classes attributes, why don't we just make it as public or inherit from that class instead?

Thank you for your help.

答: Lets say there is an external function which requires you to perform operations on private or protected members of two different classes  within your program. now, in order for that function to gain access and actualy use these class members you have to make it a friend of both classes. Keeping in mind that by making it a friend of both these classes does'nt make it a member of the classes it just gains the prevelage to refer to the private or protected members of these classes. I can say that you would need to use a friend function when you want to operate on objects of two different classes. Though  the overuse of friend function and class can reduce the value of encapsulation.</p>


答:
When dealing with public properties, the common reason given for doing

```<code>public MyClass Foo { get; set; }
</code>```

rather than

```<code>public MyClass _foo;
</code>```

is that the latter respects the open/closed principle better: if you later need to add guards/lazy loading etc to _foo, the latter requires a change to the API.

With private fields/properties though, this doesn't apply. The internal workings of your class are completely open to rewriting at all times. So if you do

```<code>private MyClass Foo { get; set; }
</code>```

rather than

```<code>private MyClass _foo;
</code>```

then, as  Mati Cicero says in his comment, you simply end up polluting your resultant IL with pointless getter and setter methods.

Taking your lazy loading example, you can create a very succinct helper property to lazy setup _foo using C# 6:

```<code>private MyClass _foo;
private MyClass Foo => _foo ?? (_foo = new MyClass());
</code>```

The compactness of the syntax, and thus the lack of noise, arguable makes the benefits of lazy-loading via a property better than using a helper method. As demonstrated by the length of your own example, using a helper method was arguably was a better solution prior to v6.

The other possible use with C# 6 is in replacing:

```<code>private readonly MyClass _bar = new MyClass();
</code>```

with

```<code>private MyClass Bar { get; } = new MyClass();
</code>```

Whether the latter is more readable is highly questionable though; arguably it both creates a pointless getter and makes the intention of the code less clear.

Title: Using a private auto-implemented property vs. a private field

Body:
If I have a need for simple, private fields, is there any reason I shouldn't just make it a convention to use private, auto-implemented properties instead?

For instance, I could do this:

```<code>private MyClass _foo;
</code>```

or I could do this:

```<code>private MyClass Foo { get; set; }
</code>```

It seems like the only time I need actual fields is when I'm doing something like lazy loading:

```<code>private MyClass Foo
{
    get
    {
        if (_foo == null) _foo = new MyClass();
        return _foo;
    }
}
</code>```

Body:
When dealing with public properties, the common reason given for doing

public MyClass Foo { get; set; }

rather than

public MyClass _foo;

is that the latter respects the open/closed principle better: if you later need to add guards/lazy loading etc to _foo, the latter requires a change to the API.

With private fields/properties though, this doesn't apply. The internal workings of your class are completely open to rewriting at all times. So if you do

private MyClass Foo { get; set; }

rather than

private MyClass _foo;

then, as  Mati Cicero says in his comment, you simply end up polluting your resultant IL with pointless getter and setter methods.

Taking your lazy loading example, you can create a very succinct helper property to lazy setup _foo using C# 6:

private MyClass _foo;
private MyClass Foo => _foo ?? (_foo = new MyClass());

The compactness of the syntax, and thus the lack of noise, arguable makes the benefits of lazy-loading via a property better than using a helper method. As demonstrated by the length of your own example, using a helper method was arguably was a better solution prior to v6.

The other possible use with C# 6 is in replacing:

private readonly MyClass _bar = new MyClass();

with

private MyClass Bar { get; } = new MyClass();

Whether the latter is more readable is highly questionable though; arguably it both creates a pointless getter and makes the intention of the code less clear.


问:
Not Invented Here - what does it take to not succumb to it?
I will start with one, which however did not work the way I wanted.

Vendor Evaluation:
In the beginning of the project, we spent some time to do a survey of existing open-source libraries that can be used as building blocks for a larger library. Despite our efforts, there were a number of libraries which we did not come across until several months into the project. Had we found out those missed libraries earlier, we might have made our design decisions differently.

Architecture Compatibility:
It was understood from the very beginning that no single library could have satisfied all requirements, so several existing libraries are needed, along with some custom implementation to fill the gaps. These libraries would have to be wrapped into a single architecture so that the users will not need to know the internal construction of the library. Efficiency (in multiple aspects; can be summarized as "no CPU time, RAM nor Disk space can be wasted") was the main driving force in the architectural design; so the wrappers need to be equally efficient. In the beginning we did not know which open-source library would be compatible with the design (in the sense that the wrapper does not introduce any inefficiency of its own), as that would have required some pioneering work to find out.

Code quality:

One of the open-source library was about 20 years old. Another library was about 10 years old. In the prevailing thinking of open-source library, the older library is supposed to be more stable and have fewer bugs. Eventually we discovered that the opposite was true, and we ended up having to fix a number of bugs in the older library.

My original hypothesis is that "Does it take a lot of intelligence to not succumb to it? Does it take a lot of experience?" but after reviewing the project, I came to the conclusion that software reuse is like matchmaking - any notion of "missed opportunity" occurs naturally due to chance, and no amount of intentional effort will reduce missed opportunities.

What does it take to not succumb to Not Invented Here syndrome, in order to achieve the highest degree of software reuse and at the same time satisfying the software requirements perfectly?

Added (2010/12/18)

One of the reason we missed a good candidate library was that it was ruled out very early in the process. When there are more than 10 libraries in the initial list, there is some pressure to find rules that can quickly eliminate some of the candidates, because otherwise we would have spent too much time analyzing (analysis paralysis). However, this fast-track elimination caused the undesirable effect of rejecting one good library. (just like hiring?)

答: I had a team member who was adamant that we should write our system (a 3D engine) from scratch despite the fact that we had identified an engine that the team was familiar with and would mostly do. I took him aside and ask him if he was ready to take full responsibility for the failure of the project if he was unable to deliver his engine on time. He was not.</p>

ContentLicense: CC BY-SA 2.5


问:
Writing Selenium Tests - Modifying Markup Under Test
We'd like to know what you view as best practices and what has worked for your projects

My organization is in the beginning phases of creating a Selenium test suite, and have had some early discussions about how to ensure that our tests are robust.

In one of the first tests, we modified the markup under test to facilitate testing:

The original markup was something along the lines of:

Some Text

And the author of the test added an ID to the anchor tag:

Some Text

A few points of view emerged:

Adding anything to the markup solely for the purpose of facilitating testing is a bad thing.

a.) It clutters the markup, which hurts front-end developers (i.e. where is this id even being used?).

b.) It increases the payload being sent to the clients.

Adding an id to an element to facilitate testing is okay.

a.) It allows for more robust selectors (traversing the DOM / using a XPath can be much more brittle and difficult to read).

b.) Assuming that you use unique id's, there's no material downside to adding identifiers to elements on a page.

Adding another attribute (i.e. data-testing-id) is preferable to adding an id.

a.) While it clutters the markup and is also sent in the response to clients,   the purpose of the attribute is very clear.

b.) Similar to point 2, you can write more robust selectors.

答:
Adding anything to the markup solely for the purpose of facilitating testing is a bad thing.

Not necessarily. Dependency Injection means injecting dependent classes into other classes, instead of instantiating them. One of the main reasons you do this is to facilitate testing, which has value in and of itself. Every system, from relatively simple cars to ships, airplanes and spaceships has things like maintenance hatches that are not meant to be used in the normal operation of said system, but to facilitate maintenance. Imagine if cars didn't have a hood...

Adding an id to an element to facilitate testing is okay. Adding another attribute (i.e. data-testing-id) is preferable to adding an id.

There are probably alternatives to adding an id in some cases. You could simply look for a link that displays a certain text if you wanted to. If your tests are well-designed, even a change to that text would only result in a very limited change to your tests.

Remember that, at this level, your test is interested in how your user interacts with the application. A user does not 'click the button with the id buttonSave' but he 'clicks the button labeled save'. If you suddenly change the labeling of the button, you will not only break the test but also break what the user is used to seeing. If you have multiple buttons labeled as 'save' all of a sudden and you break the tests, you might have a problem with your interface. Both things are worth being notified of by your tests.


问:
Style guide for C++
Right now I am using Google C++ Style Guide in my C++ code and I was pretty happy with it.

Recently I was told that this guide is very bad: it is used internally by Google (I knew that), is outdated, and promotes some very bad practices. So I want to use another coding style.

What good and fairly used C++ style guides are there? I write code for both gcc and Visual Studio, and I use a lot of the C++11 features.

What I liked very much about Google C++ Style Guide was the indentation, the whitespace and the naming conventions (specially naming all classes, types - including typedefs, type aliases and template aliases - with capital first letter).

I know any answer is subjective (I hope this is ok on this site) and I would appreciate any opinion, but I am interested which guides are used these days.

答:
The C++ Core Guidelines are a set of tried-and-true guidelines, rules, and best practices about coding in C++, you can find them here: https://github.com/isocpp/CppCoreGuidelines

They are written by, among the others, Bjarne Stroustrup  and Herb Sutter.

Title: Style guide for C++


问:
How to test code that depends on complex APIs (Amazon S3 for instance)?
I am struggling with testing a method that uploads documents to Amazon S3, but I think this question applies to any non-trivial API/external dependecy. I've only come up with three potential solutions but none seem satisfactory:

Do run the code, actually upload the document, check with AWS's API that it has been uploaded and delete it at the end of the test. This will make the test very slow, will cost money every time the test is run and won't alway return the same result.

Mock S3. This is super hairy because I have no idea about that object's internals and it feels wrong because it's way too complicated.

Just make sure that MyObject.upload() is called with the right arguments and trust that I am using the S3 object correctly. This bothers me because there is no way to know for sure I used the S3 API correctly from the tests alone.

I checked how Amazon tests their own SDK and they do mock everything. They have a 200 lines helper that does the mocking. I don't feel it's practical for me to do the same.

How do I solve this?

答:
You need to do both.

Running, uploading and deleting is an integration test. It interfaces with an external system and can therefore be expected to run slow. It should probably not be part of every single build you do locally, but it should be part of a CI build or nightly build. That offsets the slowness of those tests and still provides the value of having it tested automatically.

You also need unittests that run more quickly. Since it is generally smart to not hard-depend on an external system too much (so you can swap out implementations or switch over) you should probably try and write a simple interface over S3 that you can code against. Mock that interface in unittests so you can have quick-running unittests.

The first tests check that your code actually works with S3, the second tests that your code correctly calls the code that talks to S3.


问:
Is it possible to adopt agile methodologies for outsourced projects?
I've had experience as a developer or team lead on several projects that have been outsourced and have seen less than stellar results in all cases. Most of these projects have employed a waterfall philosophy, with large kickoff meetings, months-long requirements gathering phases, plenty of conference calls, and innumerable emails. One thing that's always frustrated me is an absence of early access to the code. The contracts are setup in a way where the offshore team is responsible for meeting functional requirements, which is what the executives are concerned with. This means, however, that architecture decisions, implementation details, pattern usage, and things that concern other developers are so deeply settled by the time the product is delivered that we're unable to offer feedback or request any real changes. </p>

<p>Has anybody here managed an offshore project that hasn't experienced these problems? Specifically, I'm wondering if there's any way to structure the contracts to compel offshore teams to work in shorter cycles and re-factor or re-design based on feedback from on-shore developers. I haven't had too much experience with agile methodologies (I agree with the general principles, but work in a conservative shop that has it's entrenched methodologies), but wonder whether these could somehow be adapted to help manage offshore development. Overall, I'm looking to minimize the surprises and maintenance nightmares that inevitably arise when a development team is left to work in isolation for months at a time. </p>

答: Agile development works best when it is fully implemented. Trying to combine just one or two agile concepts with waterfall development is a recipe for failure. Both clients and development teams must full embrace agile methodology. This means that both sides need to completely understand the advantages and restrictions of agile development as well as what is — and is not — possible, the commitments that each side must make and what changes each must make to achieve the maximum benefit. Typically, it is the outsourcer who must make the greatest number of adjustments, but clients must also have a good grasp of the agile methodology to avoid conflicts.</p>


答:
There are two issues we have to look at here.

The first is that you seem to be looking at all of your tests from the unit test perspective. Unit tests are extremely valuable, but are not the only kinds of tests. Tests can actually be divided into several different layers, from very fast unit tests to less fast integration tests to even slower acceptance tests. (There can be even more layers broken out, like functional tests.)

The second is that you are mixing together calls to third-party code with your business logic, creating testing challenges and possibly making your code more brittle.

Unit tests should be fast and should be run often. Mocking dependencies helps to keep these tests running fast, but can potentially introduce holes in coverage if the dependency changes and the mock doesn't. Your code could be broken while your tests still run green. Some mocking libraries will alert you if the dependency's interface changes, others cannot.

Integration tests, on the other hand, are designed to test the interactions between components, including third-party libraries. Mocks should not be used at this level of testing because we want to see how the actual object interact together. Because we are using real objects, these tests will be slower, and we will not run them nearly as often as our unit tests.

Acceptance tests look at an even higher level, testing that the requirements for the software are met. These tests run against the entire, complete system that would get deployed. Once again, no mocking should be used.

One guideline people have found valuable regarding mocks is to not mock types you don't own. Amazon owns the API to S3 so they can make sure it doesn't change beneath them. You, on the other hand, do not have these assurances. Therefore, if you mock out the S3 API in your tests, it could change and break your code, while your tests all show green. So how do we unit test code that uses third-party libraries?

Well, we don't. If we follow the guideline, we can't mock objects we don't own. But… if we own our direct dependencies, we can mock them out. But how? We create our own wrapper for the S3 API. We can make it look a lot like the S3 API, or we can make it fit our needs more closely (preferred). We can even make it a little more abstract, say a PersistenceService rather than an AmazonS3Bucket. PersistenceService would be an interface with methods like #save(Thing) and #fetch(ThingId), the types of methods we might like to see (these are examples, you might actually want different methods). We can now implement a PersistenceService around the S3 API (say a S3PersistenceService), encapsulating it away from our calling code.

Now to the code that calls the S3 API. We need to replace those calls with calls to a PersistenceService object. We use dependency injection to pass our PersistenceService into the object. It's important not to ask for a S3PersistenceService, but to ask for a PersistenceService. This allows us to swap out the implementation during our tests.

All the code that used to use the S3 API directly now uses our PersistenceService, and our S3PersistenceService now makes all the calls to the S3 API. In our tests, we can mock out PersistenceService, since we own it, and use the mock to make sure that our code makes the correct calls. But now that leaves how to test S3PersistenceService. It has the same problem as before: we can't unit test it without calling to the external service. So… we don't unit test it. We could mock out the S3 API dependencies, but this would give us little-to-no additional confidence. Instead, we have to test it at a higher level: integration tests.

This may sound a little troubling saying that we shouldn't unit test a part of our code, but let's look at what we accomplished. We had a bunch of code all over the place we couldn't unit test that now can be unit tested through the PersistenceService. We have our third-party library mess confined to a single implementation class. That class should provide the necessary functionality to use the API, but does not have any external business logic attached to it. Therefore, once it is written, it should be very stable and should not change very much. We can rely on slower tests that we don't run that often because the code is stable.

The next step is to write the integration tests for S3PersistenceService. These should be separated out by name or folder so we can run them separately from our fast unit tests. Integration tests can often use the same testing frameworks as unit tests if the code is sufficiently informative, so we don't need to learn a new tool. The actual code to the integration test is what you would write for your Option 1.

Title: How to test code that depends on complex APIs (Amazon S3 for instance)?

Body:
I am struggling with testing a method that uploads documents to Amazon S3, but I think this question applies to any non-trivial API/external dependecy. I've only come up with three potential solutions but none seem satisfactory:

Do run the code, actually upload the document, check with AWS's API that it has been uploaded and delete it at the end of the test. This will make the test very slow, will cost money every time the test is run and won't alway return the same result.

Mock S3. This is super hairy because I have no idea about that object's internals and it feels wrong because it's way too complicated.

Just make sure that MyObject.upload() is called with the right arguments and trust that I am using the S3 object correctly. This bothers me because there is no way to know for sure I used the S3 API correctly from the tests alone.

I checked how Amazon tests their own SDK and they do mock everything. They have a 200 lines helper that does the mocking. I don't feel it's practical for me to do the same.

How do I solve this?


答:
I would say that it depends on the complexity of your use of the API.

You definitely need to do at least some testing that actually invokes the S3 API and confirms that it worked from end to end.

You also definitely need to do additional testing that doesn't actually call the API, so you can test your own software adequately without invoking the API all of the time.

The question that remains is: do you need to mock the API?

And I think that depends on how much you do with it.  If you are only performing one or two simple actions, I don't think you need to go to all the trouble of a mock-up.  I would be satisfied with just checking my use of the functions and doing some live testing.

However, if your use of it is more complex, with different scenarios and different variables that could affect the results, you probably need to mock it up to do more thorough testing.


问:
Cleaner Windows Forms
Backstory:
I am working on a Wizard Setup project and I've ended up with a very big(a lot of lines of code) Form class. Because my form holds a Wizard control which in turn has lots of pages and each page has input controls that need to be taken into account and saved in the database, the events that fire upon user input have quite a lot of things to do.

Question:
Are there any clean code rules specific to Form classes?

I'm trying to figure out if it would make more sense for me to move my event functionaity in a different class and just send my data and controls to that class for processing?

答:
Your goal should be to push as much of your program logic out of the form class and into other classes as possible.  This decouples the content of the form from the actual program functionality, and makes everything easier to test.

Consider following a software pattern specifically designed for this purpose: Model-View-Presenter or MVP.  The "Build your own CAB" article by Jeremy Miller describes this process in detail.  There are also MVP examples on Codeplex like Claymore MVP that you can try.

Further Reading

Build your own CAB

Title: Cleaner Windows Forms