问:
Python OO problem
I started learning Python yesterday and I ran into a problem. I like to hear some thoughts on it.

As an exercise, I decided to build a chatserver. As part of the exercise, I wanted to write some inheritance code.

```<code>Class A
  def foo
    print "foo"

Class B(A)
  def bar
    print "bar"

c = B()
c.foo()
>>> prints: foo
</code>```

okay, to me that seems like very normal basic inheritance (please let me know if you disagree). So to get back to my chatserver, I thought it would be nice to extend the socket and make it into a chat socket. The first thing I wanted to do is add an attribute called nickname (important in a chat).
Oh, and I thought about using select as a threading solution because it seemed to come highly recommended, so you need an array of sockets (I also like to hear your thoughts on this).
Now, the problem you get is, that socket, instantiates sockets, so

```<code>s = socket.socket(family, type,..)
</code>```

in stead of

```<code>s = Socket()
</code>```

so what I wanted todo is

```<code>class ChatSocket(Socket)
  def getNickname()
    return "bob" # obviously an example for simplicity

s = ChatSocket()
</code>```

First question:
Why does it work this way and doesn't it have a 'normal' instantiation?

Second question:
What is in your opinion an elegant solution to this challenge?

I hope this makes sense...
Any thoughts are very welcome

答:
As someone stated befor a python file is basically a module so if you have a class called Socket in a file socket.py and you use the import statement like

```<code>import socket
</code>```

you have to refer to the Socket calls (for instanciation) like

```<code>s = socket.Socket()
</code>```

You could also use the from statement to import  a special function or class fro the module like

```<code>from socket import Socket, ChatSocket
</code>```

This is python 2.x syntax if you using python 3.x you might need to be more specific with your refernces in the import statements. And in your example you used old style classes thats considered bad style. Since 2.5 (if I remember right ) you should  inherite your class from object like

```<code>class A(object):
</code>```

in python everything is basically an object.

Title: Python OO problem

Body:
As someone stated befor a python file is basically a module so if you have a class called Socket in a file socket.py and you use the import statement like

import socket

you have to refer to the Socket calls (for instanciation) like

s = socket.Socket()

You could also use the from statement to import  a special function or class fro the module like

from socket import Socket, ChatSocket

This is python 2.x syntax if you using python 3.x you might need to be more specific with your refernces in the import statements. And in your example you used old style classes thats considered bad style. Since 2.5 (if I remember right ) you should  inherite your class from object like

class A(object):

in python everything is basically an object.


问:
How do I avoid having to compute square roots for every element in a data set?
I have a list of points, with floating point coordinates, of which I've computed the square of the Euclidean distance between these points. I have not computed the actual Euclidean distance between these points because computing a square root is an expensive operation. So, I have a list of floating point squares {a², b²...}.

My goal is to find the arithmetic mean of the actual Euclidean distance values, (a + b + ...) / n).

Is there a way to avoid computing square root for every element?

答:
Is there a way to avoid computing square root for every element?

Absolutely. Raise the value to the power of ½.

Great. Is this faster?

It is a well trodden road, but unfortunately I have yet to find any language, platform or CPU where the default implementation of such is more efficient.

Various algorithms exist if you wanted to roll your own.

ContentLicense: CC BY-SA 3.0


问:
How to avoid business rules in repository?
If there is Employees repository and I have to get Employee that has a greatest salary - where to put filtering that represents business rule for that?
I can get all Employees and filter them out in Domain Model, but that does not seem as efficient as SQL Query in repository. What patterns come into play?</p>

答:
Since a salary, its presentation and database computation is quite natural and has no strict domain, I would not call it business logic here. It's just an ORDER BY query for the database.

Let me give you another example with business logic:

If you would like to have the most "profitable" employee and there are some domain specific values like "probability of on time completion in projects" and "illness absent factor", and at least the salary, then there might be some weights for calculating the scoring factor which would be business logic.

Conclusion:

Keep in mind, that there are frameworks with repositories with no DI, thus just dbal operations are possible. In other words a business logic component should be able to use DI.

In my opinion repositories should be simple and also only depend on the dbal. Ordering and simple where are okay. Joining and computation over different entities is not the job of the repository.

So I would leave the simple queries to a repository which have no business logic and create services for more complex queries, which have business logic.

All in all it's more opinion-based I think.


答:
Aitch proposed using a cache if you have integers, but you stated you have floats. A cache is however still possible if:

the points whose distance you are calculating are on a grid (so the set of likely values is small)

- or -

the resulting value does not need high accuracy (in which case you may use intervals as keys in your cache).

In the second case, if you keep pairs (a²;b²) → (a;b) with a and b close, you can also get a lower and upper bound on the average, if that's useful to the client. (It would be helpful to mention what that average is needed for)

Title: How do I avoid having to compute square roots for every element in a data set?

Body:
I have a list of points, with floating point coordinates, of which I've computed the square of the Euclidean distance between these points. I have not computed the actual Euclidean distance between these points because computing a square root is an expensive operation. So, I have a list of floating point squares {a², b²...}.

My goal is to find the arithmetic mean of the actual Euclidean distance values, (a + b + ...) / n).

Is there a way to avoid computing square root for every element?


