答:
It depends partially on your requirements:

If the configuration is supplied/updated by third parties (e.g. multilingual text resources that translation agencies work on), use whatever they can use easily. If you can choose the format, a very simply text format like YAML or Java Properties is best (but code that consists just of constant declarations could also work).

If you need to be able to update the data while the application is running and via a UI (i.e. admin section of the app), a DB table may be best.

If the configuration is complex (has conditions, hierarchies, overrides, etc.), that's really programming logic and should be done in code. Avoid soft coding.

If none of these is the case, just use what is most popular in your language/framework/community/ecosystem, so other developers will be familiar with it. For Rails projects that seems to be YAML, for Java it's .properties files, etc.


问:
Multithreading synchronization interview question: Find n words given m threads

Is there a way this problem could benefit from a solution with multiple threads, rather than a single thread?

In an interview, I was asked to solve a problem using multiple threads. It appears to me that the multiple threads lends no benefit.

Here's the problem:

You are given a paragraph , which contain n number of words, you are
  given m threads. What you need to do is , each thread should print one
  word and give the control to next thread, this way each thread will
  keep on printing one word , in case last thread come, it should invoke
  the first thread. Printing will repeat until all the words are printed
  in paragraph. Finally all threads should exit gracefully. What kind of
  synchronization will use?

I strongly feel we cannot take any advantage of threads here, but believe the interviewer is trying to measure my synchronization skills. Am I missing something in this problem that would make multiple threads have value?

No need of code, just put some thoughts. I will implement by myself.

答:
Use condition wait/signal APIs to solve this problem.

Let say first thread picks 1 word and meanwhile rest all threads are waiting for a signal.
1st thread print 1st word and generates signal to next thread and then 2nd thread print the second word and generates signal to 3rd thread and so on.

```<code>#include <iostream>
#include <fstream>
#include <pthread.h>
#include <signal.h>
pthread_cond_t cond[5] = {PTHREAD_COND_INITIALIZER,};
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

using namespace std;

string gstr;

void* thread1(void*)
{
    do {
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond[0],&mutex);
    cout <<"thread1 :"<<gstr<<endl;
    pthread_mutex_unlock(&mutex);
    }while(1);
}

void* thread2(void*)
{
    do{
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond[1],&mutex);
    cout <<"thread2 :"<<gstr<<endl;
    pthread_mutex_unlock(&mutex);
    }while(1);
}

void* thread3(void*)
{
    do{
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond[2],&mutex);
    cout <<"thread3 :"<<gstr<<endl;
    pthread_mutex_unlock(&mutex);
    }while(1);
}

void* thread4(void*)
{
    do{
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond[3],&mutex);
    cout <<"thread4 :"<<gstr<<endl;
    pthread_mutex_unlock(&mutex);
    }while(1);
}

void* thread5(void*)
{
    do{
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond[4],&mutex);
    cout <<"thread5 :"<<gstr<<endl;
    pthread_mutex_unlock(&mutex);
    }while(1);
}

int main()
{
    pthread_t t[5];
    void* (*fun[5])(void*);
    fun[0]=thread1;
    fun[1]=thread2;
    fun[2]=thread3;
    fun[3]=thread4;
    fun[4]=thread5;

    for (int i =0 ; i < 5; ++i)
    {
        pthread_create(&t[i],NULL,fun[i],NULL);
    }
    ifstream in;
    in.open("paragraph.txt");
    int i=0;
    while(in >> gstr)
    {

        pthread_cond_signal(&cond[i++]);
        if(i == 5)
            i=0;
        usleep(10);
    }
    for (int i =0 ; i < 5; ++i)
    {
        int ret = pthread_cancel(t[i]);
        if(ret != 0)
            perror("pthread_cancel:");
        else
            cout <<"canceled\n";
    }
    pthread_exit(NULL);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use condition wait/signal APIs to solve this problem.

Let say first thread picks 1 word and meanwhile rest all threads are waiting for a signal.
1st thread print 1st word and generates signal to next thread and then 2nd thread print the second word and generates signal to 3rd thread and so on.

#include <iostream>
#include <fstream>
#include <pthread.h>
#include <signal.h>
pthread_cond_t cond[5] = {PTHREAD_COND_INITIALIZER,};
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

using namespace std;

string gstr;

void* thread1(void*)
{
    do {
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond[0],&mutex);
    cout <<"thread1 :"<<gstr<<endl;
    pthread_mutex_unlock(&mutex);
    }while(1);
}

void* thread2(void*)
{
    do{
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond[1],&mutex);
    cout <<"thread2 :"<<gstr<<endl;
    pthread_mutex_unlock(&mutex);
    }while(1);
}

void* thread3(void*)
{
    do{
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond[2],&mutex);
    cout <<"thread3 :"<<gstr<<endl;
    pthread_mutex_unlock(&mutex);
    }while(1);
}

void* thread4(void*)
{
    do{
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond[3],&mutex);
    cout <<"thread4 :"<<gstr<<endl;
    pthread_mutex_unlock(&mutex);
    }while(1);
}

void* thread5(void*)
{
    do{
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond[4],&mutex);
    cout <<"thread5 :"<<gstr<<endl;
    pthread_mutex_unlock(&mutex);
    }while(1);
}

int main()
{
    pthread_t t[5];
    void* (*fun[5])(void*);
    fun[0]=thread1;
    fun[1]=thread2;
    fun[2]=thread3;
    fun[3]=thread4;
    fun[4]=thread5;

    for (int i =0 ; i < 5; ++i)
    {
        pthread_create(&t[i],NULL,fun[i],NULL);
    }
    ifstream in;
    in.open("paragraph.txt");
    int i=0;
    while(in >> gstr)
    {

        pthread_cond_signal(&cond[i++]);
        if(i == 5)
            i=0;
        usleep(10);
    }
    for (int i =0 ; i < 5; ++i)
    {
        int ret = pthread_cancel(t[i]);
        if(ret != 0)
            perror("pthread_cancel:");
        else
            cout <<"canceled\n";
    }
    pthread_exit(NULL);
}


问:
MVC - Isolating view and model logic
I understand that the model should generally consist of data manipulation and the view for data display from the model, but how do I keep my model and view layers decoupled?

My simple view has a few tables that display data. Its associated model manipulates the data based on the view's type of TableModel. Most of its methods involve using the TableModel type. Should the view generally "breakdown" the data into a more generic type of integers and strings for the model? Therefore all the model handles are simple generic lists of data without needing to use TableModel in case the view is changed into another interface. The model should be "unaware" of the view for good programming practices, right? If I change my view to a command-line interface, the associated model should still be able to perform its functions, given the correct associated Lists of integers/strings/whatever.

答:
The first thing to understand is that the decoupling between model and view is only one-way. The model should not care how its data is presented to the outside world (it should be unaware of the view other than possibly knowing something is observing the model).

The view on the other hand does have knowledge about the model, in particular about how to get data out of it.

In an ideal world, the model should expose its data in a way that is convenient for the model and the concepts it represents. The view has to conform to the API of the model.

In the real world, people will want to reuse widgets across different projects, so you get libraries of widgets that expect a certain common API from the model they work with, often in the form of a generic abstraction such as a list, table or tree. In such cases, it is often easier to let the model reflect the generic abstraction it fits best with (with the associated common API) and to augment the interface where appropriate.

Although the model's API has been adapted to meet common view expectations, the two are still decoupled, because the model does not know which portion of the model gets actually presented in the view and how it gets presented.

Title: MVC - Isolating view and model logic


问:
Under which area of Artificial Intelligence is my knowledge store?
I've a maturing idea regarding a knowledge store.

For the purposes of this question, the store would be used by a police force for the recording and querying of crimes.  I believe that historically, police forces used to hold vast index card systems, allowing cross-correlation and querying.

The knowledge store would contain a collection of known facts, collated in a way that supports unknown future questions.

Obviously if I knew the future questions "how many crimes this month", "what tool is most commonly used for breaking and entering" it would be fairly straightforward to store, collate, and present the data.

My requirement for unknown future questions presents the problem.

I imagine a series of authors collating details of crimes. They'd submit details, making heavy use of relationships: "crime occurred in the evening", "burglar used a brick", "crime committed by Person_A".  The when considering a crime, the user would enter "brick" and be presented with collated knowledge related to that concept.

frequently used at night

frequently used in opportunist burglary

frequently used in in assault

most common entry object used in Neighbourhood D

most used object by Person_A, Person_B

The user would then browse/wander through the information set learning more about past crimes.

The underlying information store seems close to that in a Graph Database - but I don't want to "sleepwalk" into using one of those if there's a more natural, AI based solution that not only solves the storage/retrieval problem but which also provides expert-system style deductions.

答:
Sounds like a job for Prolog

If you decide to implement this system using Prolog, then this article will help you with choosing an appropriate data store. It dates back to 2002 but Prolog has been around a lot longer than that so the information should still be useful.


问:
POST/Redirect/GET with invalid form submission?
In the field of web development, is it good practice to do a POST/Redirect/GET when fields in a form submission are invalid, as well?

Typically, no sensitive transaction would have taken place, in this event. However, can an argument be made that, nonetheless, it is still good practice to utilize the POST/Redirect/GET pattern?

答:
From a REST perspective the web conversation should go like this

GET /example

200 OK - contains empty form HTML

The user fills in the form

POST /example

formfield1=ok

formfield2=bad

400 BAD REQUEST - contains populated form HTML with errors

The user identifies the problem with the form submission and fixes it

POST /example

formfield1=ok

formfield2=fixed

201 CREATED - contains HTML with success message and onward links (also Location header for REST clients) or 200 OK and 204 NO CONTENT are acceptable

There is no need to introduce a redirect, and it would break the semantics of the conversation to do so.


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

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

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

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

答:
Ok, so you are doing what you think is the simplest thing that works, but you haven't defined your problem adequately.

Turn the problem around and look at what you have. "Implement a List clone" has many nuances to it which need to be expanded and documented. What is the purpose of this List clone? What number of items is it expected to support?

Generally answers to these and other questions come out at the beginning. For example, ask yourself why are you implementing a List replacement? If it's just a coding exercise, you need to flesh out a scenario a bit. In the real world you might be doing this because the existing List implementation does not exhibit certain characteristics you want. It might be too slow or not sorted or unable to cope with a gazillion items or what ever. That is what you are lacking here.

To restate the problem, how will you know that you are done? What are your acceptance criteria? What does "Working and complete" mean for this problem? TDD may flush out issues like what happens if you try and access an item at position "-3.2", but it actually doesn't have to. What it is supposed to do is make sure your code a) does what it is expected to do and b) continues to do what is expected of it when you refactor or replace it.


问:
Why is reverse debugging rarely used?
gdb implemented support for reverse debugging in 2009 (with gdb 7.0). I never heard about it until 2012. Now I find it extremely useful for certain types of debugging problems. I wished that I heard of it before.

Correct me if I'm wrong but my impression is that the technique is still rarely used and most people don't know that it exists. Why?

Do you know of any programming communities where the use of reverse debugging is common?

Background information:

Stackoverflow: How does reverse debugging work?

gdb uses the term "reverse debugging" but other vendors use other terms for identical or similar techniques:

Microsoft calls it IntelliTrace or "Historical Debugging"

There's a Java reverse debugger called Omniscient Debugger, though it probably no longer works in Java 6

There are other Java reverse debuggers

OCaml's debugger (ocamldebug) calls it time travel

答:
From my experience as a sales engineer for TotalView debugger, people do know that it exists but they don't think it works, regardless of the (acceptable or not) slowdown.

University of Cambridge recently did a survey entitled "Failure to Adopt Reverse Debugging Costs Global Economy $41 Billion Annually".

And coming back to GDB, I've heard (a lot) that slowdown makes it quite unusable on a "real-life" application.

I'd personally love to hear back from more people using reverse debugging on applications others than "Hello world!"

Title: Why is reverse debugging rarely used?


问:
What's the difference in content between Chris Okasaki's 1996 thesis and 1999 book, Purely Functional Data Structures?
I want to read Purely Functional Data Structures. I've easily found the thesis (which is freely available as a PDF), but see that there's a book available also. So I'd like to know what the differences are, if any, between these two publications.</p>

答:
As an owner of the book (though I haven't gotten through much of it) I can point out that it adds a rather large appendix with Haskell translations of his ML code.

Aside from that, it looks like he's essentially taken his thesis, reworked it and officially published it, much like you'd see out of a new edition of any programming reference out there. You can probably get a lot out of the thesis for free, but there will be some fixes, rewordings and extra references available in the book.


问:
Does TDD really work for complex projects?
I’m asking this question regarding problems I have experienced during TDD projects.
I have noticed the following challenges when creating unit tests.

Generating and maintaining mock data

It’s hard and unrealistic to maintain large mock data. It’s is even harder when database structure undergoes changes.

Testing GUI

Even with MVVM and ability to test GUI, it takes a lot of code to reproduce the GUI scenario.

Testing the business

I have experience that TDD works well if you limit it to simple business logic. However complex business logic is hard to test since the number of combinations of tests (test space) is very large.

Contradiction in requirements

In reality it’s hard to capture all requirements under analysis and design.  Many times one note requirements lead to contradiction because the project is complex. The contradiction is found late under implementation phase. TDD requires that requirements are 100% correct. In such cases one could expect that conflicting requirements would be captured during creating of tests. But the problem is that this isn’t the case in complex scenarios.

I have read this question: Why does TDD work?

Does TDD really work for complex enterprise projects, or is it practically limit to project type?

答:
I've seen a large complex project completely fail when TDD was used exclusively, i.e. without at least setting up in an debugger/IDE.
The mock data and/or tests proved insufficient. The Beta clients real data was sensitive and could not be copied or logged. So, the dev team could never fix the fatal bugs that manifested when pointed at real data, and the whole project got scrapped, everyone fired, the whole bit.

The way to have fixed this problem would have been to fire it up in a debugger at the client site, live against the real data, step through the code, with break points, watch variables, watch memory, etc.
However, this team, who thought their code to be fit to adorn the finest of ivory towers, over a period of nearly one year had never once fired up their app. That blew my mind.

So, like everything, balance is the key. TDD may be good but don't rely on it exclusively.

ContentLicense: CC BY-SA 2.5


答:
Here's a blog post by the author, where he says

I thought that the basic organization of my dissertation was pretty solid, so mostly I was able to focus on adding and adjusting things to make it work better as a book. For example, I no longer had the constraint from my dissertation of having to focus on original work, so I was free to add data structures that had been developed by other people.

and

The main additions were expanded introductory material (such as my simplification of red-black trees, which was developed a few weeks after my thesis defense in a series of emails with Richard Bird), exercises, and an appendix including all the source code in Haskell (the main text used source code in Standard ML).

Title: What's the difference in content between Chris Okasaki's 1996 thesis and 1999 book, Purely Functional Data Structures?

Body: I want to read Purely Functional Data Structures. I've easily found the thesis (which is freely available as a PDF), but see that there's a book available also. So I'd like to know what the differences are, if any, between these two publications.</p>


问:
What is the purpose of NaN boxing?
Reading 21st Century C I arrived at chapter 6 at the section "Marking Exceptional Numeric Values with NaNs", where it explains the use of the bits in the mantissa to store some arbitrary bit patterns, to use them as markers or pointers (the book mentions that WebKit uses this technique).

I'm not really sure I understood the utility of this technique, that I see as an hack (it relies on the hardware not caring on the value of the mantissa in a NaN) but coming from a Java background I'm not used to the roughness of C.

Here is the snippet of code that sets and reads a marker in a NaN

```<code>#include <stdio.h>
#include <math.h> //isnan

