问:
Handling multiple login methods
Currently, I'm using Parse to handle my backend, and I have multiple ways to login -> via regular email/password and via linkedin.

Parse has a specific method of logging in requiring username/password.

If a user registers through linkedin, I hash a combination of his information as his password, and login through parse. (i.e. username: user's linkedin account / password: hashed version of user information).

If a user registers through email, the user sets his own password, logs in through parse (i.e. username: user's email / password: user's predefined password).

There's no way to retrieve a plain text version of the password, so what would be a good way to handle login through linkedin when the user has registered regularly (set his own password), and vice versa?

答:
What StackExchange seems to do (I haven't seen the database schema) is to separate the notions of user account and login/authentication. You can have (and I do) multiple authentication methods linked to the same account: Once you are logged in, you have the option to add other methods.

I would implement that by having a table for authentication accounts that point to user records in a 1:n relationship. That way, when you have someone log in, you can perform the full authentication and then look up which user record to use. I don't see any reason to keep the log-in type stored in the session, but obviously, you could.

Title: Handling multiple login methods


问:
What do you deliver in the first couple of iterations in Agile?
As I understand, the idea with Agile methodologies is that you deliver something functional and you deliver it often. The application gets into its final shape increment after increment.

But in the early iterations you might build the framework or foundations on which the application will stand so it's something important but not visible to users.

What gets delivered to the client in these first iterations? How do you show progress in the right direction when you build scaffolding code?

答:
What we try to do is to deliver in the first iterations the simplest application possible (a hello world version of what we are delivering).
We see 3 important benefits in this:

Setup the delivery procedure (always one of the most difficult parts imho) (get environments, servers in place, update security for this environment). As we will deliver often, it is important to get this right as soon as possible.

Give the users a first glimps of how the application will look like. This helps the users and the developers to understand what they really want and need.

Have a basic idea about how the architecture of the application will look like (the application should cover the basic 'layers' or components of the application).

ContentLicense: CC BY-SA 3.0


问:
Quick algorithm to find matches between two arrays
I'm faced with the following problem:

I have an array which is produced by the parsing of a yaml file which contains patterns in the following structure.

```<code>"Programming books"
    Title:
          a list of titles
    Author:
"Art Books"
    Title:
          foo
          bar
    Author:
          Mrs. Foo
          Mr. Bar
    Year:
</code>```

the program is supposed to be given random input and find if there is a book with that particular Title,Author and Year.

So far I'm using the following

```<code> foreach book_type,values from config{
       tag_match = 0
       foreach tag from values{
            tag_no = values.length()
            foreach value from tag{
                 if value in input
                      tag_match++
            }
      }
      if tag_match == values.length()
           /* tag the book matched continue matching*/
 }
</code>```

The program is not supposed to receive many matching lines bu it is supposed to receive a huge amount of data.
So far it has to do
book_type.length() * tag.length() * value.length() iterations for each line of input, is there a better way to do this?

答: Hashing/indexing is the way to go. Up to a few million items or so, create a single or multilevel hashtable/hashmap/whatever it's called in your language. In C# it could be Dictionary<string, Dictionary<string, List<Book>>> books_by_title_and_author. The first key is the title, the second is the author, and the value is a list of matching books, supposed to hold only a few items. If you have too much data, you should do what a database would do, build a B-tree index. Again, this can be single or multi column. An index takes a bit longer to build, but can be more efficient with many items. Also an on-disk structure is the only way if your data is too big to fit in memory.


问:
How to create a Python method prototype
If I'm giving an interview coding question in Java, I can specify the most of the question just by giving a method signature.  (Made-up example follows.)

```<code>public class Table {
  public String identifier;
  public int seatCount;
}

public static List<String> tablesWithEnoughSeats(List<Table> tables, int minSeats)
</code>```

If the candidate prefers Python, how do I present the problem for them?  The Python method signature doesn't specify the data type.  Is there some standard Python way of doing this?

If I look at Python coding challenges online, they tend to specify the requirements as taking certain input to produce certain output.  I don't want the candidate to waste their time writing code to parse an input file.  (My example has just String and int, but the actual interview problem might contain more complex data.)  What's the best way to express the parameter constraints so that the candidate can implement the algorithm I'm interested in without doing a bunch of plumbing?

答:
Or just use annotations in function, and comments in class?

```<code>class Table:
    def __init__(self, identifier, seat_count):
        self.identifier = identifier  # str
        self.seat_count = seat_count  # int

def tablesWithEnoughSeats(tables: [ Table ], minSeats: int) -> [str]:
    pass
</code>```

WARNING: works only in p3k, p2.x doesn't support annotations. I'd use comments instead:

```<code>def tablesWithEnoughSeats(tables,  # list of Table
                          minSeats # int
                          ):       # return list of str
    pass
</code>```

Other option is docstring with some markup language, but I don't really like this idea.

Title: How to create a Python method prototype

Body:
Or just use annotations in function, and comments in class?

class Table:
    def __init__(self, identifier, seat_count):
        self.identifier = identifier  # str
        self.seat_count = seat_count  # int

def tablesWithEnoughSeats(tables: [ Table ], minSeats: int) -> [str]:
    pass

WARNING: works only in p3k, p2.x doesn't support annotations. I'd use comments instead:

def tablesWithEnoughSeats(tables,  # list of Table
                          minSeats # int
                          ):       # return list of str
    pass

Other option is docstring with some markup language, but I don't really like this idea.


问:
Use null object as argument to method
Consider the following piece of code

```<code>class Foo
    {
    public:
    //...
        bool valueFirstGet(int& value) const
            {
            if(this==nullptr)
                {return 0;}
            value=values[0];
            return 1;
            }
    //...

    private:
        int* values;
        size_t n_values;
    };

int main()
    {
    Foo* obj=findObject("key");
    int value;
    if(!obj->valueFirstGet(value))
        {printf("key does not exist\n");}

    return 0;
    }
</code>```

findObject returns nullptr if it cannot find the object. Is it ok to let the member function do the null check instead of its caller. In my code, there are several calls to findObject directly followed by a call to valueFirstGet so leaving the check to the caller makes the code ugly.

EDIT:

Is there a cleaner way to avoid all null checking besides having findObject to throw an exception instead of returning null?

EDIT 2:

What about a static wrapper?

答:
Sometimes, working with large chunks of legacy code, such null checking proves to be helpful. But I will never recommend it for a class being written from scratch.

Also note, that in valueFirstGet() the &value could also be null. I have worked with legacy code, where such situations had to be taken care of, too.

Title: Use null object as argument to method


问:
Why do C++ and Java both use the notion of "reference" but not in the same sense?
In C++ a reference argument to a function allows the function to make the reference refer to something else:

```<code>int replacement = 23;

void changeNumberReference(int& reference) {
    reference = replacement;
}

int main() {
    int i = 1;
    std::cout << "i=" << i << "\n"; // i = 1;
    changeNumberReference(i);
    std::cout << "i=" << i << "\n"; // i = 23;
}
</code>```

Analogously, a constant reference argument to a function will throw a compile time error if we try to change the reference:

```<code>void changeNumberReference(const int& reference) {
    reference = replacement; // compile-time error: assignment of read-only reference 'reference'
}
</code>```

Now, with Java, the docs say that functions arguments of non-primitive types are references. Example from the official docs:

```<code>public void moveCircle(Circle circle, int deltaX, int deltaY) {
    // code to move origin of circle to x+deltaX, y+deltaY
    circle.setX(circle.getX() + deltaX);
    circle.setY(circle.getY() + deltaY);

    // code to assign a new reference to circle
    circle = new Circle(0, 0);
}
</code>```

Then circle is assigned a reference to a new Circle object with x = y
  = 0. This reassignment has no permanence, however, because the reference was passed in by value and cannot change.

To me this doesn't look at all like C++ references. It doesn't resemble regular C++ references because you cannot make it refer to something else, and it doesn't resemble C++ const references because in Java, the code that would change (but really doesn't) the reference does not throw a compile-time error.

This is more similar in behavior to C++ pointers. You can use it to change the pointed objects values, but you cannot changes the pointer's value itself in a function. Also, as with C++ pointers (but not with C++ references), in Java you can pass "null" as value for such an argument.

So my question is: Why does Java use the notion of "reference"? Is it to be understood that they don't resemble C++ references? Or do they indeed really resemble C++ references and I'm missing something?

答:
A reference is a thing that refers to another thing. Various languages have ascribed a more specific meaning to the word “reference”, usually to “some thing like a pointer without all the bad aspects”. C++ ascribes a specific meaning, as do Java or Perl.

In C++, references are more like aliases (which can be implemented via a pointer). This allows pass by reference or out arguments.

In Java, references are pointers except that this isn't a reified concept of the language: All objects are references, primitive types like numbers are not. They don't want to say “pointer” because there is no pointer arithmetic and there are no reified pointers in Java, but they want to make clear that when you pass an Object as an argument, the object is not copied. This also isn't pass by reference, but something more like pass by sharing.


答:
Why? Because, although consistent terminology is generally good for the entire profession, language designers don't always respect the language use of other language designers, particularly if those other languages are perceived as competitors.

But really, neither use of 'reference' was a very good choice. "References" in C++ are simply a language construct to introduce aliases (alternative names for exactly the same entity) explicitly. Things would have been much clearer of they had simply called the new feature "aliases" in the first place. However, at that time the big difficulty was to make everyone understand the difference between pointers (which require dereferencing) and references (which don't), so the important thing was that it was called something other than "pointer", and not so much specifically what term to use.

Java doesn't have pointers, and is proud of it, so using "pointer" as a term was no option. However, the "references" that it does have behave quite a bit as C++'s pointers do when you pass them around - the big difference is that you can't do the nastier low-level operations (casting, adding...) on them, but they result in exactly the same semantics when you pass around handles to entities that are identical vs. entities that merely happen to be equal. Unfortunately, the term "pointer" carries so many negative low-level associations that it's unlikely ever to be accepted by the Java community.

The result is that both languages use the same vague term for two rather different things, both of which might profit from a more specific name, but neither of which is likely to be replaced any time soon. Natural language, too, can be frustrating sometimes!

Title: Why do C++ and Java both use the notion of "reference" but not in the same sense?

Body:
In C++ a reference argument to a function allows the function to make the reference refer to something else:

```<code>int replacement = 23;

void changeNumberReference(int& reference) {
    reference = replacement;
}

int main() {
    int i = 1;
    std::cout << "i=" << i << "\n"; // i = 1;
    changeNumberReference(i);
    std::cout << "i=" << i << "\n"; // i = 23;
}
</code>```

Analogously, a constant reference argument to a function will throw a compile time error if we try to change the reference:

```<code>void changeNumberReference(const int& reference) {
    reference = replacement; // compile-time error: assignment of read-only reference 'reference'
}
</code>```

Now, with Java, the docs say that functions arguments of non-primitive types are references. Example from the official docs:

```<code>public void moveCircle(Circle circle, int deltaX, int deltaY) {
    // code to move origin of circle to x+deltaX, y+deltaY
    circle.setX(circle.getX() + deltaX);
    circle.setY(circle.getY() + deltaY);

    // code to assign a new reference to circle
    circle = new Circle(0, 0);
}
</code>```

Then circle is assigned a reference to a new Circle object with x = y
  = 0. This reassignment has no permanence, however, because the reference was passed in by value and cannot change.

To me this doesn't look at all like C++ references. It doesn't resemble regular C++ references because you cannot make it refer to something else, and it doesn't resemble C++ const references because in Java, the code that would change (but really doesn't) the reference does not throw a compile-time error.

This is more similar in behavior to C++ pointers. You can use it to change the pointed objects values, but you cannot changes the pointer's value itself in a function. Also, as with C++ pointers (but not with C++ references), in Java you can pass "null" as value for such an argument.

So my question is: Why does Java use the notion of "reference"? Is it to be understood that they don't resemble C++ references? Or do they indeed really resemble C++ references and I'm missing something?


答:
Use a dictionary or collection, which has a Key-value pair, if the size of the data allows, if not a database - as stated above.

There are lots of different collections, dictionary, hash table etc implementations, and the right/fastest one to use will depend on the nature of its indented use, so you will have to look around to find the most suitable one. For example some will load faster, but take longer to read, some load slower, but have faster access times, and so on.

On other thing, might be, currently you are O(3n), by which I mean type X tag X value so if that's loops it might be 10 + 10 + 10 = 30 worst case. You could combine Type and Tag, and Value, which would be 10 worst case - just a thought.

Heres a link to an articular I found useful, but is .Net specific. IDictionary Options - Performance Test - SortedList vs. SortedDictionary vs. Dictionary vs. Hashtable

Title: Quick algorithm to find matches between two arrays

Body:
I'm faced with the following problem:

I have an array which is produced by the parsing of a yaml file which contains patterns in the following structure.

```<code>"Programming books"
    Title:
          a list of titles
    Author:
"Art Books"
    Title:
          foo
          bar
    Author:
          Mrs. Foo
          Mr. Bar
    Year:
</code>```

the program is supposed to be given random input and find if there is a book with that particular Title,Author and Year.

So far I'm using the following

```<code> foreach book_type,values from config{
       tag_match = 0
       foreach tag from values{
            tag_no = values.length()
            foreach value from tag{
                 if value in input
                      tag_match++
            }
      }
      if tag_match == values.length()
           /* tag the book matched continue matching*/
 }
</code>```

The program is not supposed to receive many matching lines bu it is supposed to receive a huge amount of data.
So far it has to do
book_type.length() * tag.length() * value.length() iterations for each line of input, is there a better way to do this?


问:
Patterns for a tree of persistent data with multiple storage options?
I have a real-world problem which I'll try to abstract into an illustrative example.

So imagine I have data objects in a tree, where parent objects can access children, and children can access parents:

```<code>// Interfaces
interface IParent<TChild> { List<TChild> Children; }
interface IChild<TParent> { TParent Parent; }

// Classes
class Top : IParent<Middle> {}
class Middle : IParent<Bottom>, IChild<Top> {}
class Bottom : IChild<Middle> {}

// Usage
var top = new Top();
var middles = top.Children; // List<Middle>
foreach (var middle in middles) {
    var bottoms = middle.Children; // List<Bottom>
    foreach (var bottom in bottoms) {
        var middle = bottom.Parent; // Access the parent
        var top = middle.Parent; // Access the grandparent
    }
}
</code>```

All three data objects have properties that are persisted in two data stores (e.g. a database and a web service), and they need to reflect and synchronise with the stores. Some objects only request from the web service, some only write to it.

Data Mapper

My favourite pattern for data access is Data Mapper, because it completely separates the data objects themselves from the communication with the data store:

```<code>class TopMapper {
    public Top FetchById(int id) {
        var top = new Top(DataStore.TopDataById(id));
        top.Children = MiddleMapper.FetchForTop(Top);
        return Top;
    }
}

class MiddleMapper {
    public Middle FetchById(int id) {
         var middle = new Middle(DataStore.MiddleDataById(id));
         middle.Parent = TopMapper.FetchForMiddle(middle);
         middle.Children = BottomMapper.FetchForMiddle(bottom);
         return middle;
    }
}
</code>```

This way I can have one mapper per data store, and build the object from the mapper I want, and then save it back using the mapper I want.

There is a circular reference here, but I guess that's not a problem because most languages can just store memory references to the objects, so there won't actually be infinite data.

The problem with this is that every time I want to construct a new Top, Middle or Bottom, it needs to build the entire object tree within that object's Parent or Children property, with all the data store requests and memory usage that that entails. And in real life my tree is much bigger than the one represented here, so that's a problem.

Requests in the object

In this the objects request their Parents and Children themselves:

```<code>class Middle {
    private List<Bottom> _children = null; // cache
    public List<Bottom> Children {
        get {
            _children = _children ?? BottomMapper.FetchForMiddle(this);
            return _children;
        }
        set {
            BottomMapper.UpdateForMiddle(this, value);
            _children = value;
        }
    }
}
</code>```

I think this is an example of the repository pattern. Is that correct?

This solution seems neat - the data only gets requested from the data store when you need it, and thereafter it's stored in the object if you want to request it again, avoiding a further request.

However, I have two different data sources. There's a database, but there's also a web service, and I need to be able to create an object from the web service and save it back to the database and then request it again from the database and update the web service.

This also makes me uneasy because the data objects themselves are no longer ignorant of the data source. We've introduced a new dependency, not to mention a circular dependency, making it harder to test. And the objects now mask their communication with the database.

Other solutions

Are there any other solutions which could take care of the multiple stores problem but also mean that I don't need to build / request all the data every time?

答:
I ended up sticking with the DataMapper pattern, but then changing my application:

For a long time I was using a builder to build up the complex object tree. But over time, I discovered that the inflexibility of this system made the code un-maintainable.

I now think that the problem of constructing objects where parent objects can access children and children can access parents is difficult for a good reason: because it's trying to create objects that are too tightly coupled to each other. Because of the tight coupling, it is impossible to create any objects without building up the entire tree.

What I ended up doing was restructuring the rest of my application to remove any hard dependencies, and instead including FetchForChild and FetchForParent methods on my DataMapper object, loosening the coupling.

This now works very well.


问:
Is it possible to keep only one Database for both web and desktop applications?
I'm experiencing a trouble with my business model, let me explain better.

I'm developing a software for 1 year and few months, it's for the food industry, more exactly a software to: Delivery, Take Way, Table Reservation, POS, Accounts Payable and Receivable, Prints(receipt), Kitchen Monitors Orders, Customers Orders Control and Fiscal Area.

Well, I had separated the software mainly in two areas, one is web area and the other is desktop area (Used by Admins only) and local installed.

1 - Web Area (Basically do the follow:)

Show Catalog with the products

Customers Make Orders

Customers Pay for the Orders

etc ... as mentioned above

2 - Desktop Area

Manage Orders

Manage Customers

Manage Suppliers

Manage Accounts Payable and Receivable

etc ... as mentioned above

The web area is hosted in an online web server (scripts and database are online). The Desktop area is hosted locally in a Linux machine with a local database and local scripts files.

My question is:
Is it possible to keep only one Database for both applications? If YES, please what is the best approach?

Follow my technical specification environment

Database: Actually I have two databases working and I would love to keep only one.

Operating System: Linux (Kernel 2.6.X and above) or Windows (XP and above)

For the Web Area

Apache, PHP, Python, Java Script, Shell Script and MySQL.

For the Desktop Area:

PHP-GTK2, Apache, PHP, MySQL and Shell Script.

Addtional Information about the system [EDITED]

The main purposes to have a Desktop environment is:

I need to print and give out Tax Coupon on each new order.

I have the drawer.

I have a serial reader (Bar code).

I have a terminal to query for information.

and few other stuffs that is so hard if not impossible to do in the web environment.

Desktop relational schema: 104 tables.
Web relational schema: 42 tables.

Permissions is assigned based on: Deny all by default, and assigns as needed.

(Validation / Sanitization) has already been done in the web application.

Until now performance is not a problem, since every fiscal year part of my database will be archived.
(Also customer, suppliers and all related data about them will be archived after 3 years of inactivity).

My real problem is I have 2 environments today and I would love to have only 1.
Then "merge" the both worlds into one is an option, but not sure about.
I would love to read here a lot of ideas about this matter.

Observation about the process: Today it is in operation and it works fine, but I feel like waste time in some process.

Take a look in the scenario:

The order is made in the internet, then stored in my Web database.

The "order" is sent to the kitchen and prepared.

Print a receipt (Tax Coupon), put it with the order and delivery to the customer.

A Tax Coupon is generated by my Desktop Environment and it need a call to the orders table, but it is not the Web Order Table but a Desktop Order Table.

In few words I need to generate again the order to fill up the Tax Coupon. The same happen to Customer Register, Supplier Register and few other stuffs.

I hope this information turn my question more readable. Thanks Again!

答:
You could also consider a third approach, a single database and a web API for the application to access the information.

This way you don't need to directly expose your SQLServer to external sources and can better manage what the application accesses.

It is also easier to update a web API to changes in the database structure than redeploying the desktop application every time.


问:
Deployment: Best Practices (and real practices)
One thing that I've learnt in my short dev career is that there are best practices (like TDD) and then there are actual practices that occur under pressure, or through budgetary/time constraints.

I'm working in a small PHP dev team on a project using Zend framework. The project has the potential to demand a lot of scalability, and so we are trying to establish a good development environment to promote ease of development long term. Architectural patterns/practices aside, I'm looking at trying to automate deployment, checking code quality through svn hooks, possibly even setting up a CI environment.

So I'm interested in hearing people's experience of deployment practices. I've checked other examples as they pertain to other languages - but I'm ideally looking to hear from people who have worked in a PHP/Zend environment

To make the question less vague:
What are people's experiences of using deployment systems like phpUnderControl and rSync?

答:
Basically it needs to be easy (if everything is acceptable) to deploy.  This usually means, that after a checkin the system rebuilds automatically.  If ok, the user can at a single click cause the test server to update to the new version.

You should be able to roll-back as easy.

The easier to use you can keep it, the happier people will be.

If at all possible set up a CI.  Hudson Jenkins is nice, but there are plenty others.  You WILL appreciate it quickly.

ContentLicense: CC BY-SA 2.5


问:
Is there a good reason to avoid node.js for non-realtime web apps?
I've seen a lot of talk about how awesome Node.js is for realtime web apps -- things that need sockets, Comet, AJAX-heavy communications, and so forth. I know that its event-driven, asynchronous, thread-driven model is also good for concurrency with low overhead.

I've also seen Node.js tutorials for more simple, 'traditional', non-realtime apps (e.g., the standard blog example, which seems to be the standard 'Hello World' for people learning app development). And I also know that node-static allows you to serve static assets.

My question is: is there any good reason to avoid Node.js for traditional web apps, like classifieds, forums, the aforementioned blog example, or the sort of CRUD apps you build for internal business applications? Just because it excels at all the funky realtime stuff, does that contraindicate it for more staid uses?

The only thing I can think of, off the bat, is the lack of mature libraries (although that's changing).

(The reason I'm asking is that I'm considering ditching PHP for Node.js, mostly to get over the impedance mismatch of switching between languages, but also so I can reuse validation code and whatnot. My superego admonishes me to choose the best tool for the job; however, I don't have a lot of time to learn fifteen languages and all their userland libraries just to have a comprehensive arsenal. It's also reassuring that Node.js might give me an easier optimisation path than PHP/Apache in the future when I have to start thinking about heavy traffic.)

[EDIT] Thanks for the answers so far, folks; I just want to see if anyone else will weigh in before I choose an answer. The answer from @Raynos kinda confirms what I'm thinking, and the links from the commenters provided good food for thought, but I want to see if anyone else has any Node-specific answers, like 'DON'T USE NODE FOR PROBLEM X'. (Besides high-CPU tasks; I know that already :-)

答:
Is there any benefit of using node over X for non-realtime applications:

Scaling: Node has good performance but other platforms do too; PHP, Ruby, Python and Java all scale. You can find BIG names with millions of users are using them.

One language for frontend and backend: It's a joke, just like Java's "Write once run anywhere"

Hot and sexy: The only valid point. But no one cares that your website is using edgy tech!

Benefit of using X over Node for non-realtime applications:

Best Practice: Because Node is new it has fewer best practices than other platforms, specially for CRUD web applications.

Javascript Language: People don't like Javascript. While Node.js is hot, Javascript is not. This is why people created Coffeescript to avoid writing Javascript even for the client side.

Developing Speed: The old and boring frameworks including and not limited to Rails and Django are well tested and improved over many years for CRUD websites. While you can implement similar applications in Node, it's just easier to do in your grandpa's framework.

Stability: Node's web frameworks are getting better at a faster pace. It means they are changing and will have more API incompatibility in the near future.

Libraries and tools: The older technologies with more users have more libraries and tools.

My answer definitely won't be valid in 2015. In 2014, skip Node for non-realtime web applications but keep an eye on it.

Every web framework has a strong point. You'll be happy while you are using it for that point. Non-realtime web applications are not Node's web frameworks strong point.


答:
Node.js is very popular platform and it has a lot of interesting features blah blah blah, but usage of a tool is a personal preference. I gave Node.js a four times and I wasn't happy with it. Here are my reasons. Please keep in mind that some of those reasons are outdated, or simply personal :P

I preferred different language/syntax (I like Python, Scala, my favourite language is Prolog so yeah).

Quality of documentation for frameworks and libraries that I used is not as good for Java, Scala, Python libraries.

Designers of the nodejs are quite obsessed with callbacks instead of event model, observer or futures.

There is ready sollutions for what I want to do in Ruby, Python, Java developed back in 2005, I just need to edit config file.

Title: Is there a good reason to avoid node.js for non-realtime web apps?

Body:
I've seen a lot of talk about how awesome Node.js is for realtime web apps -- things that need sockets, Comet, AJAX-heavy communications, and so forth. I know that its event-driven, asynchronous, thread-driven model is also good for concurrency with low overhead.

I've also seen Node.js tutorials for more simple, 'traditional', non-realtime apps (e.g., the standard blog example, which seems to be the standard 'Hello World' for people learning app development). And I also know that node-static allows you to serve static assets.

My question is: is there any good reason to avoid Node.js for traditional web apps, like classifieds, forums, the aforementioned blog example, or the sort of CRUD apps you build for internal business applications? Just because it excels at all the funky realtime stuff, does that contraindicate it for more staid uses?

The only thing I can think of, off the bat, is the lack of mature libraries (although that's changing).

(The reason I'm asking is that I'm considering ditching PHP for Node.js, mostly to get over the impedance mismatch of switching between languages, but also so I can reuse validation code and whatnot. My superego admonishes me to choose the best tool for the job; however, I don't have a lot of time to learn fifteen languages and all their userland libraries just to have a comprehensive arsenal. It's also reassuring that Node.js might give me an easier optimisation path than PHP/Apache in the future when I have to start thinking about heavy traffic.)

[EDIT] Thanks for the answers so far, folks; I just want to see if anyone else will weigh in before I choose an answer. The answer from @Raynos kinda confirms what I'm thinking, and the links from the commenters provided good food for thought, but I want to see if anyone else has any Node-specific answers, like 'DON'T USE NODE FOR PROBLEM X'. (Besides high-CPU tasks; I know that already :-)


问:
Payment Gateways and RESTful API
I have a RESTful API that offers eCommerce functionality. One area I'm struggling to decide on the correct implementation is how to process payments.

Lets say I have the following URI GET .../checkout/{id}/payment. This resource provides details to the client application of what details needs to be submitted to make a payment. The specifics of the information in the resource depends on the implementations below

Implementation 1 The resource contains basic payment fields to be filled in like card number, billing address etc. The data is sent to the API using POST .../checkout/{id}/payment. The API then submits a request to the payment gateway (e.g. paypal), waits for the response, and then sends an appropriate response back to the client application.

Implementation 2 The resource contains details of how to submit a request directly to the payment gateway (e.g. paypal). The client submits the payment to the gateway, waits for a response, and then sends the payment reference (normally always provided by a payment gateway) back to the API using POST .../checkout/{id}/payment.

The problem I am having is that both have pros and cons.

Implementation 1 I would say is the more fail safe method as everything is contained in one request to the API. The API can then update backend tables once the payment has been processed, and return success or failure status to the client. Since the API is sending a response to the gateway, it knows the response it receives is genuine.

Implementation 2 frees the API from having to process the payment which is great, but requires the client to make two requests. One to the payment gateway and one to the API with the reference. Additionally, how can I validate the payment reference on the API without calling the gateway? A dishonest client could send any reference back to the API which then may be incorrectly marked as paid.

Just wanted to throw my ideas out there, but if anyone has a really good solution for implementing Payment Gateways and RESTful API web services that would be great.

UPDATE
Just thought of an Implementation 3. I could actually create a separate smaller API to handle the payments. It would work in a similar way to implementation 1 except that the client application doesn't post to api.site.com/.... but posts to gateway.site.com/... This give me a degree of security as I control the code on gateway.site.com and ensures that api.site.com isn't being bogged down by waiting for the payment provider to respond. The gateway api then essentially becomes a client of the main API and posts the payment success details to it.

Any thoughts on this?

答:
I assume you are expecting your site have a large amount of traffic. If that assumption is correct, I would say go with a tweaked version of Implementation 3.
If api.site.com and gateway.site.com are on two different servers, I would also have a third server to house the DB and have both apps leverage the centralized DB. This will eliminate the need for api.site.com and gateway.site.com to even know about each other and keep all work in a designated area, making any debugging that much easier.

And if my assumption is incorrect, I'd say go a differently tweaked version of Implementation 3. So you'd build you two separate apps that communicate with the same Db, and simply house everything on the same server. Which is basically what I just said above but all on the same server. This should reduce initial overhead and make scaling a breeze when the time comes.

Title: Payment Gateways and RESTful API


答:
But in the early iterations you might build the framework or foundations on which the application will stand so it's something important but not visible to users.

This is wrong, since you do not need to build a framework you may use in the future. The idea is to build only what is needed (see also YAGNI).

In the sprint zero, you need to prepare for the real work. Lots of people argue what should be done in this sprint, but in my opinion, it is finished when you can start working on the items in the backlog. This step includes setting PCs, setting build process, picking frameworks, etc.

When you are done with sprint zero (or iteration zero), you can start working on your application. Take items from the backlog, and finish them one by one. After you finish iteration one, you are going to have something useful. The first iteration usually includes some of most important features.

What gets delivered to the client in these first iterations? How do you show progress in the right direction when you build scaffolding code?

After iteration zero, obviously you do not have anything to deliver. The deliverable comes after iteration one. It contains features that you set for the iteration.

If your question is "how to pick what goes into iteration X?", then take a look into these videocasts (videos for iteration 0 A and part of B).

Title: What do you deliver in the first couple of iterations in Agile?

Body:
As I understand, the idea with Agile methodologies is that you deliver something functional and you deliver it often. The application gets into its final shape increment after increment.

But in the early iterations you might build the framework or foundations on which the application will stand so it's something important but not visible to users.

What gets delivered to the client in these first iterations? How do you show progress in the right direction when you build scaffolding code?


问:
Variables initialization and for loops in a flowchart
I have to create a flowchart to a C# programm and I am not very familiar with it.
My problem is that I do not know if one should represent variables initialization in a flowchart and if so how should I do it. Second problem is that I am not sure about the correctness of my for loop.

Here is the flowchart I created tot a part of the programm.
It would be very nice if you can tell me if that is correct and if not what should I correct.

Thank you!

答: I think what you've done is very nice and easy to understand. Whether or not you include variable initialization largely depend on what level of abstraction you're trying to achieve. However, I think if you're at the point of needing to show variable initializations, you might as well just write the code and present that instead. Code itself is practically just a flow chart without lines. And so I don't personally think that variable initialization is appropriate for a flow chart. </p>


答:
Flowcharts are to capture solution logic in a stable/readable form.  If this is sufficient for your audience, that is all that matters.  Is this for yourself or a different audience?  What are the audiences expectations?  Is there an established standard that they are expecting?

If it is important to your logic that the variables be initialized, then add a preparation symbol (a wide hexagon) with the initializations.  If the variable initializations aren't useful, then ignore them.  In this case, it does not look like credit is being used as an accumulator, so it would not be important to initialize it.

Your loop looks fine, but I believe you should have a line from the top loop structure to the bottom.  You could also move the exit condition to the bottom loop symbol.

Title: Variables initialization and for loops in a flowchart

Body:
I have to create a flowchart to a C# programm and I am not very familiar with it.
My problem is that I do not know if one should represent variables initialization in a flowchart and if so how should I do it. Second problem is that I am not sure about the correctness of my for loop.

Here is the flowchart I created tot a part of the programm.
It would be very nice if you can tell me if that is correct and if not what should I correct.

Thank you!


问:
Term for an error when code is executed before its ajax response?
What's the term for an error caused by executing a block of code before its relevant ajax response has come back? e.g., a timeline:

13:00:01 execute getDataViaAjax();

13:00:02 execute doSomethingWithMyAjaxData();

13:00:03 ajax data comes back, too late since I forgot to make the code wait for it...

I have a feeling I may say "doh!" when someone tells me the answer, but I can't for the life of me think what type of error it might be called.

答:
It's simply called an asynchronous error since this relates to incorrect asynchronous behavior.

The data was managed in a synchronous fashion when it's the result of an asynchronous event. So the handler function executed before another function finished.

Asynchronous Error

What is asynchronous programming? It's defined as a one-way operation. Which means code sends a signal one-way into an object and there is no immediate signal sent back. So either it's a black-hole or you attach a handler to listen for a signal to come out later.

What is an asynchronous error? It is a problem with how the object triggers handlers for the one-way signal. They could be fired to soon, to late or not at all.

Synchronous Error

What is synchronous programming? It's defined as a two-way operation. Code sends a signal into an object and the object sends a response signal back.

What is a synchronous error? It's an error related to the two-way signals that define a synchronous operation. For example; a web browser connects to a web server, and the web server send a HTTP response before the web browser sends a HTTP request.

Synchronization Error

Synchronization error is what happens when two objects fail to achieve the same equal state. Think of synchronizing two databases on a fail-over server. If the second machine doesn't keep it's database identical to it's master, then it's a synchronization error.


问:
Where to place configuration files sources
I am developing a C# windows service application, which have different configuration files for development, for production system, for test system, like:

```<code>Dev.config
Test.config
Prod.config
</code>```

Now we are using SVN version control system, and configuration files stored in projects directories:

```<code>-trunk
  -MyFooService
    -Configs
      Dev.config
      Test.config
      Prod.config
  -MyFooService2
    -Configs
      Dev.config
      Test.config
      Prod.config
</code>```

Prior publishing service to production you should get respective configuration file from that folders. How do you think, it is correct? Or configuration files should be placed in another repository? Or in another folder or should not be placed in VCS?

Or may be it will be better to place files like that:

```<code>-trunk
  -src
    -MyFooService
    -MyFooService2
  -configs
    -MyFooService
      -Configs
        Dev.config
        Test.config
        Prod.config
    -MyFooService2
      -Configs
        Dev.config
        Test.config
        Prod.config
</code>```

答:
Building on @fejesjoco's answer, one config only config for dev machines.

For the environments, I would store 1 file, like ServiceX.environments under source control.

During the deployment or build process, you could have a script create a configuration file based on the environment file passing which environment you want to create.  For example, maybe you have integration, qa, performance for in house environments.   It would read the environment file, locate the appropriate section, and then create a configuration file.

Then you have a consistent way to deploy config files across internal environments.  It also doesn't confuse developers with many config files in a solution.  You still want the environment file under source control, but don't mark it as a config, then if envronments change its just a update and check in.

As far a external customers or builds, you could have a step to create a config that is more or less a template for them.  After that, they take the config and modify for thier own needs, but there is not need to store those under source control as the external customer should maintain them.


答: About the loop: the variable i is an implementation detail. You don't really care that a variable named i goes from 0 to max-1 - you only care that the loop is being executed max times. I think it should be replaced with Repeat max times or something similar.


问:
Should if/else statements be arranged by rareness of cases or difficulty of dealing with them?
In some code I'm writing right now, I have something like this:

```<code>if (uncommon_condition) {
    do_something_simple();
} else {
    do();
    something();
    long();
    and();
    complicated();
}
</code>```

Part of me thinks "It's fine the way it's written. Simple cases should go first and more complicated cases should go next." But another part says: "No! The else code should go  under the if, because if is for dealing with unusual cases and else is for dealing with all other cases." Which is correct or preferable?

答:
No fixed rule as such I heard about the usage but I follow like this

```<code>if(usual)
{
(more often)
}
else (unusual)
{
(rarely occurring)
}
</code>```

But if both have same function with different properties then better go for unusual first then usual so that you can save one instruction.

```<code>if(x == 0)  // 1
  {x = 1;}  // 2
else
  {x = 2;}  // 3
</code>```

For above code assembly code will be something like this:

```<code>1. 000d 837DFC00        cmpl    $0, -4(%ebp)
   0011 7509            jne .L2

2. 0013 C745FC01        movl    $1, -4(%ebp)
   001a EB07            jmp .L3

    .L2:
3.001c C745FC02         movl    $2, -4(%ebp)

        .L3:
</code>```

If condition inside if is true then flow is 1->2( 4 intructions)

IF condition inside if is false then flow is 1->3 (3 intructions)

So its better to put unusual or rarely occurring events in if part and normal condition in else so that we can save one instruction every time ;-)

Body:
No fixed rule as such I heard about the usage but I follow like this

if(usual)
{
(more often)
}
else (unusual)
{
(rarely occurring)
}

But if both have same function with different properties then better go for unusual first then usual so that you can save one instruction.

if(x == 0)  // 1
  {x = 1;}  // 2
else
  {x = 2;}  // 3

For above code assembly code will be something like this:

1. 000d 837DFC00        cmpl    $0, -4(%ebp)
   0011 7509            jne .L2

2. 0013 C745FC01        movl    $1, -4(%ebp)
   001a EB07            jmp .L3

    .L2:
3.001c C745FC02         movl    $2, -4(%ebp)

        .L3:

If condition inside if is true then flow is 1->2( 4 intructions)

IF condition inside if is false then flow is 1->3 (3 intructions)

So its better to put unusual or rarely occurring events in if part and normal condition in else so that we can save one instruction every time ;-)


答:
This is a very good question, that we must ask, in order too advance the state of the art.

I was very curious to know (like Paul d'Aoust) where the limitations of Node.JS exist. Sadly, many answers are FULL of subjective bias and temporarily relevant rationale.

I asked myself: CAN WE FILTER OUT SUBJECTIVE BIAS AND GET DOWN TO SOLID ANSWERS TO THIS RELEVANT QUESTION?

The remaining points seem to be:

1. NodeJS is not as mature as Traditional Frameworks. As Paul d'Aoust suggests, this is only a temporarily relevant reason, not for full avoidance - but instead review and due diligence. Doing our homework as web professionals is expected, and it is our job to determine the best-fit of the technology to the organization, their needs, their future, the team (and not us). Maturity is a need for clarification and a judgement for appetite for risk, but not avoidance.

2. NodeJS as a Proxy Server. A wise suggestion, of prior discussion, that is worth review and consideration. It is the notion of using Node in correlation with existing technologies as a front-end interface proxy design pattern. But also, it is not a reason to AVOID using node, but instead a reason to avoid using it as a full replacement. Instead opting for a corollary approach.

3. Debugging Node. In conversation with core Node developers at Joyent there is much complication surrounding debuggability and tracing back the root cause of problems resulting from the core (based on single thread execution and inability to see into past threads). This is worth consideration and evaluation - but (again) likely not aversion for common usage only edge-cases that may push the envelope. Maybe your specific needs would fall into this category and maybe they will not.

4. Human Resources. This is the best reason to AVOID using JS on this page, and in my humble opinion it is a stark and inconvenient truth. It begs the question: does your company have the right talented professionals on hand to see the project through full life cycle? If not, there is no question that you need to avoid NodeJS. Or instead consider A) locating the correct talent, or B) Educating existing talent.