答:
Defining what is an Employee (according to your existing storage model) is a Business Rule (it is a definition, so it's a fact).

First article of the Business Rules manifesto (http://www.businessrulesgroup.org/brmanifesto.htm).

Title: How to avoid business rules in repository?

Body:
If there is Employees repository and I have to get Employee that has a greatest salary - where to put filtering that represents business rule for that?
I can get all Employees and filter them out in Domain Model, but that does not seem as efficient as SQL Query in repository. What patterns come into play?</p>


问:
What are the impact to the server when using ajax polling for live web pages?
I've been searching on the internet about using interval ajax polling for live web pages and I've been using it along with SignalR. Now I always read an article online about using ajax polling for live web pages that there could be an impact on your server or maybe there's a downside effect when using ajax polling if you have heavy traffic on your site and/or when you're polling large data from the database.

If this would be true, I guess my questions are, what are the server impacts that they are talking about that could lead to any downside effect on your site? and how to avoid those server impacts if you choose to use ajax polling for your live web pages?

答: The server impact is simply the request volume. Each time you poll the server, it has to handle the request. If you've got five widgets on your page and each one is polling for updates, that means that each user is generating five requests every second (or whatever your polling interval is). For many (possibly most) applications, this isn't a big deal, unless the requests cause a bottleneck on the server (e.g., if each request triggers a database read). However, if you're writing a commercial app that you hope will be used by thousands of people, it probably isn't a good idea. To mitigate the impact, you could implement some form of request throttling, increasing the polling delay when the system gets busy, but that's going to lead to some complex heuristics on the client side. As @Li Yin Kong suggested, you're better off using something like websockets for periodic updates.</p>


答:
It depends on how exact your average needs to be. If there is a large disparity between the size of the cubes you can "ignore" the smaller cubes and not calculate their sqrt and still get a good average estimate:

```<code>(1000 + 1000 + 1000 + 0.001) / 4 = 750.00025
</code>```

Ignore the last value:

```<code>(1000 + 1000 + 1000 + 0) / 4 = 750
</code>```

Body:
It depends on how exact your average needs to be. If there is a large disparity between the size of the cubes you can "ignore" the smaller cubes and not calculate their sqrt and still get a good average estimate:

(1000 + 1000 + 1000 + 0.001) / 4 = 750.00025

Ignore the last value:

(1000 + 1000 + 1000 + 0) / 4 = 750


问:
How to frame the concept behind CMake?
I'm using CMake for several years now and found that - in the cases where I'm struggling with CMake - I'm still not completely sure about the concept behind CMake (not taking into account CTest, CPack or CDash also shipped with CMake).

When I started I came across Bill Hoffman's presentation on Google Tech Talks and one claim there has stick to my mind:

CMake aims to give C++ compile portability like the compile once and run everywhere of Java, Python and C#

Starting from there and the basic concepts of CMake page, I came to thinking about CMake in terms of the following three major high-level programming concepts:

CMake is an abstraction layer for the build and operating systems it's supporting

CMake is a high level programming language for build procedure descriptions

CMake assists you in cross-platform development by making code parts configurable

I'm fully aware of the complexity of CMake's task, but I hope you can help me nonetheless with:

As being an abstraction layer it can't/shouldn't expose all functionality of the underlying layer. So why are there so many holes to explore in CMake?

Especially commands from the beginning do have bypasses. E.g. add_definitions(): "This command can be used to add any flags, but it is intended to add pre-processor definitions"

I see CMake going in the right direction with e.g. target_compile_features() for abstracting compiler flags

For the cases where I really need a bypass (something I can only accomplish in the native language) why does CMake not provide some generic way of "inline native code" as other high level programming languages do?

E.g. like the asm macro/command in C++

Is it OK in CMake to add another layer of abstraction to CMake itself (to hide the complexity of CMake to the users of my build environments)?

I think yes. And since I understand it's a high level programming language, why not?

Thanks in advance for your insights and help with this.

答:
Disclaimer: My experience with CMake is extremely limited, so I could easily be mistaken in some of the following.

As I understand it, CMake is a simply a build system.  In particular, it aims to be a build system for cross-platform projects, usable across multiple OSes and compilers.

For solid technical reasons, the CMake developers chose to implement their build system as a layer on top of platform-specific build systems (Visual Studio project files, makefiles, etc.), but this may help explain why presenting a leak-proof abstraction layer is not its primary design goal.

The Architecture of Open Source Applications has a chapter on CMake. It may provide some more insights. For example, they discuss the design of CMake's language:

The CMake language is meant to be very simple. However, it is one of the major obstacles to adoption when a new project is considering CMake. Given its organic growth, the CMake language does have a few quirks. The first parser for the language was not even lex/yacc based but rather just a simple string parser. Given the chance to do the language over, we would have spent some time looking for a nice embedded language that already existed. Lua is the best fit that might have worked. It is very small and clean. Even if an external language like Lua was not used, I would have given more consideration to the existing language from the start.

Title: How to frame the concept behind CMake?


问:
What is the most readable way of passing arguments to the function?
I'm using JavaScript but the question can be generalized to all the languages.

In a nutshell - I'm checking if a browser connecting to my site is a microwave and cater for that accordingly.

What would be the best way to structure my code?

Best way is in "most readable", "most maintainable" (insert your own metric here)...

Option 1.0

```<code>var iammicrowave = /(microwave)/.test(navigator.userAgent);
if (iammicrowave) {
    var settings = { blah : 42 };
    magicFunction(settings);
} else {
    magicFunction();
}
</code>```

Option 1.1

```<code>var iammicrowave = /(microwave)/.test(navigator.userAgent);
if (iammicrowave) {
    magicFunction({ blah : 42 });
} else {
    magicFunction();
}
</code>```

Option 2.0

```<code>var iammicrowave = /(microwave)/.test(navigator.userAgent);
var settings;
if (iammicrowave) {
    settings = { blah : 42 };
}
magicFunction(settings);
</code>```

Option 2.1

```<code>var iammicrowave = /(microwave)/.test(navigator.userAgent);
var settings = imamicrowave ? { blah : 42 } : undefined;
magicFunction(settings);
</code>```

Option 2.1.1

```<code>var iammicrowave = /(microwave)/.test(navigator.userAgent);
var settings = imamicrowave ? { blah : 42 } : {};
magicFunction(settings);
</code>```

Option 2.2

```<code>var iammicrowave = /(microwave)/.test(navigator.userAgent);
magicFunction(imamicrowave ? { blah : 42 } : {});
</code>```

Option 2.3

```<code>magicFunction(/(microwave)/.test(navigator.userAgent) ? { blah : 42 } : {});
</code>```

Many thanks!

答:
For something like this where there isn't much meat to the code, the most readable way is the way that is most consistent with the idioms of your language and consistent with your codebase (probably in that priority). The bugs will come when people read the code assuming it does one thing, but your code is different. The readability issues come when people read the code assuming it is one thing, but your code is different.

In a vacuum, I like none of these. Instead:

```<code>if(/(microwave)/.test(navigator.userAgent)) {
  magicFunction({blah: 42});
} else {
  magicFunction();
}
</code>```

It allows you to break in the conditional. It doesn't make local vars which make the reader worried that the value is used later. It makes each branch explicit, which makes it easier to change in the future.

For conditionals that are less clear, I would split them into their own well named function rather than using a local variable for that since less clear logic tends to need reusing and/or testing in isolation.

Body:
For something like this where there isn't much meat to the code, the most readable way is the way that is most consistent with the idioms of your language and consistent with your codebase (probably in that priority). The bugs will come when people read the code assuming it does one thing, but your code is different. The readability issues come when people read the code assuming it is one thing, but your code is different.

In a vacuum, I like none of these. Instead:

if(/(microwave)/.test(navigator.userAgent)) {
  magicFunction({blah: 42});
} else {
  magicFunction();
}

It allows you to break in the conditional. It doesn't make local vars which make the reader worried that the value is used later. It makes each branch explicit, which makes it easier to change in the future.

For conditionals that are less clear, I would split them into their own well named function rather than using a local variable for that since less clear logic tends to need reusing and/or testing in isolation.


问:
Design architecture advice on relation between objects and singleton JS
I would like your feedback regarding some best practices on design relationship  between objects, specially when a singleton object is involved.

Let's imagine I need to simulate a Shop with Customers.

There is only one Shop in my application and a Customer belong only to that Shop.

When the Shop closes I need to notify each Customer.

Below some pseudo code.

In both approaches I consider a Shop as a single object.

In approach 01, I call addCustomer on shop.

In approach 02, I call addCustomer when actually creating a Customer object keeping a reference on Shop in every Customer.

I believe a third approach could be also possible, basically where shop and Customer communicate with events. So for example when creating a Customer, an event is broadcasted, shop listen to that event and add a Customer to itself.

What are your opinions, pro/cons regarding these approaches? I am using JavaScript as language. Thanks in advance for your support.

```<code>  // 01 approch
            var shop = {
                customers: [],
                addCustomer: function (customer) {
                    this.customers.push(customer);
                },
                close: function () {
                    this.customers.forEach(function (customer) {
                        customer.goOut();
                    });

                }
            };
            function Customer(name) {
                this.name = name;
                this.goOut = function () {
                    console.log(this.name + ' goes out')
                }
            }
            // set up
            shop.addCustomer(new Customer('a'));
            shop.addCustomer(new Customer('b'));
            shop.addCustomer(new Customer('c'));
            shop.close();
            console.log('-------------------------');
</code>```

```<code>        // 02 approch
        var shop2 = {
            customers: [],
            addCustomer: function (customer) {
                this.customers.push(customer);
            },
            close: function () {
                this.customers.forEach(function (customer) {
                    customer.goOut();
                });
                this.customers = [];
            }
        };

        function Customer2(name) {
            this.shop = shop2;
            this.name = name;
            this.goOut = function () {
                console.log(this.name + ' goes out')
            }
            this.shop.addCustomer(this); // make sense?
        }
        new Customer2('d');
        new Customer2('e');
        new Customer2('f');
        shop2.close();
</code>```

答:
It is difficult to recommend anything in particular because we are discussing only small amount of code. But there are some comments

In approach 01, I call addCustomer on shop.

In this case shop knows about customers. Customers doesn't know about shop. So, there is a one link.

In approach 02, I call addCustomer when actually creating a Customer
  object keeping a reference on Shop in every Customer.

In this case both shop knows about customers and customers know about shop. So, there are two links and the coupling between classes becomes even stronger (which is mostly bad)

I believe a third approach could be also possible, basically where
  shop and Customer communicate with events.

This relaxes the coupling somewhat, but does not remove it anyway.

For my understanding coupling should be removed as Shop is not referenced in ? Customer as in the second approach. Am I wrong?

Well, will it be removed or not depends on what exactly you do when event is received. Coupling is just knowledge. If after event is received, customer adds itself to the shop or stores inside itself a reference to the shop, coupling is still there.

There is also an indirect coupling. You are sending an event and this event is processed. It might be processed without involving actual object reference, but it is still there. Your system imposes knowledge about relation between these two classes.

So, you must give objects minimum knowledge about each other. But not less knowledge, that is required for them to function correctly.


问:
Interface Implementation: A parameter I don't need

Pseudo-Code

interface IPagingInfo
{
    int CurrentPageNo { get; }
    int RowsPerPage { get; }
    ...
}

interface ResultsRetriver
{
    ResultRows GetResults(IPagingInfo pagingInfo);
}

class ANewResultsRetriver : ResultsRetriver
{
    ResultRows GetResults(IPagingInfo pagingInfo)
    {
        // TODO: Retrieve and return all results, ignore pagingInfo.
    }
}
```

Explanation

interface ResultsRetriver has existed since as long as we know time. There are many implementations of ResultsRetriver all happily working in the system. The new programmer comes in and is tasked with writing the ANewResultsRetriver. His results retriever however is different in that it does not have a concept of paging, it must always return all results.

The programmer feels the person who wrote interface ResultsRetriver should have provided a version of the call without the paging parameter for cases such as this, where the parameter is not required. Now he wants to add it in, a GetResults().

A colleague suggests that it's okay to not use the pagingInfo  parameter in this special case, but what if the caller sends in valid pagingInfo expecting results to conform to the supplied pagingInfo? Then ignoring the callers request may not be prudent. So the colleague also suggests we throw a PagingNotSupportedException() to alert the caller if a valid pagingInfo is supplied.

Suggestions:

Add a new GetResults method to ResultsRetriver which does not take any parameters. Rewire all code around the interface to call the correct version based on validity of pagingInfo.

Ignore the pagingInfo parameter.

Ignore the pagingInfo parameter but throw a PagingNotSupportedException() if a valid pagingInfo parameter is supplied to alert the caller to the fact that the parameter will be ignored and they may need to work around this.

Argue that what the programmer is writing is not really a ResultsRetriver as a ResultsRetriver must support paging by its original definition. So a new interface must be defined NonPagedResultsRetriver with a GetResults() method taking no parameters. The refactor to include this interface with surrounding code that currently works with ResultsRetriver to also work with NonPagedResultsRetriver

Something else?

Question

What is the optimal solution and why?

See Also

Minimal design vs anticipated use

答:
In general, the best solution would be to make the new results retriever conform to the contract of the interface by doing paging in code. Ignoring the paging info is a violation of the Liskov Substitution Principle, and will lead to bugs. If that is prohibitively expensive, take that as a hint that this new retriever maybe isn't a good idea.

Adding a plain old GetResults() is maybe fine, but given it isn't there already makes me think that it isn't there to dissuade its misuse. Combine that with having to go back in and modify a bunch of existing implementations makes me think that you're not gaining much by doing that, so would probably not do that.


答:
The classical pattern you could use to implement this is the observer pattern. It's the abstraction of your first solution basically. With the observer pattern it doesn't matter to your shop, which type of objects are listening to your "close-event". So that could be customers but also suppliers (well ..whatever you can think of :) ).

See those links as a starting point:

http://www.dofactory.com/javascript/observer-design-pattern

https://en.wikipedia.org/wiki/Observer_pattern

Title: Design architecture advice on relation between objects and singleton JS

Body:
I would like your feedback regarding some best practices on design relationship  between objects, specially when a singleton object is involved.

Let's imagine I need to simulate a Shop with Customers.

There is only one Shop in my application and a Customer belong only to that Shop.

When the Shop closes I need to notify each Customer.

Below some pseudo code.

In both approaches I consider a Shop as a single object.

In approach 01, I call addCustomer on shop.

In approach 02, I call addCustomer when actually creating a Customer object keeping a reference on Shop in every Customer.

I believe a third approach could be also possible, basically where shop and Customer communicate with events. So for example when creating a Customer, an event is broadcasted, shop listen to that event and add a Customer to itself.

What are your opinions, pro/cons regarding these approaches? I am using JavaScript as language. Thanks in advance for your support.

```<code>  // 01 approch
            var shop = {
                customers: [],
                addCustomer: function (customer) {
                    this.customers.push(customer);
                },
                close: function () {
                    this.customers.forEach(function (customer) {
                        customer.goOut();
                    });

                }
            };
            function Customer(name) {
                this.name = name;
                this.goOut = function () {
                    console.log(this.name + ' goes out')
                }
            }
            // set up
            shop.addCustomer(new Customer('a'));
            shop.addCustomer(new Customer('b'));
            shop.addCustomer(new Customer('c'));
            shop.close();
            console.log('-------------------------');
</code>```

```<code>        // 02 approch
        var shop2 = {
            customers: [],
            addCustomer: function (customer) {
                this.customers.push(customer);
            },
            close: function () {
                this.customers.forEach(function (customer) {
                    customer.goOut();
                });
                this.customers = [];
            }
        };

        function Customer2(name) {
            this.shop = shop2;
            this.name = name;
            this.goOut = function () {
                console.log(this.name + ' goes out')
            }
            this.shop.addCustomer(this); // make sense?
        }
        new Customer2('d');
        new Customer2('e');
        new Customer2('f');
        shop2.close();
</code>```


问:
Modular Filter Architecture for WPF
I am creating a little stock-management tool for private use.

I have different views, which need similar but different filters.  As an example I have a "current stock" list where I can filter for supplier, product group and name.   I have the same list again but with additional filters for certain boolean flags.  I am going to create a little statistic view where I will need all of the mentioned filters and some more like date range.

An last but not least I am creating a little csv Export where I have similar requirements as in the statistic view.

It isn't much but enough to think about a decent architecture. If you do it right on a small scale, chances are you do it right on bigger projects.

I use WPF with MVVM.

So far I have thought of some ways to tackle my problem:

Individual filter for each view: It is of course the most flexible variant but also leads to the most work if something concerning the filters is changed.

Filter generator: A control gets generated according to the configuration,
sounds good but i loss the flexibility of styling the filter according to the view (i could add this to the configuration, but it would still lose me the advantages of xaml) and I can't really preview it in xaml during design time.

Creating a single ViewModel which contains all possible filters and Controls + ViewModels for each filter type (Checkbox, Combobox, Textbox).
This approach would allow my to simply style the filter in xaml by using the filter controls for each view while capsuling the filter VM in one implementation.

For me the 3. option looks preferable but as i have never done anything alike, so I am looking for some feedback on how such a problem is usually approached or if some related pattern exist.

答:
I would start by determining the collection types to be used throughout the application, trying to keep only one 'Major' collection of data where possible.

From there when the new 'Major' collection is set, it can fire an event to any listener that may show a different view. (Events are an Observer pattern).  Each observer then has addressibility to the 'Major' collection and can wrap it with a CollectionViewSource which allows for excellent filtering ability.  Each view having different filtering requirements. Filtering for other views only happens when that view receives focus.

Each view then can either add columns to the View or Hide columns not needed.

There are tricks to this whereby you can use functions in a method to allow for filtering a grid based on what 'a caller' to determine what is needed to filter.  All filtering is then able to be abstracted to the app.config file so that new dynamic filters can be added at will based on values the user places in the config file, this allows for new behavior without recompiling projects.

From there, as the application grows, you may want to add a 'repository' layer which pretty much moves all data access and business logic to one place one time.  All views then would simply call the 'repository' functions to get everything they need.

Using LINQ and CollectionViewSource objects bound to datagrids is one of the best combination of tools out there.  In addtion where possible I really like Entity Framework as well if back end is SQL.  If you are dealing with JSON then JSON.NET is the best tool for that.

Title: Modular Filter Architecture for WPF


问:
Designing voucher system in e-commerce application
I'm currently designing voucher system to be implemented in our company e-commerce application.

I'm currently have voucher table in database which contains following information :

Unique voucher code

Voucher remaining count -> How many times this voucher can be used in purchase transaction

Other columns

Currently, customer input the voucher code in checkout page, before payment ( using credit card and internet banking ) happens.

I'm using hosted payment gateway, which means I redirect customer to payment gateway website. There customer input and complete the payment and get redirected back to our website

My question is about when should I decrement the voucher remaining count information?

I have consider two alternatives, as follows :

Customer input the voucher code and push validate voucher code button. There will be ajax call to validate the voucher code, get discounted transaction amount and then decrement the voucher remaining count. The weakness of this solution is that, when payment fails or stock suddenly runs out, the voucher is already used thus customer get angry.

Customer input the voucher code and push validate voucher code. there will be ajax call just to get the validate the code and discounted transaction amount because of voucher usage. We decrement the voucher remaining count after payment is successfully committed. The weakness of this solutions is that, if after payment, the voucher remaining count already become zero because of another usage from different customer, it means that the we have charged the wrong transaction amount and suffered loss.

Is there any other better alternatives that those two above or should I just choose one of above solution?

答:
You don't need to add voucher remaining column. Instead, use maximum allowed vouchers field only and store all created vouchers in another table.

Customer can start creating new voucher if stock available (Maximum allowed vouchers value - Total counts in voucher created table) is greater than zero.


答:
I think giving magicFunction() a better name would do more help readability than any of the other options you present. Or make a well named wrapper function that constructs the settings map and passes it to magicFunction(). I don't think the iammmicrowave variable is strictly necessary or adds that much to readability.

In a language with types you could also name your settings data type, formalize its allowable keys, and write a description of it in comments where it is defined.  That might help too, but I still think a more descriptive function name would help the most.

Title: What is the most readable way of passing arguments to the function?

Body:
I'm using JavaScript but the question can be generalized to all the languages.

In a nutshell - I'm checking if a browser connecting to my site is a microwave and cater for that accordingly.

What would be the best way to structure my code?

Best way is in "most readable", "most maintainable" (insert your own metric here)...

Option 1.0

```<code>var iammicrowave = /(microwave)/.test(navigator.userAgent);
if (iammicrowave) {
    var settings = { blah : 42 };
    magicFunction(settings);
} else {
    magicFunction();
}
</code>```

Option 1.1

```<code>var iammicrowave = /(microwave)/.test(navigator.userAgent);
if (iammicrowave) {
    magicFunction({ blah : 42 });
} else {
    magicFunction();
}
</code>```

Option 2.0

```<code>var iammicrowave = /(microwave)/.test(navigator.userAgent);
var settings;
if (iammicrowave) {
    settings = { blah : 42 };
}
magicFunction(settings);
</code>```

Option 2.1

```<code>var iammicrowave = /(microwave)/.test(navigator.userAgent);
var settings = imamicrowave ? { blah : 42 } : undefined;
magicFunction(settings);
</code>```

Option 2.1.1

```<code>var iammicrowave = /(microwave)/.test(navigator.userAgent);
var settings = imamicrowave ? { blah : 42 } : {};
magicFunction(settings);
</code>```

Option 2.2

```<code>var iammicrowave = /(microwave)/.test(navigator.userAgent);
magicFunction(imamicrowave ? { blah : 42 } : {});
</code>```

Option 2.3

```<code>magicFunction(/(microwave)/.test(navigator.userAgent) ? { blah : 42 } : {});
</code>```

Many thanks!


答:
If you don't need to know the exact answer, you should read this paper:

http://www2.mta.ac.il/~adish/Pubs/Papers/av-metric-r3.pdf (archive.org link to prevent link rot)

First, it's clear from the paper that there is no way to do this to get an exact answer that's faster than the brute force approach:

Our aim is beating the obvious algorithm that computes the exact value of the
  aforementioned average (by considering all pairs of points). But, unlike in the
  graph theoretic setting (cf. [4]), we cannot hope for approximation algorithms
  that run in time that is sub-linear in the number of points (because a single
  “exceptional” point may dominate the value of the average of all pairwise distances).
  Thus, we seek approximation algorithms that run in time that is almost
  linear in the number of points. We consider two algorithmic approaches.

Then they have an easy answer: rather than computing the Euclidean distance for all pairs of points, you can get a sqrt(d) approximation by averaging the distances of the coordinates (unfortunately, Programmers.SE doesn't have MathJax so a screenshot will have to do):

tl;dr math language: basically the formula is just saying add all the pairs of distances between the coordinates. For example, sqrt((x2-x1)^2 + (y2-y1)^2) just becomes x2 - x1 + y2 - y1, and your answer will only be off by a factor of sqrt(d), which in this case is sqrt(2).

Then, the paper goes on to discuss a random sampling algorithm, which is more accurate.

I recommend reading the paper to see why this works, they explain it better than I can.


答:
You can associate vouchers with orders as Muhammad suggested and use ajax to check availability. Count all vouchers for open and paid orders. Don't count vouchers for cancelled orders.
This way someone might not be able to use a voucher, but later someone else might. If that first someone complains about that, make sure, you have one extra stock item that you can let go for the discounted rate and everybody is happy ;)</p>

Title: Designing voucher system in e-commerce application

Body:
I'm currently designing voucher system to be implemented in our company e-commerce application.

I'm currently have voucher table in database which contains following information :

Unique voucher code

Voucher remaining count -> How many times this voucher can be used in purchase transaction

Other columns

Currently, customer input the voucher code in checkout page, before payment ( using credit card and internet banking ) happens.

I'm using hosted payment gateway, which means I redirect customer to payment gateway website. There customer input and complete the payment and get redirected back to our website

My question is about when should I decrement the voucher remaining count information?

I have consider two alternatives, as follows :

Customer input the voucher code and push validate voucher code button. There will be ajax call to validate the voucher code, get discounted transaction amount and then decrement the voucher remaining count. The weakness of this solution is that, when payment fails or stock suddenly runs out, the voucher is already used thus customer get angry.

Customer input the voucher code and push validate voucher code. there will be ajax call just to get the validate the code and discounted transaction amount because of voucher usage. We decrement the voucher remaining count after payment is successfully committed. The weakness of this solutions is that, if after payment, the voucher remaining count already become zero because of another usage from different customer, it means that the we have charged the wrong transaction amount and suffered loss.

Is there any other better alternatives that those two above or should I just choose one of above solution?


问:
Multi user website for MVC project: one, or multiple solutions?
We're starting a new MVC 5 project that will ultimately consist of 4 websites depending on the kind of user:

One internal, for company employees.

One for agents, independent contractors that work for the company.

One for external salespeople.

One for customers, which could be any one from their homes.

The internal website will have considerably more functionality than all the others, and since it will be only accessed by employees it will be kept in a private network. The solution is structured like this:

A Data project where the model classes are kept. This has been done using Entity 6 Database First.

A Resources project with strings and images.

A Web project with the MVC stuff: controllers and views, plus CSS/JS, etc.

Given that one website will be internal while the other will be accessed through a public IP, my first thought was having two separate solutions: one for the internal web and one for all the other ones (changing between views based on the logged user), deploying them to a different server. The downside I see is that there would be a ton of duplicate code between the solutions: not only the Data project would have to be very similar or even the same, the resources and the views would have a lot of common stuff.

I'm wondering if it would make more sense to have just one solution with a Data project, a Resources project and then InternalWeb and ExternalWeb projects. Maybe even having three different projects instead of ExternalWeb: AgentsWeb, CustomerWeb, SalesWeb.

I have as little experience bulding MVC applications as I have deploying them, so I would like to know which way is seen as best practice for this kind of situation.

答:
The structure may depend on the service of your servers.

If I were you, for quick answer I may check UI pages first which have many common parts or not.
If overall pages , functions and features are different by roles, you don't need to worry about making multi server. You have many choices and even you can use only one DB with multi servers. Sometime separating servers is better in terms of management, fault tolerance, security and development.

But if there are many common pages among roles, i recommend you implement managing roles and abilities by customer so that server can display different pages by roles or abilities. You can also separate pages by port or URL that prevents code duplication. It may be better in terms of code-management. You may choose this means if you estimate future additional huge requirements. But the weakness is the benefit of first one. For example, if you have to serve important server like payment, you'd better saperate it.


问:
Identical Databases for Multiple Users Reading Efficiency
Our project utilizes a static database (no writes). With many users we don't actually have a problem per se reading it. If a database "locks" per read request by any user, then would it not be more efficient (though perhaps unnoticeable) to have multiple databases that each user connects to individually?

We are database noobs. Apologies in advance if this is in the wrong place. We are planning on using BoltDB or LMDB for our project, but personally I was intrigued by this idea.

答:
Unless your database is measured in Terabytes and your concurrent user count is astronomical, don't bother.

Modern databases are very fast, especially for reading.

You should wait until you actually have the problem then measure to confirm you have the problem before you try to fix anything.

If you run multiple read-only databases in parallel, you now have the maintenance problem of ensuring they are in fact identical.  Debugging the situation when they're not can be painful.


问:
Should formatter do validation?
Say I have a SSN field in a form. I want SSN to be in format of xxx-xx-xxx.

I may just have a SSN formatter checking whether the input are all digits and adding dashes when necessary.

Another option is to have both SSN formatter and validator. SSN formatter doesn't check type or range, so it accepts asdfghjkl and formats to asd-fg-hjkl. Then regular expression validator kicks in, telling me the input doesn't matach pattern \d{3}-\d{2}-\d{3}.

I find some formatting libraries have built-in validation functions, eg. formatter.js and FieldKit.

If formatter does both formatting and validating, is it single responsibility?

答:
The Single Responsibility Principle applies to classes of objects.

Robert Martin defines a "responsibility" as "a reason for the class to change," which basically means that a class can do more than one thing, so long as those things are related.  For example, a data access class might have Create, Read, Update and Delete methods, but that doesn't mean it has four responsibilities, only one: that of data access.

Ergo, it's entirely reasonable for formatting and validation to be in one class, as both activities relate to the responsibility of managing UI input.

SRP goes hand-in-hand with the Open/Closed principle, which states that a class should be "open for extension, but closed for modification."  Classes which adhere to SRP are easier to extend, because you're not dealing with multiple responsibilities but only a single one.

Further Reading

Single Responsibility Principle

Open/Closed Principle

Title: Should formatter do validation?


问:
Functional programming: Compare all items in an array
In functional programming, how do I do an equality comparison of all items in an array?

I have an array of items that I want to compare, for example for equality. Is it possible to use a fold (also known as reduce) operation for this?

This code won't work, because after the first iteration, memo is a boolean:

```<code>[a, b, c].reduce((memo, item) => memo === item)
</code>```

I've tried this variant, which returns the last item if they are equal, but this is no good, since I need a boolean as the result:

```<code>[a, b, c].reduce((memo, item) => (memo === item) && item)
</code>```

Forcing a boolean !! is no good either, since the item itself may be falsy and so give the wrong result.

I would like to have a functional solution to this problem – saving the result outside of the fold is much more verbose.

答:
Most FP languages I've seen have an implementation of fold/reduce which takes in a starting value for an accumulator, e.g. in Haskell:

```<code>pairs = zipWith (,) xs ys
foldl (\accum (x,y) -> (x == y) && accum) True pairs
---------------------------- initial value ^
</code>```

There are also usually other functions which take care of calculations like this, such as and:

```<code>and [True,False,True,True,False] == False
</code>```

Body:
Most FP languages I've seen have an implementation of fold/reduce which takes in a starting value for an accumulator, e.g. in Haskell:

pairs = zipWith (,) xs ys
foldl (\accum (x,y) -> (x == y) && accum) True pairs
---------------------------- initial value ^

There are also usually other functions which take care of calculations like this, such as and:

and [True,False,True,True,False] == False


问:
Do UML classifiers with the same name combine, or is that not allowed?
If you have multiple instances of a classifier with the same name, do they simply combine, or is that not allowed?

For example, are these two equivalent?

```<code>+-----+ +-----+       +-----+
| Bar | | Bar |       | Bar |
+-----+ +-----+  vs.  +-----+
| +a  | | +b  |       | +a  |
+-----+ +-----+       | +b  |
                      +-----+
</code>```

The reason for breaking a classifier down would be for reasons of laying out a readable diagram.

Are there any standardized ways of defining a classifier (e.g. a class) piece-wise?

答:
In the end, UML is a visual language to communicate a design between humans. So while you have a lot of freedom to communicate the same information differently, you should try to choose the clearest way. If you show me an UML class diagram where two classes have the same name, I would presume this to be a mistake. It is not a good idea to represent the same class multiple times in the same diagram. Therefore, if a class is used in two contexts in the same diagram, you should only draw the class a single time.

However, it might be reasonable to draw multiple diagrams to emphasize different aspects of your architecture. In that case, you can leave out any attributes of your classes that are not relevant in this context. E.g. if the existence of a member a adds no information to a diagram, leave it out. A class diagram does not have to communicate the whole design at once.


答:
It is absolutely OK to implement this low-level in your repository and just proxy it from your service-layer. Something like:

```<code>// repo contract
public interface IEmployeeRepository {
    public Employee GetHighestPaidEmployee();
}

// service layer contract
public interface IEmployeeService {
    public Employee GetHighestPaidEmployee();
}

// service impl
public class EmployeeService : IEmployeeService {
    private readonly IEmployeeRepository employeeRepository;

    // constructor here for DI to hook onto

    public Employee GetHighestPaidEmployee() {
        return employeeRepository.GetHighestPaidEmployee();
    }
}
</code>```

Or, if you wanted to be more generic, just implement something like public IQueryable<Employee> GetEmployees(string sortColumn, SortDirection sortDirection); on your repository and call it from your service layer using something like return employeeRepository.GetEmployees("Salary", SortDirection.Descending).FirstOrDefault();

Excuse my C# leaning, no idea what language you're using. These concepts should translate to other languages, though, I'm just not as familiar with syntax.

Body:
It is absolutely OK to implement this low-level in your repository and just proxy it from your service-layer. Something like:

// repo contract
public interface IEmployeeRepository {
    public Employee GetHighestPaidEmployee();
}

// service layer contract
public interface IEmployeeService {
    public Employee GetHighestPaidEmployee();
}

// service impl
public class EmployeeService : IEmployeeService {
    private readonly IEmployeeRepository employeeRepository;

    // constructor here for DI to hook onto

    public Employee GetHighestPaidEmployee() {
        return employeeRepository.GetHighestPaidEmployee();
    }
}

Or, if you wanted to be more generic, just implement something like public IQueryable<Employee> GetEmployees(string sortColumn, SortDirection sortDirection); on your repository and call it from your service layer using something like return employeeRepository.GetEmployees("Salary", SortDirection.Descending).FirstOrDefault();

Excuse my C# leaning, no idea what language you're using. These concepts should translate to other languages, though, I'm just not as familiar with syntax.


答: You should read your chosen database's documentation more carefully. In LMDB, readers are entirely lockless and wait-free, so your entire "if a database locks" premise is invalid.</p>

Title: Identical Databases for Multiple Users Reading Efficiency

Body:
Our project utilizes a static database (no writes). With many users we don't actually have a problem per se reading it. If a database "locks" per read request by any user, then would it not be more efficient (though perhaps unnoticeable) to have multiple databases that each user connects to individually?

We are database noobs. Apologies in advance if this is in the wrong place. We are planning on using BoltDB or LMDB for our project, but personally I was intrigued by this idea.


问:
How are scripting languages compiled?
I know the term "scripting languages" is just a subset of programming languages, but I want to refer to programming languages such as Python and Ruby among others.

First of all, why don't we need a compiler for these languages? For example, IDEs like Visual Studio or Eclipse have their own compiler in order to translate the code and execute the program. What does it mean for a programming language to be interpreted and how are they (Python, Ruby) compiled before execution in the terminal without a compiler?

Also, when we install Python or Ruby in our computers before we start coding, what are we actually installing? packages? files? something that lets our computer understand the language?

答:
What does it mean for a programming language to be interpreted and how are they compiled before execution in the terminal?

Compilers and interpreters are very similar things, right up until the last step.  For a compiler, the last step is to generate code in the output language and save it.  For an interpreter, it's not trying to save your code; it's trying to execute it immediately.  It does this by breaking down the program into basic semantic commands, much like the compiler does, and then executing those commands via a runtime that implements them in software.

2) Also, when we install Python or Ruby in our computers before start coding, what are we actually installing? packages? files? something that lets our computer understand the language?

Generally speaking, you're installing the interpreter and the standard libraries.  Most likely some basic tools (such as a REPL, in the case of many scripting languages) get installed too as part of the standard package.

Title: How are scripting languages compiled?


问:
What is the UML idiom for classes that are too big to fit into one box?
I am documenting an existing system using UML 2, and a few of the classes are too big to comfortably fit into a single class box.

So far, I've resorted to breaking up the class into multiple boxes with the same header, with (cont'd) annotation added. This is supposed to represent a single Foo class with four public members a,b,c,d.

```<code>+---------+   +--------------+
|   Foo   |   | Foo (cont'd) |
+---------+   +--------------+
| +a      |   | +c           |
| +b      |   | +d           |
+---------+   +--------------+  (etc.)
</code>```

Is there a standardized UML idiom that can be used to denote this?

答:
No, there isn't a standardized approach for UML to support this.

Personally, I would even say that I wouldn't recommend doing this. Instead, I'd ask yourself why your class has so many members that it doesn't fit. It could be indicative of a poor design (too many attributes or operations on a class could indicate low cohesiveness), or it could be indicative of showing too much detail on your diagram (depending on the target audience and purpose, you may not need to show every member on every class). However, it may be fine and normal, especially since you don't say how many members the class has or how you are displaying the class diagram.


问:
Name of this pattern to wrap functionality
I have a system that allows certain functionality to be implemented different ways, but requires that the functionality of each implementing class be wrapped in another layer. For example, each implementor has a doFoo method that interacts with an API. The implementor classes can be loaded at runtime (they are, essentially, plugins for hooking into different APIs), and thus the set of possible implementors is not fixed and cannot simply be handled by a switch or an enum-like structure.

But each time one of the implementor classes executes its doFoo method, I also need to ensure that additional, method-specific code occurs before and after (think system-wide logging, error-handling, and input and output sanity-checking that are the same for all implementors).

I have the following basic setup:

an interface, FooInterface

an abstract class FooAbstract that implements FooInterface and sets up some default actions.

a concrete class Foo that extends FooAbstract. Foo serves as a kind of factory/bridge class that instantiates an implementor and adds its own code when calling any of the implementor's methods

concrete classes FooImplementorABC, FooImplementorXYZ, etc., each of which extends FooAbstract.

That way, when a user wants to use the ABC implementation of FooInterface, the user calls new Foo('ABC'). The Foo constructor instantiates the right implementor and the implementor's code as necessary.

Example code (sample code only; the real classes are more complex and are all broken into files and autoloaded appropriately):

```<code><?php
interface FooInterface
{
    public function doFoo();
    public function doBar();
    public function doGenericThing();
}

abstract class FooAbstract implements FooInterface
{
    abstract public function doFoo();
    abstract public function doBar();

    public function doGenericThing()
    {
        echo "Doing something generic\n";
    }
}

class Foo extends FooAbstract
{
    /** @var FooAbstract */
    private $implementor;

    /**
     * The constructor for this class accepts an implementation name.
     * It then attempts to instantiate the appropriate implementor
     * class.
     *
     * @param $implementationName String
     */
    public function __construct($implementationName)
    {
        $implementorClassName = 'FooImplementor' . $implementationName;
        try {
            if (class_exists($implementorClassName)) {
                $this->implementor = new $implementorClassName(); // Yes, this works in PHP! One of its best or worst features, depending on your perspective.
            } else {
                throw new Exception("ERROR: No implementation for $implementationName found!");
            }
        } catch (Exception $e) {
            echo "\n\n{$e->getMessage()}\n\n";
        }
    }

    public function doFoo()
    {
        echo "Doing Foo\n";
        // Do some stuff
        $this->implementor->doFoo();
        // Do some stuff
        echo "Done with Foo\n\n";
    }

    public function doBar()
    {
        echo "Doing Bar\n";
        // Do some stuff
        $this->implementor->doBar();
        // Do some stuff
        echo "Done with Bar\n\n";
    }
}

class FooImplementorABC extends FooAbstract
{
    public function doFoo()
    {
        echo "Foo Implementor ABC just did Foo!\n";
    }

    public function doBar()
    {
        echo "Foo Implementor ABC just did Bar!\n";
    }
}

class FooImplementorXYZ extends FooAbstract
{
    public function doFoo()
    {
        echo "Foo Implementor XYZ just did Foo!\n";
    }

    public function doBar()
    {
        echo "Foo Implementor XYZ just did Bar!\n";
    }
}

$myFooABC = new Foo('ABC');
$myFooXYZ = new Foo('XYZ');

$myFooABC->doFoo();
$myFooXYZ->doFoo();
$myFooABC->doBar();
$myFooXYZ->doBar();

$myFooQRS = new Foo('QRS'); // displays an error message
</code>```

All of this works just fine; the methods all get wrapped correctly, the implementation details are unimportant to the consumer, etc.

My questions are:

Is this a pattern or an anti-pattern?

If it's a pattern, is there a name for it? I can't figure out what it would be. It seems to me like a hybrid of the factory, bridge, and decorator patterns.

If it's an anti-pattern, why? How is this going to bite me down the road?

答:
Foo seems to be both a factory and a decorator(*). By the Single Responsibility Principle that could be an anti-pattern and you may want to split it (e.g. what if some day you want an implementation of FooInterface but don't want Foo's additions?)

Moreover I don't see what's the abstract class for. Maybe in PHP you can't implement directly an interface?

(*) many patterns look similar and differ only by intent. I'm not too good at distinguishing them, but I don't see a bridge.


问:
What's the big-O complexity of this recursive algorithm?
I am following a course of Algorithms and Data Structures.

Today, my professor said the complexity of the following algorithm is 2^n.

I waited till the lesson was over, approached him and told him I actually believed it was an O(n) algorithm, and I did the computation to prove it, and wanted to show them to it, but he continued to say it was not, without giving me any convincing explanation.

The algorithm is recursive, and its recurrence relation is:

```<code>       { 1         if n=1
T(n) = {
       { 2T(n/2)   otherwise
</code>```

I computed it down to be a O(n), this way:

Let's expand T(n)

```<code>T(n) = 2 [2 * T(n/(2^2))]
     = 2^2 * T(n/(2^2))
     = 2^2 * [2 * T(n/(2^3))]
     = 2^3 * T(n/(2^3))
     = ...
     = 2^i * T(n/(2^i)).
</code>```

We stop when the term inside the T is 1, that is:

n/(2^i) = 1  ==>  n = 2^i  ==>  i = log n

After the substitution, we obtain

```<code>T(n) = 2^log n * T(1)
     = n * 1
     = O(n).
</code>```

Since this algorithm jumped out of a lesson on Merge Sort, I noted how Merge Sort, which notoriously is O(n log n) has a complexity of 2T(n/2) + theta(n) (obviously major then 2T(n/2)), and I asked him why is it, that an algorithm with a lower complexity, gets a higher big-O. Because, at this point, it's counter intuitive for me. He replied, words for words, "If you think that is counter-intuitive, you have serious problem in your math."

My questions are:

Is there any fallacy in my demonstration?

Wouldn't the last situation be counter-intuitive?

答:
"The algorithm is recursive, and it has this complexity: ..."

From the formulation of your question it seems that the function T(n) is not the algorithm to be analyzed but its complexity. In your proof you show that, indeed, the function T behaves asymptotically as an exponential function.

Then the fallacy could be that you are trying to prove the wrong thing. In other words:

You are right that computing T takes linear time (maybe even less, logarithmic time I guess).

Your professor is right in saying that the complexity of the original algorithm, whose complexity is expressed by T, is exponential.


答:
First of all, to analyze the complexity of a simple, recursive algorithm, the first stop would be the Master Theorem, where we match your expression T(n) = 2·T(n/2) against the schema T(n) = a·T(n/b) + f(n). By comparing coefficients, we can see that a = 2, b = 2, f(n) = x for some constant x. The Master Theorem then gives us the complexity depending on whether certain relations between the coefficients hold.

Here, the case applies where there exists a c such that f(n) = O(n^c) and c < log_b a, with c = 0 (f(n) = O(1) = O(n^0) and 0 < log_2 2 <=> 0 < 1). Therefore, the Master Theorem tells us that T(n) = Theta(n^(log_b a)) = Theta(n), so that also T(n) = O(n) holds. In other words, you are right.

Your proof checks out, but to be really convincing you should use the proof by induction technique. You've essentially used induction but have not clearly labeled each step, which makes it a bit hard to follow (and, you did it backwards – you should start with the base case T(1), then show that the property holds for T(n+1) for any n rather than starting with the general case and working towards the base case).

Title: What's the big-O complexity of this recursive algorithm?

Body:
I am following a course of Algorithms and Data Structures.

Today, my professor said the complexity of the following algorithm is 2^n.

I waited till the lesson was over, approached him and told him I actually believed it was an O(n) algorithm, and I did the computation to prove it, and wanted to show them to it, but he continued to say it was not, without giving me any convincing explanation.

The algorithm is recursive, and its recurrence relation is:

```<code>       { 1         if n=1
T(n) = {
       { 2T(n/2)   otherwise
</code>```

I computed it down to be a O(n), this way:

Let's expand T(n)

```<code>T(n) = 2 [2 * T(n/(2^2))]
     = 2^2 * T(n/(2^2))
     = 2^2 * [2 * T(n/(2^3))]
     = 2^3 * T(n/(2^3))
     = ...
     = 2^i * T(n/(2^i)).
</code>```

We stop when the term inside the T is 1, that is:

n/(2^i) = 1  ==>  n = 2^i  ==>  i = log n

After the substitution, we obtain

```<code>T(n) = 2^log n * T(1)
     = n * 1
     = O(n).
</code>```

Since this algorithm jumped out of a lesson on Merge Sort, I noted how Merge Sort, which notoriously is O(n log n) has a complexity of 2T(n/2) + theta(n) (obviously major then 2T(n/2)), and I asked him why is it, that an algorithm with a lower complexity, gets a higher big-O. Because, at this point, it's counter intuitive for me. He replied, words for words, "If you think that is counter-intuitive, you have serious problem in your math."

My questions are:

Is there any fallacy in my demonstration?

Wouldn't the last situation be counter-intuitive?


答:
In object-oriented programming, this would probably have the closest resemblance to the Strategy pattern due to subclassing with the same semantics but with potentially different algorithms.

the strategy pattern (also known as the policy pattern) is a software design pattern that enables an algorithm's behavior to be selected at runtime.

There are some elements of the Decorator pattern in that you are wrapping the chosen strategy algorithm's call with some code on the base class.

the decorator pattern (also known as Wrapper, an alternative naming shared with the Adapter pattern) is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.

The implementation of the decorator pattern is not ideal, since you can only attach one decorator... the one that's wired into the base class. But if that's all you need, fine.

The combination of patterns might be more effectively achieved another way (although I'm unsure which oo constructs PHP has available). For instance, an interface is typically used for the strategy pattern so the same methods can be called no matter the actual object underneath. The decorator could be implemented a number of ways, but one way is to have a wrapper class which takes both an interface for the strategy, and the decorators which wrap the call to the interface.

Title: Name of this pattern to wrap functionality

Body:
I have a system that allows certain functionality to be implemented different ways, but requires that the functionality of each implementing class be wrapped in another layer. For example, each implementor has a doFoo method that interacts with an API. The implementor classes can be loaded at runtime (they are, essentially, plugins for hooking into different APIs), and thus the set of possible implementors is not fixed and cannot simply be handled by a switch or an enum-like structure.

But each time one of the implementor classes executes its doFoo method, I also need to ensure that additional, method-specific code occurs before and after (think system-wide logging, error-handling, and input and output sanity-checking that are the same for all implementors).

I have the following basic setup:

an interface, FooInterface

an abstract class FooAbstract that implements FooInterface and sets up some default actions.

a concrete class Foo that extends FooAbstract. Foo serves as a kind of factory/bridge class that instantiates an implementor and adds its own code when calling any of the implementor's methods

concrete classes FooImplementorABC, FooImplementorXYZ, etc., each of which extends FooAbstract.

That way, when a user wants to use the ABC implementation of FooInterface, the user calls new Foo('ABC'). The Foo constructor instantiates the right implementor and the implementor's code as necessary.

Example code (sample code only; the real classes are more complex and are all broken into files and autoloaded appropriately):

```<code><?php
interface FooInterface
{
    public function doFoo();
    public function doBar();
    public function doGenericThing();
}

abstract class FooAbstract implements FooInterface
{
    abstract public function doFoo();
    abstract public function doBar();

    public function doGenericThing()
    {
        echo "Doing something generic\n";
    }
}

class Foo extends FooAbstract
{
    /** @var FooAbstract */
    private $implementor;

    /**
     * The constructor for this class accepts an implementation name.
     * It then attempts to instantiate the appropriate implementor
     * class.
     *
     * @param $implementationName String
     */
    public function __construct($implementationName)
    {
        $implementorClassName = 'FooImplementor' . $implementationName;
        try {
            if (class_exists($implementorClassName)) {
                $this->implementor = new $implementorClassName(); // Yes, this works in PHP! One of its best or worst features, depending on your perspective.
            } else {
                throw new Exception("ERROR: No implementation for $implementationName found!");
            }
        } catch (Exception $e) {
            echo "\n\n{$e->getMessage()}\n\n";
        }
    }

    public function doFoo()
    {
        echo "Doing Foo\n";
        // Do some stuff
        $this->implementor->doFoo();
        // Do some stuff
        echo "Done with Foo\n\n";
    }

    public function doBar()
    {
        echo "Doing Bar\n";
        // Do some stuff
        $this->implementor->doBar();
        // Do some stuff
        echo "Done with Bar\n\n";
    }
}

class FooImplementorABC extends FooAbstract
{
    public function doFoo()
    {
        echo "Foo Implementor ABC just did Foo!\n";
    }

    public function doBar()
    {
        echo "Foo Implementor ABC just did Bar!\n";
    }
}

class FooImplementorXYZ extends FooAbstract
{
    public function doFoo()
    {
        echo "Foo Implementor XYZ just did Foo!\n";
    }

    public function doBar()
    {
        echo "Foo Implementor XYZ just did Bar!\n";
    }
}

$myFooABC = new Foo('ABC');
$myFooXYZ = new Foo('XYZ');

$myFooABC->doFoo();
$myFooXYZ->doFoo();
$myFooABC->doBar();
$myFooXYZ->doBar();

$myFooQRS = new Foo('QRS'); // displays an error message
</code>```

All of this works just fine; the methods all get wrapped correctly, the implementation details are unimportant to the consumer, etc.

My questions are:

Is this a pattern or an anti-pattern?

If it's a pattern, is there a name for it? I can't figure out what it would be. It seems to me like a hybrid of the factory, bridge, and decorator patterns.

If it's an anti-pattern, why? How is this going to bite me down the road?


答:
The algorithm will have execution time of O ((log n)^2), because there will be log n steps doubling a number of n bits. The result is O (n). It is easily shown by complete induction that T (n) ≤ n, assuming that n/2 means floor (n/2).

As far as intuition goes, if T (n) = O (2^n) then T (1000) should be around 2^1000. But then T (1000) = 2 * T (500) which should be around 2^501... Slight difference.

Of course n = O (2^n) by the definition of Big-O.

I might suspect that maybe the recursion isn't actually posted here correctly if what your professor says is so off the mark.


问:
quantitatively comparing AST shapes
How could one compare the shape of abstract syntax trees of similar source code programs (C, C++, Go, or anything compiled with GCC...)?

I guess that plagiarism detection on source code would use such techniques, but I have no idea of how would that be called...

For example, unification could be used to compare AST, but it gives only a boolean answer. I'm seeking for some technique giving some numerical "distance", or some kind of numerical vectors (to be later feed up e.g. to machine learning or classification algorithms, or some other big data thing).

Any references to big data or machine learning approaches on large set of source code is welcome too.

(Sorry for such a broad or fuzzy question, I don't know what terminology to use)

I don't simply want to compare two ASTs or programs. I want to process a large set of programs (e.g. half of a Debian distribution source code) and find inside it similar routines. I already have MELT to work on GCC internal representations (Gimple) and I want to leverage above that, hence store several metrics (which ones? cyclomatic complexity is probably not enough) in e.g. some database and compare & process them...

Addenda: Found about the MOSS system & paper, but it does not seem to care about syntactic shape at all. Also looking into tree edit distance.

Found also (thanks to Jérémie Salvucci) Michel Chilowicz's PhD thesis (in French, november 2010) on Looking for Similarity in Source Code

答:
One approach would be to compile the source to XML and then look at how different the two bits of source are.  For example, in the Java world, the static analysis tool pmd does this as its approach to looking for things to warn about.

class Example {
 void bar() {
  while (baz)
   buz.doSomething();
 }
}
```

<p>gets 'compiled' to:</p>

<pre class="lang-none prettyprint-override"><code>CompilationUnit
 TypeDeclaration
  ClassDeclaration:(package private)
   UnmodifiedClassDeclaration(Example)
    ClassBody
     ClassBodyDeclaration
      MethodDeclaration:(package private)
       ResultType
       MethodDeclarator(bar)
        FormalParameters
       Block
        BlockStatement
         Statement
          WhileStatement
           Expression
            PrimaryExpression
             PrimaryPrefix
              Name:baz
           Statement
            StatementExpression:null
             PrimaryExpression
              PrimaryPrefix
               Name:buz.doSomething
              PrimarySuffix
               Arguments
</code>```

And that point you would be comparing code by saying "the difference between this code and that code is that this name is different."  As the above is actually xml, this could be done with any number of xml comparison tools that exist.  Or if you were after a number, one could apply a tree edit distance algorithm on it (related SO question).

Another approach is to look at the 'signature' of the code shape. The Signature Survey was done by Ward Cunningham

That legend is a bit hard to read:

14m means 14 methods

294L is 294 lines.

. is a non blank line

' is a comment

| (green) is a single line if statement.

(.) (green) is a single statement inside an if block

[(.)] (brown) is a single statement inside of an if inside a loop.

{.} is a method with a single statement.

[.] (red) is a single statement inside a loop

([.]) (dark red) is a single statement inside a loop inside an if block.

Comparing two sets of code then is looking at the edit distance between two strings with a very limited language.

Title: quantitatively comparing AST shapes

Body:
One approach would be to compile the source to XML and then look at how different the two bits of source are.  For example, in the Java world, the static analysis tool pmd does this as its approach to looking for things to warn about.

class Example {
 void bar() {
  while (baz)
   buz.doSomething();
 }
}

gets 'compiled' to:

CompilationUnit
 TypeDeclaration
  ClassDeclaration:(package private)
   UnmodifiedClassDeclaration(Example)
    ClassBody
     ClassBodyDeclaration
      MethodDeclaration:(package private)
       ResultType
       MethodDeclarator(bar)
        FormalParameters
       Block
        BlockStatement
         Statement
          WhileStatement
           Expression
            PrimaryExpression
             PrimaryPrefix
              Name:baz
           Statement
            StatementExpression:null
             PrimaryExpression
              PrimaryPrefix
               Name:buz.doSomething
              PrimarySuffix
               Arguments

And that point you would be comparing code by saying "the difference between this code and that code is that this name is different."  As the above is actually xml, this could be done with any number of xml comparison tools that exist.  Or if you were after a number, one could apply a tree edit distance algorithm on it (related SO question).

Another approach is to look at the 'signature' of the code shape. The Signature Survey was done by Ward Cunningham

That legend is a bit hard to read:

14m means 14 methods

294L is 294 lines.

. is a non blank line

' is a comment

| (green) is a single line if statement.

(.) (green) is a single statement inside an if block

[(.)] (brown) is a single statement inside of an if inside a loop.

{.} is a method with a single statement.

[.] (red) is a single statement inside a loop

([.]) (dark red) is a single statement inside a loop inside an if block.

Comparing two sets of code then is looking at the edit distance between two strings with a very limited language.

ContentLicense: CC BY-SA 4.0


问:
"Comments are a code smell"
A coworker of mine believes that any use of in-code comments (ie, not javadoc style method or class comments) is a code smell.  What do you think?

答:
Ideally, code should be so well coded that it should be auto explicative. In the real world, we know that also very high quality code needs sometimes commenting.

What you should absolutely avoid is "comment-code redundancy" (comments that don't add anything to code):

```<code>i++; // Increment i by 1
</code>```

Then, if there's a good (and maintained/aligned) code design and documentation, commenting is even less useful.

But in some circumstances comments can be a good aid in code readability:

```<code>while( foo )
{
     if( dummy )
     {
     }
     else // !dummy
     {
     }
} // end while( foo )
</code>```

Don't forget that you have to maintain and keep in sync also comments... outdated or wrong comments can be a terrible pain! And, as a general rule, commenting too much can be a symptom of bad programming.

ContentLicense: CC BY-SA 2.5

Title: "Comments are a code smell"

Body:
Ideally, code should be so well coded that it should be auto explicative. In the real world, we know that also very high quality code needs sometimes commenting.

What you should absolutely avoid is "comment-code redundancy" (comments that don't add anything to code):

i++; // Increment i by 1

Then, if there's a good (and maintained/aligned) code design and documentation, commenting is even less useful.

But in some circumstances comments can be a good aid in code readability:

while( foo )
{
     if( dummy )
     {
     }
     else // !dummy
     {
     }
} // end while( foo )

Don't forget that you have to maintain and keep in sync also comments... outdated or wrong comments can be a terrible pain! And, as a general rule, commenting too much can be a symptom of bad programming.


答:
I want to answer a small part of your question, that is nonetheless very interesting:

Is it possible to use a fold (also known as reduce) operation for this?

Yes, it is.

In fact, it is always possible to use a fold for anything! Fold is a general operation for iteration, anything you can do with iteration, you can do with fold!

The Wikipedia page for fold has a sketch of a proof for this, but I want to give another intuition thanks to a talk by Rúnar Óli Bjarnason on Functional Programming for Beginners which unfortunately seems to have vanished from the interwebs.

A collection can be either empty or not empty. The two arguments to fold tell it what to do when the collection is empty, and what to do with the next element when the collection is not empty. That covers all the cases, so it should be intuitively clear, that fold can do anything.

Another view, thanks to that same talk, is of fold as an interpreter. Think of a collection as a series of instructions. There are two kinds of instructions: the HALT instruction (which has no operands), and the NEXT instruction, which has one operand. The two arguments you supply to fold, are the two implementations of the interpreter functions for HALT and NEXT. Again, since there are only two instructions, and you supply the code for both of them, it comes as no surprise, that fold can do anything.

I actually put this to the test, and re-implemented many of the methods from Ruby's collection framework (the Enumerable module), which normally rely solely on the each method (a foreach-style iterator which simply yields each element), so that they instead all rely on the inject method (which is how Ruby spells "fold").

So, what does it look like with a fold in ECMAScript?

```<code>someArray.reduce((memo, el, i, ary) => memo && ary[0] === el, true)
</code>```

However, just because fold can do everything, it shouldn't be used for everything. When there are more appropriate, more specialized operations, these should be used instead:

```<code>someArray.every((el, i, ary) => ary[0] === el)
</code>```

Note: technically speaking, these two implementations do not check whether every element is equal to every other element, they only check whether every element is equal to the first element. Thus, it relies on === being transitive and symmetric (as a well-behaved equality should be). If you cannot rely on that, you should first build the Cartesian Product of the array with itself, map it to whether the two elements are equal, and then ask if everything is true:

```<code>someArray.reduce((memo, el, _, ary) => memo.concat(ary.map(ell => [el, ell])), []).
map(([a, b]) => a === b).
every(el => el)
</code>```

Title: Functional programming: Compare all items in an array

Body:
In functional programming, how do I do an equality comparison of all items in an array?

I have an array of items that I want to compare, for example for equality. Is it possible to use a fold (also known as reduce) operation for this?

This code won't work, because after the first iteration, memo is a boolean:

```<code>[a, b, c].reduce((memo, item) => memo === item)
</code>```

I've tried this variant, which returns the last item if they are equal, but this is no good, since I need a boolean as the result:

```<code>[a, b, c].reduce((memo, item) => (memo === item) && item)
</code>```

Forcing a boolean !! is no good either, since the item itself may be falsy and so give the wrong result.

I would like to have a functional solution to this problem – saving the result outside of the fold is much more verbose.

Body:
I want to answer a small part of your question, that is nonetheless very interesting:

Is it possible to use a fold (also known as reduce) operation for this?

Yes, it is.

In fact, it is always possible to use a fold for anything! Fold is a general operation for iteration, anything you can do with iteration, you can do with fold!

The Wikipedia page for fold has a sketch of a proof for this, but I want to give another intuition thanks to a talk by Rúnar Óli Bjarnason on Functional Programming for Beginners which unfortunately seems to have vanished from the interwebs.

A collection can be either empty or not empty. The two arguments to fold tell it what to do when the collection is empty, and what to do with the next element when the collection is not empty. That covers all the cases, so it should be intuitively clear, that fold can do anything.

Another view, thanks to that same talk, is of fold as an interpreter. Think of a collection as a series of instructions. There are two kinds of instructions: the HALT instruction (which has no operands), and the NEXT instruction, which has one operand. The two arguments you supply to fold, are the two implementations of the interpreter functions for HALT and NEXT. Again, since there are only two instructions, and you supply the code for both of them, it comes as no surprise, that fold can do anything.

I actually put this to the test, and re-implemented many of the methods from Ruby's collection framework (the Enumerable module), which normally rely solely on the each method (a foreach-style iterator which simply yields each element), so that they instead all rely on the inject method (which is how Ruby spells "fold").

So, what does it look like with a fold in ECMAScript?

someArray.reduce((memo, el, i, ary) => memo && ary[0] === el, true)

However, just because fold can do everything, it shouldn't be used for everything. When there are more appropriate, more specialized operations, these should be used instead:

someArray.every((el, i, ary) => ary[0] === el)

Note: technically speaking, these two implementations do not check whether every element is equal to every other element, they only check whether every element is equal to the first element. Thus, it relies on === being transitive and symmetric (as a well-behaved equality should be). If you cannot rely on that, you should first build the Cartesian Product of the array with itself, map it to whether the two elements are equal, and then ask if everything is true:

someArray.reduce((memo, el, _, ary) => memo.concat(ary.map(ell => [el, ell])), []).
map(([a, b]) => a === b).
every(el => el)


问:
What is the pattern that uses multiple instances rather than multiple classes called? When would I use it?
Sometimes I find it useful to have a single class with multiple instances (configured differently via their properties), rather than multiple classes (inheritance).

??? Pattern

Single class (Fruit)

Different fruit are instances of Fruit, with properties configured correctly.

Behavior implemented as blocks.

```<code>class Fruit {
    var name: String
    var color: UIColor
    var averageWeight: Double
    var eat: () -> ()
}

class FruitFactory {
    static func apple() -> Fruit {
        let fruit = Fruit()
        fruit.name = "Apple"
        fruit.color = UIColor.redColor()
        fruit.averageWeight = 50
        fruit.eat = {
            washFruit(fruit)
            takeBite(fruit)
        }
        return fruit
    }

    static func orange() -> Fruit {
        let fruit = Fruit()
        fruit.name = "Orange"
        fruit.color = UIColor.orangeColor()
        fruit.averageWeight = 70
        fruit.eat = {
            peelFruit(fruit)
            takeBite(fruit)
        }
        return fruit
    }
}
</code>```

Inheritance Pattern

For reference, the same could have been implemented using inheritance:

Multiple classes (Fruit, Apple, Orange)

Different fruit are classes that inherit from Fruit.

Behavior implemented using standard methods that are overridden in subclasses.

```<code>class Fruit {
    var name: String
    var color: UIColor
    var averageWeight: Double
    func eat() {
        // abstract method
    }
}

class Apple: Fruit {
    var name = "Apple"
    var color = UIColor.redColor()
    var averageWeight = 50

    override func eat() {
        washFruit(self)
        takeBite(self)
    }
}

class Orange: Fruit {
    var name = "Orange"
    var color = UIColor.orangeColor()
    var averageWeight = 70

    override func eat() {
        peelFruit(self)
        takeBite(self)
    }
}

class FruitFactory {
    static func apple() -> Fruit {
        return Apple()
    }

    static func orange() -> Fruit {
        return Orange()
    }
}
</code>```

What is the first pattern called?

Are there any resources to help me decide when to use one of these patterns over the other?

Off the top of my head, I can think of at least one reason to prefer inheritance:

Imagine we need to add a new property to Apple, but not to Orange (e.g. averageCoreWeight). If you use inheritance this is trivial. If you use the first pattern, you will be left with a property that is only sometimes used.

答:
What is the first pattern called?

The first pattern looks to be the Strategy pattern disguised as the Factory pattern. I assume your goal is to have different objects conforming to the interface of a Fruit, possibly implementing different algorithms and values for members.

the strategy pattern (also known as the policy pattern) is a software design pattern that enables an algorithm's behavior to be selected at runtime.

Protocols in Swift (called Interfaces in many other languages) are often used for the strategy pattern, since classes implementing a protocol do not otherwise have to have anything in common. They don't have to derive from the same base class or have the same members (other than what the protocol defines).

Are there any resources to help me decide when to use one of these patterns over the other?

The main way to help you decide about applying a pattern is to first be aware of various patterns. There are numerous books and online resources where patterns are cataloged and explained. Searching for software design patterns is a good start.

After you learn an interesting pattern, experience and judgement come into play in deciding where to use it. It is a trap to try to apply a given pattern indiscriminately. Yet, the prospect of trying something new is a siren's call that often leads us into choosing a pattern before the problem presents itself. Do better than me and avoid that mistake.


答:
When you have a base object that you then create modified copies of, you are using the Prototype pattern. The original object (the Fruit in this case) serves as a prototypical template from which you build your individual fruits. Because they all derive from the original Fruit class, they have a prototypical inheritance relationship (as originally noted by @coredump).

You don't specify what language you are using, but Javascript is built entirely using the prototypical model rather than the classical model for inheritance.

Title: What is the pattern that uses multiple instances rather than multiple classes called? When would I use it?

Body:
Sometimes I find it useful to have a single class with multiple instances (configured differently via their properties), rather than multiple classes (inheritance).

??? Pattern

Single class (Fruit)

Different fruit are instances of Fruit, with properties configured correctly.

Behavior implemented as blocks.

```<code>class Fruit {
    var name: String
    var color: UIColor
    var averageWeight: Double
    var eat: () -> ()
}

class FruitFactory {
    static func apple() -> Fruit {
        let fruit = Fruit()
        fruit.name = "Apple"
        fruit.color = UIColor.redColor()
        fruit.averageWeight = 50
        fruit.eat = {
            washFruit(fruit)
            takeBite(fruit)
        }
        return fruit
    }

    static func orange() -> Fruit {
        let fruit = Fruit()
        fruit.name = "Orange"
        fruit.color = UIColor.orangeColor()
        fruit.averageWeight = 70
        fruit.eat = {
            peelFruit(fruit)
            takeBite(fruit)
        }
        return fruit
    }
}
</code>```

Inheritance Pattern

For reference, the same could have been implemented using inheritance:

Multiple classes (Fruit, Apple, Orange)

Different fruit are classes that inherit from Fruit.

Behavior implemented using standard methods that are overridden in subclasses.

```<code>class Fruit {
    var name: String
    var color: UIColor
    var averageWeight: Double
    func eat() {
        // abstract method
    }
}

class Apple: Fruit {
    var name = "Apple"
    var color = UIColor.redColor()
    var averageWeight = 50

    override func eat() {
        washFruit(self)
        takeBite(self)
    }
}

class Orange: Fruit {
    var name = "Orange"
    var color = UIColor.orangeColor()
    var averageWeight = 70

    override func eat() {
        peelFruit(self)
        takeBite(self)
    }
}

class FruitFactory {
    static func apple() -> Fruit {
        return Apple()
    }

    static func orange() -> Fruit {
        return Orange()
    }
}
</code>```

What is the first pattern called?

Are there any resources to help me decide when to use one of these patterns over the other?

Off the top of my head, I can think of at least one reason to prefer inheritance:

Imagine we need to add a new property to Apple, but not to Orange (e.g. averageCoreWeight). If you use inheritance this is trivial. If you use the first pattern, you will be left with a property that is only sometimes used.


答:
From the database side no locks are held for SELECT statements.

Proposing to have multiple static databases is like proposing to use files like (spreadsheets or plain text) to have the data available to each user.

The whole concept of the database is to have a centralized repository for all users to "share" the same data-base.

If you database is huge and you will have an enormous amount of concurrent users you may have to think about clustering. But in your case, I think that's not an option.

If you read a little about LMDB and BoltDB, you'll see that they behave like mainframes, and the point there is to have a single repository, even more, a single file to hold all of your data.

When thinking about databases, think about centralizing the data and distributing the workload.

Hope this helps you clear out some clouds.


问:
implementation team - Inputs and outputs
I have questions regarding software development process,

Let's assume we have three teams

Business analysts

Implementation team

Quality assurance team

I think that Business analysts inputs is BRD (Business requirements)  from the client,
My question is regarding the implementation team  input (the engineers who actually code the software)

What is the input for the implementation team?

What documentation for new requirement?  is if FSD? Functional specification?

What documentation for a change request (client is requesting a system behavior modification )

What documentation for bug fixes?

Is there a document template or a methodology to follow?

Does Agile cover this topic?

答:
I assume your organization is not very sophisticated since you are asking these questions which are about how to manage requirements. Managing requirements is what makes or breaks a project.
You listed the three types of requirements.
Known Requirements -  (What the analyists provide)
-- I would suggest finding a template on goodle and using it.

Discovered Requirements - (Change requests)
Misunderstood or Missing Requirements - (Defects)
-- I suggest using a bug tracking tool like Bugzilla for both change requiests and defects since defects are really change requests (Change what didn't work with what does)


答:
Agile does not provide suggestions. It is perhaps the best and most strict way of thinking about creating something. See the Agile Manifesto.

Agile is not a methodology. Methodologies are based on Agile.

However, Agile methodologies are very hard to implement and requires buy in from everyone involved in the project to succeed.

Title: implementation team - Inputs and outputs

Body:
I have questions regarding software development process,

Let's assume we have three teams

Business analysts

Implementation team

Quality assurance team

I think that Business analysts inputs is BRD (Business requirements)  from the client,
My question is regarding the implementation team  input (the engineers who actually code the software)

What is the input for the implementation team?

What documentation for new requirement?  is if FSD? Functional specification?

What documentation for a change request (client is requesting a system behavior modification )

What documentation for bug fixes?

Is there a document template or a methodology to follow?

Does Agile cover this topic?


问:
How can I test my application for load balancing?
We are looking to implement a load balancer that will serve requests between 2 IIS servers.

I have been tasked with the project of making sure that it is a seamless integration, but I don't have load balancing myself on my dev machine.

How can I simulate a round-robin load balancing scenario on my dev system using IIS?

答:
When I had the task of testing our website for deployment to a load balanced environment, a duplicate test environment wasn't an option.

What we did was specify more than 1 Worker Process (aka a web garden) in IIS, found under the 'Process Model' group in 'Advanced Settings' for the appropriate application pool.

This worked a treat for us, with simple round robin behaviour.


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
adding object wrappers for extensions using resources (curl, ftp, gd2 ... ). Like </p>

```<code> $oFtp = new Ftp();

 $oFtp->connect();

 $oFtp->close();
</code>```

Body:
adding object wrappers for extensions using resources (curl, ftp, gd2 ... ). Like

 $oFtp = new Ftp();

 $oFtp->connect();

 $oFtp->close();