double ref;

double set_na(){
    if (!ref) {
        ref=0/0.;
        char *cr = (char *)(&ref);
        cr[2]='a';
    }
    return ref;
}

int is_na(double in){
    if (!ref) return 0;  //set_na was never called==>no NAs yet.

    char *cc = (char *)(&in);
    char *cr = (char *)(&ref);
    for (int i=0; i< sizeof(double); i++)
        if (cc[i] != cr[i]) return 0;
    return 1;
}

int main(){
    double x = set_na();
    double y = x;
    printf("Is x=set_na() NA? %i\n", is_na(x));
    printf("Is x=set_na() NAN? %i\n", isnan(x));
    printf("Is y=x NA? %i\n", is_na(y));
    printf("Is 0/0 NA? %i\n", is_na(0/0.));
    printf("Is 8 NA? %i\n", is_na(8));
}
</code>```

it prints:

```<code>Is x=set_na() NA? 1
Is x=set_na() NAN? 1
Is y=x NA? 1
Is 0/0 NA? 0
Is 8 NA? 0
</code>```

and at JSValue.h webkit explains the encoding, but not why it's used.

What is the purpose of this technique? Are the benefits of space/performance high enough to balance its hackish nature?

答:
Using NaN for "exceptional values" is a well known and sometimes helpful technique to avoid the need of an extra boolean variable this_value_is_invalid. Used wisely, it can help one to make his code more concise, cleaner, simpler, better readable without any performance trade-offs.

This technique has some pitfalls, of course (see here http://ppkwok.blogspot.co.uk/2012/11/java-cafe-1-never-write-nan-nan_24.html), but in languages like Java (or very similar  C#) there are standard library functions like Float.isNaN to make dealing with NaNs simple. Of course, in Java you could use alternatively theFloat and Double class and in C# the nullable value types float? and double?, giving you the possibility of using null instead of NaN for invalid floating point numbers, but those techniques can have a significant negative influence on the performance and memory usage of your program.

In C the use of NaN is not 100% portable, that is true, but you can use it everywhere where the IEEE 754 floating point standard is available. AFAIK this is quite almost every mainstream hardware today (or at least the runtime environment of most compilers support it). For example, this SO post contains some information to find out more details about the use of NaN in C.

Title: What is the purpose of NaN boxing?


问:
Brain picking during job interview
Recently, I had a job interview at a big Silicon Valley company for a senior software developer/R&D position. I had several technical phone screens, an all day on-site interview and more technical phone screens for another position later.

The interviews went really well, I have a PhD and working experience in the area I was applying for yet no offer was made. So far, so good. It was an interesting experience, I am employed, absolutely no hard feelings about this.

Some of the interviewers asked really detailed questions to the point of being suspicious about new technologies I have been working on. These technologies are still in development and have not come to market yet. I know some major hardware/software companies are working on this too. I have had many interviews before and based on my former interviewing experience and the impression some of the interviewers left behind, I know now all this company wanted from me is to extract some ideas about what I did in this field. Remember, I am referring to a R&D position, not the standard software developer stuff.

Has anybody encountered this situation so far? And how did you deal with it? I am not so much concerned about "stealing" ideas but more about being tricked into showing up for an interview when there is no intension to hire anyway. I am considering refusing technical interviews in the future and instead proposing a trial period in which the company can easily reconsider its hiring decision.

答:
If you're technically adept and you put your career in play, you may run into slime, silliness, and/or shenanigans.

While I haven't had a bogus interviewer try to pick my brain for proprietary information, here are some of my less savory experiences:

A potential consulting client asked me to come do a sales pitch, so I flew on my own dime as a deductible marketing expense. When I arrived, the client's VP said he just wanted to interview me for a job, and the putative consulting was a ruse to avoid paying for my travel.

A client asked me for a proposal, which I submitted. A few days later, an Indian outsourcing firm submitted a word-for-word identical proposal, except for lower pricing. Did I mention the procurement manager had ties to that firm?

I've done a lot of interviews, and I'd guess 90% are legit, 9% are silly-but-honest wastes of time, and only about 1% involve that kind of dishonesty.

What's silly-but-honest? In the late 80s, a bioinformatics firm halted an interview for a job to write software for a DNA sequencer when I remarked about having done my grad work in organic chemistry and knowing a lot about their field. They explicitly did not want their programmers to understand DNA sequencing. Aside from the stupidity of such a policy, somebody must have missed the large parts of my resume that referred to my education and prior career as a research chemist.

I am considering refusing technical interviews in the future and instead proposing a trial period in which the company can easily reconsider its hiring decision.

Almost no Silicon Valley company will accept this. In my experience, most of them would rather not get work done than permit telecommuting, and what you're suggesting is far more radical.

Instead, I encourage you to be more philosophical, accept that some percentage of your interviews will be bogus, and laugh when they are. Oh, and go post about the dishonest interviews on anonymous-reporting site glassdoor.com.

Title: Brain picking during job interview


答:
When you are implementing a dynamically typed language, you've got to have a single type which can hold any of your objects. There are three different approaches I'm aware of for this:

Firstly, you can pass around pointers. This is what the CPython implementation does. Every object is a PyObject pointer. These pointers get passed around and operations are performed by looking at details in the PyObject struct to figure out the type.

The disadvantage is that small values like numbers get stored as boxed values, So your little 5 gets stored as a block of memory somewhere. So this leads us to the union approach, which is used by Lua. Instead of a PyObject*, each value is a struct which one field to specify the type, and then a union of all the different supported types. That way we avoid allocating any memory for small values, instead storing them directly in the union.

The NaN approach stores everything as doubles, and reuses the unused portion of NaN for the extra storage. The advantage over the union method is that we save the type field. If it's a valid double, it's a double otherwise the mantissa is a pointer to the actual object.

Remember, this is every javascript object. Every variable, every value in an object, every expression. If we can reduce all of those from 96 bits to 64 bits that is pretty impressive.

Is it worth the hack? Recall that there is a lot of demand for efficient Javascript. Javascript is the bottleneck in many web applications, and so making it faster is a higher priority. It's reasonable to introduce a certain degree of hackiness for performance reasons. For most cases, it'd be a bad idea, because its introducing a degree of complexity for little gain. But in this specific case, it is worthwhile for memory and speed improvements.

Title: What is the purpose of NaN boxing?

Body:
Reading 21st Century C I arrived at chapter 6 at the section "Marking Exceptional Numeric Values with NaNs", where it explains the use of the bits in the mantissa to store some arbitrary bit patterns, to use them as markers or pointers (the book mentions that WebKit uses this technique).

I'm not really sure I understood the utility of this technique, that I see as an hack (it relies on the hardware not caring on the value of the mantissa in a NaN) but coming from a Java background I'm not used to the roughness of C.

Here is the snippet of code that sets and reads a marker in a NaN

```<code>#include <stdio.h>
#include <math.h> //isnan