Complaints:
My observation of the complaints on JavaScript is that, many result more from User Error than they do from consistent failings of the language. We have debunked many claims against "The Hate JavaScript Diatribe" and we will continue to debunk many more. Such problems as - documentation is not good enough, it is not sexy enough, but people don't like it, it is cancer, it is the devil, or it is too "typo-prone" (-CRichardson), are subjective and biased complaints that need to be weeded out for accurate corporate decision making.

In the end, the correct answer may be - there are no good reasons to AVOID NodeJS. Maybe this is why it is experiencing rapid growth, adoption, and contribution. But for all of us perhaps the answer here is to continue to evaluate, research, and understand NodeJS better - and look for concrete aversions. In the pursuit of being open to understanding exactly where Node.JS is immature - we find exactly where we need to make it better. And that is a blessing.

Good question. I for one remain curious for someone to bring up a better reason to avoid NodeJS - than these.


答:
Try to enhance readability.  One way is to place the longer code block into the else part.

```<code>if (s == null)
     // short code
else
     // long
     // code
     // block
</code>```

is more readable than

```<code>if (s != null)
    // long
    // code
    // block
else
    // short code
</code>```

Title: Should if/else statements be arranged by rareness of cases or difficulty of dealing with them?

Body:
In some code I'm writing right now, I have something like this:

```<code>if (uncommon_condition) {
    do_something_simple();
} else {
    do();
    something();
    long();
    and();
    complicated();
}
</code>```

Part of me thinks "It's fine the way it's written. Simple cases should go first and more complicated cases should go next." But another part says: "No! The else code should go  under the if, because if is for dealing with unusual cases and else is for dealing with all other cases." Which is correct or preferable?

Body:
Try to enhance readability.  One way is to place the longer code block into the else part.

if (s == null)
     // short code
else
     // long
     // code
     // block

is more readable than

if (s != null)
    // long
    // code
    // block
else
    // short code


问:
A hint to create a db schema
I need to realize a database in this mode:

```<code>TABLE restaurant
</code>```

with "classic" fields of a place: address, street number, phone, website, etc etc etc.

I need to indicate also the days of opening // closing. E.g. From Monday to wednesday close, saturday only evening and sunday lunch + evening.

So, I did think at another table with 14 rows:

```<code>ID_RESTAURANT  MONDAY_LUNCH MONDAY_EVENING [...] SUNDAY_EVENING
    12         0             0                    1
</code>```

And "finally" every restaurant has his own cooking ("international", "chinese", "japan")

Another table with a column for every cooking?

Finally, several services. "Conditioned Air", "Credit Card", "Animals permitted" "children addicted" etc etc.

