答:
If you're looking for an authoritative source, I think the best Mac-related material will be found in the Undo Architecture document from Apple.

I don't think you're going to find a list of rules about when you should or shouldn't coalesce undo events, though. What feels right for one application won't necessarily make sense for another one. For example, coalescing keystrokes makes sense in a text editor because the user will probably see typing a paragraph as a single action and not as 539 separate actions, and also because you don't want the user to have to undo 539 times just to get to the point they were at before they typed that paragraph. But what about move operations on a shape in a drawing program? Or sequential adjustments to a fill color? You could make a good case for these being coalesced or not, depending on the nature of your program.

Always create a new Undo Typing item after the user is typing for an
  extended period of time and some condition is met (couldn't figure out
  if this was time based or character count based).

It's based on autosave. Lucky for you, the TextEdit source code is available and well commented. I think that if you take a look at it, you'll get a better idea of what's going on and why. For example:

```<code>- (void)saveToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOperation completionHandler:(void (^)(NSError *error))handler {
    // Note that we do the breakUndoCoalescing call even during autosave, which
    // means the user's undo of long typing will take them back to the last spot an
    // autosave occured. This might seem confusing, and a more elaborate solution may
    // be possible (cause an autosave without having to breakUndoCoalescing), but since
    // this change is coming late in Leopard, we decided to go with the lower risk fix.
    [[self windowControllers] makeObjectsPerformSelector:@selector(breakUndoCoalescing)];
 ...
</code>```

I know you said you're not interested in implementation details yet, but looking at the way that Apple implemented TextEdit can inform the decisions you make for your own application.

Title: How Should "Undo Typing" Behave?

Body:
I'm implementing a Java app that includes an Undo/Redo stack. I've noticed that some apps (such as TextEdit on Mac OS X) let you choose "Undo Typing" from the Edit Menu after typing some text. I'd like to implement that sort of thing into my app as well, but I'm having a really hard time finding guidelines about how it should behave.

With some trial and error, my best guess about how TextEdit's Undo Typing behaves is:

When the user types a new character (or types the delete key), merge it into the previous Undo Typing item if one is at the top of the Undo stack, unless one of the following situations occurs

Always create a new Undo Typing item after the user continues to type after at least 15 seconds of inactivity