double ref;

double set_na(){
    if (!ref) {
        ref=0/0.;
        char *cr = (char *)(&ref);
        cr[2]='a';
    }
    return ref;
}

int is_na(double in){
    if (!ref) return 0;  //set_na was never called==>no NAs yet.

    char *cc = (char *)(&in);
    char *cr = (char *)(&ref);
    for (int i=0; i< sizeof(double); i++)
        if (cc[i] != cr[i]) return 0;
    return 1;
}

int main(){
    double x = set_na();
    double y = x;
    printf("Is x=set_na() NA? %i\n", is_na(x));
    printf("Is x=set_na() NAN? %i\n", isnan(x));
    printf("Is y=x NA? %i\n", is_na(y));
    printf("Is 0/0 NA? %i\n", is_na(0/0.));
    printf("Is 8 NA? %i\n", is_na(8));
}
</code>```

it prints:

```<code>Is x=set_na() NA? 1
Is x=set_na() NAN? 1
Is y=x NA? 1
Is 0/0 NA? 0
Is 8 NA? 0
</code>```

and at JSValue.h webkit explains the encoding, but not why it's used.

What is the purpose of this technique? Are the benefits of space/performance high enough to balance its hackish nature?


问:
How safe are hidden AJAX requests that fake performance?

What is a hidden AJAX request?

I've noticed an increase in the usage of hidden AJAX requests designed to make a user's action appear to happen immediately. I'll refer to this type of AJAX request as non-blocking. It's an AJAX request made without the user being aware it's happening, it's performed in the background and it's operation is silent (there is no verbose to indicate a successful completion of the AJAX call). The goal is to make the operation appear that it has happen immediately when it really has not finished.

Here are examples of non-blocking AJAX request;

User clicks delete on a collection of emails. The items disappear immediately from their inbox, and they can continue with other operations. Meanwhile, an AJAX request is processing the deletion of the items in the background.

User fills out a form for new records. Clicks save. The new item appears in the list immediately. The user can continue to add new records.

To clarify, here are examples of blocking AJAX request;

User clicks delete on a collection of emails. An hourglass cursor appears. The AJAX request is made, and when it responds the hourglass cursor is turned off. The user has to wait a second for the operation to complete.

User fills out a form for new records. Clicks save. The form turns grey with an AJAX loader animating. A message is shown "Your data was saved", and the new record appears in the list.

The difference between the two above scenarios is that a non-blocking AJAX setup does not provide feedback of an operating performing, and a blocking AJAX setup does.

The Risk Of Hidden AJAX Requests

The biggest risk of this style of AJAX request is that the web application could be in a completely different state when the AJAX request fails.

For example, a non-blocking example;

User selects a bunch of emails. Clicks the delete button. The operation appears to happen immediately (the items just disappear from the list). The user then clicks the compose button and starts typing a new email. It's at this time that the JavaScript code discovers the AJAX request failed. The script could show an error message, but it really is pointless at this time.

Alternately, a blocking example;

User selects a bunch of emails. Clicks the delete button. Sees an hour glass, but the operation fails. They get an error message saying "error. blah blah blah". They are returned back to the list of emails, and they still have the emails they wanted to delete selected. They could attempt to delete them again.

There are also other technical risks for performing non-blocking AJAX requests. The user could close the browser, could navigate to another website and they could navigate to another location in the current web that makes the context of any error response meaningless.

So Why Is It Becoming So Popular?

Facebook, Google, Microsoft, etc.. etc.. all these large domains are increasingly using non-blocking AJAX requests to make operations appear that they are performed instantly. I've also seen an increase in form editors that have no save or submit button. As soon as you leave a field or press enter. The value is saved. There is no your profile has been updated message or saving step.

AJAX requests are not a certainty, and shouldn't be treated as successful until they have completed, but so many major web applications are operating just like that.

Are these websites that use non-blocking AJAX calls to simulate responsive applications taking an unnecessary risk at the cost of appearing fast?

Is this a design pattern that we should all be following in order to remain competitive?

答:
I think, this comes together with more and more websites that try to behave like Applications and do more processing in the browser (like validating form data) than the more traditional sites. I don't see too much of a problem in that as long as your code is reliable and you can expect it to succeed under normal conditions.

You say "It's at this time that the JavaScript code discovers the AJAX request failed. The script could show an error message, but it really is pointless at this time."

Why should it be pointless? You can go back in the list of EMails and do the delete again. Why wait instead? There is actually not much of a "risk" and they do not "appear" to be fast, they actually work faster. So if the activity is not "critical" why be slow?


问:
Behavior Driven Development and Unit Testing in Python
We might be interested in starting to incorporate a unit test suite to our project, which is coded in Python (and it uses Redis, PostgreSQL and some third-party libraries, if that bears into the solution).  The benefits we want to achieve are:

Once the project is up to speed, we want to be able to specify new behavior quickly and efficiently, to help improve communication and team productivity.  Read: We want BDD, but have already started coding without it.

Excellent textual support (i.e. the tests can be read almost as natural text), so as to make it easier to write and read tests.

Ability to automatically run tests (at the very least, to be able to include the running in a Bash script or something like that).  We use Windows and Linux for development, and Linux servers, so Linux support is our primary requirement.

Integration with github.  I don't know if it is possible, but I've seen some projects in github which have a "Passing" or "Failing" status on them and it would be great to have that for our project.

What are good tools / libraries that can help us do this, and, most importantly, what are good ways to incorporate BDD into a Python project?

Thank you very much!  Any suggestions are appreciated.

答:
While there are BDD frameworks like lettuce or behave (which you better choose by their documentation and examples), you mentioned that you've started without that. So my answer will be related more to this situation.

Original BDD has started with fork of JUnit, which, instead of asking you to name your tests with "testSomething" asked you to name them "shouldDoSomething". That's how you were supposed to be kept focused on things.

So I went the same way in my project. I just started to name tests starting with "test_should_..." and try to give them descriptive names. That's how you're still doing BDD, you're still focused on what exactly should that test do, and it's easy to write something that will convert your test names into normal sentences (if you'll need to, of course). I find this approach a silver bullet since (especially in scripted languages) I never want to waste time on useless names (like test name in case of those BDD frameworks on top).


答:
Assuming something will work and displaying an error in case it fails on the remote side is much more user-friendly than blocking the user from doing anything else until there's a response from the server.

An email client is actually a great example for this: When I have a list with 5 emails and the top one is selected I expect that when hitting DEL three times the first three emails are deleted. With "nonblocking AJAX" this works fine - everytime I hit the key the selected email is removed immediately. If something goes wrong an error is shown and either the not-properly-deleted emails are shown again OR the page is reloaded to get rid of the inconsistent local state.

So in the most common case - that is success - it improves the usability. In the rare case - failure - the usability is degraded (deleted element shows up again or the application is "restarted") but when creating an application you usually want to have the best usability for common cases, not in case of errors.

Title: How safe are hidden AJAX requests that fake performance?

Body:
What is a hidden AJAX request?

I've noticed an increase in the usage of hidden AJAX requests designed to make a user's action appear to happen immediately. I'll refer to this type of AJAX request as non-blocking. It's an AJAX request made without the user being aware it's happening, it's performed in the background and it's operation is silent (there is no verbose to indicate a successful completion of the AJAX call). The goal is to make the operation appear that it has happen immediately when it really has not finished.

Here are examples of non-blocking AJAX request;

User clicks delete on a collection of emails. The items disappear immediately from their inbox, and they can continue with other operations. Meanwhile, an AJAX request is processing the deletion of the items in the background.

User fills out a form for new records. Clicks save. The new item appears in the list immediately. The user can continue to add new records.

To clarify, here are examples of blocking AJAX request;

User clicks delete on a collection of emails. An hourglass cursor appears. The AJAX request is made, and when it responds the hourglass cursor is turned off. The user has to wait a second for the operation to complete.

User fills out a form for new records. Clicks save. The form turns grey with an AJAX loader animating. A message is shown "Your data was saved", and the new record appears in the list.

The difference between the two above scenarios is that a non-blocking AJAX setup does not provide feedback of an operating performing, and a blocking AJAX setup does.

The Risk Of Hidden AJAX Requests

The biggest risk of this style of AJAX request is that the web application could be in a completely different state when the AJAX request fails.

For example, a non-blocking example;

User selects a bunch of emails. Clicks the delete button. The operation appears to happen immediately (the items just disappear from the list). The user then clicks the compose button and starts typing a new email. It's at this time that the JavaScript code discovers the AJAX request failed. The script could show an error message, but it really is pointless at this time.

Alternately, a blocking example;

User selects a bunch of emails. Clicks the delete button. Sees an hour glass, but the operation fails. They get an error message saying "error. blah blah blah". They are returned back to the list of emails, and they still have the emails they wanted to delete selected. They could attempt to delete them again.

There are also other technical risks for performing non-blocking AJAX requests. The user could close the browser, could navigate to another website and they could navigate to another location in the current web that makes the context of any error response meaningless.

So Why Is It Becoming So Popular?

Facebook, Google, Microsoft, etc.. etc.. all these large domains are increasingly using non-blocking AJAX requests to make operations appear that they are performed instantly. I've also seen an increase in form editors that have no save or submit button. As soon as you leave a field or press enter. The value is saved. There is no your profile has been updated message or saving step.

AJAX requests are not a certainty, and shouldn't be treated as successful until they have completed, but so many major web applications are operating just like that.

Are these websites that use non-blocking AJAX calls to simulate responsive applications taking an unnecessary risk at the cost of appearing fast?

Is this a design pattern that we should all be following in order to remain competitive?


答:
It's not so much "fake" performance as real responsiveness.  There are a number of reasons why it's popular:

Internet connections are fairly reliable nowadays.  The risk of an AJAX request failing is very low.

The operations being performed are not really safety critical.  If your emails don't get deleted on the server, the worst that happens is you have to delete them again the next time you come to the page.

You can design your page to undo the action if the request fails, but you don't really have to be that subtle because it means your connection to the server is broken.  It's easier to say "Connection lost. Unable to save recent changes.  Try again later."

You can design your page to only allow one pending AJAX request, so your state won't get too out of sync from the server.

The browser warns you if you try to close or navigate away from a page while an AJAX request is pending.


问:
Why doesn't Haskell have type-level lambda abstractions?
Are there some theoretical reasons for that (like that the type checking or type inference would become undecidable), or practical reasons (too difficult to implement properly)?

Currently, we can wrap things into newtype like

```<code>newtype Pair a = Pair (a, a)
</code>```

and then have Pair :: * -> *

but we cannot do something like λ(a:*). (a,a).

(There are some languages that have them, for example, Scala does.)

答: Type inference with type level lambdas would require higher order unification which is undecidable.  This is the motivation for disallowing them.  But as has happened with other undecidable features (like type inference for GADTs), it might be possible to require type signatures and allow it.  I'm not sure if that's been investigated by anyone.</p>


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
There is no object-oriented problem that cannot be solved by adding a layer of indirection, except, of course, too many layers of indirection.

-- From "The Art of Unit Testing" Roy Osherove (attributed to an unnamed source)

LastEditorDisplayName: Roger Pate


答:
In my opinion, this is a fabulous interview question -- at least assuming (1) the candidate is expected to have deep knowledge of threading, and (2) the interviewer also has deep knowledge and is using the question to probe the candidate. It's always possible that the interviewer was looking for a specific, narrow answer, but a competent interviewer should be looking for the following:

Ability to differentiate abstract concepts from concrete implementation. I throw this one in primarily as a meta-comment on some of the comments. No, it doesn't make sense to process a single list of words this way. However, the abstract concept of a pipeline of operations, which may span multiple machines of differing capabilities, is important.

In my experience (nearly 30 years of distributed, multi-process, and multi-threaded applications), distributing the work is not the hard part. Gathering the results and coordinating independent processes are where most threading bugs occur (again, in my experience). By distilling the problem down to a simple chain, the interviewer can see how well the candidate thinks about coordination. Plus, the interviewer has the opportunity to ask all sorts of follow-on questions, such as "OK, what if each thread has to send its word to another thread for reconstruction."

Does the candidate think about how the processor's memory model might affect implementation? If the results of one operation never get flushed from L1 cache, that's a bug even if there's no apparent concurrency.

Does the candidate separate threading from application logic?

This last point is, in my opinion, the most important. Again, based on my experience, it becomes exponentially more difficult to debug threaded code if the threading is mixed with the application logic (just look at all the Swing questions over on SO for examples). I believe that the best multi-threaded code is written as self-contained single-threaded code, with clearly-defined handoffs.

With this in mind, my approach would be to give each thread two queues: one for input, one for output. The thread blocks while reading the input queue, takes the first word off of the string, and passes the remainder of the string to its output queue. Some of the features of this approach:

The application code is responsible for reading a queue, doing something to the data, and writing the queue. It doesn't care whether it is multi-threaded or not, or whether the queue is an in-memory queue on one machine or a TCP-based queue between machines that live on opposite sides of the world.

Because the application code is written as-if single-threaded, it's testable in a deterministic manner without the need for a lot of scaffolding.

During its phase of execution, the application code owns the string being processed. It doesn't have to care about synchronization with concurrently-executing threads.

That said, there are still a lot of grey areas that a competent interviewer can probe:

"OK, but we're looking to see your knowledge of concurrency primitives; can you implement a blocking queue?" Your first answer, of course, should be that you'd use a pre-built blocking queue from your platform of choice. However, if you do understand threads, you can create a queue implementation in under a dozen lines of code, using whatever synchronization primitives your platform supports.

"What if one step in the process takes a very long time?" You should think about whether you want a bounded or unbounded output queue, how you might handle errors, and effects on overall throughput if you have a delay.

How to efficiently enqueue the source string. Not necessarily a problem if you're dealing with in-memory queues, but could be an issue if you're moving between machines. You might also explore read-only wrappers on top of an underlying immutable byte array.

Finally, if you have experience in concurrent programming, you might talk about some frameworks (eg, Akka for Java/Scala) that already follow this model.

Title: Multithreading synchronization interview question: Find n words given m threads

Body:
Is there a way this problem could benefit from a solution with multiple threads, rather than a single thread?

In an interview, I was asked to solve a problem using multiple threads. It appears to me that the multiple threads lends no benefit.

Here's the problem:

You are given a paragraph , which contain n number of words, you are
  given m threads. What you need to do is , each thread should print one
  word and give the control to next thread, this way each thread will
  keep on printing one word , in case last thread come, it should invoke
  the first thread. Printing will repeat until all the words are printed
  in paragraph. Finally all threads should exit gracefully. What kind of
  synchronization will use?

I strongly feel we cannot take any advantage of threads here, but believe the interviewer is trying to measure my synchronization skills. Am I missing something in this problem that would make multiple threads have value?

No need of code, just put some thoughts. I will implement by myself.


问:
Is having a switch to turn mocking on or off a code smell?
I have a method that looks like this:

```<code>def foobar(mock=False, **kwargs):
    # ... snipped
