问:
Where to Populate Objects
As mentioned in this question, I am moving our team towards objects (as opposed to just throwing DataTables and variables around everywhere).  I have picked a suitable spot for the project that contains the object definitions, but not sure how I should go about populating some of the objects.  In particular, what do I do with classes as properties?

```<code>Public Class Class1
    Public Property SomeProperty As String
    Public Property SomeOtherProperty As String
    Public Property SomeKey As Integer
    Public Property Foo As Class2
End Class
</code>```

In this basic example, I can easily populate the first three properties from a query, but Foo has its own set of properties.  Right now, to create a List(Of Class1) I generate the data for all of the Class1 objects, and then use SomeKey to go back and, one object at a time, populate all of the Foo.  Certainly this works, but in my case it is rather slow, and it seems that perhaps I am simply doing it wrong.

Am I handling that incorrectly?  If so, what should I be doing?  The only other thing I can come up with is to create a query (or stored procedure) that returns all of the appropriate data for all of the objects.  In my test case that amounts to a list that contains 154 Class1's, with each of them having four properties like Foo, and some of those having classes as properties.

答:
To work with entities, you really should be using either Linq-to-SQL, or Entity Framework. There other ORMs but few are really worth it, they have nothing real to offer over EF6. To do this, you first create a model (or multiple models) of your datasources, and then use that model to query the data source through Linq queries. The ORM acts as an abstraction layer between the data provider and your language of choice. For example, in Linq to SQL, your example object would be queried like so:

```<code>' First you instanciate your context. This is the virtual connection to the database. You
' are actually connecting to your data model here, the connection to the database is only
' made when there is actually a query executing.
Using db As New MyDataModel

    ' Then you define your query. Linq queries work in defered execution. They
    ' are only executed when they are actually used. The type returned is an
    ' IEnumerable(Of Class1)
    Dim c1s = From c1 In db.Class1s
              Where c1.SomeProperty = someValue
              Select c1

    ' The objects retrieved maintain their relational model as well, so accessing
    ' the Foo property is as simple as using the navigation property provided by
    ' the ORM. All of the relationships are taken care for you in the background.
    For Each c1 In c1s
        Console.WriteLine(c1.Foo.SomeProperty)
    Next

    ' Navigation properties are essentially joins, links implemented by the relationships
    ' defined in your object relational model. The following example would be this SQL:
    ' SELECT c2.* FROM Class1s c1 INNER JOIN Class2s c2 ON c1.SomeKey = c2.SomeForeignKey
    Dim c2s = From c1 In c1s Select c1.Foo

End Using
</code>```

In short you would NEVER populate your object like you were describing, except in cases where you need a flattened output from a query, but even then you would use anonymous types.

```<code>' You can also select specific elements from a relationship through anonymous types
' Here we just define the output type as we go. This is the equivalent to selecting
' individual fields in a SQL select.
Dim anonTypeObj = (From c1 In db.Class1s
                   Select New With {.c1SomeProperty = c1.SomeProperty,
                                    .c2SomeOtherProperty = c1.Foo.SomeOtherProperty}).First

Console.WriteLine(anonTypeObj.c1SomeProperty & " : " & anonTypeObj.c2SomeOtherProperty)
</code>```

Title: Where to Populate Objects

Body:
To work with entities, you really should be using either Linq-to-SQL, or Entity Framework. There other ORMs but few are really worth it, they have nothing real to offer over EF6. To do this, you first create a model (or multiple models) of your datasources, and then use that model to query the data source through Linq queries. The ORM acts as an abstraction layer between the data provider and your language of choice. For example, in Linq to SQL, your example object would be queried like so:

' First you instanciate your context. This is the virtual connection to the database. You
' are actually connecting to your data model here, the connection to the database is only
' made when there is actually a query executing.
Using db As New MyDataModel

    ' Then you define your query. Linq queries work in defered execution. They
    ' are only executed when they are actually used. The type returned is an
    ' IEnumerable(Of Class1)
    Dim c1s = From c1 In db.Class1s
              Where c1.SomeProperty = someValue
              Select c1

    ' The objects retrieved maintain their relational model as well, so accessing
    ' the Foo property is as simple as using the navigation property provided by
    ' the ORM. All of the relationships are taken care for you in the background.
    For Each c1 In c1s
        Console.WriteLine(c1.Foo.SomeProperty)
    Next

    ' Navigation properties are essentially joins, links implemented by the relationships
    ' defined in your object relational model. The following example would be this SQL:
    ' SELECT c2.* FROM Class1s c1 INNER JOIN Class2s c2 ON c1.SomeKey = c2.SomeForeignKey
    Dim c2s = From c1 In c1s Select c1.Foo

End Using

In short you would NEVER populate your object like you were describing, except in cases where you need a flattened output from a query, but even then you would use anonymous types.

' You can also select specific elements from a relationship through anonymous types
' Here we just define the output type as we go. This is the equivalent to selecting
' individual fields in a SQL select.
Dim anonTypeObj = (From c1 In db.Class1s
                   Select New With {.c1SomeProperty = c1.SomeProperty,
                                    .c2SomeOtherProperty = c1.Foo.SomeOtherProperty}).First

Console.WriteLine(anonTypeObj.c1SomeProperty & " : " & anonTypeObj.c2SomeOtherProperty)


问:
Naming convention for classes that represents different versions of the same thing
Let's imagine I have an abstract class named ProtocolA that represents the basic operations to work with the protocol A. Such protocol is in version 1, but new revisions are expected in the future. Version 2 is coming. How should I name the classes that implements that abstract class for each version? ProtocolA1 and ProtocolA2?

Cheers.

答:
If you won't need to support the original version ever again, then simply overwrite the class and keep the same name.

However, I suspect if it were that simple you wouldn't be asking.

I'm a big fan of unambiguous names.  Does the protocol specification have a unique identifier?  Something like an RFC number?  If so, I'd name it something like ProtocolARfc2048.

I'd avoid a version number internal to your application, as that will get confusing.

ContentLicense: CC BY-SA 3.0


答:
Use Factory(either factory method or factory object) to accept a version number(preferably enum, but string or numbers can also work) and construct the appropriate subclass. That way, naming won't matter that much since you'll never use them directly in the code.

As for the naming themselves, if your language has namespacing you can create a namespace for each version of the protocol and give classes the same name in different namespaces.

Title: Naming convention for classes that represents different versions of the same thing

Body:
Let's imagine I have an abstract class named ProtocolA that represents the basic operations to work with the protocol A. Such protocol is in version 1, but new revisions are expected in the future. Version 2 is coming. How should I name the classes that implements that abstract class for each version? ProtocolA1 and ProtocolA2?

Cheers.


问:
How to plan for multi-platform application development
In my earlier days of programming, I was using Visual Basic for learning. It taught me many concepts, and I was able to make some cool programs (in my opinion, anyways...). I have expanded my horizon to basic C/C++, PHP, and MySQL.

One of my most favourite projects, I want to turn into a multi-platfrom (for x86/x64) windowed application, and have it open source. I decided on the license already, but I want to know, before I start developing in a new language, how can I choose which language to use, that is multi-platform, and allows for windows to be created? I do not wish to use web technologies, as the application will work with lots of local files at a time.

This is not a question about which technology is better, but about which one would be useful for this project. I know something has to be possible, because there are apps that run as Mac OSX binaries, Windows binaries, and even Linux binaries, all in windows (i.e. VLC Media Player, Firefox (Ice Wheazel), etc)

答:
It depends primarily of what platforms you're aiming at.

If you target only PC platforms (which none of is very exotic), then you have many options regarding language (C++, Java, Python, Go, etc.) and cross-platform GUI framework (Qt, GTK, SWT, Swing, wxWidgets, etc etc). Portability shouldn't be main concern when choosing a language for PC-only program (pretty much everything that is not OS-specific should be portable).

If you want to target PC and something more (web or mobile), you need higher degree of portability. Architectural style is crucial, because you want to fence off platform-specific pieces from portable code. The most popular style that addresses portability requirement is layered architecture (portable code goes into middle layer). Each layer can (and often will) be written in different language. You may want to consider structuring your code in layers even in case of PC-only program (OS-specific things will probably pop out).

Language possibilities are narrowed when targeting something more than PC. Depending on which particular platforms you're interested in, it can also make writing everything in one language impossible (unless you're prepared for writing your own compiler).

