问:
Why is an anemic domain model considered bad in C#/OOP, but very important in F#/FP?
In a blog post on F# for fun and profit, it says:

In a functional design, it is very important to separate behavior from
  data. The data types are simple and "dumb". And then separately, you
  have a number of functions that act on those data types.

This is the exact opposite of an object-oriented design, where
  behavior and data are meant to be combined. After all, that's exactly
  what a class is. In a truly object-oriented design in fact, you should
  have nothing but behavior -- the data is private and can only be
  accessed via methods.

In fact, in OOD, not having enough behavior around a data type is
  considered a Bad Thing, and even has a name: the "anemic domain
  model".

Given that in C# we seem to keep borrowing from F#, and trying to write more functional-style code; how come we're not borrowing the idea of separating data/behavior, and even consider it bad? Is it simply that the definition doesn't with with OOP, or is there a concrete reason that it's bad in C# that for some reason doesn't apply in F# (and in fact, is reversed)?

(Note: I'm specifically interested in the differences in C#/F# that could change the opinion of what is good/bad, rather than individuals that may disagree with either opinion in the blog post).

答:
I think in a business application you often don't want to hide data because pattern matching on immutable values is great to ensure that you are covering all possible cases.
But if you are implementing complex algorithms or data structures you better hide implementation details turning ADTs (algebraic data types) into ADTs (abstract data types).</p>


问:
Which scenarios to use .NET Concurrent Collections effectively?
I am investigating how to introduce parallelism into an application to improve performance. In particular, I am looking at parallel for loops and their variants and my initial experiments show significant overhead to using collections from the System.Collections.Concurrent namespace.

Typical scenario

Want to iterate over a collection in Parallel, perform some computations per iteration and then route/add the results into an appropriate collection depending on the details of the iteration.

[If you don't use the Concurrent Collections you get errors due to the usual multi-threading & synchronization issues so you appear to be forced into using the Concurrent collections.]

Unfortunately my tests mostly/often show that the single-threaded simple solutions perform faster due to the overhead of using the Concurrent Collections - is this to be expected?

Tentative Conclusions

You would need to be doing a "very large" piece of work per iteration for the Concurrent Collections to perform better than a single threaded solution?

Code Example

As per requests in the comments:

open System.Collections.Generic
open System.Collections.Concurrent
open FSharp.Collections.ParallelSeq

type Data = {
    Name:string
    mutable Age:int
    Description:string
}

[<EntryPoint>]
let main argv =

    let xs = ResizeArray<Data>()
    let n = 1000000

    let rand = System.Random()

    // create some random data
    for i in 0..n do
        let f1 = rand.NextDouble()
        let f2 = rand.NextDouble()
        let data = {Name = "My Name" + f1.ToString() + f2.ToString(); Age = 38; Description = "Happy"}
        xs.Add(data)

    // single-threaded example
    let normalCollection = Dictionary<string,Data>()
    let stopWatch = System.Diagnostics.Stopwatch()
    stopWatch.Start()
    xs |> Seq.iter (fun x ->
        x.Age <- x.Age + rand.Next()
        normalCollection.[x.Name] <- x
        )
    stopWatch.Stop()
    printfn "Single Threaded: %A" stopWatch.Elapsed

    System.GC.Collect(2)

    // single-threaded + concurrent Collection example
    let concurrentCollection = ConcurrentDictionary<string,Data>()
    let stopWatch = System.Diagnostics.Stopwatch()
    stopWatch.Start()
    xs |> Seq.iter (fun x ->
        x.Age <- x.Age + rand.Next()
        concurrentCollection.[x.Name] <- x
        )
    stopWatch.Stop()
    printfn "Single Threaded + Concurrent Collection: %A" stopWatch.Elapsed

    concurrentCollection.Clear()

    System.GC.Collect(2)

    // multi-threaded example
    let concurrentCollection = ConcurrentDictionary<string,Data>()
    let stopWatch = System.Diagnostics.Stopwatch()
    stopWatch.Start()
    xs |> PSeq.iter (fun x ->
        x.Age <- x.Age + rand.Next()
        concurrentCollection.[x.Name] <- x
        )
    stopWatch.Stop()
    printfn "Multi-Threaded: %A" stopWatch.Elapsed

    // Functional Style
    normalCollection.Clear()
    System.GC.Collect(2)
    let stopWatch = System.Diagnostics.Stopwatch()
    stopWatch.Start()
    let ys =
        xs
        |> PSeq.map (fun x -> {x with Age = x.Age + rand.Next()} )
        |> Seq.iter (fun x -> normalCollection.[x.Name] <- x)
    stopWatch.Stop()
    printfn "Functional Style: %A" stopWatch.Elapsed

    printfn "%A" argv
    0 // return an integer exit code
```

Timing

Consistent over multiple runs...

n = 10,000 (small data set)

Single Threaded: 00:00:00.0048328

Single Threaded + Concurrent Collection: 00:00:00.0053433

Multi-Threaded: 00:00:00.0197919

Functional Style: 00:00:00.0073613

n = 10,000,000 (large data set)

Single Threaded: 00:00:04.0683213

Single Threaded + Concurrent Collection: 00:00:13.6469918

Multi-Threaded: 00:00:10.9768615

Functional Style: 00:00:04.6633076

答:
You would need to be doing a "very large" piece of work per iteration for the Concurrent Collections to perform better than a single threaded solution?

You could say that, as long as "very large" means something like "operation that takes more than an order of magnitude longer than a concurrent collection operation". But since concurrent collection operations are still pretty fast, your "very large" is actually not large at all.

Concurrent collections are not really meant to compete with standard collections, instead they compete with locking, which is what you would normally do when you wanted to modify the same collection from multiple threads. And compared with locking, concurrent collections are more efficient (and also easier to use correctly).

But parallelization or concurrent collections are not a silver bullet, they won't make code that can't be parallelized well magically faster.

There are also some issues with your benchmark, which may affect the results:

Random is not thread-safe, you shouldn't use it from multiple threads.

You're reusing the same collection in subsequent tests. That's problematic, because it means only the first measurement includes resizing the collection.

Your "Functional style" test generates lots of garbage that likely won't be collected by the end of the test. For that reason, I prefer to call GC.Collect() before stopping the stopwatch. This way, code that generates lots of garbage is properly penalized.

ContentLicense: CC BY-SA 3.0


问:
Recommendations for adding exceptions messages to code
The "problem" that I am having right now its quite simple, I am creating a code with A LOT of validations, in case one of those fails it is supposed to throw an exception.

In order to make the messages explicit in favor of depicting the reason for the exception I need to write a "considerable" amount of text. This wouldn't be an issue if it were only a couple of exceptions, but now I am in direct course to end with a file with more text (for the exception messages) than code.

I would like to get some suggestions/alternatives to put all that text out of my code (I was thinking on having it in variables at the top of the file but that is not very smart "memoriwise-able" speaking).

Example

```<code>if (operator.isBitwiseOperator()) {
    // >>=, <<=, &=, |=, ^=
    if (!(IntegerStmt.isAnIntegerAsignableClass(fstOpClass)
            && IntegerStmt.isAnIntegerAsignableClass(sndOpClass))) {
        if ((operator.equals(Operator.AND_ASSIGN)
                || operator.equals(Operator.OR_ASSIGN)
                || operator.equals(Operator.XOR_ASSIGN))
                    && !(LogicalInfo.isBoolean(fstOpClass)
                        && LogicalInfo.isBoolean(sndOpClass))) {
                    throw new UnsupportedOperationException(
                            "In order to use a bitwise logical assign "
                                    + "operator (&=, |=, ^=) it is "
                                    + "necessary booth operands to be "
                                    + "either an integer assignable type "
                                    + INTEGER_ASSIGNABLE_VALUES
                                    + " or a logical boolean value "
                                    + "(b/Boolean)");
        } else {
            throw new UnsupportedOperationException(
                            "In order to use a bitwise assign operator it is "
                                    + "necessary booth operands to be an "
                                    + "integer assignable type "
                                    + INTEGER_ASSIGNABLE_VALUES);
        }
    }
}
</code>```

Now, like that example which shows that I have "some" exceptions that I consider as not terribly long, I have many, so from drop to drop I am filling the glass :/ ...

答:
I will start with the recommendation to read "Clean Code" by Robert Martin. If we follow recommendations from that book, you could :

break that huge if tree into smaller chunks of code

put throwing exceptions into private methods at the end of files

And that would be the solution to your problem. That way, the text will not interfere with the logic.

Something like this :

```<code>if (operator.isBitwiseOperator()) {
    // >>=, <<=, &=, |=, ^=
    if (!(IntegerStmt.isAnIntegerAsignableClass(fstOpClass)
            && IntegerStmt.isAnIntegerAsignableClass(sndOpClass))) {
        if ((operator.equals(Operator.AND_ASSIGN)
                || operator.equals(Operator.OR_ASSIGN)
                || operator.equals(Operator.XOR_ASSIGN))
                    && !(LogicalInfo.isBoolean(fstOpClass)
                        && LogicalInfo.isBoolean(sndOpClass))) {
            ThrowExceptionForNotIntTypes();

        } else {
            ThrowExceptionForIncopatibleTypes();
        }
    }
}

private void ThrowExceptionForNotIntTypes() {
  throw new UnsupportedOperationException(
                            "In order to use a bitwise logical assign "
                                    + "operator (&=, |=, ^=) it is "
                                    + "necessary booth operands to be "
                                    + "either an integer assignable type "
                                    + INTEGER_ASSIGNABLE_VALUES);
}

private void ThrowExceptionForIncopatibleTypes() {
  throw new UnsupportedOperationException(
                            "In order to use a bitwise assign operator it is "
                                    + "necessary booth operands to be an "
                                    + "integer assignable type "
                                    + INTEGER_ASSIGNABLE_VALUES);
}
</code>```

Body:
I will start with the recommendation to read "Clean Code" by Robert Martin. If we follow recommendations from that book, you could :

break that huge if tree into smaller chunks of code

put throwing exceptions into private methods at the end of files

And that would be the solution to your problem. That way, the text will not interfere with the logic.

Something like this :

if (operator.isBitwiseOperator()) {
    // >>=, <<=, &=, |=, ^=
    if (!(IntegerStmt.isAnIntegerAsignableClass(fstOpClass)
            && IntegerStmt.isAnIntegerAsignableClass(sndOpClass))) {
        if ((operator.equals(Operator.AND_ASSIGN)
                || operator.equals(Operator.OR_ASSIGN)
                || operator.equals(Operator.XOR_ASSIGN))
                    && !(LogicalInfo.isBoolean(fstOpClass)
                        && LogicalInfo.isBoolean(sndOpClass))) {
            ThrowExceptionForNotIntTypes();

        } else {
            ThrowExceptionForIncopatibleTypes();
        }
    }
}

private void ThrowExceptionForNotIntTypes() {
  throw new UnsupportedOperationException(
                            "In order to use a bitwise logical assign "
                                    + "operator (&=, |=, ^=) it is "
                                    + "necessary booth operands to be "
                                    + "either an integer assignable type "
                                    + INTEGER_ASSIGNABLE_VALUES);
}

private void ThrowExceptionForIncopatibleTypes() {
  throw new UnsupportedOperationException(
                            "In order to use a bitwise assign operator it is "
                                    + "necessary booth operands to be an "
                                    + "integer assignable type "
                                    + INTEGER_ASSIGNABLE_VALUES);
}


问:
Python -- Class and Object
I got a question that quite disturbs me a lot and I think it might help a lot if I had an answer to it. So I got this:

```<code>class Klasse1:
    variable1 = "haha"
class Klasse2:
    variable2 = "hoho"

print Klasse1.variable1
print Klasse2.variable2
</code>```

and this:

```<code>class Klasse1:
    variable1 = "haha"
class Klasse2:
    variable2 = "hoho"

Object1 = Klasse1()
Object2 = Klasse2()
print Object1.variable1
print Object2.variable2
</code>```

Now the question is: Why would I use the second(too much code) instead of the first(obviously easier.) In many sites and tutorials I've seen people create objects for something they could easily get without creating them. So I'm probably missing something and I would like to know.

P.S. Same case with Java

答:
Why would I use the second(too much code) instead of the
  first(obviously easier.)

Just so we're clear, I assume you know difference between class and instance variable. If you do, you know that it makes no sense to actually create an instance of a class just to access (read/write) a class variable. That would be absurd.

So I'm going to reinterpret the question like this:

If I have an instance Object1 of class Klasse1 and I wish to access a class variable variable1, should I use Klasse1.variable1 or Object1.variable1?

Technically both are correct.

IMHO you must use Klasse1.variable1 as a matter of convention (even when you had an instance of Klasse1 at hand). It's cleaner code; it tells reader that you're accessing a class variable and not instance variable.

Title: Python -- Class and Object


答:
Throw an error code, and then use it to lookup the lengthy text. That text could even be placed in a locale-specific resources file.

That said, I'd throw a short human-readable error message as well just so an admin reading logs would be able to understand which error it was without having to look it up.

Title: Recommendations for adding exceptions messages to code

Body:
The "problem" that I am having right now its quite simple, I am creating a code with A LOT of validations, in case one of those fails it is supposed to throw an exception.

In order to make the messages explicit in favor of depicting the reason for the exception I need to write a "considerable" amount of text. This wouldn't be an issue if it were only a couple of exceptions, but now I am in direct course to end with a file with more text (for the exception messages) than code.

I would like to get some suggestions/alternatives to put all that text out of my code (I was thinking on having it in variables at the top of the file but that is not very smart "memoriwise-able" speaking).

Example

```<code>if (operator.isBitwiseOperator()) {
    // >>=, <<=, &=, |=, ^=
    if (!(IntegerStmt.isAnIntegerAsignableClass(fstOpClass)
            && IntegerStmt.isAnIntegerAsignableClass(sndOpClass))) {
        if ((operator.equals(Operator.AND_ASSIGN)
                || operator.equals(Operator.OR_ASSIGN)
                || operator.equals(Operator.XOR_ASSIGN))
                    && !(LogicalInfo.isBoolean(fstOpClass)
                        && LogicalInfo.isBoolean(sndOpClass))) {
                    throw new UnsupportedOperationException(
                            "In order to use a bitwise logical assign "
                                    + "operator (&=, |=, ^=) it is "
                                    + "necessary booth operands to be "
                                    + "either an integer assignable type "
                                    + INTEGER_ASSIGNABLE_VALUES
                                    + " or a logical boolean value "
                                    + "(b/Boolean)");
        } else {
            throw new UnsupportedOperationException(
                            "In order to use a bitwise assign operator it is "
                                    + "necessary booth operands to be an "
                                    + "integer assignable type "
                                    + INTEGER_ASSIGNABLE_VALUES);
        }
    }
}
</code>```

Now, like that example which shows that I have "some" exceptions that I consider as not terribly long, I have many, so from drop to drop I am filling the glass :/ ...


问:
Custom Outlook Web App Shared Mailbox
We currently have a large amount of custom mailboxes hosted on Lotus Notes/Domino and have been tasked to migrate these over to our Outlook/Exchange environment.

The mailboxes are basic Lotus Notes shared mailbox that a group of users have access to, but the mailboxes functionality has been extended to provide features that are bespoke to the business, such as an auto-reply feature and several other workflow orientated features.

I am looking for a way to do a similar thing but with our Outlook/Exchange environment. Something along the lines of a custom Outlook Web App.

My first thought was to use the Outlook API and subscribe to the NewMail event, then run some code that would strip out the information from the incoming email and create a database record from it with maybe an MVC front end to manage it all.

However I am aware that it is also possible to create custom fields on the actual message item itself on the Exchange server, therefore it may be possible to use the actual email itself in place of the database record, however I don't know the implications of doing this from a performance or load perspective.

I'm also aware that you can create extensions for the Outlook client itself, this may be an option if we could create a plugin that provides the custom bespoke functionality.

What other approaches could I take to implement a similar kind of functionality that has not been listed above, and which if any would be the most sensible approach ?

答:
The most sensible one would be to implement the function in Exchange ( the server ) rather than on the client ( Outlook ) if for no other reason then you'd need to make sure the outlook client is running somewhere. This was an object lesson in building exchange extension through client functionality.

If they won't let you near the server I would look at using the exchange API in a custom app rather than hanging it off office mainly so you can run it as a service without user interaction, Office presumes an interactive session.

Title: Custom Outlook Web App Shared Mailbox


答:
Good exception messages are important. However, the exception messages generated by a piece of code might not always be suitable for an end user. You can therefore defer construction of an error message to an outer layer. Your exceptions should instead contain all the necessary data to construct a message. This implies that you create sufficient application-specific exception classes.

If you are creating a library rather than an application, fine-grained exception hierarchies are more useful than the ability to add a error message localization layer, but a bit of abstraction will still come in very useful. Especially, common code should be factored out. In your case, both messages have very similar syntactic structure. You could therefore create a message template and simply fill in the blanks when throwing an exception. Or you could create a helper function that creates an exception.

I would rewrite your code as

// making the exception format public makes testing easier
public static final String BITWISE_ASSIGN_ERROR_MESSAGE_FORMAT = "In order to use %1s it is necessary that both operators be %2s"

...

// >>=, <<=, &=, |=, ^=
if (operator.isBitwiseOperator()) {
    checkBitwiseOperator(...);
}

...

private void checkBitwiseOperator(...) {
    bool operandsAreIntegerAssignable =
         IntegerStmt.isAnIntegerAsignableClass(fstOpClass)
      && IntegerStmt.isAnIntegerAsignableClass(sndOpClass);
    bool operandsAreBoolean =
         LogicalInfo.isBoolean(fstOpClass)
      && LogicalInfo.isBoolean(sndOpClass)
    bool operatorIsLogicalAssign =
         operator.equals(Operator.AND_ASSIGN)
      || operator.equals(Operator.OR_ASSIGN)
      || operator.equals(Operator.XOR_ASSIGN);

    // special-case &=, |=, ^= – they can be integer or boolean
    if (operatorIsLogicalAssign && !operandsAreBoolean) {
        if (operandsAreInteger || operandsAreBoolean)
            return;

        throw new UnsupportedOperationException(
            String.format(BITWISE_ASSIGN_ERROR_MESSAGE_FORMAT,
                "a bitwise logical assignment operator (&=, |=, ^=)",
                "either integer assignable " + INTEGER_ASSIGNABLE_VALUES + " or a boolean value"));
    }

    // the shift-assignment operators can only work on integers
    if (operandsAreIntegerAssignable)
      return;

    throw new UnsupportedOperationException(
        String.format(BITWISE_ASSIGN_ERROR_MESSAGE_FORMAT,
            "bitwise assignment operator",
            "integer assignable " + INTEGER_ASSIGNABLE_VALUES));
}
```

<p>The next step would be to extract message construction. Note that your code is essentially doing type-checking, so we could create a special exception class for that. It could show the surrounding code, print the line number, and explain the types. This gets more powerful when you have a sufficient explicit model of the available operations. This could e.g. allow you to create an exception such as</p>

```throw new TypeError(expectedType, actualType, expression.sourceInfo());
```

<p>and get an error message created by that exception type like</p>

```inputFile:32:6: TypeError
expected operator |= (Int left, Int right)
      or operator |= (Bool left, Bool right)
but found "x" of type String
      and "y + 2" of type Int
here:
foo(x |= y + 2)
    ~~^~~~~~~~
```

This is extremely user-friendly, but hard to get right (for starters, you need an actual model of the type system in your code, and a mechanism to connect types with snippets of source code).

Body:
Good exception messages are important. However, the exception messages generated by a piece of code might not always be suitable for an end user. You can therefore defer construction of an error message to an outer layer. Your exceptions should instead contain all the necessary data to construct a message. This implies that you create sufficient application-specific exception classes.

If you are creating a library rather than an application, fine-grained exception hierarchies are more useful than the ability to add a error message localization layer, but a bit of abstraction will still come in very useful. Especially, common code should be factored out. In your case, both messages have very similar syntactic structure. You could therefore create a message template and simply fill in the blanks when throwing an exception. Or you could create a helper function that creates an exception.

I would rewrite your code as

// making the exception format public makes testing easier
public static final String BITWISE_ASSIGN_ERROR_MESSAGE_FORMAT = "In order to use %1s it is necessary that both operators be %2s"

...

// >>=, <<=, &=, |=, ^=
if (operator.isBitwiseOperator()) {
    checkBitwiseOperator(...);
}

...

private void checkBitwiseOperator(...) {
    bool operandsAreIntegerAssignable =
         IntegerStmt.isAnIntegerAsignableClass(fstOpClass)
      && IntegerStmt.isAnIntegerAsignableClass(sndOpClass);
    bool operandsAreBoolean =
         LogicalInfo.isBoolean(fstOpClass)
      && LogicalInfo.isBoolean(sndOpClass)
    bool operatorIsLogicalAssign =
         operator.equals(Operator.AND_ASSIGN)
      || operator.equals(Operator.OR_ASSIGN)
      || operator.equals(Operator.XOR_ASSIGN);

    // special-case &=, |=, ^= – they can be integer or boolean
    if (operatorIsLogicalAssign && !operandsAreBoolean) {
        if (operandsAreInteger || operandsAreBoolean)
            return;

        throw new UnsupportedOperationException(
            String.format(BITWISE_ASSIGN_ERROR_MESSAGE_FORMAT,
                "a bitwise logical assignment operator (&=, |=, ^=)",
                "either integer assignable " + INTEGER_ASSIGNABLE_VALUES + " or a boolean value"));
    }

    // the shift-assignment operators can only work on integers
    if (operandsAreIntegerAssignable)
      return;

    throw new UnsupportedOperationException(
        String.format(BITWISE_ASSIGN_ERROR_MESSAGE_FORMAT,
            "bitwise assignment operator",
            "integer assignable " + INTEGER_ASSIGNABLE_VALUES));
}

The next step would be to extract message construction. Note that your code is essentially doing type-checking, so we could create a special exception class for that. It could show the surrounding code, print the line number, and explain the types. This gets more powerful when you have a sufficient explicit model of the available operations. This could e.g. allow you to create an exception such as

throw new TypeError(expectedType, actualType, expression.sourceInfo());

and get an error message created by that exception type like

inputFile:32:6: TypeError
expected operator |= (Int left, Int right)
      or operator |= (Bool left, Bool right)
but found "x" of type String
      and "y + 2" of type Int
here:
foo(x |= y + 2)
    ~~^~~~~~~~

This is extremely user-friendly, but hard to get right (for starters, you need an actual model of the type system in your code, and a mechanism to connect types with snippets of source code).


问:
How can I diagnose async/await deadlocks?
I am working with a new codebase that makes heavy use of async/await. Most of the people on my team are also fairly new to async/await. We generally tend to hold to Best Practices as Specified by Microsoft, but generally need our context to flow through the async call and are working with libraries that don't ConfigureAwait(false).

Combine all of those things and we run into async deadlocks described in the article... weekly. They don't show up during unit testing, because our mocked data sources (usually via Task.FromResult) aren't enough to trigger the deadlock. So during runtime or integration tests, some service call just goes out to lunch and never returns. That kills the servers, and generally makes a mess of things.

The problem is that tracking down where the mistake was made (usually just not being async all the way up) generally involves manual code inspection, which is time consuming and not automate-able.

What's a better way of diagnosing what caused the deadlock?

答:
Here's a strategy that I used in a huge and very, very multithreaded application:

First, you need some data structure around a mutex (unfortunately) and make no synchronising calls directory. In that data structure, there's a link to any previously locked mutex. Every mutex has a "level" starting at 0, which you assign when the mutex is created and can never change.

And the rule is: If a mutex is locked, you must only ever lock other mutexes at a lower level. If you follow that rule, then you can't have deadlocks. When you find a violation, your application is still up and running just fine.

When you find a violation, there are two possibilities: You may have assigned the levels wrong. You locked A followed by locking B, so B should have had a lower level. So you fix the level and try again.

The other possibility: You can't fix it. Some code of yours locks A followed by locking B, while some other code locks B followed by locking A. There's no way to assign the levels to allow this. And of course this is a potential deadlock: If both codes run simultaneously on different threads, there's a chance of deadlock.

After introducing this, there was a rather short phase where levels had to be adjusted, followed by a longer phase where potential deadlocks were found.


问:
Should I use future or present tense when writing a design spec document?
I'm writing a Design Specification Document for a college project and wondering about the tense I should use. The development on the project has not yet started, I'm just writing the UI design section.

Should I use:

This app is built around a two column layout, with a header element.

or

This app will be built around a two column layout, with a header element.

I will obviously continue whatever tense is best throughout the document.

Edit to clarify what I'm actualy writing

The course module discriptor says this:

A detailed ‘design specification’ based on the requirements specification. The completed design specification should be comprehensive and should allow a third party to use your design specification as the basis for implementation. It therefore should be clear, concise and detailed. It may contain: a navigation map to clearly show how you propose how to link various pages or screens; a series of detailed storyboards to illustrate page layout, colour schemes, typography (fonts, sizes, styling, alignment), use of media elements (eg icons, graphics, sound, video, animation) or interaction styles. Justification of design decisions should also be present.

答:
It doesn't matter

It's the content of the spec which is important, not the presentation - and "presentation" includes things like language. The exception here is if the presentation is so bad readers are significantly hampered in their understanding of the content, but present vs future tense isn't going to cause that kind of problem.


答:
Consistency is probably the overriding concern.

For the sake of accuracy, if the documentation pertains to an existing system, possibly one being enhanced, present tense.  If the system doesn't exist yet, then future tense, since you are describing something that will happen (hopefully), but hasn't yet.

One thing to consider is that these documents often lead to generation of some of the test cases.  In that sense it is better to use future tense, which will then be confirmed in testing.  Every "will" or "shall" in the requirements is something that can be tested and confirmed.  "does" or "is" implies prior completion and therefore something that does not need to be tested.

Edit, for those who dislike the consistency perspective:

In a development world moving further and further away from rigorous design, requirements and test documents, the consistency and readability of the document are important.  And since these documents are less likely to be the sole reference for completion/correctness, the choice between present and future tense is much less important.

For a project which will still a use rigorous documentation process, precision and accuracy of wording (and the consistent application thereof) are critical.

Title: Should I use future or present tense when writing a design spec document?

Body:
I'm writing a Design Specification Document for a college project and wondering about the tense I should use. The development on the project has not yet started, I'm just writing the UI design section.

Should I use:

This app is built around a two column layout, with a header element.

or

This app will be built around a two column layout, with a header element.

I will obviously continue whatever tense is best throughout the document.

Edit to clarify what I'm actualy writing

The course module discriptor says this:

A detailed ‘design specification’ based on the requirements specification. The completed design specification should be comprehensive and should allow a third party to use your design specification as the basis for implementation. It therefore should be clear, concise and detailed. It may contain: a navigation map to clearly show how you propose how to link various pages or screens; a series of detailed storyboards to illustrate page layout, colour schemes, typography (fonts, sizes, styling, alignment), use of media elements (eg icons, graphics, sound, video, animation) or interaction styles. Justification of design decisions should also be present.


答:
In your small example it makes no difference between the first and second example. Either is fine.

The difference becomes important with real world examples, such as when you want to have multiple instances of a class. For example, consider a game. If you are a single-player game, your first example is fine. Create the class, and reference the values directly in the class.

However, what do you do when you have a multiplayer game and variable1 represents the player's score? You can create a Player1 class and a Player2 class, and your first example continues to work. Now what do you do if in addition to score, you have 100 other attributes? Do you have two identical classes that are defined exactly the same? What if you want to support 100 players? Or 1000? Do you create 1000 classes that are identical, only differing by the name of the class?

This is why classes are so powerful: you define the class exactly once, and then you can create as many instances of that class that you want. Whether you have one player or 1000, you only have to define the player class once, yet each class has it's own data 1

So, for simple examples, why go to the trouble of creating instances? The reason is that it builds good habits. If you get into the habit of creating classes and instantiating them, when the time comes to make a more complex application you won't have to change the way you work.

Bottom line: for any non-trivial definition of an object, your code will be much easier to maintain if you have a single class with multiple instances.

1 if we literally use your example code, each player will share the same score. However, if you create classes with instance attributes rather than class attributes, each player will get its own score.

Title: Python -- Class and Object

Body:
I got a question that quite disturbs me a lot and I think it might help a lot if I had an answer to it. So I got this:

```<code>class Klasse1:
    variable1 = "haha"
class Klasse2:
    variable2 = "hoho"

print Klasse1.variable1
print Klasse2.variable2
</code>```

and this:

```<code>class Klasse1:
    variable1 = "haha"
class Klasse2:
    variable2 = "hoho"

Object1 = Klasse1()
Object2 = Klasse2()
print Object1.variable1
print Object2.variable2
</code>```

Now the question is: Why would I use the second(too much code) instead of the first(obviously easier.) In many sites and tutorials I've seen people create objects for something they could easily get without creating them. So I'm probably missing something and I would like to know.

P.S. Same case with Java


答:
It depends on what you're writing.

If you're writing requirements, then the answer is "neither". Another question here on Software Engineering addresses the use of "shall" and "must" when writing requirements. The guidance that I use at work is that "shall" is used to denote any requirements that must be met for the software to be acceptable to the customer, "should" marks off desired characteristics, "may" is used to identify anything that is optional, and "will" is anything that can be relied upon after the mandatory and any desired or optional characteristics are implemented. If you're not writing your requirements as statements, but using use cases or user stories, you'll want to follow the conventions of that format.

If you're writing about software that already exists, then you should be using the present tense. The software already exists, so it "is" something or "does" something.

If you're trying to define requirements and document a design approach at the same time, I would recommend not doing that and understanding the value of separating what functions the software must expose and the non-functional attributes of the software versus documenting how the software is decomposed or how to use the software. Separation of requirements, technical design, and usage (user's manuals) is very important.

To address your specific needs, I think the best thing to do would be is to ask your course instructor or someone else who understands what they are looking for. In my experiences, this type of document doesn't exist in any form of modern software development, so asking professional software engineers how to produce a document that is acceptable to your particular customer (in this case, your professor or grader) won't get you the best answers, especially since I don't think that the answer of "don't do this, it's not good practice, look at your development methodology and approach instead" will get you very far in the course.

A detailed ‘design specification’ based on the requirements specification. The completed design specification should be comprehensive and should allow a third party to use your design specification as the basis for implementation. It therefore should be clear, concise and detailed. It may contain: a navigation map to clearly show how you propose how to link various pages or screens; a series of detailed storyboards to illustrate page layout, colour schemes, typography (fonts, sizes, styling, alignment), use of media elements (eg icons, graphics, sound, video, animation) or interaction styles. Justification of design decisions should also be present.

The requirements specification is the basis for implementing the software, either by an internal or external team. It should not only have your functional characteristics, but design constraints, performance and other quality attributes, user characteristics, required interfaces, and so on. The requirements specification is the agreement between the customer and software supplier.

What you're being told to put into the document is indeed design information. However, it's consistent with "big design up front" approaches to software development where you don't write code until you "finished" your design. However, I'm not aware of very many organizations that embrace this approach.

ContentLicense: CC BY-SA 4.0


问:
Is this code structure beneficial in any way?
I was recently thrown into a Java web application project, and I’ve come across a number of classes that follow this type of format:

```<code>public class MyThingy {
   private final int p1;
   private final String p2;
   …

   public MyThingy (int p1, String p2, …) {
      this.p1 = p1;
      this.p2 = p2;
      …
   }

   public static void doSomething(int p1, String p2, …) throws Throwable     {
      final MyThingy myThingy = new MyThingy(p1, p2, …);
      myThingy.execute();
   }

   private void execute() throws Throwable {
      //do stuff
   }
}
</code>```

It seems like this could be accomplished with the following code, which to me seems way easier to read.

```<code>public class MyThingy {

   public static void doSomething (int p1, String p2, …) throws Throwable {
      //do stuff
   }

}
</code>```

The only possible benefit I can see from doing it the first way, is that if you had to break up execute() into smaller pieces, they could all share the initial parameters without having to explicitly pass them around.  But this maybe only benefits the lazy coder, as it becomes difficult for the reader to tell which methods need which parameters and when the values might be changed (akin to global variables.)

Is there something I'm missing? Threading, performance?

Edit:
I should have mentioned, although the constructor is public, it is not called.  The only usage is like this:

```<code>MyThingy.doSomething(p1, p2...);
</code>```

Aside from this in itself being problematic for testing, I can't see any reason not to put the logic of execute() directly into doSomething().  Even if we were to get rid of the static function, the constructor still doesn't make sense to me; I think the parameters should be passed directly to the method that will use them.

答:
Well, if your second example (showing the complete code) looks like this:

```<code>public static void doSomething(int p1, String p2, …) throws Throwable     {
      final MyThingy myThingy = new MyThingy(p1, p2, …);
      myThingy.execute();
   }
</code>```

then you're still going to need the constructor

```<code>public MyThingy (int p1, String p2, …) {
      this.p1 = p1;
      this.p2 = p2;
      …
   }
</code>```

which in turn sets

```<code>   private final int p1;
   private final String p2;
</code>```

and now you're back where you started.

You could, of course, just eliminate the constructor and go with getters and setters instead

```<code>private final int p1;
private final String p2;

public void SetP1(int p1)
{
    this.p1 = p1;
}

public int GetP1()
{
    return p1;
}
// repeat for p2
</code>```

...but this will complicate your static method call, as you will now need several lines of code to call the setters first before calling your static method, where a single line making use of the constructor call would have sufficed.

Of course, this only works if your member variables are not final.  Therefore, you're still going to need the constructor.

Body:
Well, if your second example (showing the complete code) looks like this:

public static void doSomething(int p1, String p2, …) throws Throwable     {
      final MyThingy myThingy = new MyThingy(p1, p2, …);
      myThingy.execute();
   }

then you're still going to need the constructor

public MyThingy (int p1, String p2, …) {
      this.p1 = p1;
      this.p2 = p2;
      …
   }

which in turn sets

   private final int p1;
   private final String p2;

and now you're back where you started.

You could, of course, just eliminate the constructor and go with getters and setters instead

private final int p1;
private final String p2;

public void SetP1(int p1)
{
    this.p1 = p1;
}

public int GetP1()
{
    return p1;
}
// repeat for p2

...but this will complicate your static method call, as you will now need several lines of code to call the setters first before calling your static method, where a single line making use of the constructor call would have sufficed.

Of course, this only works if your member variables are not final.  Therefore, you're still going to need the constructor.


问:
How to improve performance for serializing and deserializing a large object graph?
I have a large object graph in .NET (F# as it happens) that I need to persist to disk and then will load again periodically for use in a calculation.

The performance of deserializing is more important (will be performed many times) than the seriliazing (will only be performed once) should that have a bearing on the answer.

Currently, I am using FsPickler and using their binary format. This is very convenient / easy-to-use but I am trying to get a handle on how much more performance I would get by customizing a serializer/deserializer...

One avenue I am considering is to persist and load from a small relational database (I have sqlite in mind). Should I expect this to be much faster?

Per request below, I have provided a slightly simplified version of the object graph that I am working on below:

CODE

```<code>type Value =
    | Float of float
    | String of string
    | Bool of bool

[<Struct>]
type Address (i:int, j:int, k:int) =
    member this.I = i
    member this.J = j
    member this.K = k

type Data = {
    Target:Address
    mutable SpecialIndex:int
    mutable Parameters1 : Value []
    mutable Parameters2 : Address []
    Check1 : bool
    Check2:bool
    Parent: Address option
}

type Persisted =
    {
      Inputs : Address []
      Outputs : Address []
      Aliases : Dictionary<string, Address>
      Mapping : Dictionary<string, int>
      Masters: Dictionary<Address, Value[]>
      BigCollection : Data [] }
</code>```

The object that is persisted is an instance of Persisted.

The large size is most likely to come about due to Persisted.BigCollection being in the order of 10m or more items in the array.

答:
One avenue I am considering is to persist and load from a small relational database (I have sqlite in mind). Should I expect this to be much faster?

No, you should not expect this. Though it is not completely impossible, to my experience using a relational database for deserializing an object graph is seldom quicker than deserializing from a file. To my experience, relational databases can only help to increase performance when you can play out their strengths like indexing capabilites or managing of external data which is too big to be loaded into memory at once.

I am trying to get a handle on how much more performance I would get by customizing a serializer/deserializer.

Whatever serializer/deserializer you use, the upper limit (and often the bottleneck) for performance is the I/O speed of your disk in "bytes per second". So look at the expected size in bytes of your serialized graph, divide it by the speed, and you will get a lower limit for the deserialization time. When the time your deserializer needs is near to that limit, the only resonable way to increase performance is to use a faster disk (like a modern SSD or something like that).


问:
When NOT to apply the Dependency Inversion Principle?
I am currently trying to figure out SOLID. So the Dependency Inversion Principle means that any two classes should communicate via interfaces, not directly. Example: If class A has a method, that expects a pointer to an object of type class B, then this method should actually expect an object of type abstract base class of B. This is helps for Open/Close as well.

Provided that I understood that correctly, my question would be is it a good practice to apply this to all class interactions or should I try to think in terms of layers?

The reason I am skeptical is because we are paying some price for following this principle. Say, I need to implement feature Z. After analysis, I conclude that feature Z consists of functionality A, B and C. I create a facade class Z, that, through interfaces, uses classes A, B and C. I begin coding the implementation and at some point I realize that task Z actually consists of functionality A, B and D. Now I need to scrap the C interface, the C class prototype and write separate D interface and class. Without interfaces, only the class would've needed to be replaced.

In other words, to change something, I need to change 1. the caller 2. the interface 3. the declaration 4. the implementation. In a python directly coupled implementation, I would need to change only the implementation.

答:
Some signs you may be applying DIP at too micro of a level, where it's not providing value:

you have a C/CImpl or IC/C pair, with only a single implementation of that interface

the signatures in your interface and implementation match one-to-one (violating DRY principle)

you frequently change C and CImpl at the same time.

C is internal to your project and not shared outside your project as a library.

you are frustrated by F3 in Eclipse/F12 in Visual Studio taking you to the interface instead of the actual class

If this is what you're seeing, you might be better off just having Z call C directly and skip the interface.

Also, I don't think of method decoration by a dependency injection / dynamic proxy framework (Spring, Java EE) the same way as true SOLID DIP - this is more like an implementation detail of how method decoration works in that tech stack.  The Java EE community considers it an improvement that you don't need Foo/FooImpl pairs like you used to (reference). By contrast, Python supports function decoration as a first-class language feature.

See also this blog post.


问:
Code quality : what's the worth of the looking at the ifs?
We've all seen discussions on the ideal length of a method. My favourite litmus test for code quality is to look at the "if" statements, to see whether the values being tested belong to the current class. The further removed the tested value from the context of the test, the stronger the smell of a modelling problem.

So my question is... can anyone fill me in on the origin and the worth of this measure. Is this a recognised metric? Is it possible/desireable to model objects such that all conditional logic tests only class members? What importance would you give to this measure?

答:
look at the "if" statements, to see whether the values being tested belong to the current class

What do you mean by value belongs to the current class?
Are you encouraging state to be duplicated across objects?

I'd argue the counter argument actually. An object can have public boolean properties or methods that contain state information relevant to other objects to test.

Singletons

Many times singletons (particularly in iOS dev) will have a bool to test that service's availability but it is useful for other objects to test.

```<code>if (NetworkManager.sharedInstance().isInternetAvailable())
</code>```

Data Structures

What about a DTO or custom data structure object:

```<code>if (jsonDictionary.count > 0)
if (person.age >= 21)
</code>```

Let's say the data structures above are being used by a controller (in MVC) what business does a controller have in storing the age of a person when there is an age on the person object.

Body:
look at the "if" statements, to see whether the values being tested belong to the current class

What do you mean by value belongs to the current class?
Are you encouraging state to be duplicated across objects?

I'd argue the counter argument actually. An object can have public boolean properties or methods that contain state information relevant to other objects to test.

Singletons

Many times singletons (particularly in iOS dev) will have a bool to test that service's availability but it is useful for other objects to test.

if (NetworkManager.sharedInstance().isInternetAvailable())

Data Structures

What about a DTO or custom data structure object:

if (jsonDictionary.count > 0)
if (person.age >= 21)

Let's say the data structures above are being used by a controller (in MVC) what business does a controller have in storing the age of a person when there is an age on the person object.


答:
The extra indirection through the static method call separates the concerns of how an object is created from the code that uses the object. What you have here is something very similar to a simple factory method (it does not actually return the object, but the indirection of object creation is the same).

This can be useful if you need to control the type of object that is created. In this simple example there is no decision to be made, but it would be easy to add that logic.

What the static code means to callers is "I need to do something with this state but don't know how to delegate." The static method can then delegate to the proper implementation based on the object provided.

Perhaps when running in a unit test there is a mock object being used. Maybe based on the parameters a different object could be swapped in that implements a different algorithm for doing whatever it needs to do. By localizing that code to one location, the decision can be made in one place rather than arbitrarily many.

Given how your question is worded and the fact that no construction decision is being made in the static methods, I have a feeling this might just be a case of over-engineering. Most code does not need to delegate to a factory. The fact that you keep encountering code like this that does not make any decisions as I would expect a static factory-like method to do tells me someone read the GoF book and ran amok.

Title: Is this code structure beneficial in any way?

Body:
I was recently thrown into a Java web application project, and I’ve come across a number of classes that follow this type of format:

```<code>public class MyThingy {
   private final int p1;
   private final String p2;
   …

   public MyThingy (int p1, String p2, …) {
      this.p1 = p1;
      this.p2 = p2;
      …
   }

   public static void doSomething(int p1, String p2, …) throws Throwable     {
      final MyThingy myThingy = new MyThingy(p1, p2, …);
      myThingy.execute();
   }

   private void execute() throws Throwable {
      //do stuff
   }
}
</code>```

It seems like this could be accomplished with the following code, which to me seems way easier to read.

```<code>public class MyThingy {

   public static void doSomething (int p1, String p2, …) throws Throwable {
      //do stuff
   }

}
</code>```

The only possible benefit I can see from doing it the first way, is that if you had to break up execute() into smaller pieces, they could all share the initial parameters without having to explicitly pass them around.  But this maybe only benefits the lazy coder, as it becomes difficult for the reader to tell which methods need which parameters and when the values might be changed (akin to global variables.)

Is there something I'm missing? Threading, performance?

Edit:
I should have mentioned, although the constructor is public, it is not called.  The only usage is like this:

```<code>MyThingy.doSomething(p1, p2...);
</code>```

Aside from this in itself being problematic for testing, I can't see any reason not to put the logic of execute() directly into doSomething().  Even if we were to get rid of the static function, the constructor still doesn't make sense to me; I think the parameters should be passed directly to the method that will use them.


答: Usually a class has lots of instance methods, and once the object is created, the implementation of execute can take advantage of all these instance methods. If you refuse to create an object, all these instance methods are useless. </p>


问:
Can I use data from the Amazon API in my App?
I'm having a hard time finding information on this, but using the Amazon API (such as the ItemSearch api) provides you with data on Amazon products. In my case I am interested in books.

The Amazon API generates links to pictures of the books and details on the books.

I want to use this in my smartphone app, but Google appears to want proof that I am allowed to display that information in my app. They are saying that the book information and particularly book covers, could be copyrighted and I need to show proof I can use those in my app.

The Amazon API is free and they give you a key and what not for you to use.

Could anyone who knows something about this either enlighten me or better yet, provide a link to some sort of FAQs or documentation that tells me outright whether I can or cannot use data from the Amazon API in my web-app or smartphone app or whatever app?

I can't for the life of me find what I am looking for and Amazon is so big.

Cheers!

答:
INAL, but it was quite easy to find the relevant license agreement, where it says:

2. Enrollment

To begin the enrollment process, you must submit a complete and accurate enrollment form. In your enrollment form, you must describe the application you intend to develop and use with the Product Advertising API or on which you intend to display Product Advertising Content. We will evaluate your enrollment form and notify you of its acceptance or rejection. We may reject your enrollment form if we determine that your application is unsuitable. Unsuitable applications include those that:

In other words, it seems like you need to explicitly request the permission from Amazon to use that data in your application. If Amazon accepts your enrollment form and grants you a permission, you can display it to Google as the proof they require. If Amazon rejects your request you are not allowed to use their data in your application anyways.


问:
Parsing an object from multiple source files
I receive zip files and they have as content 8 different files, each with it's own metadata inside.

I have to combine these files into 1 object containing certain metadata. The big issue here is that there will not always be 8 files and the metadata i want to retrieve could be in any of these files stored in there own way.

for now i have created a factory method that initiates the correct parser for each file type and the parser returns the object with the metadata it was able to parse.

Now when this is done i have 8 object's i have to merge into 1 result object with the metadata gathered from these results.

so i could have something like this

```<code>object  Meta1    Meta2    Meta3    Meta4    Meta5
1       A        -        15       RT       -
2       -        -        15       -        HIGH
3       A        -        15       RT       HIGH
4       -        65       -        RT       HIGH
</code>```

This needs to have only 1 object as output:

```<code>Meta1    Meta2    Meta3    Meta4    Meta5
A        65       15       RT       HIGH
</code>```

Now i'm wondering what would be the best strategy to solve this issue

Have my parsers accept my Object as parameter, try to map the data and override if present and then return the Object to be passed again in the next Parser

Parse all the Object and  try to merge them somehow in the end

Another strategy?

答:
Here I describe some similar work I did. Perhaps it will work for you. I had 7 different file formats across 2 different files.

What I must assume is that your meta-data is effectively keys. Otherwise how can one possibly know which records to merge?

Create a CommonData class

A single class to hold any record from any file.

A property for each possible meta-field from any incoming file

A property to hold the entire record

As you clearly illustrate - Where meta-fields are the same, there is only one. I.E. only 1 "Meta1", "Meta2"

Populate only the appropriate meta fields for a given file/record format.

An enum identifing the record type - what file it comes from essentially; or for me, the file format.

Has an IEqualityComparer

CommonDataEqualityComparer

Implements IEqualityComparer

In my solution your "meta data" were my keys that defined equality for each given record type (file).

The equality-comparer object is passed into the CommonData constructor.

An enum to identify each source file or unique file format.

The Factory

takes the raw record and it's type - enum value

Factory passes to appropriate parser based on the enum value

Factory returns new CommonData object, with it's record-type-specific CommonDataEqualityComparer implementation.

CommonDataCollection

Between the equality-comparer implementations and RecordType property we can find, match, etc. records for each file type.


问:
Merging Two Binary Search Trees
What time in terms of Big O will it take to merge two BST's in One?
Each having no of nodes n and height O(log n) with no common element.

Resultant should be also a BST

答: The StackOverflow post @manlio pointed out is an exact duplicate. Basically, yes, the algorithm can improved to O(n+m); the approach is to flatten the trees to sorted lists, merge them, and recreate a BST. This page also has some example code that may be of interest as well.</p>

Title: Merging Two Binary Search Trees


问:
Are these graph coloring algorithms equivalent?
Suppose you want to color the vertices of a graph in a greedy fashion, given a predetermined order of these vertices. The goal is to avoid giving two adjacent (linked by an edge) vertices the same color.

I am wondering if these two algorithms are equivalent:

Algorithm 1: Consider each vertex (in the given order) and assign the smallest color available.

Algorithm 2: While not all vertices are colored, sequentially build color classes by trying to include uncolored, non-adjacent vertices (in the given order) in the current class.

I am almost sure that these two algorithms are equivalent. Indeed, consider Algorithm 2 on a graph with 5 vertices. Suppose the first color class has vertices 1, 3, 5. This means that vertices 2 and 4 cannot take color 1. So in Algorithm 1, vertex 1 would take color 1, vertex 2 would take color 2, vertex 3 would take color 1, vertex 4 would take color 2 or 3, and vertex 5 would take color 1. This simple example convinces me it is true, but of course it is not a proof. Can we transform it into a proof by making it more generic, or can we find a counter example?

答:
I think you are correct, both algorithms are equivalent. Look which of the vertices of an arbitrary graph get the first (smallest) color C1 from both algorithms. It is easy to see that those are the same, because both algorithms do essentially the same - iterate over the vertices in the given order, assign either C1 or

a different color (algorithm 1)

no color (algorithm 2)

to a vertex, with the constraint to use C1 when the next vertice is not adjacent to a formerly C1-colored vertex.

Now you can apply the same argument for the next color C2, using all not C1-colored vertices, then C3 and so on, which leads you inductively to the same total coloring.


问:
MySQL: Application Table Design
I'm creating a new site which will have many objects, such as posts(text/photo/video), products, photo galleries, etc.

Currently my design is to put all of the objects into a posts table, but I'm starting to wonder if that might be too restrictive.

I also have a post_tag pivot table...

Would I be better off creating a posts table, and a products table, and a videos table, etc? I know the posts table could get large, but I think it would also be easier to maintain. OTOH I could break each object table into a separate database if the need ever arose, which (I think?) would help with scalability, which would also mean I'd probably need more pivot tables: tag_video, product_tag, etc. for each object table?

I'm curious: how does Tumblr do this for each of their post types...?

Any thoughts would be greatly appreciated!

答:
Ultimately this depends on: What do you want to do with the content?

A single table of posts works fine as long as you only want to access the content as posts.  However, it will become quite limiting if you want to use the content in different ways.  What if you want to find all of the images that are embedded within posts?  This would be very difficult if you only have a posts table, since you would have to process each post to find the images.

In my opinion, separating the different types of content into different tables is  a good idea, because with a complex site like you describe, you are almost certain to want functionality that will process the content in different ways.  This may not be clear now, but these uses cases are likely to arise later.

Keep in mind that a large number of tables is only one kind of complexity.  Writing a lot of extra code to work around an overly simplistic database design adds complexity of its own.  And actually, having a lot of a tables is not that big of a deal to manage (though it may seem so at first if you aren't experienced at database design).

Title: MySQL: Application Table Design


问:
Persistence models for Event Sourcing
I am intrigued by the Event Sourcing pattern but am struggling to design an event sourcing model and put it in concrete form.

First off, I want to make sure that I understand the main use cases of this pattern. As I understand it, one uses event sourcing is to capture state changes in your app at different points in time so that you can:

Replay events to rewind your app to a previous state; or

Replay events in another environment to recreate production at some point in time and troubleshoot it

So first off, if I have misunderstood the main use case(s) for event sourcing, or if I am missing any major ones, please begin by correcting me!

Assuming I'm more or less on track, my real mental roadblock lies with the event persistence model.

How many databases are there in an event sourcing system? Are there two databases (one for storing main entities, and another for storing the events)? Or is there just one database where all entities are the persisted events themselves?

How do you capture events (and persist them!) for things that are totally outside the app's control? For example: the state of some 3rd party API that your app integrates with, or a message broker (and the state of all its messages/queues) that your app integrates with, runtime command-line arguments passed into your app, etc.?

How does the replay mechanism actually work? So you have some entities. You have events describing state changes to those entities. You can read those events (and/or the entities they represent) out of the database, but then you need something to actually write those events somewhere else. So does this "replayer" just treat each subsequent event as an update to an existing entity?

My best attempt (thus far):

The entity(ies):

```<code>// Groovy pseudo-code
class Order {
    Long id
    Long userId
    Long paymentMethodId    // Perhaps an ID to a 3rd party system that
                            // is PCI compliant, etc.

    // Constructors, getters/setters, etc.
}

// Each 'Order' has 1+ 'OrderLineItems'
class OrderLineItem {
    Long id
    Long orderId
    Long productId    // 'Product' is yet another entity, etc.
    Integer quantity

    // Constructors, getters/setters, etc.
}
</code>```

The event:

```<code>abstract class BaseEvent<ENTITY> {
    Date occurredOn
    Date recordedOn
    ENTITY entity

    BaseEvent(ENTITY entity) {
        super()

        this.occurredOn = new Date() // now
        this.entity = entity
    }
}

class OrderEvent extends BaseEvent<Order> {
    // Perhaps some other metadata about order events

    OrderEvent(Order order) {
        super(order)
    }
}
</code>```

OK so this is a good step in the right direction, but still doesn't help me figure out how the "replay mechanism" will be able to load OrderEvents out of a database, and actually "replay them" to put another database into a particular state representing a single point in time.

答:
How many databases are there in an event sourcing system?

Does not really matter. You can have everything in a single database or split them out, just like you could split the data for an online store into a database with users and a database with products if you wanted to.

How do you capture events (and persist them!) for things that are totally outside the app's control?

Persisting the state of queues is not something you would do, unless I'm misunderstanding your question. As for the 3rd party API or command-line, you simply capture an event at the point that it occurs.

If you have a 3rd party API that you need to check (for example, query the exact price of a product at the time the order is placed) you either work with it in replay if the API can handle it, or store the data from the external party so you have all the needed data in your event. For this example, you would either query the API for the price at the time the event was recorded, or store the price in your event so you don't need the external API.

How does the replay mechanism actually work?

You have events operate on domain objects. If you have a list of events related to an Order you would allow each event to operate on the Order they are related to. Remember that a stored event is basically just a bunch of data. Using that data, your objects can then redo the actions they did.

Title: Persistence models for Event Sourcing


问:
How are hypermedia rel values specified in the REST uniform interface?
I am learning a bit about REST and am intrigued by the concept of a uniform interface, and the ability of a client to follow hypermedia links in order to detect service capabilities.

As I understand it, the RESTful server will return a hypermedia document "representation" of an "entity" that contains relevant links.  If using the HTML media type, for example, the links will be decorated with a "rel" attribute that specifies the meaning of the link-- the client should not look at the link's href, which is an opaque resource identifier.  The client then follows the opaque link to another resource which returns a new representation that is related to the current one in a manner described by the rel attribute.

What I don't understand is how the client knows what rel values to look for.  Seems that these still need to be agreed between the client and server.  How is this agreement communicated?  Is there a RESTful equivalent of, say, a WSDL?

答:
Even with hypermedia REST APIs, the client can not be expected that they can consume just any API without further context.

Clients can only consume documents in a format that is explicitly supported by that client, because otherwise the client has no idea what to do with fields like foo, bar or foobar.

The meaning, syntax and semantics of those fields are described in the specification of the format of the document and that specification should also contain what values are possible for a rel attribute and what those values mean.


答:
I think your intuition on this issue is right.

What we have here is a plain (in this case, static) method whose implementation has been "broken up" into a class.

The "method as a class" technique reduces the number of variables you have to explicitly pass around, while in fact obscuring how data flows using what are, in spirit, "global" variables.

None of this is actually in the spirit of OO, since the instance is throwaway and its state is ephemeral.

And yet, this is a common pattern, especially in introductory Java books and may have been on the minds of Java designers (who introduced lots of ways to declare classes, seemingly to aid this usage).

So, should you use it?

Sure, sometimes.

In fact, at issue is not just pure "methods as classes." In normal classes, you may be tempted to create fields that don't hold state in-between invocations of public methods. They're used only to avoid passing parameters between private methods. In the past, I tried to avoid it at all cost, but then realized that long parameter lists suck too.

I try to avoid pure "method classes" as I think they come with a lot of mental baggage (so much potential potential). (I also lean against disposable fields in regular classes.) But if there's a ton of variables to pass around, the win in code cleanliness may be worth it.

I try to use classes when there is a point to it, and in fact it's usually easy to imagine one. Perhaps in the future you'll extend the class with additional implementations. Perhaps the instance can be thought of as a function object that you'd want to initialize and pass around. And then, the class is no longer a pseudo-OO "method class."


问:
Why do we need the async keyword?
I just started playing around with async/await in .Net 4.5. One thing I'm initially curious about, why is the async keyword necessary? The explanation I read was that it is a marker so the compiler knows a method awaits something. But it seems like the compiler should be able to figure this out without a keyword. So what else does it do?</p>

答:
OK, here is my take on it.

There is something called coroutines that has been known for decades. ("Knuth and Hopper"-class "for decades") They are generalizations of subroutines, in such as not only do they get and release control at function start and return statement, but they also do it at specific points (suspension points). A subroutine is a coroutine with no suspension points.

They are PLAIN EASY to implement with C macros, as shown in the following paper about "protothreads". (http://dunkels.com/adam/dunkels06protothreads.pdf) Read it. I'll wait...

The bottom line of this is that the macros create a big switch, and a case label at each suspension point. At each suspension point, the function stores the value of the immediately following case label, so that it knows where to resume execution next time it is called. And it returns control to the caller.

This is done without modifying the apparent flow of control of the code described in the "protothread".

Imagine now that you have a big loop calling all these "protothreads" in turn, and you get concurrently executing "protothreads" on a single thread.

This approach has two drawbacks:

You cannot keep state in local variables between resumptions.

You cannot suspend the "protothread" from an arbitrary call depth. (all suspension points must be at level 0)

There are workarounds for both:

All local variables must be pulled up to the context of the protothread (context which is already needed by the fact the protothread must store its next resumption point)

If you feel you really need to call another protothread from a protothread, "spawn" a child protothread and suspend until completion of the child.

And if you had compiler support to do the rewrite work that the macros and workaround do, well, you could just write your protothread code just as you intend and insert suspension points with a keyword.

And this is what async and await are all about: creating (stackless) coroutines.

The coroutines in C# are reified as objects of (generic or non-generic) class Task.

I find these keywords very misleading. My mental reading is:

async as "suspensible"

await as "suspend until completion of"

Task as "future …"

Now. Do we really need to mark the function async? Apart from saying that it should trigger the code rewrite mechanisms to make the function a coroutine, it resolves some ambiguities. Consider this code.

```<code>public Task<object> AmIACoroutine() {
    var tcs = new TaskCompletionSource<object>();
    return tcs.Task;
}
</code>```

Assuming that async is not mandatory, is this a coroutine or a normal function? Should the compiler rewrite it as a coroutine or not? Both could be possible with different eventual semantics.

Title: Why do we need the async keyword?

Body:
OK, here is my take on it.

There is something called coroutines that has been known for decades. ("Knuth and Hopper"-class "for decades") They are generalizations of subroutines, in such as not only do they get and release control at function start and return statement, but they also do it at specific points (suspension points). A subroutine is a coroutine with no suspension points.

They are PLAIN EASY to implement with C macros, as shown in the following paper about "protothreads". (http://dunkels.com/adam/dunkels06protothreads.pdf) Read it. I'll wait...

The bottom line of this is that the macros create a big switch, and a case label at each suspension point. At each suspension point, the function stores the value of the immediately following case label, so that it knows where to resume execution next time it is called. And it returns control to the caller.

This is done without modifying the apparent flow of control of the code described in the "protothread".

Imagine now that you have a big loop calling all these "protothreads" in turn, and you get concurrently executing "protothreads" on a single thread.

This approach has two drawbacks:

You cannot keep state in local variables between resumptions.

You cannot suspend the "protothread" from an arbitrary call depth. (all suspension points must be at level 0)

There are workarounds for both:

All local variables must be pulled up to the context of the protothread (context which is already needed by the fact the protothread must store its next resumption point)

If you feel you really need to call another protothread from a protothread, "spawn" a child protothread and suspend until completion of the child.

And if you had compiler support to do the rewrite work that the macros and workaround do, well, you could just write your protothread code just as you intend and insert suspension points with a keyword.

And this is what async and await are all about: creating (stackless) coroutines.

The coroutines in C# are reified as objects of (generic or non-generic) class Task.

I find these keywords very misleading. My mental reading is:

async as "suspensible"

await as "suspend until completion of"

Task as "future …"

Now. Do we really need to mark the function async? Apart from saying that it should trigger the code rewrite mechanisms to make the function a coroutine, it resolves some ambiguities. Consider this code.

public Task<object> AmIACoroutine() {
    var tcs = new TaskCompletionSource<object>();
    return tcs.Task;
}

Assuming that async is not mandatory, is this a coroutine or a normal function? Should the compiler rewrite it as a coroutine or not? Both could be possible with different eventual semantics.


问:
Does syntax really matter in a programming language?
One of my professors says "the syntax is the UI of a programming language", languages like Ruby have great readability and it's growing, but we see a lot of programmers productive with C\C++, so as programmers does it really matter that the syntax should be acceptable?

I would love to know your opinion on that.

Disclaimer: I'm not trying to start an argument. I thought this is a good topic of discussion.

Update: This turns out to be a good topic. I'm glad you are all participating in it.

答:
The answer might be in separating what "matters" into computer factors and human factors. There are a lot of human factors in syntax:

Readability

Succinctness

Maintainability

Pedagogy

Error prevention

Appropriateness for the purpose -- is it a REPL language, a script language or a large systems language?

As far as the computer is concerned, the only issue of syntax is whether or not there are ambiguities that need to be resolved, and how much time it takes to tokenize/parse the code upon compile/interpret -- and it's only in the case of the latter where the overhead of parsing is a significant issue.

That might be why you'll always get a "yes and no" answer to this question -- because there's two aspects to it.

ContentLicense: CC BY-SA 2.5


问:
What is NOT MVC? (in a web app)
It is easy to find many descriptions of what MVC is - for instance here, here or in this video.

I'm curious, what is NOT MVC?

or more precisely - In a MVC-using app, what is everything else apart form MVC?

.

I see the tendency to start explaining MVC in a form of

Separate the application into three parts[...]

Which seems to suggest that you should try to fit in as much as you can (or all) of your design under either Model, View or Controller.

.

Yet, it's easy to see that in most explenations MVC is primarily described as a user interface design. How in this situation do I treat non-UI elements?

Do I bend definitions of non-UI elements and try to figure out whether they could fit to either Model or Controller?

Is there a separete description in MVC design that deals with non-UI elements?

Is there a description of how MVC interacts with such elements? Is it all through Model? All through Controller?

.

For example:

I'm wondering how do I treat the part of my application which is used only for monitoring my local network and storing the information in a database. It has no UI related functionality and its sole puprose is to fill in the database with file related information, which then in turn is presented to the user through the web interface.

答:
I'm wondering how do I treat the part of my application which is used
  only for monitoring my local network and storing the information in a
  database.

Several architectures implement such code differently, but in a layered architecture, you would need to create layers, e.g. DataAccess layer, Business logic layer. etc..

Your Model (there are different types of models) will interact with these layers as required, it all depends on your application or software architecture really.

Do I bend definitions of non-UI elements and try to figure out whether
  they could fit to either Model or Controller ?

I would say your "non-UI elements" is actually your business logic that needs to go in Model which then can interact with different layers e.g. DB layer etc..

Should I add logic to my Controller

Further Recommendations

Here are couple of sample projects developed based on DDD using MVC and other technologies that may help you understand this subject further,

EFMVC - ASP.NET MVC 4, Entity Framework 5 Code First and Windows Azure

Sample web app for ASP.NET MVC 5, EF 6 Code First, AutoMapper, Autofac and TDD

Title: What is NOT MVC? (in a web app)


答:
An MVC application is one where there is a conscious architectural decision to separate out components of the presentation (usually through the User Interface) that deal with three specific concerns:

The Model, which represents the information which is to be displayed, but which is completely agnostic of how the information is presented.

The View, which displays the information in the model, but which has no idea about how the model has been built.

The Controller, which identifies the right Model and View for the occasion, and brings the two together

In theory, and often in practice, the same model can be connected to multiple views – the appropriate view depending on the scenario (e.g. Mobile browsers vs Desktop, or html vs json). And the same view can be used to display many different models, provided the models have enough in common with each other for that to be useful.

In NOT MVC applications, these three systems are not kept separate from each other (common in older applications) or are divided up in different ways.

The MVC application can have many other components in it too. These components may be used in constructing the models, updating the data layer, enforcing security, logging, whatever else your application needs.

Title: What is NOT MVC? (in a web app)

Body:
It is easy to find many descriptions of what MVC is - for instance here, here or in this video.

I'm curious, what is NOT MVC?

or more precisely - In a MVC-using app, what is everything else apart form MVC?

.

I see the tendency to start explaining MVC in a form of

Separate the application into three parts[...]

Which seems to suggest that you should try to fit in as much as you can (or all) of your design under either Model, View or Controller.

.

Yet, it's easy to see that in most explenations MVC is primarily described as a user interface design. How in this situation do I treat non-UI elements?

Do I bend definitions of non-UI elements and try to figure out whether they could fit to either Model or Controller?

Is there a separete description in MVC design that deals with non-UI elements?

Is there a description of how MVC interacts with such elements? Is it all through Model? All through Controller?

.

For example:

I'm wondering how do I treat the part of my application which is used only for monitoring my local network and storing the information in a database. It has no UI related functionality and its sole puprose is to fill in the database with file related information, which then in turn is presented to the user through the web interface.


问:
How are native applications (C, C++) deployed on android?
I am curious how to deploy android native (that is, using android NDK or Qt C++) application to the end users. AFAIK, the apk files are much like jar files, so I assume native programs can't be deployed this way. Or can they?

Is there any difference between raw Android NDK application and Qt native application?

答:
They can and are - the native code libraries are packed into the apk and deployed with the 'wrapper' java app that is the entry point to running a NDK application.

Look at the Flow section of the concepts guide.


问:
Why does Math.min work with a one element array
According to MDN Math.min accepts only numbers, and if one of the arguments is not a number, it'll return NaN. It's true that if we pass an array with multiple numbers we get NaN, like this: Math.min([1,2]), but if we use an array with just one number, Math.min will return the the number in the array, like in this example: Math.min([5]). Does anyone have an idea why we see this undocumented behavior?

答:
According to MDN Math.min accepts only numbers, and if one of the arguments is not a number, it'll return NaN.

That's not what it says (bold emphasis mine):

If at least one of arguments cannot be converted to a number, the result is NaN.

Type Conversion:

Math.min uses ToNumber to convert its arguments.

ToNumber uses ToPrimitive to convert Objects (and Arrays are Objects).

ToPrimitive uses toString

[5].toString() is '5', which gets returned to ToPrimitive, which returns it to ToNumber, which parses it to 5 and returns it to Math.min, for which it is a valid argument, because it is not NaN.

[1, 2].toString(), OTOH, is '1, 2', which gets returned to ToPrimitive, which returns it to ToNumber, which parses it to NaN, because it is not a valid number representation. ToNumber then passes NaN to Math.min, which will then return NaN, because (as MDN states it) "one of its arguments cannot be converted to a number" or (as the spec states it) "If any value is NaN, the result is NaN.".


问:
Code for Inherit design
I want to write application that takes Wireshark File and read all the packets inside this file.
So i want to able to support several formats.
Until now i can handle Libpcap, Pcapng and TcpDump.
So i wonder hot to design my application.
I was thinking  to create abstract class:

```<code> public abstract class WiresharkFile
    {
        private string _fileName;
        private int _packets;
        private string _duration;
        protected abstract IEnumerable<Packet> ReadPackets(string file);
    }
</code>```

As you can see all the formats that inherit from this WiresharkFile have name, packet (each file contain several packets and duration).
And also ReadPackets method because every format need to read the file in other way.
So my question is in case i am choose file and want to read it's packets how can i know what the file format in order to run the correct ReadPackets method that i have for each format.

答:
What you are looking for is a Factory. In the most simple form, that is just a static method like

```<code>public abstract class WiresharkFile
{
     public static WiresharkFile WiresharkFileFactory(string filename)
     {
     //  ... logic here to create either a LibpcapWireSharkFile, a
     //  ... PcapngWireSharkFile, or another subclass instance
     }
}
</code>```

If that method has a certain complexity, you may consider to move that method out of the WiresharkFile class to a separate factory class. And if you need those classes in an extensible library, where you can add new derivations afterwards without changing the factory code, you may have a look into the abstract factory pattern.

Note that when your factory creates the object, you can already pass the filename to that object, so your ReadPackets() methods should not need any filename parameter any more.

Title: Code for Inherit design

Body:
What you are looking for is a Factory. In the most simple form, that is just a static method like

public abstract class WiresharkFile
{
     public static WiresharkFile WiresharkFileFactory(string filename)
     {
     //  ... logic here to create either a LibpcapWireSharkFile, a
     //  ... PcapngWireSharkFile, or another subclass instance
     }
}

If that method has a certain complexity, you may consider to move that method out of the WiresharkFile class to a separate factory class. And if you need those classes in an extensible library, where you can add new derivations afterwards without changing the factory code, you may have a look into the abstract factory pattern.

Note that when your factory creates the object, you can already pass the filename to that object, so your ReadPackets() methods should not need any filename parameter any more.


问:
Would it be possible to transfer an HTML file using a protocol different from HTTP?
I am reading about internet and stuff and just learned that web pages are really just HTML files.

Also, I have learned that HTTP is just a transfer protocol.

So my question is, would it be possible to view a web page using another protocol, say FTP, since a webpage is really just a file with instructions in it telling the browser how to render the page?

If it would be possible, could you describe how it would be possible?

Example: Let's say that a server hosts a webpage on port 20 (that is: FTP port). If I connected to the server with: ftp://<hostname>/<path_to_webpage>, would I be able to display it as expected?

Yet more interestingly, in the same scenario, if I connected to the server with: http://<hostname>:20/<path_to_webpage>, would it work in this scenario as well?

答:
You are confused.

Transferring a HTML page is possible with any protocol that can handle text - email, RSS, ftp, the list is endless. Viewing a HTML page is completely different: it requires code that interprets the tags and generates the corresponding characters. This is called a renderer, and only a HTML renderer can perform this task.

A web browser is simply a piece of software that combines both functionalities, because it's so useful to combine them. So yes, you can transfer a web page without a browser, but no, you normally can't view it without a browser, because most HTML renderers live in browsers.


问:
What is the difference between a mock and a test double?
I was reading an article here on Mocks. I would like to conclude to make my understanding more clear.

Anything that can be placed in place of a real object while testing is called a Test Double.

Depending on the testing need a Test Double can be categorized as follows:

You need a placeholder object needed just for compiling / running a class then, create a Dummy.

You want to test some part of the system in isolation which depends on some already tested system then, create a Stub which behaves as per your assumption.

You want to make sure a function is called with some required argument then, you need a Spy.

You need a Fakes when you want a Stub which behaves differently  depending on the use case.

What is a Mock then?

The above blog summarizes it as any of the above family member of test double with assertion included is called a Mock.

Example

```<code>public class AcceptingAuthorizerVerificationMock implements Authorizer {
  public boolean authorizeWasCalled = false;

  public Boolean authorize(String username, String password) {
    authorizeWasCalled = true;
    return true;
  }

  public boolean verify() {
    return authorizedWasCalled;
  }
}
</code>```

But, I am still confused about the assertion part because we already do assertions in our unit tests.

答:
Moving the assertion details from the test to the mock is all about abstraction.

It might not show in very simple tests like these, but sometimes you must verify complex things that happened - how many times was a method called ? Did the arguments passed match a given pattern ? This can require complex stuff behind the scenes.

Moving the details of analyzing what happened from the test to the mock allows the unit test to stay at a high language level and not pollute it with technical low level mock specifics.

[Edit]

You don't move the act of asserting to the mock. You move operational low-level assertion details.


答:
Yes. You can transmit HTML over any medium that can transmit text. Email, for example. I'm willing to bet that at least 90% of all emails you receive, and probably also most that you write, are HTML. You can also view HTML files on your local filesystem.

The browser doesn't care at all how the HTML arrived on your system. That's "someone else's problem".

Let's say that a server hosts a webpage on port 20 (that is: FTP port). If I connected to the server with: ftp://<hostname>/<path_to_webpage>, would I be able to display it as expected?

Yes, provided the server is actually running an FTP server on port 20.

Yet more interestingly, in the same scenario, if I connected to the server with: http://<hostname>:20/<path_to_webpage>, would it work in this scenario as well?

No, of course not. We are assuming that the server is running an FTP server on port 20, not an HTTP server, so obviously you can't talk HTTP to it.

If there's an FTP server listening on port 20, then the first one will work. Since there is an FTP server listening on port 20, there cannot be an HTTP server listening on port 20, so the second one will not work.

If there's an HTTP server listening on port 20, then the second one will work. Since there is an HTTP server listening on port 20, there cannot be an FTP server listening on port 20, so the first one will not work.

If there's neither an FTP nor an HTTP server listening on port 20, neither of the two will work.

None of this has anything to do with HTML. The HTTP or FTP client doesn't care what it is downloading. The HTML renderer doesn't care where the HTML came from.

Title: Would it be possible to transfer an HTML file using a protocol different from HTTP?

Body:
I am reading about internet and stuff and just learned that web pages are really just HTML files.

Also, I have learned that HTTP is just a transfer protocol.

So my question is, would it be possible to view a web page using another protocol, say FTP, since a webpage is really just a file with instructions in it telling the browser how to render the page?

If it would be possible, could you describe how it would be possible?

Example: Let's say that a server hosts a webpage on port 20 (that is: FTP port). If I connected to the server with: ftp://<hostname>/<path_to_webpage>, would I be able to display it as expected?

Yet more interestingly, in the same scenario, if I connected to the server with: http://<hostname>:20/<path_to_webpage>, would it work in this scenario as well?


问:
Why does the assignment operator assign to the left-hand side?
I began teaching a friend programming just recently (we're using Python), and when we began discussing variable creation and the assignment operator, she asked why the value on the right is assigned to the name on the left, and not vice-versa.

I had not thought about it too much before, because it seemed natural to me, but she said that left-to-right seemed more natural to her, since that's how most of us read natural languages.

I thought about it, and concluded that it makes code much easier to read, since the names that are assigned to (which the programmer will need to reuse) are easily visible, aligned on the left.

```<code>aligned = 2
on = 'foo' + 'bar' + 'foobar'
the = 5.0 / 2
left = 2 + 5
</code>```

As opposed to:

```<code>2 = aligned
'foo' + 'bar' + 'foobar' = on
5.0 / 2 = the
2 + 5 = right

# What were the names again...?
</code>```

Now I wonder if there are other reasons as well for this standard. Is there a history behind it? Or is there some technical reason why this is a good option (I don't know much about compilers)? And are there any programming languages that assign to the right side?

答:
In pseudocode the assignment operator is very commonly written on the right. For example

```<code>2*sqrt(x)/(3+y) -> z
</code>```

In Casio calculators, even non-programmable variants, the assignment variable is also displayed on the right

```<code>A+2B → C
</code>```

In Forth the variable is on the right, too

```<code>expression variable !
</code>```

In x86, Intel syntax has the destination on the left, but GAS syntax reverses the order, making some confusion to many people, especially on instructions regarding parameters' order like subtraction or comparisons. These instructions are the same in 2 different dialects

```<code>mov rax, rbx    ; Intel syntax
movq %rbx, %rax ; GAS syntax
</code>```

They both move the value in rbx to rax. No other assembly languages I know write the destination on the right like GAS.

Some platforms put the expression on the left and the variable on the right:

```<code>MOVE expression TO variable      COBOL
expression → variable            TI-BASIC, Casio BASIC
expression -> variable           BETA, R
put expression into variable     LiveCode
</code>```

https://en.wikipedia.org/wiki/Assignment_%28computer_science%29#Notation

Most languages assign the value to the left, one of the reasons being easy to align the operators, easier to read and recognize the variable, as the assignment operators and variables' positions will not vary wildly in the lines, and it's easier to read as "let variable be some value".

However some people prefer to say "move value x to y" and write the variable on the right.

OwnerDisplayName: voithos

Body:
In pseudocode the assignment operator is very commonly written on the right. For example

2*sqrt(x)/(3+y) -> z

In Casio calculators, even non-programmable variants, the assignment variable is also displayed on the right

A+2B → C

In Forth the variable is on the right, too

expression variable !

In x86, Intel syntax has the destination on the left, but GAS syntax reverses the order, making some confusion to many people, especially on instructions regarding parameters' order like subtraction or comparisons. These instructions are the same in 2 different dialects

mov rax, rbx    ; Intel syntax
movq %rbx, %rax ; GAS syntax

They both move the value in rbx to rax. No other assembly languages I know write the destination on the right like GAS.

Some platforms put the expression on the left and the variable on the right:

MOVE expression TO variable      COBOL
expression → variable            TI-BASIC, Casio BASIC
expression -> variable           BETA, R
put expression into variable     LiveCode

https://en.wikipedia.org/wiki/Assignment_%28computer_science%29#Notation

Most languages assign the value to the left, one of the reasons being easy to align the operators, easier to read and recognize the variable, as the assignment operators and variables' positions will not vary wildly in the lines, and it's easier to read as "let variable be some value".

However some people prefer to say "move value x to y" and write the variable on the right.


问:
What parameters to use to compare GUI frameworks / toolkits?
I'm doing some research on the best GUI toolkit to use for future products at the company. We're talking about a fairly large organizations with quite a bit of code and a complete rewrite project in planning. Don't ask.

Anyway, I'm trying to create a list relevant parameters to judge the toolkits. What would you use to drive the comparison?

Here's what I've got so far:

Maturity

Ease of development

Ease of prototyping

Ease of maintenance

Size of hiring pool

Available knowledge at the company

Training costs

Community size

Community level of expertise (how hard to find good answers to complex problems)

Amount of expert-level books available

Ability to interface to other technologies

Deployment considerations

Visual aesthetics

Ability to access OS resources

Multiple monitor support (something that might come in handy in our particular application)

答:
and the answer is.... Qt

seriously, it does fit all your points; and on top of it it's multiplatform and really efficient.