</code>```

foobar actually makes several calls to Amazon S3 and returns a composed result.
In order to make this testable, I introduced the mock parameter to turn off making live network connections. It feels like a code smell for me but testability is also very important. What else can I do if I want to do away with the parameter ?

答:
Sometimes, it's easier to just pass some "s3 engine" as a parameter and pass some simple mock-object instead when it's a test (and provide it's return values). Sometimes you need to call lots of random functions that cause side-effects (for example, if you would work with s3, get current time, do some sql-queries, open some files and more), and here it wouldn't be nice to pass it all as function-parameters (since it isn't needed except for testability), I'd suggest you to use mockstar to declaratively describe your side-effects. Your code would then something like this:</p>

```<code>def foobar():
    foo = get_from_database()
    bar = read_from_file()
    baz = read_from_s3()

    if foo > 10:
        return foo + bar + baz
    else:
        return foo - bar - baz

# And your test would look something like this:

from mockstar import prefixed_p
from nose.tools import assert_equal

ppatch = prefixed_p('module.with.foobar.func')

class TestFoobar(BaseTestCase):
    @ppatch('get_from_database')
    @ppatch('read_from_file')
    @ppatch('read_from_s3')
    def side_effects(self, se):
        se.read_from_file.return_value = 10  # default behaviour
        se.read_from_s3.return_value = 0  # also default behaviour
        return self.invoke(se)

    def test_should_get_30(self, se):
        se.get_from_database.return_value = 20

        # do
        result = foobar()

        assert_equal(result, 30)

    def test_should_get_minus5(self, se):
        se.get_from_database.return_value = 5

        # do
        result = foobar()

        assert_equal(result, -5)