Another table with a column for every "service"?

```<code>ID_RESTAURANT    CONDITIONED    CREDIT_CARD     ANIMALS
    12              1              1              0
    13              0              1              1
</code>```

I hope that I'm clear. Thank you very much!

答:
```<code>TABLE Service (SERVICE_ID, SERVICE_NAME, ...)
TABLE Restaurant (RESTAURANT_ID, RESTAURANT_NAME, ...)
TABLE RestaurantService (RESTAURANT_ID, SERVICE_ID)
</code>```

In short, if the field is part of the key or depends on the key of the table, you are doing it right. Read more on the very straightforward normalization link MichaelT provided already.

Title: A hint to create a db schema

Body:
TABLE Service (SERVICE_ID, SERVICE_NAME, ...)
TABLE Restaurant (RESTAURANT_ID, RESTAURANT_NAME, ...)
TABLE RestaurantService (RESTAURANT_ID, SERVICE_ID)

In short, if the field is part of the key or depends on the key of the table, you are doing it right. Read more on the very straightforward normalization link MichaelT provided already.


问:
Which useful alternative control structures do you know?
Similar question was closed on SO.

Sometimes when we're programming, we find that some particular control structure would be very useful to us, but is not directly available in our programming language.

What alternative control structures do you think are a useful way of organizing computation?