Always create a new Undo Typing item after the user is typing for an extended period of time and some condition is met (couldn't figure out if this was time based or character count based).

Always create a new Undo Typing item when any text is selected and then deleted or overwritten (selecting text, not making a change, then returning to the original insertion point and continuing to type does not trigger this)

In practice, Apple's strategy seems to work (at least it works for me when I type), but as noted by the last point, I haven't really been able to figure out the rules. Also, it seems like other programs follow different rules, such as Microsoft Word. Google has not turned up a defined list of rules for any implementation of Undo Typing and I haven't come across any best practices for how it should behave. So how should it behave? Or is it just up to the whims of the programmer?

EDIT: Just to clarify, I'm not interested in implementation details right now. I'm especially curious as to whether or not an authoritative reference (e.g. best practices or user interface document) exists describing this or a description of how it is implemented across multiple products.

Body:
If you're looking for an authoritative source, I think the best Mac-related material will be found in the Undo Architecture document from Apple.

I don't think you're going to find a list of rules about when you should or shouldn't coalesce undo events, though. What feels right for one application won't necessarily make sense for another one. For example, coalescing keystrokes makes sense in a text editor because the user will probably see typing a paragraph as a single action and not as 539 separate actions, and also because you don't want the user to have to undo 539 times just to get to the point they were at before they typed that paragraph. But what about move operations on a shape in a drawing program? Or sequential adjustments to a fill color? You could make a good case for these being coalesced or not, depending on the nature of your program.

Always create a new Undo Typing item after the user is typing for an
  extended period of time and some condition is met (couldn't figure out
  if this was time based or character count based).

It's based on autosave. Lucky for you, the TextEdit source code is available and well commented. I think that if you take a look at it, you'll get a better idea of what's going on and why. For example:

- (void)saveToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOperation completionHandler:(void (^)(NSError *error))handler {
    // Note that we do the breakUndoCoalescing call even during autosave, which
    // means the user's undo of long typing will take them back to the last spot an
    // autosave occured. This might seem confusing, and a more elaborate solution may
    // be possible (cause an autosave without having to breakUndoCoalescing), but since
    // this change is coming late in Leopard, we decided to go with the lower risk fix.
    [[self windowControllers] makeObjectsPerformSelector:@selector(breakUndoCoalescing)];
 ...

I know you said you're not interested in implementation details yet, but looking at the way that Apple implemented TextEdit can inform the decisions you make for your own application.


问:
Preventing Liskov Substitution violation
I am reimplementing some component and noticed that the original version has a Liskov Substitution violation. It's not all that critical, though I'd like to get rid of it in the new implementation . It is however not clear to me how to do this.

I have a component defining very simple value classes used by the system. This component has a DataValue interface and a dozen implementations such as NumberValue and GeoCoordinateValue.

The component I'm reworking is a storage layer meant for indexing data so it can easily be queried against. This component contains a set of classes that provide storage information for a particular DataValue implementing class. This information are things such as which fields a table needs to have to contain the DataValue in question, which field should be used for sorting, and what indexes should be placed. These classes all implement some DataValueHandler interface.

The LSP violation occurs for two particular methods in this DataValueHandler interface:

```<code>getWhereConditions( DataValue $dataValue )

getInsertValues( DataValue $dataValue )
</code>```

The interface defines these methods take a DataValue. The implementations however expect the DataValue for which they provide information. For instance, the NumberValueHandler expects a NumberValue, and will throw an exception if it gets a GeoCoordinateValue.

So how can I get rid of this? (Before anyone suggests it: putting info of some specific storage backend in DataValue is not going to happen, as this would be worse design wise then the current LSP violation.)

答:
Do the DataValue classes all implement IDataValue or inherit from the same abstract DataValue class?

I'd expect all classes to have a common set of public methods, and for the GetWhereConditions only to act on these common methods (thus facilitating the substitution).

Otherwise they're just different classes, in which case you'd expect to see...

```<code>GetWhereConditions(NumberValue){...}
GetWhereConditions(GeoCoordinateValue){...}
</code>```

...to reflect this.

ContentLicense: CC BY-SA 3.0

Body:
Do the DataValue classes all implement IDataValue or inherit from the same abstract DataValue class?

I'd expect all classes to have a common set of public methods, and for the GetWhereConditions only to act on these common methods (thus facilitating the substitution).

Otherwise they're just different classes, in which case you'd expect to see...

GetWhereConditions(NumberValue){...}
GetWhereConditions(GeoCoordinateValue){...}

...to reflect this.


答:
The specific DataValue class should be a parameter for the DataValueHandler constructor and stored as a member variable, and the get methods should not include a DataValue object as a parameter.

(Some java-ish pseudocode below to illustrate)

```<code>class NumberDataValueHandler implements DataValueHandler {
    private NumberDataValue myDataValue;

    NumberDataValueHandler (NumberDataValue newNumberDataValue) {
       myDataValue = newNumberDataValue;
    }

    String getWhereConditions () {
        myDataValue.someNumberSpecificMethod();
        // do some NumberDataValue specific operations...
    }

}
</code>```

Title: Preventing Liskov Substitution violation

Body:
I am reimplementing some component and noticed that the original version has a Liskov Substitution violation. It's not all that critical, though I'd like to get rid of it in the new implementation . It is however not clear to me how to do this.

I have a component defining very simple value classes used by the system. This component has a DataValue interface and a dozen implementations such as NumberValue and GeoCoordinateValue.

The component I'm reworking is a storage layer meant for indexing data so it can easily be queried against. This component contains a set of classes that provide storage information for a particular DataValue implementing class. This information are things such as which fields a table needs to have to contain the DataValue in question, which field should be used for sorting, and what indexes should be placed. These classes all implement some DataValueHandler interface.

The LSP violation occurs for two particular methods in this DataValueHandler interface:

```<code>getWhereConditions( DataValue $dataValue )

getInsertValues( DataValue $dataValue )
</code>```

The interface defines these methods take a DataValue. The implementations however expect the DataValue for which they provide information. For instance, the NumberValueHandler expects a NumberValue, and will throw an exception if it gets a GeoCoordinateValue.

So how can I get rid of this? (Before anyone suggests it: putting info of some specific storage backend in DataValue is not going to happen, as this would be worse design wise then the current LSP violation.)

Body:
The specific DataValue class should be a parameter for the DataValueHandler constructor and stored as a member variable, and the get methods should not include a DataValue object as a parameter.

(Some java-ish pseudocode below to illustrate)

class NumberDataValueHandler implements DataValueHandler {
    private NumberDataValue myDataValue;

    NumberDataValueHandler (NumberDataValue newNumberDataValue) {
       myDataValue = newNumberDataValue;
    }

    String getWhereConditions () {
        myDataValue.someNumberSpecificMethod();
        // do some NumberDataValue specific operations...
    }

}


问:
Is there a name for this design pattern?
I don't like singletons, but I have to compromise now (but only as temporary measure).

However I don't want to go completely singleton. I'd rather want to use this pattern:

```<code>interface NameThisInterface {

  //Returns the currently centralized object.
  static function current();

  //Centralizes the instance.
  function centralize();

}

class A implements NameThisInterface {
   ...
}

$obj = new A;

$obj->centralize();

...

A::current(); //gets $obj.
</code>```

Basically A would be my "Application" class. All controllers, models and views etc will access need only one instance of it. But for the sake of easier unit-testing among other reasons I want to have the application object stored as a reference to all MVC classes. So with the pattern above, the conversion at this later point in time will be easier and some of the unit testing might be easier.

Is there a generally accepted name for this pattern?

答:
It is a combination of Singelton and some form of "Creator Patter" (probably a Factory (Though your factory is a little on the disorganized side (since we can't see most of the code)).

There is nothing wrong with combining Singelton with other patterns. In fact I personally think that you can NOT use a singelton correctly unless you combine it with some other creator pattern (personal opinion). The reason is that tightly coupling your code to a single version of an object makes the code very inflexible and brittle (and hard to test).

Personally I like to formalize the factory and allow different versions to be registered (ie a test version/production version/an ISS version). Thus different factories can be used (one instantiated on start-up) depending on the situation thus the singelton is still created on demand (which is an important property of a singelton (especially if is a heavy weight object)).


问:
How should my web application handle common errors such as incorrect password, session timeout, etc.?
How should my web application handle common errors such as incorrect password, session timeout, etc.?

I have a class called Hotmail that contains various method such as login, logout etc.

To illustrate the confusion, I have a login method that logs the user into Hotmail via my software. The login method returns a HttpWebResponse object. But, within the login method any number of things could happen such as wrong credentials being entered or a timeout.

I'm in some confusion about how, and where to handle such errors.

In the case of the wrong credentials being entered, or a timeout, it would be pointless, or sometimes not possible to return a HttpWebResponse object. What would be the best way to handle such errors?

Should I create custom Exceptions so the code that's calling the method can check for such errors and handle them?

What's the conventional way to handle these sorts of errors as I'm sure this is a common point of confusion?

答:
The examples you give are things that require user action. I suggest that you tell the user as clearly as plainly as possible what went wrong and what they need to do.

From the user experience site

Help users recognize, diagnose, and recover from errors - Error
  messages should be easily read and understood by the users, and should
  tell them what to do to fix this (e.g don't write "Error 1052" and let
  the users search the solution themselves, but instead write "We
  couldn't locate you. Please turn on your phone's GPS under Settings").

https://ux.stackexchange.com/a/17799/21611


答:
The conventional way is to return a custom Exception, and let the calling code decide what happens then.

Imagine that your "login" command is packaged as a library, and used in multiple applications. In one application, if there is a timeout, you want to display an error message and give up. In other application, in case of a timeout, you want to retry the method three times, and give up only if all three logins fail on timeout. By providing an exception, you give both applications an opportunity to do what they want.

It may be tempting, but don't try to put both these two options into the "login" command, e.g. by adding a new parameter "howManyRetriesOnTimeout". A third application may want to do something else. Also as a regeneral rule, it is not recommended to put multiple functionality (logging in, repeating on timeout) in a single method.

Body:
How should my web application handle common errors such as incorrect password, session timeout, etc.?

I have a class called Hotmail that contains various method such as login, logout etc.

To illustrate the confusion, I have a login method that logs the user into Hotmail via my software. The login method returns a HttpWebResponse object. But, within the login method any number of things could happen such as wrong credentials being entered or a timeout.

I'm in some confusion about how, and where to handle such errors.

In the case of the wrong credentials being entered, or a timeout, it would be pointless, or sometimes not possible to return a HttpWebResponse object. What would be the best way to handle such errors?

Should I create custom Exceptions so the code that's calling the method can check for such errors and handle them?

What's the conventional way to handle these sorts of errors as I'm sure this is a common point of confusion?


问:
Is this an appropriate use of Mockito's reset method?
I have a private method in my test class that constructs a commonly used Bar object. The Bar constructor calls someMethod() method in my mocked object:

```<code>private @Mock Foo mockedObject; // My mocked object
...

private Bar getBar() {
  Bar result = new Bar(mockedObject); // this calls mockedObject.someMethod()
}
</code>```

In some of my test methods I want to check someMethod was also invoked by that particular test. Something like the following:

```<code>@Test
public void someTest() {
  Bar bar = getBar();

  // do some things

  verify(mockedObject).someMethod(); // <--- will fail
}
</code>```

This fails, because the mocked object had someMethod invoked twice. I don't want my test methods to care about the side effects of my getBar() method, so would it be reasonable to reset my mock object at the end of getBar()?

```<code>private Bar getBar() {
  Bar result = new Bar(mockedObject); // this calls mockedObject.someMethod()
  reset(mockedObject); // <-- is this OK?
}
</code>```

I ask, because the documentation suggests resetting mock objects is generally indicative of bad tests. However, this feels OK to me.

Alternative

The alternative choice seems to be calling:

```<code>verify(mockedObject, times(2)).someMethod();
</code>```

which in my opinion forces each test to know about the expectations of getBar(), for no gain.

答:
I believe this is one of the cases where using reset() is ok. The test you are writing is testing that "some things" triggers a single call to someMethod(). Writing the verify() statement with any different number of invocations can lead to confusion.

atLeastOnce() allows for false positives, which is a bad thing as you want your tests to always be correct.

times(2) prevents the false positive, but makes it seem like you are expecting two invocations rather than saying "i know the constructor adds one". Further more, if something changes in the constructor to add an extra call, the test now has a chance for a false positive. And removing the call would cause the test to fail because the test is now wrong instead of what is being tested is wrong.

By using reset() in the helper method, you avoid both of these issues. However, you need to be careful that it will also reset any stubbing you have done, so be warned. The major reason reset() is discouraged is to prevent

```<code>bar = mock(Bar.class);
//do stuff
verify(bar).someMethod();
reset(bar);
//do other stuff
verify(bar).someMethod2();
</code>```

This is not what the OP is trying to do. The OP, I'm assuming, has a test that verifies the invocation in the constructor. For this test, the reset allows for isolating this single action and it's effect. This one of the few cases with reset() can be helpful as. The other options that don't use it all have cons. The fact that the OP made this post shows that he is thinking about the situation and not just blindly utilizing the reset method.

Body:
I believe this is one of the cases where using reset() is ok. The test you are writing is testing that "some things" triggers a single call to someMethod(). Writing the verify() statement with any different number of invocations can lead to confusion.

atLeastOnce() allows for false positives, which is a bad thing as you want your tests to always be correct.

times(2) prevents the false positive, but makes it seem like you are expecting two invocations rather than saying "i know the constructor adds one". Further more, if something changes in the constructor to add an extra call, the test now has a chance for a false positive. And removing the call would cause the test to fail because the test is now wrong instead of what is being tested is wrong.

By using reset() in the helper method, you avoid both of these issues. However, you need to be careful that it will also reset any stubbing you have done, so be warned. The major reason reset() is discouraged is to prevent

bar = mock(Bar.class);
//do stuff
verify(bar).someMethod();
reset(bar);
//do other stuff
verify(bar).someMethod2();

This is not what the OP is trying to do. The OP, I'm assuming, has a test that verifies the invocation in the constructor. For this test, the reset allows for isolating this single action and it's effect. This one of the few cases with reset() can be helpful as. The other options that don't use it all have cons. The fact that the OP made this post shows that he is thinking about the situation and not just blindly utilizing the reset method.


答:
You should begin by dividing the possible errors into two categories: the ones that the user can possibly fix and the rest. Each of this categories should have a separate approach.

If there is a problem with credentials or the timeout was exceeded, the user should be informed about this in order to take measures. You should show the user a message indicating the problem in a user-friendly manner (i.e. do not print the stack trace).

What comes to creating custom exceptions, this isn't really specific to the type of application you're developing. All the general advice and best practices can be helpful. Also consider using status codes for such errors instead of throwing exceptions.

Title: How should my web application handle common errors such as incorrect password, session timeout, etc.?


问:
A simple definition of client-server
I'm looking for a simple definition of the concept of “client-server”

I'd like something similar to this definition of state.

... That "thing/information" that you need to remember is called "state".

Edit - This isn't a homework question (nor am I a student). My goal is to come up with a compact way of explaining REST to average developers. I didn't want to prejudice the response though.

答: A server is a computer that does stuff for another computer. The other computer is called a client.</p>

Title: A simple definition of client-server


问:
How Do I interview Front-End Web Developers?
For the first time I'm in the position where I'm helping interview potential front-end developers. The other interviewer is more business & PM-focused, although he is a former developer. I probe for knowledge and background in CSS, Javascript, and other related technologies, but those questions are really just testing for lingo.  I feel that it would be unfair to ask very specific questions about CSS when we're not in front of a computer.

I've also been given websites that these web developers have written. Is that enough to go on for interviewing front-ends?  We're also looking for general aptitude, rather than a databank of knowledge.

答:
For front-end developers there are some ways to gauge his skill and experience:

Websites/Portfolio

Considering that front-end developers usually have worked with things that are clearly visible, it's not difficult for them to give up a list of websites that they've worked on.
One could argue that they can't due to non-disclosure agreement, but it is also not uncommon for them to have portfolio websites that you can check.

If they can't show off what they've done or what they can do then I'd be fairly suspicious. It's so easy to create projects on the Internet today (with tools such as jsfiddle, github, etc.) that it's inexcusable for a front-end developer to not do so.

This is generally what you should ask for prior to the interview so you can examine the material. That way you can have a two-way conversation and discussion with the candidate on how he works. If the candidate is unable discuss his work then it's a clear red flag.

Demonstrate skills

During the interview you can ask them to demonstrate their skills. You can tell them to create a short Javascript/HTML demo. That way you can see if they're up for the task of front-end web development or not.

The drawback with this exercise is that it takes time both for you and your candidate to sit this through to completion (and still may not lead to a hire if the candidate is right but decided to go elsewhere).


答:
Simon's comment hit the nail on the head. What you've got there is almost exactly a global variable with get/set methods.

I say almost since your set method isn't static; this will prevent you setting your global variable to null after it has been assigned a value. You could debate whether this is a good thing. I'd argue "no": remember there's nothing forcing you to assign it a value in the first place!

If you have to dignify it with a name, maybe go with "global instance holder/container/etc". If you make sure the word "global" is in there as much as possible (i.e. even on your getter/setter methods) it should stick out like a sore thumb to anyone using it.

Title: Is there a name for this design pattern?

Body:
I don't like singletons, but I have to compromise now (but only as temporary measure).

However I don't want to go completely singleton. I'd rather want to use this pattern:

```<code>interface NameThisInterface {

  //Returns the currently centralized object.
  static function current();

  //Centralizes the instance.
  function centralize();

}

class A implements NameThisInterface {
   ...
}

$obj = new A;

$obj->centralize();

...

A::current(); //gets $obj.
</code>```

Basically A would be my "Application" class. All controllers, models and views etc will access need only one instance of it. But for the sake of easier unit-testing among other reasons I want to have the application object stored as a reference to all MVC classes. So with the pattern above, the conversion at this later point in time will be easier and some of the unit testing might be easier.

Is there a generally accepted name for this pattern?


问:
Best way to unit test methods that call other methods inside same class
I was recently discussing with some friends which of the following 2 methods is best to stub return results or calls to methods inside same class from methods inside same class.

This is a very simplified example. In reality the functions are much more complex.

Example:

```<code>public class MyClass
{
     public bool FunctionA()
     {
         return FunctionB() % 2 == 0;
     }

     protected int FunctionB()
     {
         return new Random().Next();
     }
}
</code>```

So to test this we have 2 methods.

Method 1:
Use Functions and Actions to replace functionality of the methods.
Example:

```<code>public class MyClass
{
     public Func<int> FunctionB { get; set; }

     public MyClass()
     {
         FunctionB = FunctionBImpl;
     }

     public bool FunctionA()
     {
         return FunctionB() % 2 == 0;
     }

     protected int FunctionBImpl()
     {
         return new Random().Next();
     }
}

[TestClass]
public class MyClassTests
{
    private MyClass _subject;

    [TestInitialize]
    public void Initialize()
    {
        _subject = new MyClass();
    }

    [TestMethod]
    public void FunctionA_WhenNumberIsOdd_ReturnsTrue()
    {
        _subject.FunctionB = () => 1;

        var result = _subject.FunctionA();

        Assert.IsFalse(result);
    }
}
</code>```

Method 2:
Make members virtual, derive class and in derived class use Functions and Actions to replace functionality
Example:

```<code>public class MyClass
{
     public bool FunctionA()
     {
         return FunctionB() % 2 == 0;
     }

     protected virtual int FunctionB()
     {
         return new Random().Next();
     }
}

public class TestableMyClass
{
     public Func<int> FunctionBFunc { get; set; }

     public MyClass()
     {
         FunctionBFunc = base.FunctionB;
     }

     protected override int FunctionB()
     {
         return FunctionBFunc();
     }
}

[TestClass]
public class MyClassTests
{
    private TestableMyClass _subject;

    [TestInitialize]
    public void Initialize()
    {
        _subject = new TestableMyClass();
    }

    [TestMethod]
    public void FunctionA_WhenNumberIsOdd_ReturnsTrue()
    {
        _subject.FunctionBFunc = () => 1;

        var result = _subject.FunctionA();

        Assert.IsFalse(result);
    }
}
</code>```

I want to know wich is better and also WHY ?

Update:
NOTE: FunctionB can also be public

答:
Edited following original poster update.

Disclaimer : not a C# programmer (mostly Java or Ruby). My answer would be : I would not test it at all, and I do not think you should.

The longer version is : private/protected methods are not parts of the API, they are basically implementation choices, that you can decide to review, update or throw away completely without any impact on the outside.

I suppose you have a test on FunctionA(), which is the part of the class that is visible from the external world. It should be the only one that has a contract to implement (and that could be tested). Your private/protected method has no contract to fulfil and/or test.

See a related discussion there : https://stackoverflow.com/questions/105007/should-i-test-private-methods-or-only-public-ones

Following the comment, if FunctionB is public, I'll simply test both using unit test. You may think that the test of FunctionA is not totally "unit" (as it call FunctionB), but I would not be too worried by that : if FunctionB test works but not FunctionA test, it means clearly that the problem is not in the subdomain of FunctionB, which is good enough for me as a discriminator.

If you really want to be able to totally separate the two tests, I would use some kind of mocking technique to mock FunctionB when testing FunctionA (typically, return a fixed known correct value). I lack the C# ecosystem knowledge to advice a specific mocking library, but you may look at this question.

OwnerDisplayName: Martin


答:
Adding on to what Martin points out,

If your method is private/protected - do not test it. It is internal to the class and should not be accessed outside the class.

In both the approaches that you mention, I have these concerns -

Method 1 - This actually changes the class under test's behaviour in the test.

Method 2 - This actually does not test the production code, instead tests another implementation.

In the problem stated, I see that the only logic of A is to see if the output of FunctionB is even. Although illustrative, FunctionB gives Random value, which is tough to test.

I expect a realistic scenario where we can setup MyClass such that we know what FunctionB would return. Then our expected result is known, we can call FunctionA and assert on the actual result.

Title: Best way to unit test methods that call other methods inside same class

Body:
I was recently discussing with some friends which of the following 2 methods is best to stub return results or calls to methods inside same class from methods inside same class.

This is a very simplified example. In reality the functions are much more complex.

Example:

```<code>public class MyClass
{
     public bool FunctionA()
     {
         return FunctionB() % 2 == 0;
     }

     protected int FunctionB()
     {
         return new Random().Next();
     }
}
</code>```

So to test this we have 2 methods.

Method 1:
Use Functions and Actions to replace functionality of the methods.
Example:

```<code>public class MyClass
{
     public Func<int> FunctionB { get; set; }

     public MyClass()
     {
         FunctionB = FunctionBImpl;
     }

     public bool FunctionA()
     {
         return FunctionB() % 2 == 0;
     }

     protected int FunctionBImpl()
     {
         return new Random().Next();
     }
}

[TestClass]
public class MyClassTests
{
    private MyClass _subject;

    [TestInitialize]
    public void Initialize()
    {
        _subject = new MyClass();
    }

    [TestMethod]
    public void FunctionA_WhenNumberIsOdd_ReturnsTrue()
    {
        _subject.FunctionB = () => 1;

        var result = _subject.FunctionA();

        Assert.IsFalse(result);
    }
}
</code>```

Method 2:
Make members virtual, derive class and in derived class use Functions and Actions to replace functionality
Example:

```<code>public class MyClass
{
     public bool FunctionA()
     {
         return FunctionB() % 2 == 0;
     }

     protected virtual int FunctionB()
     {
         return new Random().Next();
     }
}

public class TestableMyClass
{
     public Func<int> FunctionBFunc { get; set; }

     public MyClass()
     {
         FunctionBFunc = base.FunctionB;
     }

     protected override int FunctionB()
     {
         return FunctionBFunc();
     }
}

[TestClass]
public class MyClassTests
{
    private TestableMyClass _subject;

    [TestInitialize]
    public void Initialize()
    {
        _subject = new TestableMyClass();
    }

    [TestMethod]
    public void FunctionA_WhenNumberIsOdd_ReturnsTrue()
    {
        _subject.FunctionBFunc = () => 1;

        var result = _subject.FunctionA();

        Assert.IsFalse(result);
    }
}
</code>```

I want to know wich is better and also WHY ?

Update:
NOTE: FunctionB can also be public

OwnerDisplayName: Srikanth Venugopalan


答:
I subscribe to the theory that if a function is important to test, or is important to replace, it is important enough to not be a private implementation detail of the class under test, but to be a public implementation detail of a different class.

So if I am in a scenario where I have

```<code>class A
{
     public B C()
     {
         D();
     }

     private E D();
     {
         // i actually want to control what this produces when I test C()
         // or this is important enough to test on its own
         // and, typically, both of the above
     }
}
</code>```

Then I am going to refactor.

```<code>class A
{
     ICollaborator collaborator;

     public A(ICollaborator collaborator)
     {
         this.collaborator = collaborator;
     }

     public B C()
     {
         collaborator.D();
     }
}
</code>```

Now I have a scenario where D() is independently testable, and fully replaceable.

As a means of organization, my collaborator might not live at the same namespace level. For example, if A is in FooCorp.BLL, then my collaborator might be another layer deep, as in FooCorp.BLL.Collaborators (or whatever name is appropriate). My collaborator might further only be visible inside the assembly via the internal access modifier, which I would then also expose to my unit testing project(s) via the InternalsVisibleTo assembly attribute. The takeaway is that you can still keep your API clean, as far as callers are concerned, while producing verifiable code.

Body:
I subscribe to the theory that if a function is important to test, or is important to replace, it is important enough to not be a private implementation detail of the class under test, but to be a public implementation detail of a different class.

So if I am in a scenario where I have

class A
{
     public B C()
     {
         D();
     }

     private E D();
     {
         // i actually want to control what this produces when I test C()
         // or this is important enough to test on its own
         // and, typically, both of the above
     }
}

Then I am going to refactor.

class A
{
     ICollaborator collaborator;

     public A(ICollaborator collaborator)
     {
         this.collaborator = collaborator;
     }

     public B C()
     {
         collaborator.D();
     }
}

Now I have a scenario where D() is independently testable, and fully replaceable.

As a means of organization, my collaborator might not live at the same namespace level. For example, if A is in FooCorp.BLL, then my collaborator might be another layer deep, as in FooCorp.BLL.Collaborators (or whatever name is appropriate). My collaborator might further only be visible inside the assembly via the internal access modifier, which I would then also expose to my unit testing project(s) via the InternalsVisibleTo assembly attribute. The takeaway is that you can still keep your API clean, as far as callers are concerned, while producing verifiable code.

OwnerDisplayName: Anthony Pegram


问:
A Web application as a REST API client: how to handle resource identifiers
Several concepts related to REST conflict in my head when I try implementing it.

I have a REST-ful back-end API system that holds the business logic, and a web application that provides the UI. From various resources about REST (particularly, REST in Practice: Hypermedia and Systems Architecture) I know that I should not expose raw identifiers of my entities, but rather return hyperlinks with rel="self".

Consider the example. The REST api has a resource that returns a person:

```<code><Person>
  <Links>
    <Link rel="self" href="http://my.rest.api/api/person/1234"/>
  </Links>
  <Pets>
    <Link rel="pet" href="http://my.rest.api/api/pet/678"/>
  </Pets>
</Person>
</code>```

The problem arises with the web application. Let's assume it returns a page that contains a hyperlink to browsers:

```<code><body class="person">
  <p>
    href="http://my.web.app/pet/???????" />
  </p>
</body>
</code>```

What should I put into the href attribute? How do I keep the API entity URL in the web application to be able to get the entity when a user opens the target page?

The requirements seem conflicting:

The hyperlink href should lead to the web application because it is the system hosting the UI

The href should have some id of the entity because the web app must be able to address the entity when the target page opens

The web app should not parse/construct REST URLs beacuse it's not REST-ful, The mentioned book says

URIs should be opaque to consumers. Only the issuer of the URI knows how to interpret it and map it to a resource.

So, I cannot just take 1234 from the API response URL because as a RESTful client I should treat it as if it was something like http://my.rest.api/api/AGRIDd~ryPQZ^$RjEL0j. On the other hand, I must give some URL that leads to my web app and is enough for the app to somehow restore the API's original URL and use that URL to access the API resources.

The simplest way is probably just using the API URLs of resources as their string identifiers. But web page urls like http://my.web.app/person/http%3A%2F%2Fmy.rest.api%2Fapi%2Fperson%2F1234 are ugly.

It all seems quite easy for a desktop app or a single-page javascript app. Since they live continuously, they can just keep the URLs in memory together with the service objects for the application lifetime and use them when necessary.

With a web app I can imagine several approaches, but all seem weird:

Replace the host in the API URLs and keep the result only. The huge downside is that it requires the web application to handle whatever URL the API generates, meaning monstrous coupling. Moreover, it's not RESTful again, because my web app starts interpreting the URLs.

Expose the raw ids in the REST API together with the links, use them to build Web App's URLs, and then use the ids on the web app server to find the required resources in the API. This is better, but will affect the web app server performance because the web app will have to go through the REST service navigation issuing a chain of get-by-id requests of some form to handle any request from a browser. For a somewhat nested resource this might be costly.

Store all self URLs returned by the api in a persistent (DB?) mapping on the web app server. Generate some ids for them, use the ids to build the web app page URLs and to get the URLs of the REST service resources. I.e. I keep the http://my.rest.api/pet/678 URL somewhere with a new key, say 3, and generate the web page URL as http://my.web.app/pet/3. This looks like a HTTP Cache implementation of some sort. I don't know why, but it seems weird to me.

Or Does it all mean that RESTful APIs cannot serve as backends for web applications?

答:
I thing if you stick to something similar to the Atom Syndication Format you are good.

Here the metadata describing the Entry being represented can be specified using additional elements/attributes:

atom:id
As per [RFC4287], contains a URI which uniquely identifies the Entry

<atom:link rel="self" href=".." >
As per [RFC4287], this element is optional. If included it contains the URI a client should use to retrieve the Entry.

This is just my two cents.

Body:
Several concepts related to REST conflict in my head when I try implementing it.

I have a REST-ful back-end API system that holds the business logic, and a web application that provides the UI. From various resources about REST (particularly, REST in Practice: Hypermedia and Systems Architecture) I know that I should not expose raw identifiers of my entities, but rather return hyperlinks with rel="self".

Consider the example. The REST api has a resource that returns a person:

```<code><Person>
  <Links>
    <Link rel="self" href="http://my.rest.api/api/person/1234"/>
  </Links>
  <Pets>
    <Link rel="pet" href="http://my.rest.api/api/pet/678"/>
  </Pets>
</Person>
</code>```

The problem arises with the web application. Let's assume it returns a page that contains a hyperlink to browsers:

```<code><body class="person">
  <p>
    <a href="http://my.web.app/pet/???????" />
  </p>
</body>
</code>```

What should I put into the href attribute? How do I keep the API entity URL in the web application to be able to get the entity when a user opens the target page?

The requirements seem conflicting:

The hyperlink href should lead to the web application because it is the system hosting the UI

The href should have some id of the entity because the web app must be able to address the entity when the target page opens

The web app should not parse/construct REST URLs beacuse it's not REST-ful, The mentioned book says

URIs should be opaque to consumers. Only the issuer of the URI knows how to interpret it and map it to a resource.

So, I cannot just take 1234 from the API response URL because as a RESTful client I should treat it as if it was something like http://my.rest.api/api/AGRIDd~ryPQZ^$RjEL0j. On the other hand, I must give some URL that leads to my web app and is enough for the app to somehow restore the API's original URL and use that URL to access the API resources.

The simplest way is probably just using the API URLs of resources as their string identifiers. But web page urls like http://my.web.app/person/http%3A%2F%2Fmy.rest.api%2Fapi%2Fperson%2F1234 are ugly.

It all seems quite easy for a desktop app or a single-page javascript app. Since they live continuously, they can just keep the URLs in memory together with the service objects for the application lifetime and use them when necessary.

With a web app I can imagine several approaches, but all seem weird:

Replace the host in the API URLs and keep the result only. The huge downside is that it requires the web application to handle whatever URL the API generates, meaning monstrous coupling. Moreover, it's not RESTful again, because my web app starts interpreting the URLs.

Expose the raw ids in the REST API together with the links, use them to build Web App's URLs, and then use the ids on the web app server to find the required resources in the API. This is better, but will affect the web app server performance because the web app will have to go through the REST service navigation issuing a chain of get-by-id requests of some form to handle any request from a browser. For a somewhat nested resource this might be costly.

Store all self URLs returned by the api in a persistent (DB?) mapping on the web app server. Generate some ids for them, use the ids to build the web app page URLs and to get the URLs of the REST service resources. I.e. I keep the http://my.rest.api/pet/678 URL somewhere with a new key, say 3, and generate the web page URL as http://my.web.app/pet/3. This looks like a HTTP Cache implementation of some sort. I don't know why, but it seems weird to me.

Or Does it all mean that RESTful APIs cannot serve as backends for web applications?


问:
How to avoid giant glue methods?
In my current job, I've been tasked with cleaning up old code a few times.  Often the code is a labyrinth and the data behind it is even more tangled.  I find myself combing out things into nice, neat, modular methods.  Each method does one thing and does it well.  That's when things start to go south...

Invariably, I end up with a clean API and no real way to tie it all together.  The solution has been to write a big ugly "glue" method (generally full of conditional statements) that eventually calls all of my "clean" methods.

The glue method usually ends up being a terse version of the tangle of code/data that I was attempting to clean up.  It's generally more readable, but it's still annoying.

How can I avoid such methods?  Is this a symptom of the tangled data or a reflection of something that I'm doing wrong?

答:
Basically, you keep adding abstraction layers, until it looks right at each layer taken on its own.  The paradoxical thing about abstraction is you add complexity to reduce it, because when you read abstracted code, you only concern yourself with one layer at a time.  If each layer is small enough to be easily understood, it doesn't matter how many layers it's resting on.

That's also what makes abstractions difficult to write.  Even something as simple as a pencil is mind bending if you try to hold all its layers of abstraction in your head at once.  The key is to get one layer the way you like, which you have done, then forget all the complexity that underlies that layer and do the same thing on the next level.

Title: How to avoid giant glue methods?


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

Let's take the following example:

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

I would like to write something like:

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

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

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

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

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

答:
You should look into Deferreds.

You can implement your functions and execute them sequentially, regardless of the fact the the code inside the function is async. Once the first finishes the second will be triggered and so on.


问:
Rules about the concreteness of method parameter types, return types and property types
Some time ago I read a kind of "rule of thumb" about the concreteness of method parameter types, return types and property types, but I just do not remember it.

It said something about keep your return types as concrete as possible and your parameter types as abstract as possible... or vice versa.

I don't know if it was actually a good or bad advice, so if you have your own thoughts about it, please let a comment.

Cheers.

答: Having abstract inputs and concrete outputs makes your function more general. This means it can be used in more ways. On the other hand it puts stronger constraints of your method, limiting how future implementations of it might work. So it's a trade-off between different goals.</p>


答:
Require no more, promise no less.

The phrase comes out of "Design by Contract" ideas pioneered by Bertrand Meyer.

http://wiki3.cosc.canterbury.ac.nz/index.php/Design_by_contract

Also see the "Liskov substitution principle"

https://stackoverflow.com/questions/56860/what-is-the-liskov-substitution-principle

Title: Rules about the concreteness of method parameter types, return types and property types

Body:
Some time ago I read a kind of "rule of thumb" about the concreteness of method parameter types, return types and property types, but I just do not remember it.

It said something about keep your return types as concrete as possible and your parameter types as abstract as possible... or vice versa.

I don't know if it was actually a good or bad advice, so if you have your own thoughts about it, please let a comment.

Cheers.


答:
If you you don't mind adding a compilation step to your workflow, you can look towards using one of the sync-to-async compilers from this list:

https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS

(go to the "Synchronous to Asynchronous JavaScript Compilers" section)

Using a library based solution is OK most of the time but using an async-aware dialect will make the code as "sync-like" as possible. (this is most noticeable if you have lots of loops or jumps, like return or break statements. In those cases it can be annoying to write things using continuations)

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

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

Let's take the following example:

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

I would like to write something like:

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

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

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

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

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


问:
Mock up class object
For example I have class ItemDownloader which has method downloadItem. This method creates instance of another class - Download to perform actual downloading.

Question is: I want to test ItemDownloader in isolation, so I will probably mock up Download. How should I do it?

P.S.: Question is more about design than implementation, I can certainly mock up class object in languages like Smalltalk or Objective-C, or use Prototype pattern in C++. But as I understand there is better solution.

答:
I believe you're talking about Dependency Injection: the act of passing in a dependency to a class that requires it, via a constructor, a property, or a method parameter.

In your case this means not constructing the Download class directly in the ItemDownloader class, but passing it into the ItemDownloader class via the constructor, property or method parameter. You would then mock the Download class and pass the mocked version.

There's plenty of information about DI on the web, here for example.

Title: Mock up class object


问:
Should we use python 2.6 or 2.7 or 3.x?
The version of python which I am using is 2.6, and there is a 2.7 and 3.x. Usually I use python for some trivial program/snippet. I realize there are some major difference between 2.x and 3.x. I would really like to know, if I am going to make a bigger project with python, which version of python should I use?

Should I upgrade to 2.7, or go to 3.x or stay with 2.6?

The decision should be based on these terms:

Number of user in the internet as a community. More users mean more open-source package and help from them.

Functionality.

Support from official development team.

Compatibility for existing module/package.

Thanks!

答:
Django now "experimentally" supports Python 3.2+ as you can see from their posts here.

Given that, and the fact that Python 3.x is the future of the language, I would say Python 3 is best now.

Title: Should we use python 2.6 or 2.7 or 3.x?


答:
If I understand you right, you are talking about piping async calls.

This can be done with so-called Deffered objects, as @rusev mentioned. Here is an example combining blocking and async stuff together:

```<code>var dfd = $.Deferred();

dfd.pipe(function (data) {
    // Normal blocking computations...
    var result = data.a + data.b;
    var output = $('<p>').text('Add: ' + result);
    $('body').append(output);

    return result;
}).pipe(function (data) {
    // Async AJAX call...
    return $.post('/echo/json/', { json: '{ "value": ' + data + ' }' });
}).pipe(function (data) {
    // Again some normal computations...
    var result = data.value * data.value;
    var output = $('<p>').text('Square: ' + result);
    $('body').append(output);

    return result;
}).pipe(function (data) {
    // AJAX...
    return $.post('/echo/json/', { json: '{ "value": ' + data + ' }' });
}).pipe(function (data) {
    // Normal...
    var result = data.value + 1;
    var output = $('<p>').text('Increment: ' + result);

    $('body').append(output);
});

dfd.resolve({a: 1, b: 2}); // Initial values
</code>```

http://jsfiddle.net/sRFRC/

As yu can see, data is passed sequentially from one callback to another, but you don't have to write it in a nested fashion.

Body:
If I understand you right, you are talking about piping async calls.

This can be done with so-called Deffered objects, as @rusev mentioned. Here is an example combining blocking and async stuff together:

var dfd = $.Deferred();

dfd.pipe(function (data) {
    // Normal blocking computations...
    var result = data.a + data.b;
    var output = $('<p>').text('Add: ' + result);
    $('body').append(output);

    return result;
}).pipe(function (data) {
    // Async AJAX call...
    return $.post('/echo/json/', { json: '{ "value": ' + data + ' }' });
}).pipe(function (data) {
    // Again some normal computations...
    var result = data.value * data.value;
    var output = $('<p>').text('Square: ' + result);
    $('body').append(output);

    return result;
}).pipe(function (data) {
    // AJAX...
    return $.post('/echo/json/', { json: '{ "value": ' + data + ' }' });
}).pipe(function (data) {
    // Normal...
    var result = data.value + 1;
    var output = $('<p>').text('Increment: ' + result);

    $('body').append(output);
});

dfd.resolve({a: 1, b: 2}); // Initial values

http://jsfiddle.net/sRFRC/

As yu can see, data is passed sequentially from one callback to another, but you don't have to write it in a nested fashion.


答:
It could be you heard an extrapolation of Postel's law:  "Be conservative in what you send, liberal in what you accept."

Mostly it's about maximizing code reusability.  It's easy to come up with cases to demonstrate why it helps.  Consider Java's Iterable<T> as an example.  If the only thing your method does is iterate through all the Ts, having an Iterable<T> as your parameter type allows you to use that method with over 60 built-in classes, not to mention any custom classes that implement the interface.  If you limited it to, say, Vector<T>, then any code that calls your method would have to convert to a Vector<T> first.

On the other hand, returning an Iterable<T> from a method limits the amount of code that can use your return value to those that take an Iterable<T> parameter.  If you return a very concrete type, like Vector<T>, then your return value can be passed into any method that takes a Serializable, Cloneable, Iterable<T>, Collection<T>, List<T>, RandomAccess, Vector<T>, AbstractList<T>, or AbstractCollection<T>, and it will work as expected.


答:
I agree with Greg that dependency injection will help solve a lot of your troubles.

Here's a general idea of what your class looks like currently (just a guess):

public class ItemDownloader {
    public void Download(){
        var download = new Download();
        download.Start(); // Or whatever is done with the downloader
    }
}
```

<p>Now if we were to refactor it to take the download as a dependency (I also used the factory pattern here as I assume you are not reusing your single download object each time the Download method is called) it becomes much easier to test without worrying about the implementation of the actual Download class.</p>

<pre class="lang-cs prettyprint-override"><code>public class ItemDownloader {
    private DownloadFactory _downloadFactory { get; private set; }

    public ItemDownloader(DownloadFactory downloadFactory) {
        _downloadFactory = downloadFactory;
    }

    public void Download(){
        var download = _downloadFactory.CreateDownload();
        download.Start();
    }
}

public class ItemDownloaderTests {
    public class TestWithMockDownloadFactory(){
        var fake = new Mock<DownloadFactory>();
        /// Logic to setup the fake as needed would go here.
        var systemUnderTest = new ItemDownloader(fake.Object);
    }
}
</code>```

Title: Mock up class object

Body:
For example I have class ItemDownloader which has method downloadItem. This method creates instance of another class - Download to perform actual downloading.

Question is: I want to test ItemDownloader in isolation, so I will probably mock up Download. How should I do it?

P.S.: Question is more about design than implementation, I can certainly mock up class object in languages like Smalltalk or Objective-C, or use Prototype pattern in C++. But as I understand there is better solution.

Body:
I agree with Greg that dependency injection will help solve a lot of your troubles.

Here's a general idea of what your class looks like currently (just a guess):

public class ItemDownloader {
    public void Download(){
        var download = new Download();
        download.Start(); // Or whatever is done with the downloader
    }
}

Now if we were to refactor it to take the download as a dependency (I also used the factory pattern here as I assume you are not reusing your single download object each time the Download method is called) it becomes much easier to test without worrying about the implementation of the actual Download class.

public class ItemDownloader {
    private DownloadFactory _downloadFactory { get; private set; }

    public ItemDownloader(DownloadFactory downloadFactory) {
        _downloadFactory = downloadFactory;
    }

    public void Download(){
        var download = _downloadFactory.CreateDownload();
        download.Start();
    }
}

public class ItemDownloaderTests {
    public class TestWithMockDownloadFactory(){
        var fake = new Mock<DownloadFactory>();
        /// Logic to setup the fake as needed would go here.
        var systemUnderTest = new ItemDownloader(fake.Object);
    }
}


问:
How productive is an excellent developer compared to an average one?
I believe that I read somewhere that Google has a rule of thumb that an excellent developer is around 300 times more productive than an average one. Does anyone have any rules of thumb used by large companies or maybe there are even some empirical studies on this?</p>

答:
It's certainly not a linear scale.
I do believe a good developer (strong SOLID OO) is much more worth the money than average developers - but it depends on what the client needs.
If the code is likely to be changing or reusable in the future - then definitely get 1 strong (and expensive) developer. If the code is short term and will be disposed off ... get a few copy&paste / spaghetti developers.
[13yrs experience as OO developer]</p>


问:
What kind of abstraction/SoC should I use here?
I am starting a new project, and I want to follow the separation of concerns pattern, and I have been reading on the topic, and now I am in doubt of how I should go about this.

Here is how I thought I should go about it:

Application/Presentation Layer uses the Business Layer. Works with the entity interfaces.

The Business Layer uses the Data Access Layer (repositories, models/entities). Works with the entity interfaces.

The Data Access layer works with the Database, and is using an OR/M solution - the solution itself may change. Works with the entity implementations, but returns interfaces to the business layer.

The business layer would get a specific repository implementation injected. The repository would return entities in the form of Interfaces, so the business layer would not care what kind of OR/M we use. If we decided to switch from using e.g LLBLGen to NHibernate, we would do the following:

Code a new set of entity classes to be used with NHibernate, because the entities we have were generated by LLBLGen.

Create a new repository implementation that worked with the new entities + framework.

Switch out the repository implementation being injected into the business layer with the new one - the repository works with interfaces, so business layer could remain unchanged.

The main point of interest (pain) here, apart from having to modify the generated entities to implement our model interfaces, is that we have to create entirely new entities just because we are switching frameworks. The same would be necessary if we switched out the datasource to something the OR/M didn't support.

This is the way I've been doing it (because hey, auto-generating your entities is how you get all the ladies, right?), but then I came across this excellent article!

Here is how I think I should go about it now

Entities are stored in a separate namespace/project - MyProject.Model

Application/Presentation Layer uses the entities in MyProject.Model to display stuff. Uses Business Layer to retrieve/save them.

Business Layer also uses entities in MyProject.Model. Uses a repository from Data Access Layer that gets injected, depending on what OR/M we are using

Data Access Layer uses the OR/M frameworks with code-first, so we can work with MyProject.Model regardless of what OR/M, or even Data Source we are using.

Pro's and con's for solution 1:

Pro: Can use Database-First to auto-generate entities. Timesaver!

Pro: Works with interfaces for entities

Con: Works with interfaces for entities (this may be too much abstraction?)

Con: Have to use an entirely new set of entities to implement a new OR/M or Data Source. They need to be modified to conform to my interfaces, chances are they can't because of how they do relationship-management.

Pro's and con's for solution 2:

Pro: Write entities/models once, use for any DAL implementation

Pro: No need to use interfaces for entities

Con/Pro: Stuck with code-first for every OR/M. On the other hand, gives you full-flex on how you want them to look.

Con: Some framework (e.g EF) are simply easier to get rolling with when using DB First.

I had more pros and cons before, but I lost them again..

Conclusion: What solution would you pick, and why? Or do you have an even better solution?

Please don't close as "not a question", because I really need an answer. Thank you.

答:
Option 2 is certainly better in my view.

The models project carries all the entities and these are clean representations of your data in the application.

In your data layer project (which has a reference to your models project), you would implement repositories abstracted to interfaces, which return instances of your entities. The business layer then takes a dependency on these interfaces, and so has no interest in the implementation of the repo's or the ORM or the DB and is not impacted if those change.

You'll then have some kind of mapping to do, or what you're calling "Code First". That is, the mapping between the clean entities and the database tables. This mapping stuff could also live in your data layer project, and be swapped out per ORM/db provider.

Doing "Db First" or using code gen to make your entities is a neat trick, but in my experience creating a DB properly, application models properly, and mapping one to the other properly, is much more robust, less problematic, and doesn't take that much longer.

If portability across data sources, and keeping application entities clean (that is, they don't inherit from stuff, and don't have a crazy attribute count) are things you value - and you like massive speed and ease of use as well - have a look at Dapper. I've been using it successfully against SQL Server and Oracle for a long time, and can't recommend it highly enough.

OwnerDisplayName: Jeff


问:
Why different testing methods are so contradicting topic?
There are a lot of very smart and experienced people, who claim that if you don't write unit tests then your code will be buggy and God will kill all kittens. On other hand, another bunch of smart people will say that unittesting is counterproductive. So if you will write unittest then kittens will be damned too.

Also, I heard very good arguments on both sides for and against integration testings, for and against TDD.

Also, there are lot of popular open source projects. Some of them use some automated testings and some of them not.

So, why different testing methods are so contradicting topic?

Update 1

I wrote couple of examples of anti-unittesting sentiments in comments. However, just to be clear there are A LOT of very successful open source projects which doesn't have unittests. This implies that not everybody thinks that unittests are useful.

Update 2

As soon as we start discussing some particular piece of testing (as example mocking, which came up in the comments), we immediately try to distinguish between being a core value or a mean. However, testing by itself isn't a core value. It's just a way to decrease support cost, which in it's turn, just a way to increase profitability. So, as I see it - unittests are something like 4 connections aways from a profit.

Update 3

It's interesting that amount of people in "balanced" camp is quite small. Most of people have really strong opinion on this topic.

答:
The people who believe in unit testing fall into two camps. The "Having good coverage saved my ass from a bug that would have been a show stopper if that test wasn't there" camp and the "Everyone says Unit Testing is a good thing and so I say it is too." (Usually the second camp is paying lip service and not doing TDD until one day they decide to really do it and inevitably transition to the first camp).

The people who don't believe in unit testing see more detriment (extra time writing and maintaining unit tests) than benefit (possibility of catching bugs early).

What they fail to realize is the freedom TDD gives you to maintain/update/change your code. Knowing that you can verify that the change you made didn't create an unwanted side effect by running your unit test suite allows you to make changes more rapidly. In essence you're paying an up front cost to build the tools that will allow you to go faster as the project grows.


答:
I try to take a balanced approach.  On my personal projects, when company policy doesn't mandate tests, I don't test everything, but I will add unit tests the second time I fix a similar bug.  Complex areas of my code end up with very good coverage, and the rest of the code is hardly covered at all.  Perhaps that makes me a neutral party, if such a thing is possible in such a polarized topic.

I see the differences as simple personality conflicts.  Some methods work better for some people.  Testers like the methodical structure being added, and consider the time it takes to write and maintain tests as offset by productivity gains.  The manual double checkers have good instincts and don't tend to find many additional bugs with unit testing, and therefore consider the time it takes to write and maintain tests as not adding much value, especially since they tend to manually double check anyway.

Title: Why different testing methods are so contradicting topic?

Body:
There are a lot of very smart and experienced people, who claim that if you don't write unit tests then your code will be buggy and God will kill all kittens. On other hand, another bunch of smart people will say that unittesting is counterproductive. So if you will write unittest then kittens will be damned too.

Also, I heard very good arguments on both sides for and against integration testings, for and against TDD.

Also, there are lot of popular open source projects. Some of them use some automated testings and some of them not.

So, why different testing methods are so contradicting topic?

Update 1

I wrote couple of examples of anti-unittesting sentiments in comments. However, just to be clear there are A LOT of very successful open source projects which doesn't have unittests. This implies that not everybody thinks that unittests are useful.

Update 2

As soon as we start discussing some particular piece of testing (as example mocking, which came up in the comments), we immediately try to distinguish between being a core value or a mean. However, testing by itself isn't a core value. It's just a way to decrease support cost, which in it's turn, just a way to increase profitability. So, as I see it - unittests are something like 4 connections aways from a profit.

Update 3

It's interesting that amount of people in "balanced" camp is quite small. Most of people have really strong opinion on this topic.


答:
So, why different testing methods are so contradicting topic?

What's the old joke? "The only people who don't love it are those who haven't tried it."

I don't mean to be snarky, but I don't know of anyone who worked in an environment where there was ubiquitous, small, isolated, speedy, repeatable, maintained automated tests and then argue against their utility in non-throwaway code.

That said, there are many developers who have worked in environments where one or more of those criteria failed. Tests suck when they're not trustworthy. They suck when they take forever. They suck when they're fragile. There are tons of ways to say you're doing unit tests, and not actually do unit testing.

So yeah, many smart people will argue against what they know to be unit testing, which is a huge waste of time. Mostly though, the arguments I get against unit testing are from older developers than even me - "we've made quality software for decades without unit tests". They fail to see the costs needed to achieve that quality, or how much more quality software they could have made by spending less time doing integration and bug hunting.


问:
Is every page a new view?
I just started building an iOS app and wanted to get some feedback regarding views.

I've got specs for

```<code>Activity Page
Activity Recording
Activity Create
Activity Save
</code>```

Each of the specs show a different function, but would each of these be a brand new view in my iOS app?

答: In general, yes, each different "page" of your application is a different view. Each view will probably want its own view controller (subclass of UIViewController), too.

Title: Is every page a new view?


答:
It is better to have it as separate screens. You can use different view controllers for different screens. But if any of the features such are too small or you dont have much to fill the screen, you can add it on the main screen(for eg:- reordering of activities).

In order to connect these screens, you can use UITabbarController if the screens are completely independent of each other. In case they are dependent, use UINavigationController and/or modal view controllers.

Title: Is every page a new view?

Body:
I just started building an iOS app and wanted to get some feedback regarding views.

I've got specs for

```<code>Activity Page
Activity Recording
Activity Create
Activity Save
</code>```

Each of the specs show a different function, but would each of these be a brand new view in my iOS app?


答:
My first IT job was as a manual tester on an application.  Within two months, I moved to an automated front-end tester.  Now, on my app work, I write Unit tests to test my code.  In my short career, I've pretty much been all over the app testing horizon.

The reason I bring that up is because every type of testing has value.  On the first app with my first employer, we had an app with 670k lines of code, and only moderate Unit Testing coverage, which pretty much justified that job.  That being said, a fair number of bugs we discovered and documented had a Unit Test created for them.  Contrast to my current job; a project I am currently working on has < 2k lines of code, yet about 80% unit test coverage.  Our testers haven't yet pounded away on it, yet I have a feeling that when they do, my team will still have our share of suprises.  It's inevitable.

The problem with any type of testing is, it can never be 100% complete.  You will asymptotically close on 100% coverage through any venue; the closer you get to a fully testable application, the closer you are incapable of getting to a fully-testable application.  That thought in mind, I've grown to adopt the mindset of, 'what does a particular type of testing do to ensure the quality of my app?'

Unit Testing: Ensures that internal dependencies and complex interactions work as designed.

Automated Front-End Testing: Regressively ensures that recent changes don't break known-good features

Load/Performance Testing: Discovers issues that arise from large numbers of concurrent users.*

Manual Front-End Testing: Discovers issues that arise as a result of emergent behavior.

I have actually found bugs from executing Load Testing.  Actually, you'd be suprised what you can find with a well-formed Load/Performance Test.

Answer to original question: both 'camps' make the same argument that some of us have encountered through blood, sweat, and tears: any sort of testing has its limits.  However, those two camps you encountered are mutually wrong, because to ensure quality, all testing is necessary testing.

I think the controversy comes from resources.  Not everyone has resources to perform all types of testing, yet I think we all know at some level that it would really help if we did.  I see the problem of this controversy is less one of technology, and more one of the human element.

No kittens were harmed in the acquisition of this experience.


答:
Don't worry about the URLs, worry about the media types.

See here (third bullet point in particular).

A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types...

In the case of a typical web app, the client is a human; the browser is just an agent.

So an anchor tag like

```<code>          <a href="example.com/foo/123">click here</a>
</code>```

corresponds to something like

```<code>          <link type="text/html" rel="self" href="example.com/foo/123">
</code>```

The URL is still opaque to the user, all she cares about are the media types (e.g. text/html, application/pdf, application/flv, video/x-flv, image/jpeg, image/funny-cat-picture etc). The descriptive text contained in the anchor (and in the title attribute) is just a way of extending the relationship type in a way that is intelligible to humans.

The reason you want the URI to be opaque to clients is so that you reduce coupling (one of the primary goals of REST). The server can change/reorganize the URIs without affecting the client (as long as you have a good caching policy -- which might mean no caching at all).

In Summary

Just make sure the client (human or machine) cares about the media types and the relations rather than the URLs and you'll be fine.

Title: A Web application as a REST API client: how to handle resource identifiers

Body:
Don't worry about the URLs, worry about the media types.

See here (third bullet point in particular).

A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types...

In the case of a typical web app, the client is a human; the browser is just an agent.

So an anchor tag like

          <a href="example.com/foo/123">click here</a>

corresponds to something like

          <link type="text/html" rel="self" href="example.com/foo/123">

The URL is still opaque to the user, all she cares about are the media types (e.g. text/html, application/pdf, application/flv, video/x-flv, image/jpeg, image/funny-cat-picture etc). The descriptive text contained in the anchor (and in the title attribute) is just a way of extending the relationship type in a way that is intelligible to humans.

The reason you want the URI to be opaque to clients is so that you reduce coupling (one of the primary goals of REST). The server can change/reorganize the URIs without affecting the client (as long as you have a good caching policy -- which might mean no caching at all).

In Summary

Just make sure the client (human or machine) cares about the media types and the relations rather than the URLs and you'll be fine.


答:
To understand where the two wildly different viewpoints come from, you need to have some understanding of history.

The concept of unit testing originated in the Smalltalk community.  There are a lot of differences between Smalltalk and the languages that most people build large projects with these days, but the relevant one here is that Smalltalk is dynamically typed.  And specifically (so that this doesn't end up turning into a static-vs-dynamic flamefest, which is not the intention here,) it has no compiler capable of verifying type correctness prior to execution.  This is the primary problem that unit testing was originally created to solve: catching details like type errors that the compiler would have caught for you, if you'd been able to use one.  And that makes a lot of sense, when you don't have a compiler available.

The problem is, a bit later down the line, a bunch of Java folks (who did have a compiler and a strict type system available) heard about the idea.  Only they didn't really understand it, most likely because the problem it's designed to solve does not exist in Java.  They thought, "oh, look at this! We can test our software's functionality before we use it, and that will help catch bugs!" even though the type of bugs that unit testing was invented to catch don't happen in Java.

Java being very popular, the idea got picked up and spread quickly, and the claims about it continued growing more and more grandiose, until eventually we ended up with ridiculous things like Uncle Bob claiming that, if you write all your code with a proper testing methodology:

think about what would happen if you walked in a room full of people
  working this way. Pick any random person at any random time. A minute
  ago, all their code worked.

Let me repeat that: A minute ago all their code worked! And it doesn't
  matter who you pick, and it doesn't matter when you pick. A minute ago
  all their code worked!

Just in case you didn't catch the claim there, unit testing is supposed to be a magical thing that will make all your code work!

This is complete nonsense, of course.  If all of your tests pass, that means that all of your tests pass, nothing more, nothing less.  And specifically, it does not mean that:

your tests correctly describe what the code is supposed to be doing in the first place

your tests cover every possible error case

your tests, being code too, are free from errors themselves.  (Follow that one to its logical conclusion and you get stuck in infinite recursion. It's tests all the way down!)

Also, bear in mind that your unit tests only cover the things you thought to write tests for.  These are, of course, the things that were on your mind when you were writing them, areas where you anticipated would likely cause problems.  These are areas you're paying attention to, which you're likely to get right in the first place.  As any experienced developer will tell you, the majority of bugs (not all, of course, but a good majority) come from cases you never anticipated, which is why they turn out buggy.  Tests are far less useful there.

There's another serious problem with unit testing, one of those issues that you don't really notice as a problem until your project gets really big and then it's too late, which is that changing requirements requires changing code, which breaks your tests.  Sometimes it can break a non-trivial fraction of your tests, like 10% of them.  And if you follow Uncle Bob's advice and write "every year... thousands of tests" like he exults about, eventually you have a whole lot of tests, enough that 10% of that whole lot is still a whole lot.

And the thing is, you just intentionally changed something.  Unit testing is supposed to help you not accidentally make a change that breaks something, but you just changed something intentionally.  And now you have hundreds or thousands (or more) of failing tests screaming at you, and you have to go through each one and individually, manually verify whether or not that test is still valid according to the new requirements.  (And for the ones that aren't, you might well have to write new tests to replace them!)

And the interesting thing is, long before Uncle Bob started making his ridiculous claims about unit tests magically making all your code work, long before unit testing spread to Java and from there to the rest of the programming world, long before Java even existed in the first place, the whole concept was already known to be a silly idea by people who actually understood programming!

It is now two decades since it was pointed out that program testing
  may convincingly demonstrate the presence of bugs, but can never
  demonstrate their absence. After quoting this well-publicized remark
  devoutly, the software engineer returns to the order of the day and
  continues to refine his testing strategies, just like the alchemist of
  yore, who continued to refine his chrysocosmic purifications.

-- Edsger W. Djikstra.  (Written in 1988, so it's now closer to
  4.5 decades.)

The reason why there are two wildly different viewpoints out there regarding unit testing is that some people have enough perspective, and enough knowledge of history and/or of the fundamentals of computer science and engineering, to understand these principles and see the basic truth behind all the snake oil.

And some people don't.  What they see is that on some small project they've been working on, at some point they happened to catch a nasty bug one time with an automated test.  Or they know someone who did.  Personal experiences loom large in our memory--that's basic human psychology.  That's the thing that they really remember, and so they think it has to be some wonderful, magical thing, logic and reason notwithstanding.

They hold to the concept of unit testing with dogmatic fervor, and like any dogma, its Absolute Truth is necessarily stronger than any fact.  Just look at how often TDD proponents pull out the old "if you don't like it/if it doesn't work for you, you must be doing it wrong" argument when confronted with the facts.  That's not a logical argument; that's an emotional attack meant to shut down logical discussion.  And it works far too well (again, basic human psychology,) which is why people keep using it.


问:
Dependency Injection - Dependency Chain Pattern
On my last large project, I used dependency injection really heavily. I started out using constructor injection but even two or three dependencies resulted in really ugly code.

```<code>public MyClass(
    IDependency1 dependency1,
    IDependency2 dependency2
    IDependency3 dependency3)
</code>```

I am not a fan of property injection. Some people say it implies an "optional" dependency. I think what they mean is that there will be a default dependency (the production class) but it can be replaced with a mock object during test. Many times, my dependencies have dependencies, too, so I can't provide a default value unless I used a singleton or something. My problem with property injection is that I prefer fully initialized objects and don't want to accidentally forget to mock out a dependency during test.

So, I found a compromise. I created a "parameter object" that had properties for all of my dependencies. I passed these to my constructors. This had the benefit of keeping my code somewhat cleaner and I could ignore some dependencies during test if they weren't touched.

Based on feedback I got the impression this was a bad idea. It was constructor injection or parameter injection - no compromise allowed. Later I realized that these parameter objects sometimes became their own classes (or set of classes).

That's when I discovered an interesting pattern. Many business objects depended on other business objects, which had their own dependencies. What I ended up with was an interesting data structure, similar to a linked list.

This data structure could become fairly complex depending on the number of interacting classes. In most cases, the structure was closer to an n-ary tree. Each parameter object could link to any number of other objects (including other business objects). The business objects were the nodes of the tree and the parameter objects were like the edges connecting them.

I think connecting all these objects together without using a declarative dependency injection framework would be mind-numbing. The dependency injection framework I was using was going 8 levels deep in my code building the dependencies from the bottom up in the worst case.

The parameter objects usually just exposed the dependencies. On rare occasions, I would hide them behind friendly function calls and made them their own business objects (usually resulting yet another parameter object). I had to remind myself that the parameter objects only existed because I didn't want to construct dependencies in the constructor (or pass them to the constructor). It only made sense to create new business objects when I started repeating myself. Even then, I ended up with an explosion of parameter objects.

I've read plenty of books explaining that this situation should never happen. Classes should have very few dependencies. It was a sign that my classes did "too much". But in most of these cases, a business object used data from multiple database tables (repositories), configuration settings, services, etc. in order to calculate something. This occurred most often when implementing a series of steps making up a unit of work. When N things are needed to do a task, the best you can do is push those N things to other classes or on up the call stack. Is one class with 6 dependencies better or worse than 3 classes with two dependencies each?

I am hoping to get some feedback on this approach to dependency injection - in how it relates to architecting a business layer.

答:
To be perfectly honest, the intermediary "Parameter" classes seem like a bit of over-engineering here. You're introducing code that deepens the object graph and actually hides the dependencies.

When using a container you can set up your environment so that whatever object you need is actually created by the container with all of it's dependencies.
What I usually do is set up the infrastructure or framework so that whenever I'm in the actual application code, all my dependencies are already set.
I'll set up my testing environment in the same way, so that there's no way I'll forget a dependency.

When using a framework like Asp.Net MVC, this means setting the framework up so that each controller is actually resolved by the container. The controllers here are the entry point to the application. Since the controllers will have dependencies to various repositories and services, the container will also resolve those and their dependencies, however deep the graph is.

This means that, if I'm careful not to blindly instantiate a service or repository I'll always have objects which are completely ready to do their work, whether the dependencies are set via constructors or setters.

With some planning, the app layer (controllers/viewModels/views) and the business layer (repositories/services) can live within an infrastructure where you never have to instantiate a service using the new operator, or even resolve it using the container (which is better, but if not used carefully can lead to problems, where you introduce unnecessary dependencies to the container itself).

About setter vs constructor injection, I disagree that setter injection implies optional dependencies. They are dependencies just like the rest, and are very useful when you have a hierarchy of classes in which constructor injection would mean dragging parameters through multiple levels of constructors until finally setting the dependency in some base class. Of course, they have their trade-offs, specifically, that with setter injection, you have to be careful with your constructor logic, which IMO, should be kept to a minimum, outside of setting up the object.