</code>```

OwnerDisplayName: Bon Ami

Body:
Sometimes, it's easier to just pass some "s3 engine" as a parameter and pass some simple mock-object instead when it's a test (and provide it's return values). Sometimes you need to call lots of random functions that cause side-effects (for example, if you would work with s3, get current time, do some sql-queries, open some files and more), and here it wouldn't be nice to pass it all as function-parameters (since it isn't needed except for testability), I'd suggest you to use mockstar to declaratively describe your side-effects. Your code would then something like this:

def foobar():
    foo = get_from_database()
    bar = read_from_file()
    baz = read_from_s3()

    if foo > 10:
        return foo + bar + baz
    else:
        return foo - bar - baz

# And your test would look something like this:

from mockstar import prefixed_p
from nose.tools import assert_equal

ppatch = prefixed_p('module.with.foobar.func')

class TestFoobar(BaseTestCase):
    @ppatch('get_from_database')
    @ppatch('read_from_file')
    @ppatch('read_from_s3')
    def side_effects(self, se):
        se.read_from_file.return_value = 10  # default behaviour
        se.read_from_s3.return_value = 0  # also default behaviour
        return self.invoke(se)

    def test_should_get_30(self, se):
        se.get_from_database.return_value = 20

        # do
        result = foobar()

        assert_equal(result, 30)

    def test_should_get_minus5(self, se):
        se.get_from_database.return_value = 5

        # do
        result = foobar()

        assert_equal(result, -5)


答:
The users don't care about what your software is doing behind the scenes: they want their actions to have visible impact, and to be able to work at their pace.

If an action was successful on client side - like deleting emails - it's your job to make it successful on server side as well. Why did the deletion fail? If it's due to some kind of limitation (for exemple, you can't remove an email that has been archived), the user should be made aware of that before his action failed.

If the error is caused by something more severe (let's say a database crash), you should have a way to save the operation and re-try it when the system is up again.

A good exemple of managing this is the way Facebook handles the chat. There is no way to stop a user from disconnecting suddenly, which means they won't be able to read the messages you sent before they left. Instead of displaying an error, the system saves all those messages and makes them available to the user when he comes back. No data is lost.


问:
What's a good strategy for managing static data in an SOA?
I'm working on a web application that sits on top of a number of RESTful web services, interacting primarily with those services through JSON formatted messages over HTTP. Our application has a great deal of static data that are read from these services (internationalization lookups, configuration, etc.) during operation.

Unfortunately, we work pretty closely with the team who develops the webservces, so we know the backend architecture fairly intimately. Most of the services are using a MongoDB store for persistence, and our strategy thus far for managing the static data we require to be loaded is to utilize MongoDB dumps committed to version control that are loaded at deploy/upgrade time.

We'd like to decouple our static data from the persistence store. The best ideas that have come forth thus far mostly involve storing static data formatted as it would be passed to services (JSON files) and then writing a "loader" process/script that will live as part of the deployment process which will interact with services to load the data.

Are there patterns/strategies for managing/loading/deploying "application" data to services?

答:
It would seem you're approaching the problem correctly.  Add a layer of abstraction between your database and static data so that the receiver always gets the same thing.  It may require a little rewiring, but the end effect is that the back end can change any number of ways but the front end still gets the same format everytime.

I don't know what language/libraries you're using to convert to JSON, but I would recommend GSON if you're using Java since it has a system to convert any object into a JSON counterpart.  With the help of annotations, you can also control which properties you want to be converted into JSON.


答:
My 2c is: there's situations when it's better to have, as you put it, "non-blocking" Ajax operations and others where it's a bad design choice. Example: voting a YouTube video. You don't really want any part of the page to be blocked while you click on the little starts there. It's better to silently fail. Even a confirmation message would be over-kill. However your example with email deletion I'd qualify as mandatory for blocking-type Ajax request.

Mongo DB does something like that (and this could be considered as a Desktop application example). They have various "Write Concerns" for their operations, and you can configure it to different values for each operation, ranging from "return right away and don't wait for anything" to "block until you've confirmation of successful network transfer and then return" to "wait till the content is properly scheduled for disk write on the remote machine before your return". Obviously, if you make Desktop thick client (in like C++) using the Mongo driver, you'd set the lightest write concern for db operations of minimal "criticalness" (such as checking for new email), and others on more strict write concerns.

While I see the usefulness of non-blocking Ajax, I do agree with you that it's happening too much. At a point there was at least one famous "social networking" site which would do this for photo uploading. You'd chose your photo to upload and then bam, right away it would tell you that it's done, and then sure enough the next day when you wanted to add some more photos (or use on that you thought you already added), it was never to be found. Later on they gave up on this, and actually took the time to wait for response (and you would indeed sometimes get messages like "failed to upload photo, try later").


问:
How can I update a large legacy codebase to meet specific quality standards?
There is a lot of information about tools and techniques for improving legacy codebases, but I haven't come across any successful real world case studies.  Most advice is on the micro level, and while helpful, doesn't convince many people because of a lack of evidence it can help at the macro level.

I am looking specifically for incremental improvements that have been proven to be a success in the real world when updating a large legacy codebase to meet today's quality standards, and not a complete rewrite.

Before:

Large: greater than 1MLOC

Legacy: no automated tests

Poor quality: high complexity, high coupling, high escaped defects

After

Automated tests

Easier updates/maintenance

High quality: lowered complexity, decoupled code, few escaped defects

What kind of incremental steps have been proven in the real world to update a large legacy codebase successfully to meet above quality standards, without going through a total rewrite?

If possible, include an example company or case study of a large legacy project that has gone through a "successful" quality improvement process in your answer to back it up.

答:
On February 3, 2013, Michael Meeks, one of the LibreOffice developers, is giving a talk in a couple of days entitled, "LibreOffice: cleaning and re-factoring a giant code-base, or why re-writing it would be even worse."  It sounds like exactly what you're asking for: a discussion of what they've done to take " a poorly-understood, gigantic code-base extensively commented in German, with no unit tests, a tangled build infrastructure, and twenty-five years of un-paid technical debt" and modernize it.

The presentation can be streamed online, and (I think) recordings will be available at some future date.


问:
sqrt c# vs sqrt c++
Any idea why the C# version of sqrt (System.Math.Sqrt) is ~10 times slower than c++ version ? Furthermore, C# version seems to have one extra digit of precision. I have run my test under MSVC2012.

I have used double and call System.Math.Sqrt once before doing the bench in order to force Jit

答:
I am speaking only from the C side (and thus applicable to C++).  I have no system that can run C# to work from.

The first program I wrote was the trivial:

```<code>#include <math.h>
#include <stdio.h>

int main(void) {
    printf("%f\n",sqrt(2.0));
}
</code>```

Using gcc -S -O3 sqrt.c I got the compiled source in sqrt.s and looked at that.

```<code>    .file   "sqrt.c"
    .section    .rodata.str1.1,"aMS",@progbits,1
.LC1:
    .string "%f\n"
    .text
    .p2align 4,,15
.globl main
    .type   main, @function
main:
.LFB14:
    .cfi_startproc
    movsd   .LC0(%rip), %xmm0
    movl    $.LC1, %edi
    movl    $1, %eax
    jmp printf
    .cfi_endproc
.LFE14:
    .size   main, .-main
    .section    .rodata.cst8,"aM",@progbits,8
    .align 8
.LC0:
    .long   1719614413
    .long   1073127582
    .ident  "GCC: (SUSE Linux) 4.5.1 20101208 [gcc-4_5-branch revision 167585]"
    .section    .comment.SUSE.OPTs,"MS",@progbits,1
    .string "Ospwg"
    .section    .note.GNU-stack,"",@progbits
</code>```

One will note that there is no call to sqrt in the code - it looks like its just loading a constant (which it is).

This became more apparent when writing one that used a variable and doing the compile to demonstrate what a call to sqrt would look like.

I'm not going for any sort of elegance with this code.

```<code>#include <math.h>
#include <stdio.h>

void main(int argc, char **argv) {
    double num = atoi(argv[0]);
    printf("%f\n",sqrt(num));
}
</code>```

While gcc -O3 -S sqrt.c worked, this second program as gcc -O3 -S sqrt2.c returned

```<code>/tmp/cckmgfMS.o: In function `main':
sqrt2.c:(.text+0x46): undefined reference to `sqrt'
collect2: ld returned 1 exit status
</code>```

It was calling sqrt, and I forgot to link the math library.

When adding the link to the code, one can see the call to sqrt in it:

```<code>        .file   "sqrt2.c"
        .section        .rodata.str1.1,"aMS",@progbits,1
.LC0:
        .string "%f\n"
        .text
        .p2align 4,,15
.globl main
        .type   main, @function
main:
.LFB14:
        .cfi_startproc
        subq    $8, %rsp
        .cfi_def_cfa_offset 16
        movq    (%rsi), %rdi
        xorl    %eax, %eax
        call    atoi
        cvtsi2sd        %eax, %xmm1
        sqrtsd  %xmm1, %xmm0
        ucomisd %xmm0, %xmm0
        jp      .L5
.L2:
        movl    $.LC0, %edi
        movl    $1, %eax
        addq    $8, %rsp
        .cfi_remember_state
        .cfi_def_cfa_offset 8
        jmp     printf
.L5:
        .cfi_restore_state
        movapd  %xmm1, %xmm0
        call    sqrt
        jmp     .L2
        .cfi_endproc
.LFE14:
        .size   main, .-main
        .ident  "GCC: (SUSE Linux) 4.5.1 20101208 [gcc-4_5-branch revision 167585]"
        .section        .comment.SUSE.OPTs,"MS",@progbits,1
        .string "Ospwg"
        .section        .note.GNU-stack,"",@progbits