The goal here is to get new ways of thinking about structuring code, in order to improve chunking and reasoning.

You can create a wishful syntax/semantic not available now or cite a less known control structure on an existent programming language.

Answers should give ideas for a new programming language or enhancing an actual language.

Think of this as brainstorming, so post something you think is a crazy idea but it can be viable in some scenario.

It's about imperative programming.

答:
Seamless thread branching, it has syntax like a function, but executes in a separate thread and can't access data that has not initially been passed to it.

```<code>branch foo(data, to, be, processed){
    //code
    return [resulting, data]
}
</code>```

When a branch is called it will immediately return a handle.

```<code>handle=foo(here, is, some, data)
</code>```

The handle can be used to check if the task is done.

```<code>handle.finished() //True if the execution is complete
</code>```

If the result is requested before the execution is complete the main thread will simply wait.

```<code>[result, storage]=handle.result()
</code>```

This wouldn't cover the more advanced multithreading scenarios, but rather provide an easily accessible way of beginning to utilize multiple cores.

Body:
Seamless thread branching, it has syntax like a function, but executes in a separate thread and can't access data that has not initially been passed to it.

branch foo(data, to, be, processed){
    //code
    return [resulting, data]
}

When a branch is called it will immediately return a handle.

handle=foo(here, is, some, data)