For PC and mobile, C++ is the right choice to write portable code (logic layer) in, because all mainstream mobile platforms support it. For mobile GUI - Qt or platform-specific solutions (Java, ObjC and C#). Choosing Qt can speed everything up (most of the code runs everywhere) but some low-level knowledge of Qt and mobile platforms may be required to make it work. The more GUI you have, the more profitable choosing Qt will be.

In case you want to target PC and web, you have Java, Python and Go languages. If you choose Java, you will have everything more homogenous (frameworks like GWT and Vaadin enable writing client-side code in Java). If you choose Go, you will have younger (more fresh) language than Java, that requires less boilerplate, and doesn't need VM to run (less parties involved = less problems), but you will need different language for web GUI (JavaScript or Dart).

Things get really complicated if you want your program to run on PC, web and mobile and you want PC and mobile version to be self-sufficient (working without server component). In this case there is no single language that will run everywhere. I would probably take PC+mobile approach for logic code (write it in C++) and then, either create bindings to other language available on web platform, or write server software in C++. Another possibility is to write logic in Java (PC+web approach) and then write (using LLVM) a compiler that translates java to languages available on targeted mobile platforms. Either way, extra effort is needed to make it work on third platform type.

Above list is neither exhaustive nor complete.

After choosing technologies, I recommend designing interfaces between layers, then planning the implementation.

ContentLicense: CC BY-SA 4.0


问:
Unit Testing a method that contains two output type parameters
I was following a book Art of Unit Testing, This book says that You must not have any logic in Your asserts as this reduces readability of test, or I may be testing too many things at a time. Suppose there is a method with signature as below:

```<code>public int DoSomething(int variable1, out string variable2, out float variable3)
{
...
}
</code>```

How should I test this method, as I have to assert on return value, variable2, variable3 ???

Sample Test method that tests all of these three concerns:

```<code>    public void DosSomethingTest(){
        //add code for arrange
        int expectedvalue=12;
        string expectedVariable1="I am expected";
        string expectedVariable3=15.9;
        string actualVariable1, actualVariable3;
        var sut=new Foo();
        int actualValue=sut.DoSomething(15, out actualVariable1, out actualVariable3);

        //this is where I am testing 3 concerns in one test. Is there a better way?
        if(actualValue==expectedvalue){
            if(expectedVariable1==actualVariable1){
                if(expectedVariable3!=actualVariable3){
                    Assert.Fail("Unexpected variable2 returned");//pseudo code
                }
            }
            else{
                Assert.Fail("Unexpected variable1 returned");//pseudo code
            }
        }
        else{
            Assert.Fail("Unexpected Value returned");//pseudo code
        }
    }
</code>```

Approach 2

Seperate Test methods that tests concerns separately:

```<code>    public void DosSomething_Passing15_Returns12Test(){
        //add code for arrange
        int expectedvalue=12;
        string expectedVariable1="I am expected";
        string expectedVariable3=15.9;
        string actualVariable1, actualVariable3;
        var sut=new Foo();
        int actualValue=sut.DoSomething(15, out actualVariable1, out actualVariable3);

        Assert.IsTrue(actualValue, expectedvalue);
    }

    public void DosSomething_Passing15_ReturnsExpectedVariable1Test(){
        //add code for arrange
        int expectedvalue=12;
        string expectedVariable1="I am expected";
        string expectedVariable3=15.9;
        string actualVariable1, actualVariable3;
        var sut=new Foo();
        int actualValue=sut.DoSomething(15, out actualVariable1, out actualVariable3);

        Assert.IsTrue(actualVariable1, expectedVariable1);
    }

    public void DosSomething_Passing15_ReturnsExpectedVariable2Test(){
        //add code for arrange
        int expectedvalue=12;
        string expectedVariable1="I am expected";
        string expectedVariable3=15.9;
        string actualVariable1, actualVariable3;
        var sut=new Foo();
        int actualValue=sut.DoSomething(15, out actualVariable1, out actualVariable3);

        Assert.IsTrue(actualVariable3, expectedVariable3);
    }
</code>```

Isn't approach 2 adhering to "Tests should not test more than one concern"?

Conclusion

If redesigning of SUT is possible:

There should ideally be no out parameter instead an aggregate class
should be evaluated in Asserts.

If there are unrelated out parameters then SUT method should be
refactored into multiple methods, then those new methods should have their own Test methods and they will then test only one concern.

If redesigning of SUT is not possible then as per the answer there will be three Asserts

答:
Words Of Wisdom for those brave souls who are embracing unit testing

After struggling with this question, and googling endless days, I finally came to different conclusion:

A good Unit Test should test only one concern, but it can test multiple aspects.

In my question, I am asking about multiple aspects, so it is Ok to have three asserts and may/ may not be neccessary to refactor the SUT(System under Test) method as per the given answers:

In cases where there are different concerns which essentially means:

Different inputs and their corresponding outputs

as shown below:

//Works Only in case of Nunit.

```<code> [TestCase(15, "I am expected", 15.9, 12)]
 [TestCase(17, "I am expected1", 100, 12)]
 [TestCase(18, "I am expected2", 112, 12)]
 public void DoSomething_ReturnsExpectedTest(int inputValue, string expectedVariable1, int expectedVariable3, int expectedValue){
    //add code for arrange
    string actualVariable1, actualVariable3;
    var sut=new Foo();
    int actualValue=sut.DoSomething(15, out actualVariable1, out actualVariable3);

    Assert.IsTrue(actualValue, expectedvalue);
    Assert.IsTrue(actualVariable1, expectedVariable1);
    Assert.IsTrue(actualVariable3, expectedVariable3);    }
</code>```

Body:
Words Of Wisdom for those brave souls who are embracing unit testing

After struggling with this question, and googling endless days, I finally came to different conclusion:

A good Unit Test should test only one concern, but it can test multiple aspects.

In my question, I am asking about multiple aspects, so it is Ok to have three asserts and may/ may not be neccessary to refactor the SUT(System under Test) method as per the given answers:

In cases where there are different concerns which essentially means:

Different inputs and their corresponding outputs

as shown below:

//Works Only in case of Nunit.

 [TestCase(15, "I am expected", 15.9, 12)]
 [TestCase(17, "I am expected1", 100, 12)]
 [TestCase(18, "I am expected2", 112, 12)]
 public void DoSomething_ReturnsExpectedTest(int inputValue, string expectedVariable1, int expectedVariable3, int expectedValue){
    //add code for arrange
    string actualVariable1, actualVariable3;
    var sut=new Foo();
    int actualValue=sut.DoSomething(15, out actualVariable1, out actualVariable3);

    Assert.IsTrue(actualValue, expectedvalue);
    Assert.IsTrue(actualVariable1, expectedVariable1);
    Assert.IsTrue(actualVariable3, expectedVariable3);    }


问:
Refactoring sought for replacing shared data types in .NET component
I am in charge with updating a software product that is made up of two components the Controller process and the UI process. The Controller and the UI communicate via XML messages. Furthermore, the Controller is built on top of a shared library that implements a number of business flows.

For builing the messages for Controller-UI communication, somebody decided to use .NET built-in serialization and deserialization and therefore created class types annotated with attributes that control serialization (XmlElement, XmlAttribute, etc) for each message, serializing it and deserializing it by using the default XML serializer.

For the first couple of controllers, this was fine. But now, while some of the messages can be reused, the other cannot. They will accomplish the similar functions but are structurally incompatible with the information we need them to contain.

Because this decision was made we are stuck with data-types that cannot model the data we need, and cannot be changed because they would break the other controllers. At the same time we need the functionality and messaging sequences implemented in the shared library.

I need a way out of this conundrum, one that has the smallest technical cost in relation to changing the other controllers, I need a sort of "structural polymorphism" for these types, where the type is the same but its internal structure different.

Perhaps these messages can be changed to 'object' data types, but in that case... I need a way to control from the outside of the shared library the casting that gets made inside the shared library.

How do I approach this, I am not experienced enough to find a clean refactoring for this? I feel stuck.

We are using .NET 4.5

答:
I need a way out of this conundrum, one that has the smallest technical cost in relation to changing the other controllers, I need a sort of "structural polymorphism" for these types, where the type is the same but its internal structure different.

You mean like basic inheritance? I'm not sure I see the trouble here. If you have a common set of functionality, then define an interface (or abstract base class) for that functionality. If you have different implementations of that functionality (including internally serialized members) then simply make different implementations of that interface.

You will likely need to use KnownType or other attributes to make sure that the serializer knows about the implementation types. And you may find that using a different serialization medium (json, binary) may make your life easier. But from a design approach, this seems straightforward.


问:
What could be used to get data from server to android as fast as it reaches server?
What is the best way to get data from server as fast as it gets to it? (Like instant message, or simple broadcast for example).

I first thought about using miniature web server in android and get post requests to it with data. However with this approach I soon understood that I will get many problems with NAT and similar issues.

Later I thought about manually pooling the server from android, but it seems somewhat flaky approach to problem, because data is got in irregular intervals (like image with some text).

I was thinking about using something like webrtc or rtp to have connection between server, but these approaches are somewhat complex and half baked. I found very little info on those about data operation. Thought I managed to get in my „experiments“ video and sound transfer, I found very little info how to get data transfers.

What should I do? Now I am thinking about having some connection to server and getting some events in android, which when I got update in server could download everything from server.

Update:

My data is encode64 processed html5 canvas png image. Probably I will add to it some text data to blob. It is generated on webpage it should reach phone as fast as it can through server. The problem is part where image data goes from server to phone. Data size per request is ~50KB.

答:
Depending on the device you're using, you're going to struggle. Android has a couple of problems in the design of its networking subsystem that are going to cause you grief.

The primary issue is power management. Android devices are, as a rule, mobile devices running on battery power for the majority of the time. Therefore, they conserve power as much as possible, aggressively putting the cpu to sleep whenever it hasn't been locked in an awake state. In many android devices, this causes the device to stop receiving packets on any wireless network it may be connected to. This makes a push protocol over wireless next to useless: in order for it to work you have to keep the cpu awake, which will kill the battery pretty quickly.

You may think you can solve this by not using the wireless network but connecting to your server over 3g, but this doesn't work. Android automatically prefers wireless over 3g when it is connected, and the only api that lets you use 3g by preference is only usable for short duration connections because it has a timeout that is limited to a short period (30s, iirc).

Now, if you can restrict your target device to one that supports wake-on-wlan, maybe you can make it work, but you'll find it tricky.


问:
Is it possible to get probabilities from a support vector machine?
From what I understand, SVM's take a discrete number of x and y values from which to learn from, then when given new x values map it to one y value (category). Is it possible to use SVM's or something similar to instead map x values to probabilities of y values?
Let me give you an example, say your x values are arrays of two integers: x = [[1,1],[1,0],[0,1],[0,0]], and you have two categories, a and b such that y = [a,a,b,b]. i.e. [1,1] and [1,0] map to a, [0,1] and [0,0] map to b. Given an x value of [1,0.9], the SVM would probably predict the y value to be the category a, given another x value [1,0.89], the SVM would probably still predict the y value to be a part of the a category.

This is what I am looking for: Given x and y values as specified above, the "predict" function I am looking for would return an array of tuples for each category in y of the form: (category, probability x was in category). For example, with the case above, the output would look something like this: [(a,.93),(b,.07)]

My application of this would be somewhat like a fuzzy logic system, using pseudocode:

```<code>if x is almost certainly in category a:
    do something
if x is likely to be in category a:
    do something else
</code>```

Does a system like this already have a name? If not, how would I go about implementing something like this? I'm currently using scikit-learn in Python, so if there's something like this I could do with that library, that would be the best.

答:
As far as I remember a support vector machine has a support vector w.
You would dot-multiply a sample x with the support verctor w to get a scalar value, real number. Depending on the sign (+/-) of that number you decide wether the x belongs to the class or not.

In some cases I would prefer only a mixture model. Like a gaussian mixture model.
It provides probabilities for every class.

The book by P. Flach is good.


问:
Evaluation order of expressions in Clojure?
I'm currently learning Clojure (my first functional programming language), and I'm curious as to its order of evaluation.

Here is an example:

(take 10 (cycle [1 2 3]))

If the cycle expression was not wrapped in a take expression, this would cause a memory error, as it would iterate infinitely through the vector. So, how does Clojure know that it has been wrapped with a take expression?

(If I'm using any incorrect terminology here, I'd appreciate a nudge too!)

答:
Your issue here seems to be specifically around Clojure's sequences which can be infinite.

Clojure's sequences can either be null or implement an interface called ISeq, which among other things has 2 particularly important functions, first and next.

Consider the following java class

```<code>public class LongsFrom implements ISeq{
    private Long _currentNumber;

    public LongsFrom(Long start){
        _currentNumber = start
    }

    public Object first(){
        return _currentNumber;
    }

    public ISeq next(){
        return new LongsFrom(_currentNumber + 1);
    }
}
</code>```

It represents an infinite sequence of increasing numbers starting wherever you want. As you keep calling next() on it, you keep realizing more and more of the sequence, however all you really need to keep in memory is whatever the latest object in the sequence is.

What cycle does is create an instance of a class which implements the ISeq interface (it knows how to calculate the sequence but doesn't actually do it until you start calling next). Then your take command actually starts calling first and rest on this class to get however much of the sequence it needs.

A class which actually performs cycle would only be slightly more complicated than my LongsFrom example. The cycle class could have 2 private variables, one which holds the list of things it needs to cycle through and then an integer to remember which index it's currently on. first would return the item at the current index. next would return a new cycle object with the exact same internal list, but an index of 1 + currentIndex (unless we're at the end of the list in which case we start the index back at 0)

The reason why you have memory issues if you don't have the take command is that if you don't have the take command, the repl tries to print the sequence and the default implementation for print is to keep calling first and rest until the sequence ends (which is never in the case of cycle)

Body:
Your issue here seems to be specifically around Clojure's sequences which can be infinite.

Clojure's sequences can either be null or implement an interface called ISeq, which among other things has 2 particularly important functions, first and next.

Consider the following java class

public class LongsFrom implements ISeq{
    private Long _currentNumber;

    public LongsFrom(Long start){
        _currentNumber = start
    }

    public Object first(){
        return _currentNumber;
    }

    public ISeq next(){
        return new LongsFrom(_currentNumber + 1);
    }
}

It represents an infinite sequence of increasing numbers starting wherever you want. As you keep calling next() on it, you keep realizing more and more of the sequence, however all you really need to keep in memory is whatever the latest object in the sequence is.

What cycle does is create an instance of a class which implements the ISeq interface (it knows how to calculate the sequence but doesn't actually do it until you start calling next). Then your take command actually starts calling first and rest on this class to get however much of the sequence it needs.

A class which actually performs cycle would only be slightly more complicated than my LongsFrom example. The cycle class could have 2 private variables, one which holds the list of things it needs to cycle through and then an integer to remember which index it's currently on. first would return the item at the current index. next would return a new cycle object with the exact same internal list, but an index of 1 + currentIndex (unless we're at the end of the list in which case we start the index back at 0)

The reason why you have memory issues if you don't have the take command is that if you don't have the take command, the repl tries to print the sequence and the default implementation for print is to keep calling first and rest until the sequence ends (which is never in the case of cycle)


答:
So, how does Clojure know that it has been wrapped with a take expression?

It doesn't. Lazyness is better understood like this: nothing is ever evaluated unless it's absolutely necessary. The cycle function has the semantics of "repeat things endlessly", but this doesn't actually happen until the interpreter has to prove to you, the user, that it does. If the sequence only had to produce a value, even an infinite one, it would do nothing at all, and there would be no way for you to notice. What does start the actual computation is the need to deliver something to the caller, in this case take 10. It has to know what elements to operate on, so the cycle function reluctantly produces 10 values, but no more.

The take function, in turn, only produces a value. If it were alone in the world, it might just as well not bother to do anything at all, but it's called by the REPL, which must print values onto the terminal per its contract. Ultimately, the need to print the first character of the result is what drives the entire computation. This is exactly the opposite of the traditional approach where an inner expression is evaluated to completion and then passed on to the next level.

Title: Evaluation order of expressions in Clojure?

Body:
I'm currently learning Clojure (my first functional programming language), and I'm curious as to its order of evaluation.

Here is an example:

(take 10 (cycle [1 2 3]))

If the cycle expression was not wrapped in a take expression, this would cause a memory error, as it would iterate infinitely through the vector. So, how does Clojure know that it has been wrapped with a take expression?

(If I'm using any incorrect terminology here, I'd appreciate a nudge too!)


问:
Under what license may this PyQt-based "Hello World" app be distributed?
Update: I was wrong about the PyQt license.  It isn't merely a GPL license.  The PyQt authors include a special set of exceptions that allow users to release their own code under a different license, as long as it is one of the Open-Source licenses specifically listed in the PyQt GPL_EXCEPTION.TXT file.

For the purpose of this discussion, consider the following fully-functional app, which depends on PyQt:

# hello_world.py
from PyQt4.QtGui import QApplication, QPushButton
app = QApplication([])
button = QPushButton("Hello, World!", clicked=app.quit)
button.show()
app.exec_()
```

(In case it's relevant to the discussion, please note that Python programs like this one do not require "linking" per se.)

My preference is to distribute my code under a permissive license, e.g. the BSD license.  However, PyQt is released under the GNU GPL GNU GPL with special exceptions.  With that in mind, what are my options here?  Am I obligated to release under the GPL, even if I don't distribute PyQt itself?

To be more specific, in which (if any) of the following scenarios am I permitted to release my code under the BSD license vs. being obligated to release under the GPL?

Scenario 1: I give you a fully-packaged binary that includes hello_world.py and PyQt.

Scenario 2: I give you the source code of hello_world.py and PyQt in a single download (say, a .tar.gz), but it's up to you to get them running together.

Scenario 3: I give you hello_world.py alone, leaving you to obtain PyQt on your own.

I know that most of us aren't lawyers, so it is very much appreciated if you can cite the sources your answer is based on.

答:
OK, this is easier than I thought.  The PyQt folks didn't just release their software under the vanilla GPL.  They added a special exception to the license, which allows me to release MY code under a non-GPL license.  However, not all licenses are allowed: I must choose one of the open source licenses listed in the GPL_EXCEPTION.TXT file included with the PyQt source code.  At the time of this writing, the exception permits me to use MIT, BSD, LGPL, and several others.

So, to address the specific scenarios outlined in the question above:

Scenario 1: GPL only

Scenario 2: GPL only

Scenario 3: Any license listed in GPL_EXCEPTION.TXT from the PyQt source distribution, including BSD.


问:
Using a relational database vs JSON objects for event/activity data
I am working on a project where I am trying to decide between using a standard SQL relational database or JSON objects to store data about an event or activity.

The project will store data on multiple event types so I have decided to just describe one event type for this question.

The live music event (described in full using the JSON schema at the bottom of this question) is an object that stores data such as where the event will take place, the time/date of the event and the cost of the event. The live music event object has both one-to-one (event--> name, event --> description) and one-to-many (event--> venues, event--> dates, event--> ticket types) relationships. Furthermore, the event object can contain one or more performer IDs, which link to the performer object. The performer object stores data on musicians who are performing at the live music event.

The data will be queried by users using both simple ("Find me events with 'x' name") and complex ("Find me events with 'x' music genre and 'y' cost within a radius of 'z' from my current location") queries. The data will be submitted by users using a web form.

As you can probably tell from the defined JSON schema, I was originally going to use JSON objects to store this data but I've heard from some people who say that because my data is purely relational, I should stick to the older methods.

I would appreciate any thoughts on the pros and cons of each approach given my needs. If you need anything clarified, please feel free to ask.

```<code>{
    "event": {
        "eventID":{
            "type":"string"
        },
        "eventType":{
            "type":"array",
            "eventTypeItem":{
                "type":"string"
            }
        },
        "eventName":{
            "type":"string"
        },
        "eventDescription":{
            "type":"string"
        },
        "eventVenueList":{
            "type":"array",
            "eventVenueListID":{
                "type":"integer"
            }
        },
        "eventURL":{
            "type":"string"
        },
        "eventTwitter":{
            "type":"string"
        },
        "eventFB":{
            "type":"string"
        },
        "eventInstagram":{
            "type":"string"
        },
        "eventEmail":{
            "type":"string",
            "format":"email"
        },
        "eventContactPerson":{
            "type":"string"
        },
        "eventDoorTime": {
            "type":"string",
            "format":"date-time"
        },
        "eventPerformerIDList":{
            "type":"array",
            "liveMusicPerformerID":{
                "type":"integer"
            }
        },
        "eventSetList":{
            "type":"array",
            "eventPerformerID":{
                "type":"integer"
            },
            "eventPerformerStartTime":{
                "type":"string",
                "format":"date-time"
            },
            "eventPerformerEndTime":{
                "type":"string",
                "format":"date-time"
            }
        },
        "eventDateList": {
            "type":"array",
            "eventDateItem": {
                "type":"string",
                "format":"date-time"
            }
        },
        "eventDateStartTime": {
            "type":"string",
            "format":"date-time"
        },
        "eventDateEndTime": {
            "type":"string",
            "format":"date-time"
        },
        "eventTicket":{
            "type":"array",
            "eventTicketType":{
                "type":"string"
            },
            "eventTicketLowPrice":{
                "type":"number"
            },
            "eventTicketHighPrice":{
                "type":"number"
            },
            "eventDatesAdvancePrice": {
                "type":"number"
            }
        }
    },
    "performer": {
        "performerID": {
            "type":"integer"
        },
        "performerType": {
            "type":"string"
        },
        "performerName": {
            "type":"string"
        },
        "performerAlternateName": {
            "type":"array",
            "performerAlterateNameItem":{
                "type":"string"
            }
        },
        "performerGenreList": {
            "type":"array",
            "performerGenreItem":{
                "type":"string"
            }
        },
        "performerURL": {
            "type":"string"
        }
    }
}
</code>```

答:
I think you will have better success with using NoSQL than SQL for storing this data, because of the queries you need to do.

Also just because some data is purely relational does not mean, anymore, it must be persisted into some RDBMS (SQL). IMO relational data would translate better into graph databases.

Of course you can also write the queries in SQL but the performance will get terrible because of the number of joins you will need to have (considering your data will be somewhat normalized and not all of it into one Event table).

But in conclusion you will have more freedom by using NoSQL (thus JSON or some other format supported by the database) considering you can modify your schema in the future without taking into account already persisted data.

Considering NoSQL you could also look into graph databases if you plan to use very complex queries, since these will give you advantages in creating them easily, and also executing them very fast.


答:
First, if you're trying to Store JSON data in any storage but not a NoSQL database, I'd definitely discourage you to use JSON. The reason is that if you store your data as a JSON file, for example, then it will be extremely slow to open it, parse it, loop through it, etc.

That begin said, I can narrow your question to: What are the pros and cons of NoSQL and RDBMS? And it has been already answered thousand of times on the 'net.

Regrading your project, you can of course use either NoSQL or RDBMS; However what I can generally recommend to you is to think out of the box and look for the other less-visible factors that might help you decide between the two options. Try to see which option could speed up the development? Which is more suitable for the other team members - if you are not a sole developer. If you're selling this, which one is cheaper, easier and generally more suitable for your non-developer customers?

In this way you can finally decide which way to go, otherwise it will be really hard to decide based on the given information as both options could fit quite well.

Title: Using a relational database vs JSON objects for event/activity data

Body:
I am working on a project where I am trying to decide between using a standard SQL relational database or JSON objects to store data about an event or activity.

The project will store data on multiple event types so I have decided to just describe one event type for this question.

The live music event (described in full using the JSON schema at the bottom of this question) is an object that stores data such as where the event will take place, the time/date of the event and the cost of the event. The live music event object has both one-to-one (event--> name, event --> description) and one-to-many (event--> venues, event--> dates, event--> ticket types) relationships. Furthermore, the event object can contain one or more performer IDs, which link to the performer object. The performer object stores data on musicians who are performing at the live music event.

The data will be queried by users using both simple ("Find me events with 'x' name") and complex ("Find me events with 'x' music genre and 'y' cost within a radius of 'z' from my current location") queries. The data will be submitted by users using a web form.

As you can probably tell from the defined JSON schema, I was originally going to use JSON objects to store this data but I've heard from some people who say that because my data is purely relational, I should stick to the older methods.

I would appreciate any thoughts on the pros and cons of each approach given my needs. If you need anything clarified, please feel free to ask.

```<code>{
    "event": {
        "eventID":{
            "type":"string"
        },
        "eventType":{
            "type":"array",
            "eventTypeItem":{
                "type":"string"
            }
        },
        "eventName":{
            "type":"string"
        },
        "eventDescription":{
            "type":"string"
        },
        "eventVenueList":{
            "type":"array",
            "eventVenueListID":{
                "type":"integer"
            }
        },
        "eventURL":{
            "type":"string"
        },
        "eventTwitter":{
            "type":"string"
        },
        "eventFB":{
            "type":"string"
        },
        "eventInstagram":{
            "type":"string"
        },
        "eventEmail":{
            "type":"string",
            "format":"email"
        },
        "eventContactPerson":{
            "type":"string"
        },
        "eventDoorTime": {
            "type":"string",
            "format":"date-time"
        },
        "eventPerformerIDList":{
            "type":"array",
            "liveMusicPerformerID":{
                "type":"integer"
            }
        },
        "eventSetList":{
            "type":"array",
            "eventPerformerID":{
                "type":"integer"
            },
            "eventPerformerStartTime":{
                "type":"string",
                "format":"date-time"
            },
            "eventPerformerEndTime":{
                "type":"string",
                "format":"date-time"
            }
        },
        "eventDateList": {
            "type":"array",
            "eventDateItem": {
                "type":"string",
                "format":"date-time"
            }
        },
        "eventDateStartTime": {
            "type":"string",
            "format":"date-time"
        },
        "eventDateEndTime": {
            "type":"string",
            "format":"date-time"
        },
        "eventTicket":{
            "type":"array",
            "eventTicketType":{
                "type":"string"
            },
            "eventTicketLowPrice":{
                "type":"number"
            },
            "eventTicketHighPrice":{
                "type":"number"
            },
            "eventDatesAdvancePrice": {
                "type":"number"
            }
        }
    },
    "performer": {
        "performerID": {
            "type":"integer"
        },
        "performerType": {
            "type":"string"
        },
        "performerName": {
            "type":"string"
        },
        "performerAlternateName": {
            "type":"array",
            "performerAlterateNameItem":{
                "type":"string"
            }
        },
        "performerGenreList": {
            "type":"array",
            "performerGenreItem":{
                "type":"string"
            }
        },
        "performerURL": {
            "type":"string"
        }
    }
}
</code>```


问:
Why Num&sizeMinusOne faster than num&(size-1)
I've been told that when I have a hash table of size m and m=2^k, I can use the & operator as num & (size-1) instead of num % size, to fit the hashCode to my table size.

I've also been told that the the command Num&sizeMinusOne is more than twice faster than num & (size-1).

My question is, why?

And isn't the operation of creating a variable called SizeMinusOne takes time too?

答:
Regarding % 2**k vs. & 2**k-1: This is a micro optimization, but a feasible one. The compiler can't prove that size is always a power of two (as it's variable and possibly modified by code in different translation units), so it can't perform the optimization itself. Integer division has significantly worse throughput and latency than bitwise operations on virtually every architecture. To a degree, this can even be justified with complexity theory: Bitwise operations require linear time/circuit size, while the best known divison/modulo operations require super-linear time/circuit size. This effect is actually measurable on contemporary machines too (I know this because I didn't believe it and tried it).

Regarding size-1 versus sizeMinusOne: The idea is to store sizeMinusOne (I've seen the name mask for this) instead of size, to reduce redundancy. In a very local, short-sighted machine model, num & sizeMinusOne is (pseudo-RISC)

```<code>and r3, r1, r2
</code>```

while num & (size - 1) is

```<code>sub r3, r2, #1
and r3, r1, r3
</code>```

with otherwise identical setup and surrounding code. Since bitwise and arithmetic operations are typically equally fast (single ALU cycle, optimal latency) one could indeed argue that the first takes half the resources of the second.

But that ignores the fact that the surrounding code will take much longer, a hundred cycles overall being a very optimistic estimate. In that context, a single cycle is not just peanuts, it's a measurement error, simply noise. Don't lose sleep over it. What's more, depending on the surrounding code it may not even be a single cycle: An out-of-order CPU (such as most contemporary x86 cores) might very well squeeze the subtraction somewhere into the scheduling while an ALU is idle and be done with it before it even finished calculating num.

There are, however, other reasons to store mask instead of size. Usually the former is used more often than the latter, so by preferring mask you simplify the code.

Body:
Regarding % 2**k vs. & 2**k-1: This is a micro optimization, but a feasible one. The compiler can't prove that size is always a power of two (as it's variable and possibly modified by code in different translation units), so it can't perform the optimization itself. Integer division has significantly worse throughput and latency than bitwise operations on virtually every architecture. To a degree, this can even be justified with complexity theory: Bitwise operations require linear time/circuit size, while the best known divison/modulo operations require super-linear time/circuit size. This effect is actually measurable on contemporary machines too (I know this because I didn't believe it and tried it).

Regarding size-1 versus sizeMinusOne: The idea is to store sizeMinusOne (I've seen the name mask for this) instead of size, to reduce redundancy. In a very local, short-sighted machine model, num & sizeMinusOne is (pseudo-RISC)

and r3, r1, r2

while num & (size - 1) is

sub r3, r2, #1
and r3, r1, r3

with otherwise identical setup and surrounding code. Since bitwise and arithmetic operations are typically equally fast (single ALU cycle, optimal latency) one could indeed argue that the first takes half the resources of the second.

But that ignores the fact that the surrounding code will take much longer, a hundred cycles overall being a very optimistic estimate. In that context, a single cycle is not just peanuts, it's a measurement error, simply noise. Don't lose sleep over it. What's more, depending on the surrounding code it may not even be a single cycle: An out-of-order CPU (such as most contemporary x86 cores) might very well squeeze the subtraction somewhere into the scheduling while an ALU is idle and be done with it before it even finished calculating num.

There are, however, other reasons to store mask instead of size. Usually the former is used more often than the latter, so by preferring mask you simplify the code.


答:
I think you should use both and I don't see it as a 'versus' decision.

A relational database makes sense for fast and efficient storage and retrieval of data that has relational properties.

JSON is a great data format because it is simple, lightweight and ideal for passing around raw data in a very basic format with a syntax suited to storing and exchanging text information. It's great for passing small amounts of data between a browser and a server.  It's not in such an easy format to start using for relational type data queries.

So I would recommend SQL for the data storage and JSON for the data transport format.

It is true that there are noSQL key-value options such as Mongo, Redis, etc.  These would have the advantage of possibly simpler mapping to the JSON format but are generally a little harder to use for queries.  The main hurdle with them is unfamiliarity by the general IT community especially when compared to SQL which is so well known and hast a vast array of resources and knowledge available for almost every situation imaginable.


答:
I believe there are more considerations here that you may not be looking for. There are two broad concerns here:

Storage

Search and Retrieval

Storage

There are plenty of opinions on why to use no-sql or RDBMS store for your data. One of the most important items that we thought was useful is that we can easily define and store json objects in storage without having to worry about defining it's full structure or relationship between different types of objects. Some of the other reasons to use a NoSql db would be ability to auto shard data, location based searches and easy maintenance. There are many good NoSql databases out there, my personal preference is MongoDB. However, if you have not used NoSql database before, there is a definite learnign curve as you learn to re-wire your mind. Most of us have been using RDBMS for a while now and it takes conscious effort to break out of that habit. Plus you will find yourself wanting to redo your data model as you proceed along with your efforts and have a better usnderstanding of concepts. If ability to refactor or remodel is not an options for your project I would suggest to stick with what you already know best.

Search

If you intend to provide any kind of search that is usable, I strongly suggest that you use a dedicated text search engine such as SOLR to perform your searches. Text searches are slow and if you have multiple shards then even more so slower. SOLR supports blazing fast text searches including weighted search params, location based searches and much more. SOLR however is not suited as a primary store of your data. This does mean that you will have to create mechanisms for dual insert and update to both you primary database and your SOLR layer when adding or updating events. Plus you will have to keep the SOLR later updated by removing any outdated/ended events.

Although this does seem like lot of extra work you will thank yourself for foresight of using a full text search engine later on. None of the NoSql databases or RDBMS come close to performance and agility of SOLR/Lucene.


问:
How do I explain to non-programers what .NET is?
I don't work at a software company, and I'm one of a small handful of people in the company that know anything about programming. I spend a lot of time automating other programs that are used in the office through public APIs, and I've also created a few stand alone applications. I work almost entirely in C#.NET as every application we seem to use in the office seems to have some form of .NET API.

I've had a few people here ask me about learning "how to program", and where they should start. I think it makes a lot more sense to learn a .NET language as nearly all the programs they would want to automate have a .NET API, and it sounds like VBA is on it's way out and being replaced by VSTA.

However, I'm trying to figure out how to explain what .NET is and why they should learn it to a someone that doesn't know anything about programming. It's not really a language, as there are a number of languages that are considered .NET languages. Plus I think there is a distinction between ".NET" and "The .NET framework" as the latter is more about the libraries provided by Microsoft.

答:
People, that are non-programmers, are very afraid of special computer terms like "framework", "ASP.NET" and "Silverlight". So let's explain the thing in easy terms:

.NET is a modern programming technology that best used to make business applications, web sites, games and multimedia.


问:
DRY code, DRY tests?
At some point I had to create some class "Class1" and that class needs a method "method". So I have the following:

```<code>Class1MethodTest: A total of N tests that check the behavior of Class1.method
Class1 method: A full implementation of the method
</code>```

But a bit later I need a different class "Class2" to have a completely similar method "method". Now I have several approaches:

Approach 1

```<code>Class1MethodTest: A total of N tests
Class1 method: Full implementation
Class2MethodTest: Another set of identical tests
Class2 method: Another full implementation
</code>```

Pros: Stupid simple

Cons: not DRY

At least that's the first attempt and I might even write this before doing any refactoring, right?

Approach 2:

```<code>_hidden_private_implementation_function: Full implementation of required method
Class1MethodTest: A total of N tests
Class1 method: Call hidden_private_whatever
Class2MethodTest: Another set of identical tests
Class2 method: Also call hidden_private_stuff
</code>```

Pros: DRY code, still stupid simple

Cons: Tests aren't DRY, "Test interface, not implementation"

Approach 3:

```<code>MethodTest: A total of N tests
TotallyPublicCommonMethod: Full implementation of required method
Class1MethodTest: Just one test to verify that Class1 method calls the Public one
Class1 method: Call public common method
Class2MethodTest: One more test
Class2 method: Also call common method
</code>```

Pros: DRY, stupid simple

Cons: .. any other than "You're testing implementation, not interface"?

Approach 4:

This is where it gets a bit exotic. Python allows me to DRY the "Approach 3" directly:

```<code>_hidden_private_implementation_function: Full implementation of required method
makeTestForClass(cls): return a total of N tests for class cls
Class1MethodTest = makeTestForClass(Class1)
Class1 method: Call hidden_private_whatever
Class2MethodTest = makeTestForClass(Class2)
Class2 method: Also call hidden_private_stuff
</code>```

Pros: DRY, "Don't test implementation"

Cons: Not that simple. Too hard to modify if I ever decide to change something in Class1.method, but not Class2.method

I can think of a couple more approaches but those are not very different from these above.

Right now I have some code looking something like "Approach 1" and I am thinking on which way I should go next to make it all cleaner and better.

答:
Your test module could contain an interface common for both classes and corresponding adaptors.

Then you could wrap class under test and pass it to the common test code.

Title: DRY code, DRY tests?


问:
Rails engine testing - use dummy app or real parent app?
I'm using Rails engines to break up a big app into smaller pieces. The parent app mostly handles users and authentication.

In one of my engine tests I want to log in a user before each test. How should I access this user log in functionality, which exists in the parent app, from the engine?

It seems there are two options:

1) Build user authentication into the dummy app. When you run rails plugin new app_name --mountable a "dummy app" - just a plain Rails app - is created in your test folder. During tests the engine is mounted on to this dummy app. For feature (integration, acceptance, what-have-you) tests, I thought it would be good to use real objects whenever possible. So I was planning on using a factory to create a real user and then log in that user. To do this with the dummy app, I would need to build that user functionality in.

This seems like a pain because if the real parent app changes, I need to change this dummy app as well.

2) Put all my tests in the parent app. This will work fine, I think, but it seems fishy. I feel like I should put my engine tests in the engine.

答:
There may be something missing from my understanding of constraints you face. I would have thought:

User login is part of the setup for each test. Do it however you need as part of the test framework. If it can call the parent that's fine. If it can just set up some status variables that's fine too. [I don't know what you mean by dummy app.]

Engine tests should be part of the engine, rather than part of the parent. They should have minimal dependencies.

Perhaps the information missing is what is implied by user login and why it's at all hard.

It is a routine part of constructing any kind of automated testing, whether unit, functional or integration, that you have to write mocks and stubs. I think that's the way to think about this situation. You don't need a real user validation, just a 'good enough' mock.


问:
Using factory pattern when classes have little in common
I have used Factory pattern where I have multiple classes which does similar sort of work, but I don't want client to worry about class instantiating and return types. So Instantiate the necessary class dynamically depending on input and pass the values. These classes have similar methods but does slightly different work and these classes inherit the same common interface. Is this the correct way or can I improve it further? </p>

答:
It is perfectly legitimate to use a factory pattern to instantiate different classes that implement a common interface. The classes themselves could be derived from a variety of sources and could even offer a range of other services. The key point is that as long as the WhatIWantToDoFactory returns an object that implements the IWhatIWantToDo interface its job is done.

This kind of capability is particularly useful in assembling structures using Dependency Injection/IOC principles.

Having said all that, this is question and my answer to it border on being opinion-based, and are only a marginally good fit for this site. IMHO.


答:
.NET for the Non-programmer

Programming - Basically telling a computer what to do and how to do it.

Source File - This is a document written in a programming language that tells the computer what you want it to do.

Programming Language - This is a language that (usually) resembles a mixture of English and math. It is both simple and strict enough for a compiler to understand.

Compiler - This translates a programming language that you can understand into a language the computer can understand, you can call it Computerese.

Library - A collection of useful code that has already been translated into Computerese that you can use in the programs you write.

.NET Platform - A large collection of tools, languages and libraries for writing programs with a heavy emphasis on productivity.

Sure, there's a lot more to it than that. You could tell them about IL and JIT compiling or garbage collection but these details aren't very relevant to a non-programmer.

Title: How do I explain to non-programers what .NET is?

Body:
I don't work at a software company, and I'm one of a small handful of people in the company that know anything about programming. I spend a lot of time automating other programs that are used in the office through public APIs, and I've also created a few stand alone applications. I work almost entirely in C#.NET as every application we seem to use in the office seems to have some form of .NET API.

I've had a few people here ask me about learning "how to program", and where they should start. I think it makes a lot more sense to learn a .NET language as nearly all the programs they would want to automate have a .NET API, and it sounds like VBA is on it's way out and being replaced by VSTA.

However, I'm trying to figure out how to explain what .NET is and why they should learn it to a someone that doesn't know anything about programming. It's not really a language, as there are a number of languages that are considered .NET languages. Plus I think there is a distinction between ".NET" and "The .NET framework" as the latter is more about the libraries provided by Microsoft.

ContentLicense: CC BY-SA 2.5


问:
Is it possible to know what programming language a web-site uses?
For example, stackexchange.com, without asking the site owner or Google their information about developing the website, is this possible to know what language is used in the back end?

Seems, the website don't have .extension bar, for example .php that can indicated which is developed in PHP, but without the extension, how can I know that?

答: No  it is  not possible to find language used in the websites by viewing the source code of the web page and search the existence of languages. because of usage of more than one languages for creation of website to provide high security  </p>


问:
What does HATEOAS offer for discoverability and decoupling besides ability to change your URL structure more or less freely?
Lately I've been reading about Hypermedia as the Engine of Application State (HATEOAS), the constraint that is claimed to make a web API "truly RESTful". It boils down to basically including links with every response to the possible transitions you can make from the current state.

Let me illustrate what HATEOAS is based on my understanding - and please do correct me if I missed something.

```<code>/
    GET: {
        "_links": {
            "child": [
                { "href": "http://myapi.com/articles", "title": "articles" }
            ]
        }
    }

/articles?contains=HATEOAS
    GET: {
        "_items": [
            { "uri": "http://myapi.com/articles/0", "title": "Why Should I Care About HATEOAS?" },
            { "uri": "http://myapi.com/articles/1", "title": "HATEOAS: Problem or Solution?" }
        ],
        "_links": {
            "self": { "href": "http://myapi.com/articles", "title": "articles" },
            "parent": { "href": "http://myapi.com/", "title": "home" }
        }
    }

    POST: {
        "title": "A New Article",
        "body": "Article body",
        "tags": [ "tag1", "tag2" ]
    }

/articles/0
    GET: {
        "title": "Why Should I Care About HATEOAS?",
        "body": "Blah blah blah"
        "tags": [ "REST", "HATEOAS" ],
        "_links": {
            "self": { "href": "http://myapi.com/articles/0", "title": "article" },
            "parent": { "href": "http://myapi.com/articles", "title": "articles" }
        }
    }
</code>```

HATEOAS is claimed to provide two major benefits:

The entire service is discoverable starting form the root URI, documentation is no longer needed.

The client is decoupled from the server which can now change the URI structure freely. This eliminates the need for API versioning.

But in my view, a service is a lot more than its URI structure. To use it effectively, you also need to know:

what query parameters you can use and their possible values

the structure of the JSON/XML/whatever documents you need to send in your POST/PATCH/etc requests

the structure of the response sent by the server

the possible errors that might occur

...

Based on the above, HATEOAS only solves a tiny fraction of the discoverability and coupling problems. You still need to document the above four aspects and clients will still be strongly coupled to the server because of them. To avoid breaking clients, you still need to version your API.

The only benefit it provides is that you can change your URL structure more or less freely (by the way, what happened to the principle "Cool URIs don't change"?). Is my understanding correct?

答:
I think your instincts are largely correct; those proclaimed benefits really aren't all that great, as for any non-trivial web application the clients are going to have to care about the semantics of what they're doing as well as the syntax.

But that doesn't mean that you shouldn't make your application follow the principles of HATEOAS!

What does HATEOAS really mean? It means structuring your application so that it is in principle like a web site, and that all operations that you might want to do can be discovered without having to download some complex schema. (Sophisticated WSDL schemas can cover everything, but by the time they do, they've exceeded the ability of virtually every programmer to ever understand, let alone write! You can view HATEOAS as a reaction against such complexity.)

HATEOAS does not just mean rich links. It means using the HTTP standard's error mechanisms to indicate more exactly what went wrong; you don't have to just respond with “waaah! no” and can instead provide a document describing what was actually wrong and what the client might do about it. It also means supporting things like OPTIONS requests (the standard way of allowing clients to find out what HTTP methods they can use) and content type negotiation so that the format of the response can be adapted to a form that clients can handle. It means putting in explanatory text (or, more likely, links to it) so that clients can look up how to use the system in non-trivial cases if they don't know; the explanatory text might be human readable or it might be machine readable (and can be as complex as you want). Finally, it means that clients do not synthesise links (except for query parameters); clients will only use a link if you told it to them.

You have to think about having the site browsed by a user (who can read JSON or XML instead of HTML, so a little weird) with a great memory for links and an encyclopædic knowledge of the HTTP standards, but otherwise no knowledge of what to do.

And of course, you can use content type negotiation to serve up an HTML(5)/JS client that will let them use your application, if that's what their browser is prepared to accept. After all, if your RESTful API is any good, that should be “trivial” to implement on top of it?


问:
Rich domain model and container services
I have a long experience in programming Java EE projects, but as I noticed most of the job I have done was with Transaction Script (anti)pattern.

So I want to learn using a rich domain model, but then there is a question, shall Domain Object be depended on container/system services (such a persistence, mail, ...)?

I have read this article and I don't agree with it at all!

How services are initialized and injected into domain entities?

What about single responsibility paradigm?

And isn't it against reusablity?

I also read Applying UML and Patterns fantastic book, but I don't know why didn't author describe the how shall responsibilities be assigned to entities after defining data access layer (in chapter 38).

So what is the best practice about having rich domain model, and do not having dependency on container/system services!

An example, consider following scenario in a software:

There are agents (which work with the system)

Our agents' business is selling insurance policies.

Each insurance policy type has a special type of pre-printed card which is given to agents, and agents give them to insureds.

We need to track each agent's number of available cards.

So there is a use case, which records how many cards of each type is given to each agent.

There is a use case, for recording agent's number of damaged unused cards of each type.

And the cards are used as the agent sells insurance policies.

I believe Rich Domain Model suggests that I shall have a method as following in agent class:

```<code>class Agent {
    int computeRemainigCards(CardType cardType) {}
}
</code>```

But then Agent shall depend on 3 DAO classes for just one responsibility:

One for calculating SUM of count of each card type given to an agent.

One for calculating count of used cards (by selling insurance policies).

One for calculating SUM of damaged unsold cards.

I believe that will make domain entities a mess. So what is the good practice?

答:
What do you mean by But then Agent shall depend on 3 DAO classes for just one responsibility?  If you're talking about avoiding DAO call from domain classes, maybe you can design it like this:

```<code>class Agent {

   List<Card> assignedCards;

   int numberOfRemainingCards() {
      return assignedCards.size();
   }

   void sell(Card card) {
      // do something
      assignedCards.remove(card);
   }

   void damaged(Card card) {
      card.damaged = true;
      assignedCards.remove(card);
   }

}

class Card {

   String id;

   boolean damaged;

}
</code>```

You only need one call to DAO (or repository) to retrieve an Agent with their assignedCards.  It only involves one DAO, for example:

```<code>List<Agent> agents = AgentDAO.getAllAgents();
for (Agent agent: agents) {
   System.out.println("Remaining cards for " + agent.name +
                      " is " + agent.numberOfRemainingCards());
}
</code>```

Another example:

```<code>Agent agentA = AgentDAO.findByName("Agent A");
agentA.sell(aCard);
agentA.damaged(anotherCard);
System.out.println("Number of remaining cards: " + agentA.numberOfRemainingCards());
AgentDAO.update(agentA); // if necessary
</code>```

If Agent has a lot of Card and you don't want to retrieve all Card just for determining number of remaining Cards, you can store the number of remaining cards as state, for example:

```<code>class Agent {

   List<Card> assignedCards;

   int numberOfRemainingCards;

   int getNumberOfRemainingCards() {
      return this.numberOfRemainingCards;
   }

   void sell(Card card) {
      // do something
      assignedCards.remove(card);
      numberOfRemainingCards--;
   }

   void damaged(Card card) {
      card.damaged = true;
      assignedCards.remove(card);
      numberOfRemainingCards--;
   }

   void assign(Card card) {
      assignedCards.add(card);
      numberOfRemainingCards++;
   }

}
</code>```

Body:
What do you mean by But then Agent shall depend on 3 DAO classes for just one responsibility?  If you're talking about avoiding DAO call from domain classes, maybe you can design it like this:

class Agent {

   List<Card> assignedCards;

   int numberOfRemainingCards() {
      return assignedCards.size();
   }

   void sell(Card card) {
      // do something
      assignedCards.remove(card);
   }

   void damaged(Card card) {
      card.damaged = true;
      assignedCards.remove(card);
   }

}

class Card {

   String id;

   boolean damaged;

}

You only need one call to DAO (or repository) to retrieve an Agent with their assignedCards.  It only involves one DAO, for example:

List<Agent> agents = AgentDAO.getAllAgents();
for (Agent agent: agents) {
   System.out.println("Remaining cards for " + agent.name +
                      " is " + agent.numberOfRemainingCards());
}

Another example:

Agent agentA = AgentDAO.findByName("Agent A");
agentA.sell(aCard);
agentA.damaged(anotherCard);
System.out.println("Number of remaining cards: " + agentA.numberOfRemainingCards());
AgentDAO.update(agentA); // if necessary

If Agent has a lot of Card and you don't want to retrieve all Card just for determining number of remaining Cards, you can store the number of remaining cards as state, for example:

class Agent {

   List<Card> assignedCards;

   int numberOfRemainingCards;

   int getNumberOfRemainingCards() {
      return this.numberOfRemainingCards;
   }

   void sell(Card card) {
      // do something
      assignedCards.remove(card);
      numberOfRemainingCards--;
   }

   void damaged(Card card) {
      card.damaged = true;
      assignedCards.remove(card);
      numberOfRemainingCards--;
   }

   void assign(Card card) {
      assignedCards.add(card);
      numberOfRemainingCards++;
   }

}


问:
What is the difference between a software process model and software engineering methods (methodology)?
I'm an academic guy, who is now venturing into the software engineering world, puzzled by the fact that many terms seem to overlap each other. I'm reading some books and cannot quite distinguish/correlate a software process model from software engineering methods.

For instance, in Software Engineering Ian Sommerville defines a software process model as:

A simplified representation of a software process, presented from a
  specific perspective.

And software methodology (software engineering methods) as:

Structured approaches to software development which include system models, notations, rules, design advice and process guidance.

However, Wikipedia defines software development methodology like this:

A software development methodology or system development methodology in software engineering is a framework that is used to structure, plan, and control the process of developing an information system.

In my opinion, Sommerville's definition of a software process model can enter on the scope of the Wikipedia definition. Can anyone enlighten me on this issue? An example would rock, e.g, A is a software process model and B is a software engineering methods (methodology).

答:
Software Process Model is an abstraction or a visual representation of an idea, event or a process. Modeling is used mainly to help us understand complex processes or events and decide what to do with them. Modeling is also used in other domain like Mathematics (Mathematical Model) and Economics (Financial Model).

By applying the definition above in software engineering context, we simply model the software processes that we understand specifically during requirements gathering.

Software Development Methodology is simply a guideline for developing a software that consists of steps and deliverables to finish the software. A development method is consist of model, tools and techniques.
The most common method or approach to developing a software is the SDLC a.k.a Waterfall model that consist of different stages (e.g. Planning, Analysis, Design, Implementation, and Maintenance).
Each of the stage can be accomplish by using techniques (e.g relational database design techniques, requirements gathering and analysis techniques), models ( use- case model, data flow diagram, relational database model, etc..) and tools (Visio, Visible Analyst and other software tools).
There are various methodologies that exists today with the efforts of industry professionals and academe; Each of these methodologies, however, has strengths and weaknesses and their techniques,tools and model may differ from the SDLC. (e.g. Scrum, Unified Process and Extreme Programming).


答:
My guiding principle here would be that test code has to meet the same level of quality as implementation code.  If your test code can't reach that level, then something is wrong with the implementation design.

In the specific context of a method that is now common to two classes, I would try to refactor that into a common class that both Class1 and Class2 inherit. As noted by @MainMa, if you had Cat and now have Dog, refactor their feed method into class Pet.

If you feel this is not right, because Class1 and Class2 conceptually have nothing in common, then you need to define a new class that the others use in order to attain their purpose. As you ask in a comment, if the method to refactor is save_to_database, then you may need to introduce a class called Database, which classes Cat and Screwdriver use internally to persist their state.

Then your question turns into testing the interface of this new class, whose sole purpose is to store things, regardless if they come from a cat or from a screwdriver.

The first approach gives something like this:

class Cat:
    def feed(self):
        """
            >>> cat = new Cat()
            >>> cat.feed()
        """
        pass

# turns into

class Pet:
    def feed(self):
        """
            >>> pet = new Pet()
            >>> pet.feed()
        """
        pass

class Dog(Pet):
    pass

class Cat(Pet):
    pass
```

<p>The second approach, which is I guess more relevant to you, would look like this:</p>

<pre class="lang-py prettyprint-override"><code>class Customer:
    def save(self):
        """
            >>> customer = new Customer()
            >>> customer.save()
            >>> another_db_conn = db.connect()
            >>> another_db_conn.read(customer.id) == customer.name
            True
        """
        conn = db.connect()
        conn.write(self.name)

# turns into

class Database:
    def save(self, data):
        """
            >>> db = new Database()
            >>> db.save("whatever")
            >>> another_db_conn = db.connect()
            >>> another_db_conn.read() == "whatever"
            True
        """
        conn = db.connect()
        conn.write(self.name)

class Customer:
    def __init__(self, database):
        self.db = database

    def save(self):
        self.db.save(self.name)

class Whale:
    def __init__(self, database):
        self.db = database

     def save(self):
         self.db.save("the whales!")
</code>```

Notice I have used doctests here in order to show implementation and tests mixed together.  You may prefer to use unittests or whatever.  Also, the Database example is too generic and as it stands the class does not add value:  it should do something interesting on the data it gets and that behavior is what you want to test; but this is just an example.

If you have a concern that defining new classes to be used may "open up" your package with a lot more public API than you would like to, remember you can alway define such classes as package-private (in Java), or just not export them out of your package (in Python).  Tests defined within the package will still be able to access them.

Title: DRY code, DRY tests?

Body:
At some point I had to create some class "Class1" and that class needs a method "method". So I have the following:

```<code>Class1MethodTest: A total of N tests that check the behavior of Class1.method
Class1 method: A full implementation of the method
</code>```

But a bit later I need a different class "Class2" to have a completely similar method "method". Now I have several approaches:

Approach 1

```<code>Class1MethodTest: A total of N tests
Class1 method: Full implementation
Class2MethodTest: Another set of identical tests
Class2 method: Another full implementation
</code>```

Pros: Stupid simple

Cons: not DRY

At least that's the first attempt and I might even write this before doing any refactoring, right?

Approach 2:

```<code>_hidden_private_implementation_function: Full implementation of required method
Class1MethodTest: A total of N tests
Class1 method: Call hidden_private_whatever
Class2MethodTest: Another set of identical tests
Class2 method: Also call hidden_private_stuff
</code>```

Pros: DRY code, still stupid simple

Cons: Tests aren't DRY, "Test interface, not implementation"

Approach 3:

```<code>MethodTest: A total of N tests
TotallyPublicCommonMethod: Full implementation of required method
Class1MethodTest: Just one test to verify that Class1 method calls the Public one
Class1 method: Call public common method
Class2MethodTest: One more test
Class2 method: Also call common method
</code>```

Pros: DRY, stupid simple

Cons: .. any other than "You're testing implementation, not interface"?

Approach 4:

This is where it gets a bit exotic. Python allows me to DRY the "Approach 3" directly:

```<code>_hidden_private_implementation_function: Full implementation of required method
makeTestForClass(cls): return a total of N tests for class cls
Class1MethodTest = makeTestForClass(Class1)
Class1 method: Call hidden_private_whatever
Class2MethodTest = makeTestForClass(Class2)
Class2 method: Also call hidden_private_stuff
</code>```

Pros: DRY, "Don't test implementation"

Cons: Not that simple. Too hard to modify if I ever decide to change something in Class1.method, but not Class2.method

I can think of a couple more approaches but those are not very different from these above.

Right now I have some code looking something like "Approach 1" and I am thinking on which way I should go next to make it all cleaner and better.

Body:
My guiding principle here would be that test code has to meet the same level of quality as implementation code.  If your test code can't reach that level, then something is wrong with the implementation design.

In the specific context of a method that is now common to two classes, I would try to refactor that into a common class that both Class1 and Class2 inherit. As noted by @MainMa, if you had Cat and now have Dog, refactor their feed method into class Pet.

If you feel this is not right, because Class1 and Class2 conceptually have nothing in common, then you need to define a new class that the others use in order to attain their purpose. As you ask in a comment, if the method to refactor is save_to_database, then you may need to introduce a class called Database, which classes Cat and Screwdriver use internally to persist their state.

Then your question turns into testing the interface of this new class, whose sole purpose is to store things, regardless if they come from a cat or from a screwdriver.

The first approach gives something like this:

class Cat:
    def feed(self):
        """
            >>> cat = new Cat()
            >>> cat.feed()
        """
        pass

# turns into

class Pet:
    def feed(self):
        """
            >>> pet = new Pet()
            >>> pet.feed()
        """
        pass

class Dog(Pet):
    pass

class Cat(Pet):
    pass

The second approach, which is I guess more relevant to you, would look like this:

class Customer:
    def save(self):
        """
            >>> customer = new Customer()
            >>> customer.save()
            >>> another_db_conn = db.connect()
            >>> another_db_conn.read(customer.id) == customer.name
            True
        """
        conn = db.connect()
        conn.write(self.name)

# turns into

class Database:
    def save(self, data):
        """
            >>> db = new Database()
            >>> db.save("whatever")
            >>> another_db_conn = db.connect()
            >>> another_db_conn.read() == "whatever"
            True
        """
        conn = db.connect()
        conn.write(self.name)

class Customer:
    def __init__(self, database):
        self.db = database

    def save(self):
        self.db.save(self.name)

class Whale:
    def __init__(self, database):
        self.db = database

     def save(self):
         self.db.save("the whales!")

Notice I have used doctests here in order to show implementation and tests mixed together.  You may prefer to use unittests or whatever.  Also, the Database example is too generic and as it stands the class does not add value:  it should do something interesting on the data it gets and that behavior is what you want to test; but this is just an example.

If you have a concern that defining new classes to be used may "open up" your package with a lot more public API than you would like to, remember you can alway define such classes as package-private (in Java), or just not export them out of your package (in Python).  Tests defined within the package will still be able to access them.


答:
Your question is exactly the question that is answered by reading Domain-Driven Design.

The comment from Andy is spot-on. The entities don't depend on DAOs. They depend on abstractions that represent operations the entities need to function. The fact those abstractions represent data storage and are implemented using database is irrelevant to entities or any part of domain model. Those abstractions are called Repository in DDD.

To answer your questions:

How services are initialized and injected into domain entities? - When entity is pulled from persistence, it is initialized with realizations of abstractions it needs, alongside the data of the entity.

What about single responsibility paradigm? - What about it? The entity has only one responsibility : represent behavior related to single domain concept.

And isn't it against reusablity? - It is actually highly reusable. Especially if you apply other SOLID principles and use composition instead of inheritance.

For your example, that can be easily solved by Agent having reference to interface, that allows it to query cards in different way. The methods then call this interface.

Title: Rich domain model and container services

Body:
I have a long experience in programming Java EE projects, but as I noticed most of the job I have done was with Transaction Script (anti)pattern.

So I want to learn using a rich domain model, but then there is a question, shall Domain Object be depended on container/system services (such a persistence, mail, ...)?

I have read this article and I don't agree with it at all!

How services are initialized and injected into domain entities?

What about single responsibility paradigm?

And isn't it against reusablity?

I also read Applying UML and Patterns fantastic book, but I don't know why didn't author describe the how shall responsibilities be assigned to entities after defining data access layer (in chapter 38).

So what is the best practice about having rich domain model, and do not having dependency on container/system services!

An example, consider following scenario in a software:

There are agents (which work with the system)

Our agents' business is selling insurance policies.

Each insurance policy type has a special type of pre-printed card which is given to agents, and agents give them to insureds.

We need to track each agent's number of available cards.

So there is a use case, which records how many cards of each type is given to each agent.

There is a use case, for recording agent's number of damaged unused cards of each type.

And the cards are used as the agent sells insurance policies.

I believe Rich Domain Model suggests that I shall have a method as following in agent class:

```<code>class Agent {
    int computeRemainigCards(CardType cardType) {}
}
</code>```

But then Agent shall depend on 3 DAO classes for just one responsibility:

One for calculating SUM of count of each card type given to an agent.

One for calculating count of used cards (by selling insurance policies).

One for calculating SUM of damaged unsold cards.

I believe that will make domain entities a mess. So what is the good practice?


问:
Scrum task over estimation
In my current company we're using Scrum with 2 week iterations and a regular planning session.
How planning normally works in our company is that we take a predefined , prioritized (by PO before the planning) product backlog of user stories / PBIs, take PBIs from the top one by one  and break it down to tasks to then estimate them in hours (using poker planning and fibonacci) until we reach a given team's capacity.

While this works for most of the teams, there is one 2-person team where I'm a SM, that tends to systematicaly  overestimate the tasks by far (as those developers are being paid by an hour in this project, and from the record of working with them in another project I know for a fact they have a far better velocity).
Not being a part of this team as a developer, trying to adhere to Scrum I'm refraining from influencing those estimates by any means, however as we approach the deadlines in the project this situation is becoming more and more troublesome.

My question is - is there a way / good practice in such situations, to keep the team on the edge of their velocity and not influence their estimations, or maybe we're doing sth wrong in the process ?

答:
The sin of overestimation is probably less serious than that of underestimation, because the team is at least meeting its commitments and not contributing to the chaos that can occur when commitments are missed (particularly when others depend on a team's output for their own work, as is often the case).

How do you know they are overestimating / undercommitting? Are they spending hours on end in the Starbucks in the lobby? Or is it just something you "sense" based on your understanding of the scope and complexity of their per-sprint output? If the latter, are the individuals perhaps more thorough in elimination (or better yet, prevention) of technical debt? Do they have better test coverage than other teams? Is their software better designed? Do they refactor when necessary?

I'm not standing in defense of all "slow" teams - I've managed some. What you have to know before acting is why they're slow, and what steps can be reasonably taken to increase velocity, without sacrificing the quality of work produced.

Title: Scrum task over estimation


问:
Why should I declare a class as an abstract class?
I know the syntax, rules applied to abstract class and I want know usage of an abstract class

Abstract class can not be instantiated directly but can be extended by other class

What is the advantage of doing so?

How it is different from an Interface?

I know that one class can implement multiple interfaces but can only extend one abstract class. Is that only difference between an interface and an abstract class?

I am aware about usage of an Interface. I have learned that from Event delegation model of AWT in Java.

In which situations I should declare class as an abstract class? What is benefits of that?

答:
You would declare a class abstract when you don't want the developer (probably yourself) to be allowed to instantiate it, because it wouldn't work or wouldn't make sense.

For example, consider a game where there are different types of game entities. They all inherit from the base GameEntity class.

```<code>abstract class GameEntity{

    int lifePoint, speed, damage;

    public attack(GameEntity target){ target.damage(damage); }

    public damage(int damageInflicted){ lifePoint -= damageInflicted - speed; }

    // etc...

}
</code>```

This class is declared abstract since it wouldn't make sense to instantiate it. It declares some actions for the game entities and some attributes, but nowhere in this class are these attributes initialized. This class serves as a template for the game entities, but isn't meant to be instantiated on it's own, and as such declared abstract.

Regarding the difference in usage between an abstract class and an interface:

As I see it, an interface is a way to gain polymorphic behavior without being limited by some languages' single-inheritance mechanism.

Let's return to the game as an example. Consider a class Enemy which is derived from GameEntity. This class has a method attackMeFromDistance(RangedAttacker attacker). This method is meant to allow entities to attack the enemy from far away.

As you can see, this method takes a RangedAttacker type as a parameter. However, all of the game entities already inherit from GameEntity. They can't extend another class.

Take the classes Mage and Archer for example. We want to allow both of them to be accepted as parameters in the attackMeFromDistance(RangedAttacker attacker) method, but they're already derived from GameEntity.

To solve this, we create a new interface:

```<code>interface RangedAttacker{
    public void attackFromDistance();
}
</code>```

A class that implement this interface must implement the attackFromDistance() method, and thus it is ensured that it has ranged attacking capabilities. This means that the attackMeFromDistance method can now safely accept classes that implement this interface. So making Mage and Archer implement that interface solves our problem.

To me, this is the power of interfaces.

So to sum up, you would usually use an abstract class when you want to have a base class for some classes, but it wouldn't make sense to instantiate it by itself (or in a case where it has abstract methods, that have to be implemented by the subclasses, and in this case the compiler would enforce you to make the class abstract). You would use an interface to gain polymorphic behavior without being limited by the single-inheritance mechanism.

Body:
You would declare a class abstract when you don't want the developer (probably yourself) to be allowed to instantiate it, because it wouldn't work or wouldn't make sense.

For example, consider a game where there are different types of game entities. They all inherit from the base GameEntity class.

abstract class GameEntity{

    int lifePoint, speed, damage;

    public attack(GameEntity target){ target.damage(damage); }

    public damage(int damageInflicted){ lifePoint -= damageInflicted - speed; }

    // etc...

}

This class is declared abstract since it wouldn't make sense to instantiate it. It declares some actions for the game entities and some attributes, but nowhere in this class are these attributes initialized. This class serves as a template for the game entities, but isn't meant to be instantiated on it's own, and as such declared abstract.

Regarding the difference in usage between an abstract class and an interface:

As I see it, an interface is a way to gain polymorphic behavior without being limited by some languages' single-inheritance mechanism.

Let's return to the game as an example. Consider a class Enemy which is derived from GameEntity. This class has a method attackMeFromDistance(RangedAttacker attacker). This method is meant to allow entities to attack the enemy from far away.

As you can see, this method takes a RangedAttacker type as a parameter. However, all of the game entities already inherit from GameEntity. They can't extend another class.

Take the classes Mage and Archer for example. We want to allow both of them to be accepted as parameters in the attackMeFromDistance(RangedAttacker attacker) method, but they're already derived from GameEntity.

To solve this, we create a new interface:

interface RangedAttacker{
    public void attackFromDistance();
}

A class that implement this interface must implement the attackFromDistance() method, and thus it is ensured that it has ranged attacking capabilities. This means that the attackMeFromDistance method can now safely accept classes that implement this interface. So making Mage and Archer implement that interface solves our problem.

To me, this is the power of interfaces.

So to sum up, you would usually use an abstract class when you want to have a base class for some classes, but it wouldn't make sense to instantiate it by itself (or in a case where it has abstract methods, that have to be implemented by the subclasses, and in this case the compiler would enforce you to make the class abstract). You would use an interface to gain polymorphic behavior without being limited by the single-inheritance mechanism.


问:
Test driven development when implementing a flexible length list
According to the commonly used TDD strategy, to implement something, you write a test that fail the code first, write the simplest code, refactor, and then repeat. I am trying to imagine this scenario with implementing a flexible length list (e.g. List<T> in .net.

Let's say I first test by inserting one item. Probably the simplest way to achieve this is by backing the list with an array with length 1 (which will pass the test). Nothing to refactor here, so I'll go ahead and write another test that insert 2 items. I'll simply change the array length to 2, and the test pass again. Then I write test with 3 items, expand the array, and repeat again. I will end up forever doing this until I'm tired.

Is this an exception to the fail-test-first strategy? Or am I missing something in the above strategy?

PS: The actual implementation backs the list with an array which grows twice as large every time the number of elements exceed the array length.

答:
I think you are confusing unit tests with property-based testing in your question.

Unit tests look at a class as if it was a unit of processing in a signal processing chain, such as an amplifier circuit or a guitar effects rack. I think Kent Beck used exactly this metaphor in his work "Test Driven Development: By Example", but right now I don't have a copy of the book to check.

The point is to explain that it is easier to check that a certain filter always takes out high frequencies, than to check if a specific combination of many filters and distortions make you sound exactly like Jimi Hendrix.

Applied to your case, you may want to test in a unit test that a List class can add elements as needed.  Being strict with TDD philosophy, you should arrange for the List to already hold a random number of elements before adding to it -- otherwise, a minimal implementation might know the expected total number and just return that.

Property-based testing, on the other hand, checks that a function is mathematically well-defined in the sense that it returns what is expected for the whole domain where it is defined (the definition here is mine, and may be inaccurate).  You can get an idea of how this works by reading on QuickCheck and ScalaCheck.

The core concept is that if you pass to the test framework a function that has a typed signature, e.g. sum(one: Int, another: Int), then the framework generates many tests by traversing all possible variations of the type.  In the sum example, Int goes from Int.MinValue to Int.MaxValue: the framework picks, say, 100 value pairs and tries to sum them. For more complex classes, you may need to tell the framework how to create an Arbitrary instance of your class.

Applied to your case, you may want to show that the length of your List is always increased by one after an add operation.  Define an Arbitrary List as a List that already holds a random number of items, and define that after an add this number is increased by 1.

The main benefit of property-based testing is that you get a lot of tests written automatically for you, and you may even control the generation in order to look for edge cases. The property-based test will generate a 100 lists and check that the invariant holds; the unit test would have to be repeated a 100 times in order to give you such a guarantee.  However, property-based testing is not a silver bullet, it is just a complement for unit tests in certain situations.