</code>```

One can see in this code the call to sqrt, and the lack of the constants that the optimizer put in.

From the comment above:

I have of course store the 10^6 sqrt(2.0) calls by doing a sum in a
  variable ( i.e: var += sqrt(2.0) ) and print it on screen at the end
  to be sure that compilator will not skip some codes. – Guillaume07 Dec
  24 '12 at 19:19

So, consider - if you are dealing with constants, this is something that the C and C++ optimizers will identify and optimize out.

Failing having access to C#, I looked at how Java deals with the line:

```<code>System.out.println(Math.sqrt(2.0));
</code>```

This instruction is compiled to the Java byte code of:

```<code>0  getstatic java.lang.System.out : java.io.PrintStream [16]
3  ldc2_w <Double 2.0> [22]
6  invokestatic java.lang.Math.sqrt(double) : double [24]
9  invokevirtual java.io.PrintStream.println(double) : void [30]
</code>```

One can see that the Java complier doesn't have access to the information of the output of sqrt() to be able to optimize into a constant.  It is possible that the JIT optimizer might have access to the information about the purity of calls through Math to StrictMath and replace multiple calls of Math.sqrt(2.0) to the same value (and not call it again), however it still has to call it once at that point to get the value.  That said, I don't have any insight into what goes on at runtime in the JIT and how calls to pure functions that end up native might be optimized.

However, the C optimizer is still ahead of the game with a big loop (assuming that the JIT optimizer only needs to make one call to sqrt() to get that first value).

When looking at the optimization of the loop in C, the optimizer even precalculates the loop.

```<code>#include <math.h>
#include <stdio.h>

int main(void) {
    double sum = 0;
    int i = 0;
    for(i; i < 10; i++) {
        sum += sqrt(2.0);
    }
    printf("%f\n",sum);
}
</code>```

through gcc -O3 -S sqrt3.c (still no -lm needed) becomes:

```<code>    .file   "sqrt3.c"
    .section    .rodata.str1.1,"aMS",@progbits,1
.LC1:
    .string "%f\n"
    .text
    .p2align 4,,15
.globl main
    .type   main, @function
main:
.LFB14:
    .cfi_startproc
    movsd   .LC0(%rip), %xmm0
    movl    $.LC1, %edi
    movl    $1, %eax
    jmp printf
    .cfi_endproc
.LFE14:
    .size   main, .-main
    .section    .rodata.cst8,"aM",@progbits,8
    .align 8
.LC0:
    .long   2034370
    .long   1076644038
    .ident  "GCC: (SUSE Linux) 4.5.1 20101208 [gcc-4_5-branch revision 167585]"
    .section    .comment.SUSE.OPTs,"MS",@progbits,1
    .string "Ospwg"
    .section    .note.GNU-stack,"",@progbits
</code>```

And one can see that this code is identical to the first one, with different constants in .LC0 section.  The loop has been calculated down to just "the ultimate value is this, don't bother doing it at run time."

Title: sqrt c# vs sqrt c++

Body:
I am speaking only from the C side (and thus applicable to C++).  I have no system that can run C# to work from.

The first program I wrote was the trivial:

#include <math.h>
#include <stdio.h>

int main(void) {
    printf("%f\n",sqrt(2.0));
}

Using gcc -S -O3 sqrt.c I got the compiled source in sqrt.s and looked at that.

    .file   "sqrt.c"
    .section    .rodata.str1.1,"aMS",@progbits,1
.LC1:
    .string "%f\n"
    .text
    .p2align 4,,15
.globl main
    .type   main, @function
main:
.LFB14:
    .cfi_startproc
    movsd   .LC0(%rip), %xmm0
    movl    $.LC1, %edi
    movl    $1, %eax
    jmp printf
    .cfi_endproc
.LFE14:
    .size   main, .-main
    .section    .rodata.cst8,"aM",@progbits,8
    .align 8
.LC0:
    .long   1719614413
    .long   1073127582
    .ident  "GCC: (SUSE Linux) 4.5.1 20101208 [gcc-4_5-branch revision 167585]"
    .section    .comment.SUSE.OPTs,"MS",@progbits,1
    .string "Ospwg"
    .section    .note.GNU-stack,"",@progbits

One will note that there is no call to sqrt in the code - it looks like its just loading a constant (which it is).

This became more apparent when writing one that used a variable and doing the compile to demonstrate what a call to sqrt would look like.

I'm not going for any sort of elegance with this code.

#include <math.h>
#include <stdio.h>

void main(int argc, char **argv) {
    double num = atoi(argv[0]);
    printf("%f\n",sqrt(num));
}

While gcc -O3 -S sqrt.c worked, this second program as gcc -O3 -S sqrt2.c returned

/tmp/cckmgfMS.o: In function `main':
sqrt2.c:(.text+0x46): undefined reference to `sqrt'
collect2: ld returned 1 exit status

It was calling sqrt, and I forgot to link the math library.

When adding the link to the code, one can see the call to sqrt in it:

        .file   "sqrt2.c"
        .section        .rodata.str1.1,"aMS",@progbits,1
.LC0:
        .string "%f\n"
        .text
        .p2align 4,,15
.globl main
        .type   main, @function
main:
.LFB14:
        .cfi_startproc
        subq    $8, %rsp
        .cfi_def_cfa_offset 16
        movq    (%rsi), %rdi
        xorl    %eax, %eax
        call    atoi
        cvtsi2sd        %eax, %xmm1
        sqrtsd  %xmm1, %xmm0
        ucomisd %xmm0, %xmm0
        jp      .L5
.L2:
        movl    $.LC0, %edi
        movl    $1, %eax
        addq    $8, %rsp
        .cfi_remember_state
        .cfi_def_cfa_offset 8
        jmp     printf
.L5:
        .cfi_restore_state
        movapd  %xmm1, %xmm0
        call    sqrt
        jmp     .L2
        .cfi_endproc
.LFE14:
        .size   main, .-main
        .ident  "GCC: (SUSE Linux) 4.5.1 20101208 [gcc-4_5-branch revision 167585]"
        .section        .comment.SUSE.OPTs,"MS",@progbits,1
        .string "Ospwg"
        .section        .note.GNU-stack,"",@progbits

One can see in this code the call to sqrt, and the lack of the constants that the optimizer put in.

From the comment above:

I have of course store the 10^6 sqrt(2.0) calls by doing a sum in a
  variable ( i.e: var += sqrt(2.0) ) and print it on screen at the end
  to be sure that compilator will not skip some codes. – Guillaume07 Dec
  24 '12 at 19:19

So, consider - if you are dealing with constants, this is something that the C and C++ optimizers will identify and optimize out.

Failing having access to C#, I looked at how Java deals with the line:

System.out.println(Math.sqrt(2.0));

This instruction is compiled to the Java byte code of:

0  getstatic java.lang.System.out : java.io.PrintStream [16]
3  ldc2_w <Double 2.0> [22]
6  invokestatic java.lang.Math.sqrt(double) : double [24]
9  invokevirtual java.io.PrintStream.println(double) : void [30]

One can see that the Java complier doesn't have access to the information of the output of sqrt() to be able to optimize into a constant.  It is possible that the JIT optimizer might have access to the information about the purity of calls through Math to StrictMath and replace multiple calls of Math.sqrt(2.0) to the same value (and not call it again), however it still has to call it once at that point to get the value.  That said, I don't have any insight into what goes on at runtime in the JIT and how calls to pure functions that end up native might be optimized.

However, the C optimizer is still ahead of the game with a big loop (assuming that the JIT optimizer only needs to make one call to sqrt() to get that first value).

When looking at the optimization of the loop in C, the optimizer even precalculates the loop.

#include <math.h>
#include <stdio.h>

int main(void) {
    double sum = 0;
    int i = 0;
    for(i; i < 10; i++) {
        sum += sqrt(2.0);
    }
    printf("%f\n",sum);
}

through gcc -O3 -S sqrt3.c (still no -lm needed) becomes:

    .file   "sqrt3.c"
    .section    .rodata.str1.1,"aMS",@progbits,1
.LC1:
    .string "%f\n"
    .text
    .p2align 4,,15
.globl main
    .type   main, @function
main:
.LFB14:
    .cfi_startproc
    movsd   .LC0(%rip), %xmm0
    movl    $.LC1, %edi
    movl    $1, %eax
    jmp printf
    .cfi_endproc
.LFE14:
    .size   main, .-main
    .section    .rodata.cst8,"aM",@progbits,8
    .align 8
.LC0:
    .long   2034370
    .long   1076644038
    .ident  "GCC: (SUSE Linux) 4.5.1 20101208 [gcc-4_5-branch revision 167585]"
    .section    .comment.SUSE.OPTs,"MS",@progbits,1
    .string "Ospwg"
    .section    .note.GNU-stack,"",@progbits

And one can see that this code is identical to the first one, with different constants in .LC0 section.  The loop has been calculated down to just "the ultimate value is this, don't bother doing it at run time."


问:
MVVM Clarification
We are about to write our first WPF application and are becoming familiar with the MVVM pattern. We've built many Winform applications and have an architecture that has been very successful for us.  We're having a little bit of trouble translating that architecture or determining where certain pieces of our architecture fit in the MVVM model.

Historically we have a Gui (the main exe) that then communicates to a BusinessLogic dll. The BusinessLogic communicates to a DAL dll through a web service and the DAL interacts with the DB.  The DAL, BusinessLogic and GUI all reference the same BusinessObjects dll.

Some of the transition to MVVM is fairly straight forward.  Our Gui will still contain the views, our BusinessOjbects will still contain the model and our DAL will still interact with the DB (although the technology to implement them may change).

What we're not sure of is our BusinessLogic component. Historically this would provide functions for the GUI to call to then populate controls in the views (ie. GetCustomerList which would return a list of Customer objects or the typical CRUD functions).

The main hang up we have is whether the MVVM pattern would call for an additional component to house the ViewModels or if we just change our thinking and migrate what we have used as our BusinessLogic component to the ViewModels?

Does our BusinessLogic component represent the ViewModels?

答:
Yes.

The business logic layer is represented by the VM layer.  So just migrate your mental model.

To help with your mental model migration, one slight nuance is that the GUI (View) objects should be bound to objects within the VM layer.  That binding translates into | implies that the View no longer being the layer that "makes the call" in order to retrieve something else.  The call for data retrieval will come from the VM instead.

To better explain:  Yes, an object within the View will need to change in order to trigger the sequence of things that will make the call.  But the View doesn't make the call itself.  And in this case, I consider a button click as equivalent to something within the View changing, but still not making the call.

In the first case, that View object will be bound to a VM object. The VM should be listening for a property changed event on the bound object.  The object change event can then be wired to a VM function to make the Model call.

In the second case (button click event), the change (click) event can be wired to a function call exposed by the VM.

Either way, it's always an event that sequences into the VM which then calls the Model which in turn calls the DAL / DB.

I bring it up because some WinForm code is used to making a call to the DB layer directly from the code-behind of the WinForm GUI.  That approach breaks the separation that MVVM is providing.

Title: MVVM Clarification


问:
Better way of storing key-value pairs in the database?
I have a C#/SQL Server program that sometimes needs to store data. The data could be a response from a web service, a result of a database query, or any number of other things. There's no way of knowing before the data is stored how many fields it might have or what the data structure might be. We have this kind of painful table we're using for this... four columns and lots of rows. An example of the data might be easier than an explanation.

```<code>InstanceID RowID PropertyName PropertyValue
1          1     Property1    Value1
1          1     Property2    Value2
1          1     Property3    Value3
1          2     Property1    Value1
1          2     Property2    Value2
1          2     Property3    Value3
2          1     OtherProp1   Value1
2          1     OtherProp2   Value2
2          2     OtherProp1   Value1
2          2     OtherProp2   Value2
</code>```

These values will then be pulled back and fed into a dictionary object, which can be updated, then the fields will be fed back into the database. This can be painful to code against, and also requires a lot of inserts which can make it very slow.

I can't think of a better way of doing this, but I feel like there must be one. Any advice?

答:
If you don't need to make queries against the data, you could just store all of that in a single column that is in XML-format. Like

```<code><properties>
    <property name="property1">Value1</property>
    <property name="property2">Value2</property>