The handle can be used to check if the task is done.

handle.finished() //True if the execution is complete

If the result is requested before the execution is complete the main thread will simply wait.

[result, storage]=handle.result()

This wouldn't cover the more advanced multithreading scenarios, but rather provide an easily accessible way of beginning to utilize multiple cores.


答:
There's a joke I heard some time back.

If you ask a C programer to count to 10, you get '0, 1, 2, 3, 4, 5, 6, 7, 8, 9'.
  If you ask a DBA to count to 10, you get '0, 1, many'.

The key to the understanding of this joke is that if you ever are dealing with more than one thing in a database, you really need to have it be a many... not a 2 or a 3.  There are many many's described in this database that should be treated as such.

```

       +-----------+   +-----------+     +------------+
       | restaurant|   | rest_time |     | meal       |
       |-----------|   |-----------|     |------------|
   +-->| id        |&lt--+ rid       | +-->| id         |
   |   | name      | | | day (enum)| |   | name       |
   |   +-----------+ | | mealid    +-+   +------------+
   |                 | | open (b)  |
   |   +-----------+ | +-----------+
   |   | phone     | |
   |   |-----------| | +------------+    +------------+
   |   | phnum     | | | rest_serv  |    | service    |
   +---+ rid       | | |------------|    |------------|
       | type      | +-+ rid        | +--> id         |
       +-----------+   | sid        +-+  | name       |
                       | has        |    |            |
                       +------------+    +------------+
```

You have a restaurant which has some attributes.  Things that the restaurant can only have one of are columns in that table.  It can only have one name, and one id.  Depending on the description, it may have only one address (though if you have a chain like McDonalds).  Other things it has only one of are things like capacities.

A restaurant may have multiple phones (fax your order in vs reservations?) And phones only belong to one restaurant.  This is a one to many relationship.

The restaurant also has some services - but all restaurants also may have those same services.  You want to be able to do a query of 'what restaurants has air conditioning?'

Likewise, a restaurant also has some meals that it serves on some days.  I've got a simplified approach that works with mysql there for days, but having days be a separate table wouldn't be inappropriate and would be entirely appropriate if you have things like holidays being called out specially (new years eve: lunch, no dinner).

Title: A hint to create a db schema

Body:
I need to realize a database in this mode:

```<code>TABLE restaurant
</code>```

with "classic" fields of a place: address, street number, phone, website, etc etc etc.

I need to indicate also the days of opening // closing. E.g. From Monday to wednesday close, saturday only evening and sunday lunch + evening.

So, I did think at another table with 14 rows:

```<code>ID_RESTAURANT  MONDAY_LUNCH MONDAY_EVENING [...] SUNDAY_EVENING
    12         0             0                    1
</code>```

And "finally" every restaurant has his own cooking ("international", "chinese", "japan")

Another table with a column for every cooking?

Finally, several services. "Conditioned Air", "Credit Card", "Animals permitted" "children addicted" etc etc.

Another table with a column for every "service"?

```<code>ID_RESTAURANT    CONDITIONED    CREDIT_CARD     ANIMALS
    12              1              1              0
    13              0              1              1
</code>```

I hope that I'm clear. Thank you very much!

Body:
There's a joke I heard some time back.

If you ask a C programer to count to 10, you get '0, 1, 2, 3, 4, 5, 6, 7, 8, 9'.
  If you ask a DBA to count to 10, you get '0, 1, many'.

The key to the understanding of this joke is that if you ever are dealing with more than one thing in a database, you really need to have it be a many... not a 2 or a 3.  There are many many's described in this database that should be treated as such.

       +-----------+   +-----------+     +------------+
       | restaurant|   | rest_time |     | meal       |
       |-----------|   |-----------|     |------------|
   +-->| id        |&lt--+ rid       | +-->| id         |
   |   | name      | | | day (enum)| |   | name       |
   |   +-----------+ | | mealid    +-+   +------------+
   |                 | | open (b)  |
   |   +-----------+ | +-----------+
   |   | phone     | |
   |   |-----------| | +------------+    +------------+
   |   | phnum     | | | rest_serv  |    | service    |
   +---+ rid       | | |------------|    |------------|
       | type      | +-+ rid        | +--> id         |
       +-----------+   | sid        +-+  | name       |
                       | has        |    |            |
                       +------------+    +------------+

You have a restaurant which has some attributes.  Things that the restaurant can only have one of are columns in that table.  It can only have one name, and one id.  Depending on the description, it may have only one address (though if you have a chain like McDonalds).  Other things it has only one of are things like capacities.

A restaurant may have multiple phones (fax your order in vs reservations?) And phones only belong to one restaurant.  This is a one to many relationship.

The restaurant also has some services - but all restaurants also may have those same services.  You want to be able to do a query of 'what restaurants has air conditioning?'

Likewise, a restaurant also has some meals that it serves on some days.  I've got a simplified approach that works with mysql there for days, but having days be a separate table wouldn't be inappropriate and would be entirely appropriate if you have things like holidays being called out specially (new years eve: lunch, no dinner).


问:
What graph traversal algorithm should I use?
I would like to write an algorithm which can traverse a graph and hopefully later I can implement it to use for an indoor navigation system.
The graph would come from floor plans of a building and the graph nodes represent the building objects such as doors, corridors, stairs, rooms, etc.

The navigation system will accept different users with different capabilities, these capabilities are stored in user profile. For each individual user (or a group of users of the same type, e.g. staff member) the system returns a path specific to that user/s considering his personal functionality. For example if the user of the system is using a wheelchair the system should exclude all the stair nodes from the path (they will be marked non-traversable). Similarly if in order to enter into an indoor space, the user needs to have a key or be an staff member but he is NOT, the system should mark the node (e.g. the door  which requires the key) non-traversable and should search for those paths which don't require these specifics requirements.