</properties>
</code>```

If you do need to make queries against the key value pairs you have couple of options. If you are using SQL Server it has support for xml columns so you can use XPath in your queries. You can also create indexes for XPaths. Other database engines might have similar features as well

You could also use a separate search engine like ElasticSearch which would index your content.

Body:
If you don't need to make queries against the data, you could just store all of that in a single column that is in XML-format. Like

<properties>
    <property name="property1">Value1</property>
    <property name="property2">Value2</property>
</properties>

If you do need to make queries against the key value pairs you have couple of options. If you are using SQL Server it has support for xml columns so you can use XPath in your queries. You can also create indexes for XPaths. Other database engines might have similar features as well

You could also use a separate search engine like ElasticSearch which would index your content.


问:
Should my small software library avoid using other libraries?
I've just released a small Java library that offers only a few classes and methods. Since I built the project with Maven, I immediately used several third-party libraries to achieve my goals, specifically:

commons-lang3 (for some general Java stuff)

slf4j-api (for logging)

commons-io (for a tiny bit of file stuff - literally reading a file once, I think)

I don't want my library to appear bloated in the eyes  of others. Should I be trying to remove my reliance on these libraries to minimise my footprint? Any advice on what types of libraries would be best to avoid when considering using more in the future?

答:
I'm answering this considering your specific situation.  I would say it's fine to use those libraries.  Just make sure your slf4j-api doesn't bring along the implementation with it.  By that, I mean mark the implementation dependency as "test".  EG:

```<code><dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.2</version>
    <scope>test</scope>
</dependency>
</code>```

This is described in detail on the SLF4j FAQ.

As for the other two, IME, they're always backwards compatible.  Therefore, if 5 years from now I need to use your library but you're using an old version of those, I can just exclude your dependencies and our code will still work.  In other words, by using these specific libraries you won't introduce jar-hell for others.

If I use your library via maven, I won't notice if your library is bloated or not.  I'll just depend on yours and use it.  I think it's more important that your code works correctly than its got a smaller footprint.  I prefer you use commons-io instead of reinventing the wheel with a bug in it.

Body:
I'm answering this considering your specific situation.  I would say it's fine to use those libraries.  Just make sure your slf4j-api doesn't bring along the implementation with it.  By that, I mean mark the implementation dependency as "test".  EG:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.2</version>
    <scope>test</scope>
</dependency>

This is described in detail on the SLF4j FAQ.

As for the other two, IME, they're always backwards compatible.  Therefore, if 5 years from now I need to use your library but you're using an old version of those, I can just exclude your dependencies and our code will still work.  In other words, by using these specific libraries you won't introduce jar-hell for others.

If I use your library via maven, I won't notice if your library is bloated or not.  I'll just depend on yours and use it.  I think it's more important that your code works correctly than its got a smaller footprint.  I prefer you use commons-io instead of reinventing the wheel with a bug in it.


问:
Error checking in actor-based paradigm
I have an existing Scala application that I am trying to refactor in order to use Akka. One of the problems I have is how to manage error-checking in actor-based applications.

Usually error-checking is done through one of two mechanisms:

either one returns a value indicating an error condition, such as Option[A] or Failure[A], or

by the use of exceptions.

Neither of these style seems particulary useful here. On the one hand, actor messages are usually "fire and forget", hence there are no return values. [One can have a return value using Futures, but it certainly not customary to ask for futures on every message.] On the other hand, processing of the message usually happens on another thread, so that one cannot catch an exception arising from the processing of a message.

One could simulate the first mechanism by sending back error or confirmation messages, such as

```<code>class FooActor extends Actor {
  def receive = {
    case Foo => ...
      if (errorCondition) sender ! ErrorMessage
  }
}
</code>```

But if one has to do this for every actor, it becomes a lot of boilerplate and it seems a poor man's simulation of stack unwinding.

What is a good strategy to recover from errors in actor-based applications?

答:
Fault tolerance is one of the key concepts of Akka and "let it crash" is one of their mottos. Akka's mechanism for handling failures is called supervision, and it's right there on akka.io/#supervision:

Actors form a tree with actors being parents to the actors they've created. As a parent, the actor is responsible for handling its children’s failures (so-called supervision), forming a chain of responsibility, all the way to the top. When an actor crashes, its parent can either restart or stop it, or escalate the failure up the hierarchy of actors. This enables a clean set of semantics for managing failures in a concurrent, distributed system and allows for writing highly fault-tolerant systems that self-heal. Learn more.

Hence, you don't need to explicitly fire failure messages in case of an exception. The supervisor strategy of an actor's parent (or the parent's parent and so on) is invoked automatically. Although you can of course do it if you want to.

Also take a look at Supervision, Lifecycle Monitoring and Restart Hooks.

Title: Error checking in actor-based paradigm


答:
From personal experience working on a multi-million line code base I have found a few strategies that seem to work.

Look at all of the bugs (even closed ones) and try to break them down into categories.  Specifically to try break them down by the component that they belong to.  If they belong to more than one component note that they do.  Once you have done this look at which bucket is the biggest and use that to determine where to start.  Additionally you can look at the revision history of the files to determine what changes the most and use that as a guide of where to start.  Basically what you are trying to do is to find what is most broken fix that and repeat.  Additionally I have found that trying to fix everything at the same time never works it just causes more problems.

If you find that there a lot of things that belong to multiple components that is an indication of "system" issues and may point to code that is too tightly coupled or an API that needs refreshing.

Another area where I have spent a lot of time is testing the existing code base.  There are multiple strategies here and all have merit but no one is a complete solution to the problem.

Unit testing can work but often times you are limited to what can be unit tested due to tightly coupled code.  However do it where you can.

External testing is another avenue.  I assume that you probably already have this and if not I would spend some time creating it.  Additionally something that has worked for me is to add the ability to randomly inject faults/events into the system.  In addition to that try to inject multiple things at the same time to try to make it fail in new ways.

Title: How can I update a large legacy codebase to meet specific quality standards?

Body:
There is a lot of information about tools and techniques for improving legacy codebases, but I haven't come across any successful real world case studies.  Most advice is on the micro level, and while helpful, doesn't convince many people because of a lack of evidence it can help at the macro level.

I am looking specifically for incremental improvements that have been proven to be a success in the real world when updating a large legacy codebase to meet today's quality standards, and not a complete rewrite.

Before:

Large: greater than 1MLOC

Legacy: no automated tests

Poor quality: high complexity, high coupling, high escaped defects

After

Automated tests

Easier updates/maintenance

High quality: lowered complexity, decoupled code, few escaped defects

What kind of incremental steps have been proven in the real world to update a large legacy codebase successfully to meet above quality standards, without going through a total rewrite?

If possible, include an example company or case study of a large legacy project that has gone through a "successful" quality improvement process in your answer to back it up.


问:
In MVC, can/should basic data retrieval from the Model be done in the View?
Given the concept of 'skinny controllers, fat models' and the general acceptance that Views can directly call on Models when requiring data for output, should one consider handling the 'get and display' parts of requests within the Views and not the Controller? For example (attempted to keep code fairly generic):

Controller

```<code><?php

class Invoice extends Base_Controller {

    /**
     * Get all the invoices for this month
     */

    public function current_month() {

        // as there's no user input let's keep the controller very skinny,
        // DON'T get data from the Model here, just load the view

        $this->load->view('invoice/current_month');

    }

}
</code>```

View

```<code><?php

// directly retrieve current month invoices here

$invoices = $this->invoice_model->get_current_month();

// get some other display-only data, e.g. a list of users for a separate list somewhere on the page

$users = $this->user_model->get_users();

?>

<h1>This month's invoices</h1>