This was the first part and here I use a function to check these conditions for a given user. The inputs to this function are a node and a user. If the conditions that are required by the node are NOT fulfilled (means user profile doesn't match the condition required by the node) the function returns false= non-traversable.
 If the condition holds true, the node stays isTraversable and will be stored somewhere and will be considered for the final path calculation.

The second part is that I have a list that contains all the nodes that are traversable and now the shortest path will be calculate based on 3 different costs, Energy, time and money. The final cost can be a combination of these costs and it sets the weights for the edges.

My problem is with the first part. I want to know how can I make an algorithm that produces the subgraph (the list with the traversable nodes in it). And later how can I use this algorithm to modify Dijkstra to fit this system.

Can anybody help with writing a pseudocode for the algorithm so that I can understand how would it work in clear steps or any hints on how can I make these steps into pseudocode?

Please note that at this stage the performance is not very important for me.

答:
The usual way to solve that would be instead of doing a preprocessing step before running Dijkstra, just run Dijkstra and give all the non-traversable edges a really high weight.  That way you avoid preprocessing any nodes that are definitely not in the shortest path, and also you avoid the problem of not finding a path that may actually be shorter, but came later when you search by the order of children.

You might also consider A* if your weights are distances.  It's more efficient in eliminating nodes you don't need.


问:
DDD: Can immutable objects also be entities?
I've read countless posts on differences between Entities and Value objects and while I do think that at least conceptually I understand how the two differ, it appears that in some of these posts authors consider a particular domain concept to be a VO simply because it is immutable ( thus its state will never change, at least within that particular domain model ).

Do you agree that if the state of an object will never change within particular domain model, then this object should never be an entity?  Why?

答:
The way I've read this is that a value object is an object that does not have an identity unto itself and that has nothing to do with its state changing or not changing. This makes the difference between an entity and a value object that an entity has a primary key, whereas a value object does not; it will have a foreign key to the entity it belongs to.

http://lostechies.com/joeocampo/2007/04/23/a-discussion-on-domain-driven-design-value-objects/

I can still change the value object's properties, but it doesn't need to ever be identified independent of it's entity.


答:
Going by the book (Evans, 2004), "An object defined primarily by its identity is called an ENTITY". This definition is independent of whether the object is mutable or immutable. I think it's much less likely for an immutable object to be an entity in a given domain, so it's a useful heuristic for deciding whether an object is a "value object" or an "entity", but that's not part of the definition.

For example, let's say you have an entity representing an employee, who may or may not have a direct supervisor. If you decide to represent the idea of not having a direct supervisor as being a reference to a "null" supervisor object, then the "null" supervisor object is reasonably considered an entity. And you could probably make this "null" object immutable.

Title: DDD: Can immutable objects also be entities?

Body:
I've read countless posts on differences between Entities and Value objects and while I do think that at least conceptually I understand how the two differ, it appears that in some of these posts authors consider a particular domain concept to be a VO simply because it is immutable ( thus its state will never change, at least within that particular domain model ).

Do you agree that if the state of an object will never change within particular domain model, then this object should never be an entity?  Why?


问:
Using std::sort et al. with user-defined comparison routine
In the evaluator of a custom language, I would like to replace our own sort routines with std::sort or other routines, possibly tbb::parallel_sort. The problem is that we allow users of the language to supply their own comparison routine, and in the implementations I have tried, std::sort does not take kindly to routines that fail to be a strict order. In particular, it quickly starts looking at “elements” outside the iterator range to sort.

I assume that if I put an indirection layer on top of the iterators, I could avoid that by using virtual sentinels, but there is no reason to assume that the resulting calls would necessarily ever terminate.

So, given a black box bool f(widget const &a, widget const &b) and a non-user-controlled total order operator<(widget const &a, widget const &b), what would be the minimal amount of calls I would need to make to get a sort call that does terminate and that does order according to f if that is, in fact, an order? It looks to me like the following should work, but I am hoping that I could get by with fewer calls to f by some clever method, possibly remembering previous comparison calls:

```<code>bool f_stabilized(widget const &a, widget const &b) {
  bool fab = f(a, b);
  bool fba = f(b, a);
  return (fab != fba) ? fab : (a < b);
}
</code>```

Would it be reasonable to start out by just calling f and only after seeing n^2 calls for a list of length n to fall back to such a “stabilized” version? I realize that there is no reason to assume the result would be correctly ordered and I would need to start over from the beginning with such a wrapper.

答:
Your question seems to boil down to whether or not C++'s std::sort can be used with comparison functions that do not behave like the < operator. Operator < is a strict weak order, not a total order. Any container or algorithm in the C++ standard library that depends on operator < assume that it forms a strict weak ordering, and if you violate that assumption then havoc can ensue (as you've seen.) So, to bluntly answer the question in your title, std::sort works absolutely fine with custom comparator routines, but those custom routines must behave properly.

As for how to generate a proper ordering for std::sort given a possible total ordering, you might try the following. Given a custom ordering function f, define a new ordering function f_weak like so:

```<code>template <typename T, typename F>
auto f_weak(F comparator)
{
    return [comparator](T a, T b) {
               return comparator(a, b) // true if a <= b
                        && a != b;
    };
}
</code>```

and then pass f_weak<T>(f) as the last parameter to std::sort. This code is untested, and uses some modern C++ features, but I'm sure you get the gist of it.

Body:
Your question seems to boil down to whether or not C++'s std::sort can be used with comparison functions that do not behave like the < operator. Operator < is a strict weak order, not a total order. Any container or algorithm in the C++ standard library that depends on operator < assume that it forms a strict weak ordering, and if you violate that assumption then havoc can ensue (as you've seen.) So, to bluntly answer the question in your title, std::sort works absolutely fine with custom comparator routines, but those custom routines must behave properly.

As for how to generate a proper ordering for std::sort given a possible total ordering, you might try the following. Given a custom ordering function f, define a new ordering function f_weak like so:

template <typename T, typename F>
auto f_weak(F comparator)
{
    return [comparator](T a, T b) {
               return comparator(a, b) // true if a <= b
                        && a != b;
    };
}

and then pass f_weak<T>(f) as the last parameter to std::sort. This code is untested, and uses some modern C++ features, but I'm sure you get the gist of it.


问:
How do you track third party services SSL certificates?
Recently Windows Azure Storage SSL certificate unexpectedly expired and since a lot of dependent services defaulted to "refuse to connect to a site with expired SSL certificate" that became a serious problem.

Now the SSL certificate of any web service can be retrieved by anyone at any time for validation. The picture is from the linked to question:

So it means that the information was available at all times to "anyone it might concern" and any user of the service could have noticed the upcoming expiration and for example post a message on Microsoft forums before it was too late.

However I can't find any information about how such cases are typically handled except this question for doing that in code.

Is there any kind of best practice for validating third party services SSL certificates? What tools are typically used?

答:
If you are one such user, and run a Nagios/Icinga installation already anyway, there's a check to warn before a certificate expires.

This is what we use at work.

You'll “just” have to enumerate (by virtual host / server hostname) all those external services your things depend on (and keep that list up-to-date, which may not be as easy as it sounds).


问:
What popular "best practices" are not always best, and why?
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.

答:
Methodologies, particularly scrum. I can't keep a straight face when I hear grownups use the phrase "Scrum Master".  I get so tired of hearing developers protest that some aspect of Methodology X isn't working for their company, only to be told by Guru So-and-So that the reason it's not working is that they are not, in fact, true practitioners of Methodology X.  "Scrum harder, you must, my Padawan learner!"

There are nuggets of wisdom in agile methodologies---lots of them---but they're often couched in so much manure that I can't fight my gag reflex.  Take this bit from Wikipedia's scrum page:

A number of roles are defined in Scrum. All roles fall into two distinct groups—pigs and chickens—based on the nature of their involvement in the development process.

Really? Pigs and chickens, you say? Fascinating! Can't wait to pitch this one to my boss...


问:
Design suggestion required to create an Export plugin
I am trying to create Export Module for our application, this seems to me a bit complex so I am posting it here
to get some guide lines.

In our database we have a list of Products, which can be exported as XML, RTF or PDF

The user can select one or many products from the list to export. After Selecting the product(s)
he/she is presented with list of Export type(XML, RTF, PDF) and a list of Connections( where to send this export files)
like FTP, HTTP, EMail etc whose details are already configured.

And this export is used for many different users, who have different needs. For example User1 need only Description, User2 needs
Description+Thumbnail etc.

Should I create for Export type(XML, RTF, PDF) a Manager class?
and For Connections also a Manager class?

And for Different users should I create an Interface?

答:
Firstly I think Manager is the wrong term here - Factory is probably a bette concept.

It sounds like you have three variables: format of export, columns to export, where to export.

Each one of these is a set of classes all conforming to an interface. A Factory would be useful in each case to create the correct class given the inputs (option fields on a UI?). Then they could be given to another class which coordinates their actions.

For example something like the below pseudo-code where Formatter, ColumnPicker, and DataStore are the interfaces I mentioned above. Concrete instance of them are created via factories based upon user input.

```<code>class Exporter {
    Exporter(Formatter formatter, ColumnPicker picker, DataStore storage) { ... }
    exportData(ProductList products) {
       storage.store(formatter.format(products.map(picker.pickColumns)))
    }
}
</code>```

Body:
Firstly I think Manager is the wrong term here - Factory is probably a bette concept.

It sounds like you have three variables: format of export, columns to export, where to export.

Each one of these is a set of classes all conforming to an interface. A Factory would be useful in each case to create the correct class given the inputs (option fields on a UI?). Then they could be given to another class which coordinates their actions.

For example something like the below pseudo-code where Formatter, ColumnPicker, and DataStore are the interfaces I mentioned above. Concrete instance of them are created via factories based upon user input.

class Exporter {
    Exporter(Formatter formatter, ColumnPicker picker, DataStore storage) { ... }
    exportData(ProductList products) {
       storage.store(formatter.format(products.map(picker.pickColumns)))
    }
}


问:
Win loss code that does not make 1-0 record better than someone like 20-3
ok, am just looking for a win loss code example. This can be for any language, just wanting the outline. Fairly new to programming, so dummy it up for me :)

I can do (win-loss/total of win loss). Guessing that is a good standard win loss ratio, but I don't want a new person that has 1-0 to be ranked higher than someone that has 20-3.

Any help is appreciated and thank you.

EDIT:

The chess styles are a little more than needed. Just want a ranking system with win/loss. so lest say 20-3 is top in league right now. he is, say 23 weeks in so far. if one guy comes in and wins first match against anyone, I don't want him to take #1 spot over people thats been there longer and have a great winning record. To respond to ampt... maybe he will be best in league, but I don't want him instantly there cause he had one good match. Not sure if that clarify any more. Didn't really follow Doc all the way. Looks as if he is hindered in list up to his 11th game. Not sure if thats what you ment there. Thanks again for all reasponses.