<ul>
<?php foreach ($invoices as $invoice) { ?>

<li><?php echo $invoice['ref']; ?></li>

<?php } ?>
</ul>
</code>```

To me, this makes at least some sense in the cases where a request is essentially just a View. Why should the Controller have to collect and pass on the data to the View when it can just retrieve it itself? This leaves the Controller open for purely 'Application level' processing (e.g. handling GET/POST requests, managing access rights and permissions etc.) as well as keeping the Models reusable and all the other good stuff.

If this example was extended to allow a user to filter the results, the Controller would just handle the POST from the form and pass the filters to the View, which would then request the data again, this time with the filters.

Is this a valid approach to developing an MVC application? Or am I overlooking an important part of the role a Controller should play?

答:
Yes, it can technically be done.  No, it shouldn't be done.  And yes, you're missing a bit of what the controller is there for.

The controller is there to decouple the View from the Model.  The decoupling is beneficial because you should look at the View as almost throw-away code.  As your UI technology changes, you want to minimize the rework required in generating a new View.  The controller enables that decoupling and provides a place for your code that will live through UI technologies.

It works in reverse as well if you need to add to or change out your Model.  All of the upstream changes will be contained within the Controller and your Views will be left alone.

The other risk is that while the View is very simple now, you have less guarantee that it will remain so simple throughout its life.  By calling the Model directly from the (very simple) View, you've opened the door a bit to allow additional bad practice to creep in later when the very simple View needs to become not-so-very simple.  A future developer will be tempted to make more Model calls from the not-so-very simple View instead of refactoring the code and interacting with a Controller.


答:
Given the concept of 'skinny controllers, fat models' and the general acceptance that Views can directly call on Models when requiring data for output

No. This is not correct. View can not directly call on Models. Views should not have access to Model objects, unless for some reason the programmer has exposed those objects to the View.

should one consider handling the 'get and display' parts of requests within the Views and not the Controller?

That basically erases the Controller, and defeats the point of having them.

Why should the Controller have to collect and pass on the data to the View when it can just retrieve it itself?

The Controller doesn't collect the data. The Model does the collecting of the data. The Controller decides if this data should be passed to the view. The View just does the presentation of the data.

If this example was extended to allow a user to filter the results, the Controller would just handle the POST from the form and pass the filters to the View, which would then request the data again, this time with the filters.

No.

The Controller checks if the POSTed data is valid, it then passes this data as options to the Model, which would then query the datasource and return the data, and the Controller passes that to the View.

Is this a valid approach to developing an MVC application? Or am I overlooking an important part of the role a Controller should play?

The Controller operates as a handler to requests by the browser. A dispatcher sends the request to a controller's action, which in turn, spreads the request out to the Models. The Models contain all the business logic (this is the fat part), and give the data back to the controller. The controller can then simplify and adjust the data so that it's easier for the View to present it.

The point of the View is to decouple the structure and dependency between the presentation of HTML and the DataSource. While this can be difficult. Views don't always present data that came directly from a Model. The controller often adds extra data that is relevant.

I'm sure there are a lot of tutorials out there on MVC. I'd recommend reading some of them.

Title: In MVC, can/should basic data retrieval from the Model be done in the View?

Body:
Given the concept of 'skinny controllers, fat models' and the general acceptance that Views can directly call on Models when requiring data for output, should one consider handling the 'get and display' parts of requests within the Views and not the Controller? For example (attempted to keep code fairly generic):

Controller

```<code><?php

class Invoice extends Base_Controller {

    /**
     * Get all the invoices for this month
     */

    public function current_month() {

        // as there's no user input let's keep the controller very skinny,
        // DON'T get data from the Model here, just load the view

        $this->load->view('invoice/current_month');

    }

}
</code>```

View

```<code><?php

// directly retrieve current month invoices here

$invoices = $this->invoice_model->get_current_month();

// get some other display-only data, e.g. a list of users for a separate list somewhere on the page

$users = $this->user_model->get_users();

?>

<h1>This month's invoices</h1>

<ul>
<?php foreach ($invoices as $invoice) { ?>

<li><?php echo $invoice['ref']; ?></li>

<?php } ?>
</ul>
</code>```

To me, this makes at least some sense in the cases where a request is essentially just a View. Why should the Controller have to collect and pass on the data to the View when it can just retrieve it itself? This leaves the Controller open for purely 'Application level' processing (e.g. handling GET/POST requests, managing access rights and permissions etc.) as well as keeping the Models reusable and all the other good stuff.

If this example was extended to allow a user to filter the results, the Controller would just handle the POST from the form and pass the filters to the View, which would then request the data again, this time with the filters.

Is this a valid approach to developing an MVC application? Or am I overlooking an important part of the role a Controller should play?


答:
You are correct that you would essentially be replacing your BusinessLogic dll with your ViewModel layer, however I think the biggest difference you will face is how the View/UI layer interacts with your ViewModel/BusinessLogic layer.

In WinForms, the GUI is your application, and is responsible for application flow. In WPF/MVVM, your ViewModels are you application, and the GUI becomes just a user-friendly interface to interact with the ViewModels.

For example, with WinForms, you might have a DataGrid and a Button, and when you click that Button you call BusinessLogicLayer.GetProducts() and load the resulting Product objects into the DataGrid.

With WPF, you would have a ViewModel that contains an ObservableCollection<Products> and an ICommand GetProducts, and executing the command calls the DAL and loads the collection of products. But to provide a user-friendly interface for this, you would create a View which renders your ViewModel using a DataGrid for the Products collection, and a Button for the GetProducts command.

I actually wrote a fairly recent post for my blog about the change in mindset when moving from Winforms to WPF on my blog, and I think the best way to summarize the difference is with these pictures:

Title: MVVM Clarification

Body:
We are about to write our first WPF application and are becoming familiar with the MVVM pattern. We've built many Winform applications and have an architecture that has been very successful for us.  We're having a little bit of trouble translating that architecture or determining where certain pieces of our architecture fit in the MVVM model.

Historically we have a Gui (the main exe) that then communicates to a BusinessLogic dll. The BusinessLogic communicates to a DAL dll through a web service and the DAL interacts with the DB.  The DAL, BusinessLogic and GUI all reference the same BusinessObjects dll.

Some of the transition to MVVM is fairly straight forward.  Our Gui will still contain the views, our BusinessOjbects will still contain the model and our DAL will still interact with the DB (although the technology to implement them may change).

What we're not sure of is our BusinessLogic component. Historically this would provide functions for the GUI to call to then populate controls in the views (ie. GetCustomerList which would return a list of Customer objects or the typical CRUD functions).

The main hang up we have is whether the MVVM pattern would call for an additional component to house the ViewModels or if we just change our thinking and migrate what we have used as our BusinessLogic component to the ViewModels?

Does our BusinessLogic component represent the ViewModels?


问:
How to implement syntax sugar in OO

The Problem

I regularly find myself writing the same code over and over again.

For example if I want a value from a nested array structure I end up writing something like this:

```<code>$config = function_to_get_nested_array();
$node = $config;
foreach(array('vendor','product','config','leave') as $index => $key){
    if(! isset($node[$key])){
      //throw exception
    }
    $node = $node[$key];
}
</code>```

I would prefer to have something like

```<code>$config = function_to_get_nested_array();
$node = get_node($config, 'vendor/product/config/leave');
</code>```

But how do I implement it?

Possible Solutions

I could implement a function as I did above. BUT my packages heavily rely on autoloading and are purely OO. Right now I just have to clone an submodule in the right directory and everything works fine.

I could implement this where I need it. BUT this means I have to implement it countless times in independent projects.

I could use a trait, if I was not stuck with PHP 5.3. Not an option for me.

I could implement a static service provider.

For various reasons static classes and methods are usually a bad choice, but I am tempted
to do so in this case.

```<code>use vendor\product\helpers\ArrayTree as Tree
...
$config = function_to_get_nested_array();
$node = Tree::getNode($config, 'vendor/product/config/leave');
</code>```

Looks very tempting, because it supports autoloading and namespaces.

The Question

Is there a better solution to implement this kind of helper functions?

答:
This is a good scenario to use a static method.

Static methods can be problematic since they are essentially global functions, i.e. the call is hard wired to that specific class. During unit testing it is hard to replace a static method with a mocked one.

However, in your case, getNode is a pure stateless utility function. Go ahead and implement that tempting solution.

```<code>class ArrayTree {
    public static function getNode($array, $path) {
        ...
    }
}
</code>```

Title: How to implement syntax sugar in OO

Body:
This is a good scenario to use a static method.

Static methods can be problematic since they are essentially global functions, i.e. the call is hard wired to that specific class. During unit testing it is hard to replace a static method with a mocked one.

However, in your case, getNode is a pure stateless utility function. Go ahead and implement that tempting solution.

class ArrayTree {
    public static function getNode($array, $path) {
        ...
    }
}


答:
In general, I would not place business logic in the view model layer. But the term "Business Logic" is misleading.

Eric Evans uses a model where business logic is divided into two categories

Domain logic - Logic related to the actual problem domain you are solving

Application logic - Logic related to the fact, that you are building an application

He mentions the example of an accounting application. Rules about accounts, posts, tax accounts, etc. are domain rules, rules pertaining to the domain of accounting. Logic about CSV import/export has nothing to do with the domain of accounting. These rules exists purely because we are building a software application. These are examples of application logic.

Domain rules should NEVER go into the view model layer. If you are following the MVVM pattern, then the domain rules go, without question, in the model layer.

Application rules, like CSV import/export, could go in the view model layer. But personally, I would prefer to separate that out into a separate application logic layer.

The View Model should be very simple. Looking up the data needed by the view in the corresponding model, updating the model when the view changes, listening to events in the model, and propagating those events to the view, allowing the view to be updated when the model is updated behind the scenes (if applicable).

Personally I would make sure that the view model layer contains only one type of logic, presentation logic.

Title: MVVM Clarification