答:
http://www.evanmiller.org/how-not-to-sort-by-average-rating.html

The math is a bit advanced, but the idea is to calculate a confidence interval for the win percentage, and then use the lower bound to rank.

95% confidence intervals for your examples:

```<code>20-3: 0.68-0.95
 1-0: 0.21-1.00
</code>```

Since the 20-3's lower bound is higher (0.68 vs 0.21), it would rank higher.

Body:
http://www.evanmiller.org/how-not-to-sort-by-average-rating.html

The math is a bit advanced, but the idea is to calculate a confidence interval for the win percentage, and then use the lower bound to rank.

95% confidence intervals for your examples:

20-3: 0.68-0.95
 1-0: 0.21-1.00

Since the 20-3's lower bound is higher (0.68 vs 0.21), it would rank higher.


问:
Is it possible to loosely couple an application to its framework?
Let's say I'm developing a web application. My first choice is to use PHP with Fat-Free Framework (F3) and MVC pattern. Next year, I might decide I want to switch to Zend Framework, or maybe even ASP.NET MVC. Does it make sense to try and design my application in such a way that it is loosely coupled to its framework, or is the framework too integral to make this realistic?

The only reason I ask is because it came up in conversation with a peer recently, who criticized my pie in the sky idea of loosely coupling my application to F3.

答:
No can do.

You can design in a way that's portable across frameworks. MVC is MVC, and the principles are roughly the same whatever language or platform is used.

The actual code, however, is going to be very framework or language dependent. The only way to abstract yourself from that would be to code based on a intermediate framework. Then you can have the intermediate implementation change (from F3 to .NET ?) without changing the application. Which is a lot of work, assumes non leaky abstractions, and just moves the problem without solving it: you're now tied to your intermediate framework.

On a more positive note: consider expressing some of your tests (BDD style) in a platform independent from your implementation. Those might survive major rewrites.


答:
Loosely coupling your application to its framework essentially means you are going to write a proxy framework. Writing that proxy framework is a lot of work, and if you ever switch to a new framework you'll have to do a lot of work to make the proxy framework support the new framework. Of course, different frameworks use different idioms and patterns, which will make the proxy framework either very complex (if you try to make it fit to everything) or very limited (if you go for the lowest common denominator). Either way you'll have to struggle with that proxy framework.

Is having the ability to change frameworks on a whim worth all this trouble? Like I said, you won't be able to change it on a whim because you'll have to adjust the proxy framework, which might turn out to be more work than adjusting the application code directly.

Title: Is it possible to loosely couple an application to its framework?

Body:
Let's say I'm developing a web application. My first choice is to use PHP with Fat-Free Framework (F3) and MVC pattern. Next year, I might decide I want to switch to Zend Framework, or maybe even ASP.NET MVC. Does it make sense to try and design my application in such a way that it is loosely coupled to its framework, or is the framework too integral to make this realistic?

The only reason I ask is because it came up in conversation with a peer recently, who criticized my pie in the sky idea of loosely coupling my application to F3.


问:
What am I missing in my (mis)understanding of IoC/DI/Castle Windsor?
Okay, so here's how I understand IoC and DI in Web API to work when using Castle Windsor.

Note, though, that my confidence that I understand it as I should, though, falls somewhere between my confidence I could best Dennis Rodman in a one-on-one basketball game and my confidence in his sanity.

Another way to put it is to say that I have spent the last several days reading up on IoC/DI/Castle Windsor with Web API and experimenting with it, but I still feel like wearily responding, "All down but nine, pard; set 'em up on the other alley."

I have several more specific questions on Stack Overflow about it, such as this one, but am not yet much clearer about it.

So I'm going to "talk out loud" and hope that somebody responds with something that will refine my understanding, shed some light on this opaque (to me) subject, or help unravel this Gordian knot.

Point: The basis of IoC/DI lies in passing interfaces to constructors, so that the class with the constructor does not have to instantiate its own objects; in fact, has no need to know the concrete component/class.

Point: To set this up, you need code like so in your Controllers:

```<code>private readonly IDepartmentRepository _deptsRepository;

public DepartmentsController(IDepartmentRepository deptsRepository)
{
    if (deptsRepository == null)
    {
        throw new ArgumentNullException("deptsRepository is null");
    }
    _deptsRepository = deptsRepository;
}
</code>```

Point: Some class that implements IDepartmentRepository is passed to the DepartmentsController constructor

Point: The coder doesn't do that explicitly - the IOC container (Castle Windsor, in this case) does that "automatically" by intercepting the Web API routing mechanism with its own, as with code like this, in global.asax.cs:

```<code>GlobalConfiguration.Configuration.Services.Replace(
                typeof(IHttpControllerActivator), new WindsorCompositionRoot(_container));
</code>```

Point: global.asax.cs' Application_Start() gets the ball rolling and calls the Installer/Registrar with code such as:

```<code>protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    ConfigureWindsor(GlobalConfiguration.Configuration);
}

public static void ConfigureWindsor(HttpConfiguration configuration)
{
    _container = new WindsorContainer();
    _container.Install(FromAssembly.This());
    _container.Kernel.Resolver.AddSubResolver(new CollectionResolver(_container.Kernel, true));
    var dependencyResolver = new WindsorDependencyResolver(_container);
    configuration.DependencyResolver = dependencyResolver;
}
</code>```

Point: Lots of other Castle Windsor scaffolding has to be set up for this. Specifically, classes need to be "installed" (registered - I think registered would have been a better/more easily grokkable term for it).

This is one of my major "say what?"/headscratching areas. I don't know if that registration code should look like this:

```<code>public object GetService(Type serviceType)
{
    return _container.Kernel.HasComponent(serviceType) ? _container.Resolve(serviceType) : null;
}

public IEnumerable<object> GetServices(Type serviceType)
{
    if (!_container.Kernel.HasComponent(serviceType))
    {
        return new object[0];
    }

    return _container.ResolveAll(serviceType).Cast<object>();
}
</code>```

...or like this:

```<code>public class ApiControllersInstaller : IWindsorInstaller
{
    public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly() // should it be Types instead of Classes?
         .BasedOn<ApiController>()
         .LifestylePerWebRequest());
    }
}
</code>```

...or like this:

```<code>public class ServiceInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component.For<IDeliveryItemRepository>().ImplementedBy<DeliveryItemRepository>().LifestylePerWebRequest(),
            Component.For<IDeliveryRepository>().ImplementedBy<DeliveryRepository>().LifestylePerWebRequest(),
            Component.For<IDepartmentRepository>().ImplementedBy<DepartmentRepository>().LifestylePerWebRequest(),
            Component.For<IExpenseRepository>().ImplementedBy<ExpenseRepository>().LifestylePerWebRequest(),
            Component.For<IInventoryItemRepository>().ImplementedBy<InventoryItemRepository>().LifestylePerWebRequest(),
            Component.For<IInventoryRepository>().ImplementedBy<InventoryRepository>().LifestylePerWebRequest(),
            Component.For<IItemGroupRepository>().ImplementedBy<ItemGroupRepository>().LifestylePerWebRequest());
    }
}
</code>```

...or elsewise...

Point: Once all this is set up, and the Controllers (and Repositories? Is there more that do I have to about them, to make them safe for CW?) have been registered by the Castle Windsor routing engine, a call to my Web API app like:

```<code>http://platypus:28642/api/Departments
</code>```

...will be resolved to a "component" (concrete class) that implements IDepartmentRepository. CW will be able to figure that out, as long as I have one class that implements IDepartmentRepository, that that is the one to silently pass to the Controller's constructor which takes an arg for a class that implements IDepartmentRepository.

But...what if there are are N classes that implement IDepartmentRepository? How does CW know which one to pass to the Controller's constructor? How can I, the lowly human in this meeting of silicon and pink squishy stuff, designate which of the N I want CW to pass to the constructor?

答:
CW knows which on N classes implement IDepartmentRepository via reflection.  It knows which one you want because you registered it - that's the point of registering.  It's kind of smart though, it looks at the constructors of what you've registered and tries to deduce the concrete types based on what you have registered.  So sometimes registering the top of a dependency tree will be enough to let it figure out the rest.

There are multiple ways to register, for your convenience (and confusion).  Using a fluent API for your convenience (and confusion).  You also can control things about the life-cycle of dependencies (imagine a dependency needs to call dispose(), but the class getting the dependency didn't create it and can't know about it's life cycle - a more advanced topic though).

You should register the concrete classes you want, then resolve them in your Main method (in your case Application_Start serves this purpose), this will create all your objects in the dependency graph right away.  Call release on the container when you are done.  Don't call the container anywhere else in the app.

I hope that helps - there were a lot of questions.

I personally liked Dependency Injection in .NET as a reference (no affiliation with me), but it isn't free.