问:
Is creating subclasses for specific instances a bad practice?
Consider the following design

```<code>public class Person
{
    public virtual string Name { get; }

    public Person (string name)
    {
        this.Name = name;
    }
}

public class Karl : Person
{
    public override string Name
    {
        get
        {
            return "Karl";
        }
    }
}

public class John : Person
{
    public override string Name
    {
        get
        {
            return "John";
        }
    }
}
</code>```

Do you think there is something wrong here? To me Karl and John classes should be just instances instead of classes as they are exactly the same as :

```<code>Person karl = new Person("Karl");
Person john = new Person("John");
</code>```

Why would I create new classes when instances are enough? The classes does not add anything to the instance.

答:
There is no need to have specific subclasses for every person.

You're right, those should be instances instead.

Goal of subclasses: to extend parent classes

Subclasses are used to extend the functionality provided by the parent class. For example, you may have:

A parent class Battery which can Power() something and can have a Voltage property,

And a subclass RechargeableBattery, which can inherits Power() and Voltage, but can also be Recharge()d.

Notice that you can pass an instance of RechargeableBattery class as a parameter to any method which accepts a Battery as an argument. This is called Liskov substitution principle, one of the five SOLID principles. Similarly, in real life, if my MP3 player accepts two AA batteries, I can substitute them by two rechargeable AA batteries.

Note that it is sometimes difficult to determine whether you need to use a field or a subclass to represent a difference between something. For example, if you have to handle AA, AAA and 9-Volt batteries, would you create three subclasses or use an enum? “Replace Subclass with Fields” in Refactoring by Martin Fowler, page 232, may give you some ideas and how to move from one to another.

In your example, Karl and John don't extend anything, nor do they provide any additional value: you can have the exactly same functionality using Person class directly. Having more lines of code with no additional value is never good.

An example of a business case

What could possibly be a business case where it would actually make sense to create a subclass for a specific person?

Let's say we build an application which manages persons working in a company. The application manages permissions too, so Helen, the accountant, cannot access SVN repository, but Thomas and Mary, two programmers, cannot access accounting-related documents.

Jimmy, the big boss (founder and CEO of the company) have very specific privileges no one has. He can, for example, shut down the entire system, or fire a person. You get the idea.

The poorest model for such application is to have classes such as:

because code duplication will arise very quickly. Even in the very basic example of four employees, you will duplicate code between Thomas and Mary classes. This will push you to create a common parent class Programmer. Since you may have multiple accountants as well, you will probably create Accountant class as well.

Now, you notice that having the class Helen is not very useful, as well as keeping Thomas and Mary: most of your code works at the upper level anyway—at the level of accountants, programmers and Jimmy. The SVN server doesn't care if it's Thomas or Mary who needs to access the log—it only needs to know whether it's a programmer or an accountant.

if (person is Programmer)
{
    this.AccessGranted = true;
}
```

<p>So you end up removing the classes you don't use:</p>

<p>          <img src="https://i.stack.imgur.com/YAbmY.png" alt="The class diagram contains Accountant, Programmer and Jimmy subclasses with its common parent class: abstract Person."></p>

<p>“But I can keep Jimmy as-is, since there would always be only one CEO, one big boss—Jimmy”, you think. Moreover, Jimmy is used a lot in your code, which actually looks more like this, and not as in the previous example:</p>

<pre class="lang-cs prettyprint-override"><code>if (person is Jimmy)
{
    this.GiveUnrestrictedAccess(); // Because Jimmy should do whatever he wants.
}
else if (person is Programmer)
{
    this.AccessGranted = true;
}
</code>```

The problem with that approach is that Jimmy can still be hit by a bus, and there would be a new CEO. Or the board of directors may decide that Mary is so great that she should be a new CEO, and Jimmy would be demoted to a position of a salesperson, so now, you need to walk through all your code and change everything.

Body:
There is no need to have specific subclasses for every person.

You're right, those should be instances instead.

Goal of subclasses: to extend parent classes

Subclasses are used to extend the functionality provided by the parent class. For example, you may have:

A parent class Battery which can Power() something and can have a Voltage property,

And a subclass RechargeableBattery, which can inherits Power() and Voltage, but can also be Recharge()d.

Notice that you can pass an instance of RechargeableBattery class as a parameter to any method which accepts a Battery as an argument. This is called Liskov substitution principle, one of the five SOLID principles. Similarly, in real life, if my MP3 player accepts two AA batteries, I can substitute them by two rechargeable AA batteries.

Note that it is sometimes difficult to determine whether you need to use a field or a subclass to represent a difference between something. For example, if you have to handle AA, AAA and 9-Volt batteries, would you create three subclasses or use an enum? “Replace Subclass with Fields” in Refactoring by Martin Fowler, page 232, may give you some ideas and how to move from one to another.

In your example, Karl and John don't extend anything, nor do they provide any additional value: you can have the exactly same functionality using Person class directly. Having more lines of code with no additional value is never good.

An example of a business case

What could possibly be a business case where it would actually make sense to create a subclass for a specific person?

Let's say we build an application which manages persons working in a company. The application manages permissions too, so Helen, the accountant, cannot access SVN repository, but Thomas and Mary, two programmers, cannot access accounting-related documents.

Jimmy, the big boss (founder and CEO of the company) have very specific privileges no one has. He can, for example, shut down the entire system, or fire a person. You get the idea.

The poorest model for such application is to have classes such as:

because code duplication will arise very quickly. Even in the very basic example of four employees, you will duplicate code between Thomas and Mary classes. This will push you to create a common parent class Programmer. Since you may have multiple accountants as well, you will probably create Accountant class as well.

Now, you notice that having the class Helen is not very useful, as well as keeping Thomas and Mary: most of your code works at the upper level anyway—at the level of accountants, programmers and Jimmy. The SVN server doesn't care if it's Thomas or Mary who needs to access the log—it only needs to know whether it's a programmer or an accountant.

if (person is Programmer)
{
    this.AccessGranted = true;
}

So you end up removing the classes you don't use:

“But I can keep Jimmy as-is, since there would always be only one CEO, one big boss—Jimmy”, you think. Moreover, Jimmy is used a lot in your code, which actually looks more like this, and not as in the previous example:

if (person is Jimmy)
{
    this.GiveUnrestrictedAccess(); // Because Jimmy should do whatever he wants.
}
else if (person is Programmer)
{
    this.AccessGranted = true;
}

The problem with that approach is that Jimmy can still be hit by a bus, and there would be a new CEO. Or the board of directors may decide that Mary is so great that she should be a new CEO, and Jimmy would be demoted to a position of a salesperson, so now, you need to walk through all your code and change everything.


答:
It's silly to use this kind of class structure just to vary details which should obviously be settable fields on an instance. But that is particular to your example.

Making different Persons different classes is almost certainly a bad idea - you'd have to change your program and recompile every time a new Person enters your domain. However, that doesn't mean that inheriting from an existing class so that a different string is returned somewhere isn't sometimes useful.

The difference is how you expect the entities represented by that class to vary. People are almost always assumed to come and go, and almost every serious application dealing with users is expected to be able to add and remove users at run-time. But if you model things like different encryption algorithms, supporting a new one is probably a major change anyway, and it makes sense to invent a new class whose myName() method returns a different string (and whose perform() method presumably does something different).

ContentLicense: CC BY-SA 3.0

Title: Is creating subclasses for specific instances a bad practice?

Body:
Consider the following design

```<code>public class Person
{
    public virtual string Name { get; }

    public Person (string name)
    {
        this.Name = name;
    }
}

public class Karl : Person
{
    public override string Name
    {
        get
        {
            return "Karl";
        }
    }
}

public class John : Person
{
    public override string Name
    {
        get
        {
            return "John";
        }
    }
}
</code>```

Do you think there is something wrong here? To me Karl and John classes should be just instances instead of classes as they are exactly the same as :

```<code>Person karl = new Person("Karl");
Person john = new Person("John");
</code>```

Why would I create new classes when instances are enough? The classes does not add anything to the instance.


答:
Why would I create new classes when instances are enough?

In most cases, you wouldn't. Your example is really a good case where this behaviour doesn't add real value.

It also violates the Open Closed principle, as the subclasses basically aren't an extension but modify the parent's inner workings. Moreover, the public constructor of the parent is now irritating in the subclasses and the API thus became less comprehensible.

However, somtimes, if you will only ever have one or two special configurations that are often used throughout the code, it is sometimes more convenient and less time consuming to just subclass a parent that has a complex constructor. In such special cases, I can see nothing wrong with such an approach. Let's call it constructor currying j/k


问:
Does this diagram give a good representation of the MVVM pattern?
I am having a really hard time understanding the basic structure of the Model, View, View Model pattern.

I have honestly been pretty ignorant of design pattern conventions until recently. My formal education is in web media, so I got into programming through Javascript. Lately, though, I've been building a complex game design from scratch as an exercise to build my skills. It's interface will need to be rather extensive, with numerous outputs and controls required. These controls may need to affect the Model, the View, or both.

I arrived at MVVM after researching MVC at the suggestion of a friend. MVC looked like it would get rather messy, with all the different views and controls I'll have. At first I was under the impression that MVVM was simply an MVC with many views in mind but I have had a very hard time nailing down a definition, or even a literal structure.

That being said, I have created the following diagram in an effort to visualize my thoughts. This is meant to represent the basic structure & event propagation of the MVVM pattern, as per my understanding of it.

To explain my understanding in words, I would say:

The Model holds the actual data and simulation itself with no control or visibility. A View Model translates information between the Model and View, and has multiple Controllers within it for input and output. The Binder listens for updates to either the Model or the View Model and notifies each item's paired partner(s) of changes. A View is just a "dumb" output given by a View Model and modified by its Controllers.

As my understanding goes, I'd like to compare View Models to the game data. For example, the game Model holds all the data like player position, and then a state machine/loop acts on and modifies this data. Is this similar to View Model/View Controller relationship? Wherein the View Model would control instantiation and data storage (the View), while the Controllers handle state?

Is this an accurate representation of MVVM, and/or is it a good design pattern for a game design?

Or put another way, what are the ways my representation differs from the paradigm, that I might want/need to alter?

Aside, do I use an additional "Controller" for physical/offscreen inputs (such as keyboard input), or do I put it in the View Controller? (With Javascript, detection of keyboard input will be tied to the View surface anyways (ex. canvas.addEventListener("keyup", func(ev)))

I hope that my text and graphical descriptions do not differ in their implications. If they do please let me know.

Update: I am seeing (now) that it looks like most MVVM implementations don't "require" the View Controller as I have it here. I really just don't get it, I guess. Anyways I'll gladly update this with a fixed diagram if anyone can help me get around my vast ignorance. I think this is a great way to show design patterns, if I only I knew what it actually was!

答:
You're mixing MVC and MVVM here a bit.

Simply spoken:

In MVVM, you create an abstract representation of your View independent of the UI technology in use and bind your concrete (UI technology dependent- ) view to it with some sort of glue code.

MVC simply means: the view has a strategy pattern to communicate with the model and is an observer of the model. This strategy pattern is called "Controller"

The Model holds the actual data itself with no control or visibility.

The model is not only data. The model is your business logic. Most people get it wrong. It's not just a collection of data attributes encapsulated into classes, it is also behaviour.

I am seeing (now) that it looks like most MVVM implementations don't
"require" the View Controller as I have it here. I really just don't
get it, I guess.

Your thoughts are not so wrong. You want to put InputProcessors (You call them controllers) into your ViewModel. This is OK for a game, but if you want to implement the pattern as purely as possible, you'd bind keyboard commands to actions which are present in your ViewModel. So you'd bind them from concrete view (keyevent) to ViewModel(action).

ContentLicense: CC BY-SA 4.0


答:
In some cases you know there will only be a set number of instances and then it would kind of OK (although ugly in my opinion) to use this approach. It is better to use an enum if the language allows it.

Java example:

```<code>public enum Person
{
    KARL("Karl"),
    JOHN("John")

    private final String name;

    private Person(String name)
    {
        this.name = name;
    }

    public String getName()
    {
        return this.name;
    }
}
</code>```

Body:
In some cases you know there will only be a set number of instances and then it would kind of OK (although ugly in my opinion) to use this approach. It is better to use an enum if the language allows it.

Java example:

public enum Person
{
    KARL("Karl"),
    JOHN("John")

    private final String name;

    private Person(String name)
    {
        this.name = name;
    }

    public String getName()
    {
        return this.name;
    }
}


问:
Does internal state "leak" when it influences externally-visible behavior?
I have a method (in C++) which generates a value based on a parameter and the parameters from previous calls. Calling it more than once with the same parameter may generate different values each time. For example:

```<code>public:

    int getValue(const int param)
    {
        int value = param ^ previousParam;
        previousParam = param;
        return value;
    }

private:

    int previousParam;
</code>```

Does it make sense to allow this method to be called on const objects? Is previousParam part of the object's internal state, or does it "leak" since the internal state affects the object's external behavior?

I think of this method like a generator that just creates a series of values on subsequent calls, rather than a method which modifies the object. The caller is not supposed to depend on a particular parameter generating a specific value. Would it be sensible to change the declarations to the following?

```<code>int getValue(const int param) const;
mutable int previousParam;
</code>```

答:
I think that depends on the semantics of the object.

If it is a random number generator or similar, RandGen say, then what would it mean for a RandGen object to be const? Is the object usable at all if it were const?

For example, you might have a member method to set the seed, which I would consider should be non-const. Then it might make sense for getValue to be const:

```<code>void setSeed(long seed);
</code>```

Another example might be a function which accepts a RandGen object and checks whether its internal param is "sufficiently random". We likely do not want isSufficientlyRandom to call getValue, and so getValue might be non-const here:

```<code>bool isSufficientlyRandom(const RandGen& randGen) {
    return randGen.getPreviousParam() > 17;
}
</code>```

Body:
I think that depends on the semantics of the object.

If it is a random number generator or similar, RandGen say, then what would it mean for a RandGen object to be const? Is the object usable at all if it were const?

For example, you might have a member method to set the seed, which I would consider should be non-const. Then it might make sense for getValue to be const:

void setSeed(long seed);

Another example might be a function which accepts a RandGen object and checks whether its internal param is "sufficiently random". We likely do not want isSufficientlyRandom to call getValue, and so getValue might be non-const here:

bool isSufficientlyRandom(const RandGen& randGen) {
    return randGen.getPreviousParam() > 17;
}


问:
Decision making and maintenance
I'm trying to find an elegant way to implement a decision making algorithm that allow easy maintenance because the conditions for the decision making might change often.

I'm going to try and be more specific with an example here :

Let's say I'm trying to manage a team of Cooking chefs in a restaurant kitchen.

Every chef knows how to cook 3 types of pies : Apple pie, pumpkin pie and raspberry pie and 2 types of pizza : cheese pizza and bacon pizza. They all know how to cook everything.

Now, I would like to send orders to these chief regarding what's coming for the clients.

The conditions are :

A chief can only cook one pie at a time. If I order a chef to cook an apple pie for example, I cannot order him to cook a raspberry pie or a pumpkin pie unless the apple pie is done or I send an cancel request for the apple pie.

I can ask a chef to cook up to 5 pizzas at a time, given it's for different clients.

I woud like to create an algorithm that returns the set of orders I'm allowed to send to a specific chef, regarding what he already is cooking.

I'm working with c++. I could write a simple switch/case statement, but the maintenance would not be easy if conditions change or new pies are added, and so...

I'm kinda stuck and really don't see how I could encapsulate the conditions and decision making to decrease couplign beetween conditions and to allow easy maintenance on the conditions of pie cooking.

How would you handle complexe decision making algorithm implementation?

答:
The data consists of Chefs, Orders and a single Schedule.  Note that Chefs rarely change, but Orders are constantly being created, removed and optionally edited, and the Schedule has to change in response.

The logic for the new Schedule really depends on all of the data including Chefs, Orders and the old Schedule.  For that reason you really need to keep the scheduling logic together in a single place such as a Scheduler class.

Using test-driven development is really well suited to this problem.  Start by writing unit tests for the simple cases and then build up to more complex ones where the Chefs already have stuff in their queue and then new orders come in or get removed or edited.  Then in your Scheduler class, just write the most straightforward logic you can think of to express the rules.  You are completely free to use whatever internal architecture or structure you want.  Don't get too complicated or tricky.  Whenever you see an opportunity to make the logic simpler and easier to understand, do it, and just make sure all your tests still pass.

Now when you want to make a change, you add a new test case, and modify existing no-longer-correct test cases, and then you modify the logic of Scheduler until all the tests pass again.  In this way you know you won't break existing assumptions or logic.

I have used this successfully on several similar problems.

Title: Decision making and maintenance


问:
Why can't a server continue to act on a request after sending the response?
Say for example I've got a RESTful webservice, and I need to support creating a widget via a POSTed http request. I need to

Deserialize the POSTed widget.

Validate the deserialized widget.

Persist the widget to a backing service.

Send a success response back to the client.

Now, the problem is that my SLA does not allow 3 to block 4--persistence in this case takes too long and the client needs to know right away that the request has succeeded (this is the standard use case for the 202 http status code).

Almost everywhere I look, the assumption is that the way to solve this is to "background" the expensive persistence part. This is typically an awkward process with many moving parts and often its own latency (e.g. making a blocking call to a separate queuing service).

Simply parallelizing 3 and 4 using native constructs is generally out of the question, as is switching the order so that 4 blocks 3. As near as I can tell, this is mainly because the web and app servers are built with the fundamental assumption that a process (and any children it's forked off) is free to be killed/reused as soon as it's sent its response. Or, equivalently, that the response can't be sent until the app has finished doing everything it's going to do.

This is intensely frustrating to me! In any other context, I can do what I like with the program's control flow. But when I'm running a Phusion Passenger -> Ruby on Rails setup, and I want to do a thing after I send the response, I'm left with a wide variety of baroque options that all seem to consider it perfectly natural and acceptable to, say, serialize the application state, post it to Amazon SQS, have basically separate web service that polls SQS, deserializes the old application state, then do the thing. I had application state all set up the way I wanted it after sending the response! Why isn't anything written so I can just do

```<code>def create
  widget = Widget.new(params[:widget])
  if widget.valid?
    respond_with(widget)
    widget.save
  else
    respond_with(widget.errors)
  end
end
</code>```

Why is there a pervasive assumption that web service stacks will never support this kind of flow? Is there a hidden drawback, or tradeoff, to making it possible to do this?

答:
Is there a hidden drawback, or tradeoff, to making it possible to do this?

Yes. The benefit of constraining everything to a request-response cycle is that the framework and web server can automatically free up any resources held up by the request, e.g. memory, network connections, database transaction and database connection, processes, file handles, worker process, etc. Writing high-quality long-lived daemons/servers are very hard, because any resource leaks in a long-lived processes will amplify over time and could bring a server that has been running fine for weeks to a halt for no apparent reason. Tying resources to request-response cycle would allow automatic cleanup not only when your code is in the happy path, but also when it get the rare, unexpected exceptions. This reduces the burden for application developer, instead cleanups can be left to the framework, where they can be done in a systematic, consistent manner.

Also, having requests continue to be processed after the response finishes opens up the possibility that the request will fail after the response is terminated (say, the persistence server has gone missing or it has full disk or your web server runs out of memory and is ungracefully terminated by the kernel's OOM killer), and now since you're outside the request-response cycle, the error message can no longer be delivered to the user. You can certainly engineer your way out of these situations, say by creating a status resource for the user agent to check the status of Accepted but not completed requests, that requires a lot of thoughts and engineering but that's exactly how 202 is meant to be used. Note that 202 does not specify how the status should be checked. It is possible that a 202 response would ask the client to poll the status resource, or to open a Websocket connection to the resource, etc. You're free to do what's best for your situation.

Many resources that could leak in long-lived daemons sometimes just isn't obvious, and writing your application in high-level languages with automatic garbage collectors doesn't really solve all of it.

Going back to your question:

Is there a hidden drawback, or tradeoff, to making it possible to do this?

When you break out of the request-response cycle, you are now on your own. While it is certainly possible to write a server that doesn't follow the request-response cycle, this is extremely hard to do and require lots of engineering. There are a limited number of architectural pattern which can solve the problems of long-lived daemons satisfactorily, request-response is one of the simplest and easiest to use, and simple == good.

There are other architectures which allows you to do work after request-response cycle has finished which works well with request-response paradigm. This usually revolves around message passing. With message passing, after persisting data and just before you terminate the response off, you send a command to worker processes to process the data that has just been submitted, usually through a message queue service. This gives you the advantage of a clean separation between the web server processes which processes short, interactive requests that need to respond message as quickly as possible, from the background workers which takes a long time to finish and is much less sensitive delays (interesting tidbit: many process scheduler algorithms inside kernels have heuristics to detect whether a process looks like an interactive process or a batch-oriented processes and schedules them differently, the former usually gets priority for low latency interrupts, the latter gets longer time slices).

TL;DR. The constraint of request-response cycle is a good thing, try to work with it rather than against it.

the response can't be sent until the app has finished doing everything it's going to do.

That isn't correct. Most decent web framework should also support HTTP chunked Transfer-Encoding which can return partial data to the client while the rest of the data is still being calculated.


问:
How do I compile my software for all platforms from Ubuntu Linux 64 bit?
I write a lot of open source software that I make available on my website.   How do I get my software compiled for all relevant platforms including:

Windows

OS X

Linux 32 bit deb

Linux 64 bit deb

Linux 32 bit rpm

Linux 64 bit rpm

etc

I currently only have Linux 64 bit boxes, so I can only compile the 64 bit deb and rpm myself.   I'm relying on users contributing other versions.   That isn't ideal because the versions are not all available right after a new release.  Indeed the Windows binary is several versions behind at this point.

Edit: My software is QQWing. It is written in C++. I would love to have a build system that can generate binaries for all platforms, or have a place to run builds for multiple systems.

答:
GCC is able to compile both 32-bit and 64-bit on the same machines using the -m32 and -m64 flags, respectively (source). Of course, your code should also be tested to make sure there are no bugs introduced between 32 and 64 bits.

You can cross-compile your code into a Windows executable using Wine libraries. The mingw libraries provide compilers that act similarly to gcc, while outputting a Windows-compatible (technically a Wine-compatible) binary. You could have a command like i586-mingw32msvc-gcc -Wall "main.c" -o "Program.exe" to compile your program (source). There are differences between Wine and Windows, so there may be subtle and unexpected bugs from using this method. Once again, thorough testing is critical.

You can see the answers at this SO question for suggestions on how to compile for the Mac.

Disclaimer: I've never used any of these in a production capacity, so YMMV.


答:
If this is the extent of the practice, then I agree this is a bad practice.

If John and Karl have different behaviors, then things change a little bit. It could be that person has a method for cleanRoom(Room room) where it turns out that John is a great roommate and cleans very effectively, but Karl is not and doesn't clean the room very much.

In this case, it would make sense to have them be their own subclass with the behavior defined. There are better ways to achieve the same thing (for example, a CleaningBehavior class), but at least this way isn't a terrible violation of OO principles.


问:
Separating Code into Smaller Files in C
I am in the process of cleaning up my code and making it easier to maintain. I am doing this by turning my 5000+ line file into separate smaller files.

I have successfully created separate source and header files for obvious things like utilities and other components that are not tightly integrated with the application.

I am now thinking it would be good to break up the rest of my application into smaller files also. But the issue mostly concerning me is that everything that is left uses a bunch of Structs that are Globally declared.

So this is the choice moving forward (happy to hear other suggestions also):

1) I could leave everything in the same file and that way I could just define all functions as static (which has its benefits, and is often recommended). It is then a simple choice to leave the Globals at the top of this large source file.

OR

2) I could separate into smaller files. It is relatively simple to work out which parts should go into which new files. It is also not too difficult to work out the structural hierarchy (which parts call which parts). But I am uncertain on how best to deal with all these Globals. Where should they be placed, since every function uses them in some way?

NOTE: I am aware that the use of Globals should be avoided. However this is an embedded device with limited memory. Globals are the best way to reduce memory usage, and the more memory I save, the more I can perform a certain task.

答: I would recommend typedef-ing all the structs, and putting those declarations in a separate include file. Then define all your actual instances of the structs in whatever your "main" file ends up being. Then, simply include the header and declare the needed instances extern in the other files. The linker will take care of matching up all the references, it shouldn't be any problem at all.

Title: Separating Code into Smaller Files in C


答:
const only "guarantees" that an object's members don't change. Nothing stops you from making const methods that depend on mutable state outside of the object (e.g. a global variable). However, most people expect const to mean that the object's state won't change when you call const methods on it. Since you're not supposed to know about an object's members, and since you can cheat with the mutable keyword, its state is effectively what it returns from its methods. Thus a const method that changes what the object returns in future calls will definitely surprise people.

If you want a "generator" that returns a sequence of values, then return a different non-const object (preferably an iterator) that contains your original object's state.

Title: Does internal state "leak" when it influences externally-visible behavior?

Body:
I have a method (in C++) which generates a value based on a parameter and the parameters from previous calls. Calling it more than once with the same parameter may generate different values each time. For example:

```<code>public:

    int getValue(const int param)
    {
        int value = param ^ previousParam;
        previousParam = param;
        return value;
    }

private:

    int previousParam;
</code>```

Does it make sense to allow this method to be called on const objects? Is previousParam part of the object's internal state, or does it "leak" since the internal state affects the object's external behavior?

I think of this method like a generator that just creates a series of values on subsequent calls, rather than a method which modifies the object. The caller is not supposed to depend on a particular parameter generating a specific value. Would it be sensible to change the declarations to the following?

```<code>int getValue(const int param) const;
mutable int previousParam;
</code>```


问:
RESTful API design. What should I return if there are no rows?
I'm currently coding an API for a social network with the Slim Framework. My question is: What are the best practices when there are no rows to return in the json structure?

Lets say that this call /v1/get/movies returns 2 rows from the table movie names:

```<code>[
    {"name": "Ghostbusters"},
    {"name": "Indiana Jones"}
]
</code>```

But, then I call /v1/get/books and there are no rows in that table. Should I just return an empty structure?

```<code>[
]
</code>```

...or would it be better a message and an error code?

```<code>[
    "errors": {
        "message": "no matches found",
        "code": 134
    }
]
</code>```

Which is a better practice? (the API will be used in iOS and Android apps) Thanks!

答:
You really should do only one of two things

Either
Return a 200 (OK) status code, and an empty array in the body.

Or
Return a 204 (NO CONTENT) status code and NO response body.

To me, option 2 seems more technically correct and keeping in line with REST and HTTP principles.

However, option 1 seems more efficient for the client - because the client does not need extra logic to differentiate between two (success) status codes. Since it knows that it will always receive an array, it simply has to check for whether it got none, one, or many items and process it appropriately


答:
Part of software development is managing complexity. By specifying multiple output targets, you are adding complexity. Asking that there "must be an easier way" in this case is a bit like the Simpsons episode where the lady asks "put all the groceries in one bag, and don't make it heavy!".

If you have complexity, sometimes it's better to manage it correctly, rather than trying to reduce it.

One solution would be to use Vagrant to define a virtual machine specification for each of your target platforms. This would include OS, compiler, and whatever other tools are required.

Then, use a build tool such as Jenkins, TeamCity, Bamboo, etc. to to create build plans for each of your platforms. Link these build plans to your source repository (this is basic CI, and execute them all when changes occur.

Now, you not only have multi-platform support, but you have a build process that both works, and is self-documenting. This way, you don't have the issue where you spend a bunch of hours configuring a real machine to build on Windows, then when the hard drive fails six months later, you've forgotten how you got it all working, and have to start over.

Title: How do I compile my software for all platforms from Ubuntu Linux 64 bit?

Body:
I write a lot of open source software that I make available on my website.   How do I get my software compiled for all relevant platforms including:

Windows

OS X

Linux 32 bit deb

Linux 64 bit deb

Linux 32 bit rpm

Linux 64 bit rpm

etc

I currently only have Linux 64 bit boxes, so I can only compile the 64 bit deb and rpm myself.   I'm relying on users contributing other versions.   That isn't ideal because the versions are not all available right after a new release.  Indeed the Windows binary is several versions behind at this point.

Edit: My software is QQWing. It is written in C++. I would love to have a build system that can generate binaries for all platforms, or have a place to run builds for multiple systems.


答:
There are three good reasons to not make getValue const.

Principle of least astonishment - I would find it very, very surprising to discover that a const method caused an externally visible change in the behavior of the object (even if I'm not supposed to depend on a particular parameter generating a specific value).

Logical versus physical const - There's some discussion as to whether const should indicate logically constant (no change in the visible state or behavior) or physically constant (bitwise identical). getValue is obviously not physically const, and since the visible behavior changes, it's hard to see how you could make a case for logical const (even if callers aren't supposed to depend on a particular parameter generating a specific value).

const in C++11 - C++11 has tightened the semantics of const to mean, approximately, "usable in a thread-safe fashion." (This is an oversimplification; see here, here, and here for details and discussion.) getValue isn't thread-safe and so isn't be const in the sense C++11 expects const to mean.  (Whether you need to comply with this C++11 meaning of const depends on your application.)


答:
Some good answers here already, but I think there is something more to say about your "mental model" of the object, since you wrote

I think of this method like a generator that just creates a series of values on subsequent calls, rather than a method which modifies the object.

But since previousParam is a member of your object, the method actually does modify the object. However, in your mental model, previousParam seems not to be part of the object. So I guess your real problem is that the whole getValue method including the previousParam member is misplaced - it should probably be part of a different class, which provides an abstraction for your generator, and where getValue is naturally a non-const method.


问:
What is the normative (best) use of Javascript arguments object
JS offers the 'arguments' object inside of functions to represent all passed arguments. Is there any broadly accepted concept for when/where this should be used?

I've seen items like this in the 'wild' that seem like code smell to me:

```<code>function myFxn () {
  var myVar = arguments[0];
  // do something with myVar
}
</code>```

this is a very simplified example, but it illustrates what seems to me to be a poor coding practice. I would prefer

```<code>function myFxn (myVar) {
  // do something with myVar
}
</code>```

A colleague used it in a number of places where they only wanted to name the 'required' args ('required' by the implemenation ) but omit the 'optional' ones:

```<code>function myFxn (myReqVar) {
  var myOptVar = (arguments[1] !== undefined) ? arguments[1] : false;
  // do something with vars
}
</code>```

This didn't seem wise on grounds of reduced readability and maintainability. It seems to me to create functions with confusing interfaces that must rely on the developer's knowledge of its intent or external documentation to understand and use.

Is this just a matter of opinion, or is there a preponderance of opinion on this?

答:
The arguments object is useful for mimicking the behavior or overloaded methods, or creating functions that accept arbitrary numbers of arguments. A good native example is the Array#push method:

```<code>var x = [];
x.push(1, 2);
</code>```

Is the equivalent of:

```<code>var x = [];
x.push(1);
x.push(2);
</code>```

A good example of mimicking method overloading is the jQuery on method:

```<code>$("#foo").on("click", function(event) {
    // process the click event when "#foo" gets clicked
});

$("#foo").on("click", ".bar", function(event) {
    // process click event when any element with "bar" as one of its
    // classes gets clicked inside "#foo"
});
</code>```

It's the same method name (on) but the different numbers and types of arguments change the behavior of the method, giving you the impression that the on method has two overloads.

Body:
The arguments object is useful for mimicking the behavior or overloaded methods, or creating functions that accept arbitrary numbers of arguments. A good native example is the Array#push method:

var x = [];
x.push(1, 2);

Is the equivalent of:

var x = [];
x.push(1);
x.push(2);

A good example of mimicking method overloading is the jQuery on method:

$("#foo").on("click", function(event) {
    // process the click event when "#foo" gets clicked
});

$("#foo").on("click", ".bar", function(event) {
    // process click event when any element with "bar" as one of its
    // classes gets clicked inside "#foo"
});

It's the same method name (on) but the different numbers and types of arguments change the behavior of the method, giving you the impression that the on method has two overloads.


答:
I think you are right, the best practice would be to use parameters over var paramName = arguments[0] .  It is cleaner, easier to read and it shows the intent better.   As a general rule of thumb the arguments object should be used over params under a few scenarios:

There can be N number of params:

```<code>    function sum(){
    var total = 0;
    for (var i = 0; i < arguments.length; i++) {
        total += arguments[i];
    }
    return total;
}
</code>```

If you want to generically call other functions with the passed in arguments:

```<code>function other() {
    otherFunction.apply(this, arguments);
}

vs

function other(arg1, arg2, arg3) {
    otherFunction.call(this, arg1, arg2, arg3);
}
</code>```

Using reusable functions that use arguments:

Here is an example of a generic argument validating :
https://codereview.stackexchange.com/questions/31593/throwing-error-if-settings-arguments-are-undefined-is-this-a-good-breakout-fun/31602#31602

Title: What is the normative (best) use of Javascript arguments object

Body:
JS offers the 'arguments' object inside of functions to represent all passed arguments. Is there any broadly accepted concept for when/where this should be used?

I've seen items like this in the 'wild' that seem like code smell to me:

```<code>function myFxn () {
  var myVar = arguments[0];
  // do something with myVar
}
</code>```

this is a very simplified example, but it illustrates what seems to me to be a poor coding practice. I would prefer

```<code>function myFxn (myVar) {
  // do something with myVar
}
</code>```

A colleague used it in a number of places where they only wanted to name the 'required' args ('required' by the implemenation ) but omit the 'optional' ones:

```<code>function myFxn (myReqVar) {
  var myOptVar = (arguments[1] !== undefined) ? arguments[1] : false;
  // do something with vars
}
</code>```

This didn't seem wise on grounds of reduced readability and maintainability. It seems to me to create functions with confusing interfaces that must rely on the developer's knowledge of its intent or external documentation to understand and use.

Is this just a matter of opinion, or is there a preponderance of opinion on this?

Body:
I think you are right, the best practice would be to use parameters over var paramName = arguments[0] .  It is cleaner, easier to read and it shows the intent better.   As a general rule of thumb the arguments object should be used over params under a few scenarios:

There can be N number of params:

    function sum(){
    var total = 0;
    for (var i = 0; i < arguments.length; i++) {
        total += arguments[i];
    }
    return total;
}

If you want to generically call other functions with the passed in arguments:

function other() {
    otherFunction.apply(this, arguments);
}

vs

function other(arg1, arg2, arg3) {
    otherFunction.call(this, arg1, arg2, arg3);
}

Using reusable functions that use arguments:

Here is an example of a generic argument validating :
https://codereview.stackexchange.com/questions/31593/throwing-error-if-settings-arguments-are-undefined-is-this-a-good-breakout-fun/31602#31602


答:
This is an exception to the 'should be instances' here - although slightly extreme.

If you wanted the compiler to enforce permissions to access methods based on whether it is Karl or John (in this example) rather than ask the method implementation to check for which instance has been passed then you might use different classes. By enforcing different classes rather than instantiation then you make differentiation checks between 'Karl' and 'John' possible at compile time rather than run time and this might be useful - particularly in a security context where the compiler may be more trusted than run-time code checks of (for example) external libraries.


问:
Base Class, with method that returns Derived Class. design flaw?
I'm writing a Math equation solver in python (for fun).
The first design that came to my mind:

Expression: base class for every item in an equation (maybe bad name).

BinaryExpression extends Expression: two expressions with a sign.

Expression + Expression should provide a BinaryExpression, I do this through overriding the __add__ method of Expression.

this is sort of circular dependency, which me and python both hates.

```<code>class Expression(object):
    def __add__(self, other):
        return BinaryExpresison(self, OP.ADD, other)

class BinaryExpress(Expression):
    def __init__(self, op, other):
        pass # super and staff
</code>```

How would you do it?

答:
How would you do it?

I'm not familiar with Python, but that sort of construct to build a composite or decorator pattern is something I've done a few times (albeit in C# and C++). It makes for a very nice interface and very usable code.

As long as you consider the BinaryExpression and similar composite/decorators part of the core library/API that everyone will want/use, that design perfectly fine.


问:
When should something be a class? And are my chosen classes good OO design?
My background:

I am new to programming. Python is my only programming knowledge. I program as a hobby, and I'm teaching myself by reading copious amounts of books.

I understand enough about OOP to write OO software. However, I keep feeling uneasy about the things I write... The design seems messy, etc. And I'm unsure as to what should be a class, method, or function.

I have read OOP books such as, 'Object Oriented Thought'. Such books are useful, however, they always deal with easy topics such as making a 'blackjack' game. The applications that I want to write, however, are not based on easy-to-imagine, real world objects.

The application:

I am currently working on a project. The aim of the software is to download images and video from my favourite blogs. (eg, Google Blogger blogs, or WordPress hosted blogs.)

(Yes, it is easy to make, and I've already made it, but the problem is I want to learn  how to make elegant and properly designed OO software.)

Classes:

I have decided on the following classes:

API Client: This will make it easier to deal with sending and receiving various API requests.

BloggerClient, WordPressClient: I will inherit from a generic API Client class, so that I can specialize with specific APIs, eg. Google's, Tumblr's, and Wordpress' APIs.

Parser: A generic media parser. This will get the media from the blogs.

BloggerParser, WordPressParser: I will inherit from the generic Parser, so I can grab posts and media specific to each website.

Use Case:

I will present an example of getting images from a WordPress.com blog.

WordPressParser asks WordPressClient to get blog-posts from photography.wordpress.com

WordPressClient sends an API request to WordPress.

WordPress Client receives a response and sends the posts to WordPressParser.

WordPressParser parses the media links/urls from each blog-post.

The media links are downloaded to disk.

The problems:

I actually don't know if I have made good choices here.

For example, I need the media (photo and video) downloaded to disk. In this case should I make 'download_media()' methods in the Parser class, or is it better design to create a Downloader class?

'Parse' could easily be a method, instead I have used 'Parser', so it could easily be a class. I really don't know when something should be a class or a method.

Should there be a class for BlogPosts? It seems to me that blog-posts are objects (the equivalent to pages of a book, perhaps).

I seem to be taking verbs, 'download', 'parse', and then converting them to nouns in order to make them appear as valid classes.

I feel very lost and confused. Again, the purpose for me is to learn how to properly make and design OO software. I'm not looking just to get the program to work.

Here is the sourcecode for each of my classes so far:

API Client: http://pastebin.com/QRdPqM5F

Base Parser: http://pastebin.com/kV8gBEe6

Parser: http://pastebin.com/cC0yPYdK

In terms of extensibility, I will be adding more websites in the future, so I need something maintainable.

I hope someone could advise me as to what I'm doing wrong. You can view my source code in the links above to really see what I'm talking about.

Thank you!

答:
It really depends on where you're going. The reason to go with classes over method is classes are the starting point for some powerful OO patterns that you can take advantage of.

Take classes, add inheritance and polymorphism and now you can start taking advantage of contract based programming (i.e. Interfaces). This is very important. It allows you to define behavior abstractly and create clean lines of separation between the different parts of your code base. This is Inversion of Control (IoC). Your code should rely on abstractions/interfaces, not concrete classes.

Start programming against interfaces and you've decoupled the implementation of one piece of code from another. Now changing the code of one doesn't have to affect the other, as long as the contract doesn't change.

SOLID starts coming into play here, the Single Responsibility Principle (SRP) says that code should only have one reason to change. If your classes are separated cleanly that will be so.

Next the Open/Closed principle (OCP) states that your code should be open for extension and closed for modification. That means you can extend an interface, by making a new one that uses an old one, that way the old interface implementations are still valid. Similarly you can refactor what goes on in a concrete implementation of an interface as long as the input/output (our contract) stays the same.

Now that you have that separation you can do even more cool stuff like dependency injection and unit testing via mocked dependencies. With DI you structure your code so that all external dependencies are "injected" into the object via (typically) the constructor. The class should not do any service creation of it's own and rely on it's consumer to provide them. This is inline with the SRP. Doing this also gives you testability because now you can pass in mocked objects and isolate the testing to that class.

There are other things I could go into here, it's a very broad topic. But that's the high level. Basically, making your services into classes is a good idea if you think in any way that they could change or be done in a different way.  For instance, your download, it should definitely be it's own thing according the SRP. As to whether it should be a helper method or a class, ask yourself: Can I write this in a way that it will be consumed the same way by everything (input)? Are there other places you might want to download them to besides disk (output)? If you think there could be other cases, make it an interface with implementations that vary based on consumer. (You would retrieve that implementation with a factory).

Parser too benefits from being a class and/or interface because you can use polymorphism to vary the implementation at runtime based on what kind of thing you're parsing as you've started to do.

What you're missing here is that there should be one interface for Parser (or IParser by some typical standards). You want to have an IParser interface, a Parser base class that implements common code of all parsers, and concrete implementations of IParser that inherit from Parser, which would fulfill the contract in a site-specific manner. Then your main code path would use DI or a factory to get a concrete instance of IParser and do your work against that. Now it's only dependency is on the interface and none of the implementations, which again, makes refactoring, testing and maintainability much better.

I could go on but I feel like I've rambled enough. Hope this is helpful.


问:
Why should I use MSBuild instead of Visual Studio Solution files?
We're using TeamCity for continuous integration and it's building our releases via the solution file (.sln). I've used Makefiles in the past for various systems but never msbuild (which I've heard is sorta like Makefiles + XML mashup). I've seen many posts on how to use msbuild directly instead of the solution files but I don't see a very clear answer on why to do it.

So, why should we bother migrating from solution files to an MSBuild 'makefile'? We do have a a couple of releases that differ by a #define (featurized builds) but for the most part everything works.

The bigger concern is that now we'd have to maintain two systems when adding projects/source code.

UPDATE:

Can folks shed light on the lifecycle and interplay of the following three components?

The Visual Studio .sln file

The many project level .csproj files (which I understand an "sub" msbuild scripts)

The custom msbuild script

Is it safe to say that the .sln and .csproj are consumed/maintained as usual from within the Visual Studio IDE GUI while the custom msbuild script is hand-written and usually consumes the already existing individual .csproj "as-is"? That's one way I can see reduce overlap/duplicate in maintenance...

Would appreciate some light on this from other folks' operational experience

答:
Let me offer my take on this question.

Although you certainly can simply use your .SLN file as your 'build process', the file itself really doesn't constitute a build process.  The Solution file is really just a part of Visual Studio and is used for development.  But Visual Studio is only a part of the build and release process.  You can't rely on Solutions to manage your build, and Solutions certainly don't offer a scalable build situation.

The entire purpose of establishing a build process is to create reliable builds.  That is to say, the build process is so reliable that no matter the build configuration, you will get a predictable build output.  Every time, every machine.  The result of a predictable and reliable build is that the test, deployment, and release process can then be highly automated, further reducing the risk of human error.

Establishing a build process requires an investment, but in certain cases, the investment is required.  Here are some factors that favor an msbuild process:

Your product has multiple teams (cross-functional or otherwise) who are working in the same team project

Your organization has only one team project (should be the case for 99% of traditional shops, even those with 200+ developers)

You have more than 20 projects that need to be built, some of which have dependencies on others and are maintained by different teams

Your product incorporates multiple .NET technologies (C#, C++, VB, F#, ASP.NET, etc), or even non-.NET technologies (Grunt, node, npm, Java, etc)

Your product has heavyweight dependencies or is built on top of a heavyweight platform.  SharePoint, as an example

Let me give an example to expand on my last point.  My current company does SharePoint development.  SharePoint development at a minimum requires SharePoint foundation to be installed to perform builds on SharePoint projects.  Speaking in terms of a lightweight build server, it's completely impractical to require the build server to have SharePoint installed.  Not only is SharePoint a beast with high requirements but it would have serious performance implications on a build - and builds are supposed to be as fast and lean as possible.  Leveraging MSBuild allows me to eliminate this installation requirement on the build server.  In fact, our build server has no installation requirements other than the .NET framework (required by MSBuild) and Node.

As a reference, I would recommend checking out this book by Sayed Ibrahim Hashimi:
http://www.amazon.com/Inside-Microsoft-Build-Engine-Foundation/dp/0735645248/ref=sr_1_fkmr0_1?ie=UTF8&qid=1412014650&sr=8-1-fkmr0&keywords=msbuild+reliable+build


答:
WordPressParser asks WordPressClient to get blog-posts...

Is this really what a parser should do? Asking to get blog posts is not "parsing" by any definition of the term.

It's like scissors sending you an invitation to come over to your local barber shop. Now, scissors surely have their business in making it happen, but triggering this entire chain of events doesn't sound like something they should be in charge of.

For example, I need the media (photo and video) downloaded to disk. In
  this case should I make 'download_media()' methods in the Parser
  class, or is it better design to create a Downloader class?

I would create a separate class, because:

Downloading is a different responsibility than parsing - keep single responsibility principle in mind. It helps to keep track of which class does what as the project grows and allows to keep the code flexible - easy to change.

Different parsers may handle downloading in a similar, or even identical manner. By extracting this functionality into a separate class we can avoid code duplication, because the same Downloader implementation can be reused by different Parsers.

Should there be a class for BlogPosts? It seems to me that blog-posts
  are objects (the equivalent to pages of a book, perhaps).

If they are nothing but strings - sheer text - it might not be necessary, but the cost of creating a BlogPost class isn't all that high and at the very least it would make it explicit throughout your code that such and such variable represents a blog post and nothing else!

A good rule of thumb is to prefer domain specific types over primitive types. BlogPost means something. A piece of text could be just anything. We are only humans and using domain specific types helps us to write bug-free code, because we let the type system guard us against committing type mismatch offenses (eg. confusing a blog post's url link with blog post's content).

Disclaimer: I don't know Python, I approach the question as a universal OOD question. If there is something Python-specific that escapes me here, I'd be happy if someone points it out.

Title: When should something be a class? And are my chosen classes good OO design?

Body:
My background:

I am new to programming. Python is my only programming knowledge. I program as a hobby, and I'm teaching myself by reading copious amounts of books.

I understand enough about OOP to write OO software. However, I keep feeling uneasy about the things I write... The design seems messy, etc. And I'm unsure as to what should be a class, method, or function.

I have read OOP books such as, 'Object Oriented Thought'. Such books are useful, however, they always deal with easy topics such as making a 'blackjack' game. The applications that I want to write, however, are not based on easy-to-imagine, real world objects.

The application:

I am currently working on a project. The aim of the software is to download images and video from my favourite blogs. (eg, Google Blogger blogs, or WordPress hosted blogs.)

(Yes, it is easy to make, and I've already made it, but the problem is I want to learn  how to make elegant and properly designed OO software.)

Classes:

I have decided on the following classes:

API Client: This will make it easier to deal with sending and receiving various API requests.

BloggerClient, WordPressClient: I will inherit from a generic API Client class, so that I can specialize with specific APIs, eg. Google's, Tumblr's, and Wordpress' APIs.

Parser: A generic media parser. This will get the media from the blogs.

BloggerParser, WordPressParser: I will inherit from the generic Parser, so I can grab posts and media specific to each website.

Use Case:

I will present an example of getting images from a WordPress.com blog.

WordPressParser asks WordPressClient to get blog-posts from photography.wordpress.com

WordPressClient sends an API request to WordPress.

WordPress Client receives a response and sends the posts to WordPressParser.

WordPressParser parses the media links/urls from each blog-post.

The media links are downloaded to disk.

The problems:

I actually don't know if I have made good choices here.

For example, I need the media (photo and video) downloaded to disk. In this case should I make 'download_media()' methods in the Parser class, or is it better design to create a Downloader class?

'Parse' could easily be a method, instead I have used 'Parser', so it could easily be a class. I really don't know when something should be a class or a method.

Should there be a class for BlogPosts? It seems to me that blog-posts are objects (the equivalent to pages of a book, perhaps).

I seem to be taking verbs, 'download', 'parse', and then converting them to nouns in order to make them appear as valid classes.

I feel very lost and confused. Again, the purpose for me is to learn how to properly make and design OO software. I'm not looking just to get the program to work.

Here is the sourcecode for each of my classes so far:

API Client: http://pastebin.com/QRdPqM5F

Base Parser: http://pastebin.com/kV8gBEe6

Parser: http://pastebin.com/cC0yPYdK

In terms of extensibility, I will be adding more websites in the future, so I need something maintainable.

I hope someone could advise me as to what I'm doing wrong. You can view my source code in the links above to really see what I'm talking about.

Thank you!


问:
How do rails project know about rake tasks from other repositories
We have a rake task called db:sanity_check which exists in a 'core' repo.

Other repositories that we have also show this rake task.

But they do not define the rake task.  It 'comes' from core'

How do these other repositories know about the rake tasks from the 'core' repository ?

Is it because they include that repository in their Gemfile ?

I have a new repository that I want to have the db:sanity_check available for but I don't know how to have the reference to the task which exists in the other repo.

This is NOT about creating the task itself!

答: If it is a rails project and you set your 'core' repository as a gem in the Gemfile, then rake has access to the 'core' rake tasks.</p>


问:
recalculation model for GUIs
I often come across this problem.

Say to have a form with some controls:

```<code>A
B
C = A + B
D
E = C * 2 ONLY IF D==TRUE
F
G = A - F
</code>```

The user fills A, then B.

The system calculates C.

The user fills D (boolean)

The system calcluates E

The user fills F

The system calculates G

But now:

The user clears A

The system clears C, E and G

The user clears B

The system does nothing

The user inserts A

The system recalculates only F

And so on and on.

There clearly is a tree of dependences, and that's not difficult to understand.
But pragmatically i found quite difficult implement it without any 'framework' to model it.

Be them inputs in a HTML form or controls in a javafx application, the problem of creating a comprehensive 'recalculation' algorithm still remains.

(Javafx offers a 'binding' architecture that despite being a bit verbose, yet is very powerfull and addresses (part of) this specific issue.)
But i'm more interested in a methodology that can be used across the different platforms.
I use to use a bunch of tecniques to solve the issues that come across but not yet a methodology, that is a way to go from the definition to the implementation with the minimum amount of trials.

The tecniques are the good old: invalidations, lazy init, wrapping each control in a 'node' of a recalc-graph.

But i feel that there should be a more canonical approach to this recurrent problem, and a paper where this approach is explained and so on.
Can anyone suggest me where can i find such information?

EDIT 1: terms of the problem

One of the key goals of such a solution is to have a way to organize the code in a predictable way, so that, knowing the method, it should be easy to evaluate its correctness.

Initial state: many system fail to return to their initial state, that's the smell of a poor design that such methodology should prevent

It should be designed for real cases such as (hitting back to the example): when the user changes A, the system should clear B in the case in which they were coupled. It's easy to think of such cases: a user selects a contry and the system provides a list of regions for the user to choose one. If the user changes the city, the region previously chosen has to be cleared even if it's not strictly a dependent field since it's not calculated by the system.

As an example of a very partial solution:

Each control should have a backing 'update' method that should trigger only update of 'directly connected' controls. This hypothesis should guarantee that when C is based on A, A is always up-to-date.

function update_A() {
  update_C;
}

function update_B() {
  update_C;
}

function update_C() {
  C.setValue(A + B);
  update_E();
}

etc. etc.

since there mustn't be circular references, these update function should form a 'tree'.

Other contributes to come.

答:
Assuming the amount of recalculation is trivial, then some kind of Model-View-Controller structure would be appropriate:

The user changes B

The View notifies the Controller (via event, etc.) that B changed (or that something changed) and the Controller passes B (or everything editable) to the Model.

The Model updates internal values and exposes the values for G, etc.

The Controller copies the result values from the Model to the View.

That way, the dependency only exists in the Model.  The View is very dumb, and the Controller knows which fields are read/write and which are read-only, but knows nothing of interdependencies.

Edit:

I want to make a point of clarifying the term "Model".  There are typically more than one layer of Model in a program, even though we always just talk about "The Model".  In the case of a client application talking to a remote server, there is typically a Server Model and a Client Model.  If the client is a web browser then the Client Model might be written in JavaScript and the Server Model could be in any server-side language like C#, PHP, etc.

There's a natural question which arises: "Does this recalculation logic belong in the Client Model, the Server Model, or both?"  Since you can't trust the client, you're really forced to always implement the recalculation in the Server Model, and optionally implement it in the Client Model if you want to prevent unnecessary round-trips to the server.  Unfortunately this can end up violating the once-and-only-once principle, unless you're lucky enough to be working in a language/framework that allows you to re-use certain modules and logic in both the server and client side (Node.js?)

Title: recalculation model for GUIs


答:
The tecniques are the good old: invalidations, lazy init, wrapping
  each control in a 'node' of a recalc-graph.  But i feel that there
  should be a more canonical approach to this recurrent problem, and a
  paper where this approach is explained and so on. Can anyone suggest
  me where can i find such information?

I believe the canonical approach would be the state pattern.

Have a look at http://gameprogrammingpatterns.com/state.html, for instance.

Obviously it's not associated with game programming specifically, I just happen to like this particular explanation.

Especially suiting is the hierarchical state machine, where there is more interdependency between states.

Another resource, focused on hierarchical state machine specifically: http://www.eventhelix.com/realtimemantra/hierarchicalstatemachine.htm#.VCm9nPmSzOg

Each state knows what happens when it's switched on, what should happen when it's switched off. It can trigger other states, possibly causing a cascade of updates. This can allow for flexible and maintainable APis.

Take a look at this project, for example - written in my favorite programming language (C#): https://github.com/nblumhardt/stateless (I'm in no way associated with the project or its authors).

I don't mean the code, but the samples. They are clear and instructive, and so they can already serve as a good indication on how to implement the thing:

```<code>var phoneCall = new StateMachine<State, Trigger>(State.OffHook);

phoneCall.Configure(State.OffHook)
    .Permit(Trigger.CallDialed, State.Ringing);

phoneCall.Configure(State.Ringing)
    .Permit(Trigger.HungUp, State.OffHook)
    .Permit(Trigger.CallConnected, State.Connected);

phoneCall.Configure(State.Connected)
    .OnEntry(() => StartCallTimer())
    .OnExit(() => StopCallTimer())
    .Permit(Trigger.LeftMessage, State.OffHook)
    .Permit(Trigger.HungUp, State.OffHook)
    .Permit(Trigger.PlacedOnHold, State.OnHold);

// ...

phoneCall.Fire(Trigger.CallDialled);
Assert.AreEqual(State.Ringing, phoneCall.State);

// ...

phoneCall.Configure(State.OnHold)
    .SubstateOf(State.Connected)
    .Permit(Trigger.TakenOffHold, State.Connected)
    .Permit(Trigger.HungUp, State.OffHook)
    .Permit(Trigger.PhoneHurledAgainstWall, State.PhoneDestroyed);
</code>```

Neat, huh?

Title: recalculation model for GUIs

Body:
I often come across this problem.

Say to have a form with some controls:

```<code>A
B
C = A + B
D
E = C * 2 ONLY IF D==TRUE
F
G = A - F
</code>```

The user fills A, then B.

The system calculates C.

The user fills D (boolean)

The system calcluates E

The user fills F

The system calculates G

But now:

The user clears A

The system clears C, E and G

The user clears B

The system does nothing

The user inserts A

The system recalculates only F

And so on and on.

There clearly is a tree of dependences, and that's not difficult to understand.
But pragmatically i found quite difficult implement it without any 'framework' to model it.

Be them inputs in a HTML form or controls in a javafx application, the problem of creating a comprehensive 'recalculation' algorithm still remains.

(Javafx offers a 'binding' architecture that despite being a bit verbose, yet is very powerfull and addresses (part of) this specific issue.)
But i'm more interested in a methodology that can be used across the different platforms.
I use to use a bunch of tecniques to solve the issues that come across but not yet a methodology, that is a way to go from the definition to the implementation with the minimum amount of trials.

The tecniques are the good old: invalidations, lazy init, wrapping each control in a 'node' of a recalc-graph.

But i feel that there should be a more canonical approach to this recurrent problem, and a paper where this approach is explained and so on.
Can anyone suggest me where can i find such information?

EDIT 1: terms of the problem

One of the key goals of such a solution is to have a way to organize the code in a predictable way, so that, knowing the method, it should be easy to evaluate its correctness.

Initial state: many system fail to return to their initial state, that's the smell of a poor design that such methodology should prevent

It should be designed for real cases such as (hitting back to the example): when the user changes A, the system should clear B in the case in which they were coupled. It's easy to think of such cases: a user selects a contry and the system provides a list of regions for the user to choose one. If the user changes the city, the region previously chosen has to be cleared even if it's not strictly a dependent field since it's not calculated by the system.

As an example of a very partial solution:

Each control should have a backing 'update' method that should trigger only update of 'directly connected' controls. This hypothesis should guarantee that when C is based on A, A is always up-to-date.

function update_A() {
  update_C;
}

function update_B() {
  update_C;
}

function update_C() {
  C.setValue(A + B);
  update_E();
}

etc. etc.

since there mustn't be circular references, these update function should form a 'tree'.

Other contributes to come.

Body:
The tecniques are the good old: invalidations, lazy init, wrapping
  each control in a 'node' of a recalc-graph.  But i feel that there
  should be a more canonical approach to this recurrent problem, and a
  paper where this approach is explained and so on. Can anyone suggest
  me where can i find such information?

I believe the canonical approach would be the state pattern.

Have a look at http://gameprogrammingpatterns.com/state.html, for instance.

Obviously it's not associated with game programming specifically, I just happen to like this particular explanation.

Especially suiting is the hierarchical state machine, where there is more interdependency between states.

Another resource, focused on hierarchical state machine specifically: http://www.eventhelix.com/realtimemantra/hierarchicalstatemachine.htm#.VCm9nPmSzOg

Each state knows what happens when it's switched on, what should happen when it's switched off. It can trigger other states, possibly causing a cascade of updates. This can allow for flexible and maintainable APis.

Take a look at this project, for example - written in my favorite programming language (C#): https://github.com/nblumhardt/stateless (I'm in no way associated with the project or its authors).

I don't mean the code, but the samples. They are clear and instructive, and so they can already serve as a good indication on how to implement the thing:

var phoneCall = new StateMachine<State, Trigger>(State.OffHook);

phoneCall.Configure(State.OffHook)
    .Permit(Trigger.CallDialed, State.Ringing);

phoneCall.Configure(State.Ringing)
    .Permit(Trigger.HungUp, State.OffHook)
    .Permit(Trigger.CallConnected, State.Connected);

phoneCall.Configure(State.Connected)
    .OnEntry(() => StartCallTimer())
    .OnExit(() => StopCallTimer())
    .Permit(Trigger.LeftMessage, State.OffHook)
    .Permit(Trigger.HungUp, State.OffHook)
    .Permit(Trigger.PlacedOnHold, State.OnHold);

// ...

phoneCall.Fire(Trigger.CallDialled);
Assert.AreEqual(State.Ringing, phoneCall.State);

// ...

phoneCall.Configure(State.OnHold)
    .SubstateOf(State.Connected)
    .Permit(Trigger.TakenOffHold, State.Connected)
    .Permit(Trigger.HungUp, State.OffHook)
    .Permit(Trigger.PhoneHurledAgainstWall, State.PhoneDestroyed);

Neat, huh?


答:
It's considered a bad practice to have duplicated code.

This is at least partially because lines of codes and therefore size of codebase correlates to maintenance costs and defects.

Here's the relevant common sense logic to me on this particular topic :

1) If I were to need to change this, how many places would I need to visit? Less is better here.

2) Is there a reason why it is done this way?  In your example - there couldn't be - but in some examples there might be some kind of reason for doing this.  One I can think of off the top of my head is in some frameworks like early Grails where inheritance didn't necessarily play nicely with some of the plugins for GORM. Few and far between.

3) Is it cleaner and easier to understand this way?  Again, it isn't in your example - but there are some inheritance patterns that may be more of a stretch where separated classes is actually easier to maintain (certain usages of the command or strategy patterns come to mind).


问:
Java Serialization for long-ish-term storage
I have an application that uses a database of about 15,000 Java objects, which I have to read every time the application starts.  Originally I've been using JSON to store the data, but that has a few issues, mostly that it's slow (it can take 8-10 seconds to read all the objects on my lower-end machine) and also, it's very common for the objects in my database to have fields that point to the same object.  Java serialization handles this by using references to the same object, whereas with JSON, I just have to write the state of each object and then intern them during reading.  This also bloats the file size.

The contents of this database will be updated fairly infrequently (maybe about once a month or so).  I've heard from pretty much every source that Java serialization is always a poor choice for long-term storage, and I understand why.  Given these conditions, however, is there a good reason not to use Java serialization here?

答:
While you do not anticipate changing the nature of your objects now very much - needs change over time.

I would highly suggest you consider using protobuf or Apache Thrift or a similar design instead of relying on default Java serialization.

Their advantages include strong support for avoiding impact during minor version changes, significantly better serialization and deserialization speed and smaller footprint of objects.

When I do this, typically I include the message version as a field on the object.  This allows me to implement version-to-version changes during the serialization by wrapping that method, if that need should arise in the future.


答:
Well, why not start with a very simple approach? You have "level 0" fields where the user can enter values, "level 1" fields which only depend on "level 0" field, "level 2" fields depending on "level 1" or "level 0" fields, and so on. Behind each "level n" field with n>0 there is a function which takes care of incomplete input values (like C = f(A,B) with f(A,B) = A+B if A and B are numeric, and "no value" if not.

Now, whenever a "level 0" field is changed by a user, recalculate everything, and do this in the order of increasing levels 1, 2 3, ... and so on.

This is probably not the most efficient solution, but in a lot of real-world cases it is just efficient enough. It is the approach you should start with, and only if it turns out to be not fast enough, you should try to implement something more sophisticated. Otherwise you risk to run into the "premature optimization" trap.

Title: recalculation model for GUIs


问:
Method waits for user action
I have a structural problem for an application I'm working on.  In the interest of full disclosure, it is for a university assignment so I'm not looking for you to code me an answer, just help me think through the best approach.

I'm building a game using an OO approach.  I have an abstract class called Player from which several types derive.  These represent the computer and human players.  So I have a derived HumanPlayer class which must provide an implementation for a method called ChooseCard.  The way the user selects a card is by clicking on a card in a GUI.  So the card will be identified by the user through an event handler.

The relevant part of my code is listed below.  At the moment the Game class loops through each player and calls the PlayCard method on each Player.  I'm just not sure how to program the ChooseCard method in the HumanPlayer class so that it can wait for the user to select a card to play but have the UI remain responsive.   Ideally I want to be able to treat each of the derived player types the same (ie as the base class Player).

This question is asking basically the same thing I am but I don't really like the answers.

The answer to this question is interesting, using the TaskCompletionSource class.

I'm not fixed on this structure if there is a superior solution although I need to keep the class structure.

Edits:
Added a class diagram for the models of my application as well as a screenshot of what the gameboard looks like (currently).

Here is my current thinking:
The user will click on the card they want to play.  The click event will propagate to the bound CardViewModel (At this point the action could be handled at the Model or ViewModel layer).  Now the CardViewModel (or Card) doesn't know who is interested in knowing that the user selected it.  The interested party will be the PlayerViewModel/HumanPlayer to whom the Card belongs, but they will only be interested when they are expecting a response from the user.  I.e. when HumanPlayer.PlayCard() is called.

So I'm thinking that the CardViewModel/Card should raise an event to which the HumanPlayer object can subscribe to when it is interested in the user making a card selection.

I can make HumanPlayer.ChooseCard() subscribe to the CardSelected events of each of the cards.  I'm just not sure how to make the method wait without blocking until one of those events fires.

```<code>abstract public class Player
{
    public IReadOnlyList<Card> Cards { get { return cards.AsReadOnly(); } }

    public Card PlayCard()
    {
        var cardToPlay = ChooseCard();
        // ...
    }

    protected abstract Card ChooseCard();
}

public class HumanPlayer : Player
{
    protected override Card ChooseCard()
    {
        // TODO: request a card from the user.
        throw new NotImplementedException();
    }
}

public class Game
{
    private List<Player> livingPlayers = new List<Player>();

    public void PlayRound()
    {
        var cardsPlayedByPlayers = GetCardsPlayed();
        // ...
    }

    private Dictionary<Player, Card> GetCardsPlayed()
    {
        var cardsPlayedByPlayers = new Dictionary<Player, Card>();

        foreach (var player in livingPlayers.Where(p => !p.IsDead))
        {
            // Player.PlayCard() called here getting chosen card from the player.
            cardsPlayedByPlayers.Add(player, player.PlayCard());
        }

        return cardsPlayedByPlayers;
    }
}
</code>```

Update:

I've put the final code up on GitHub here since the assignment is over.  You can now see the full code clearly and if you would like to critique it, I'd be keen to hear your thoughts.

答:
You have the organization of the code "inside-out".  What you're trying to do is respond to a player having chosen a card but instead you're forcing it in the construction of the object which is an awkward place to block (most people don't expect constructors to be "heavy").

Here's your options within the game loop :

1) When evaluating the game loop - do so from a separate thread besides the UI thread and block that thread until the UI has finished choosing a card.  This allows you to use 'chooseCard' as a method on the player object - you'd remove it from the constructor and make the method public.

2) If you evaluate the game loop on the main thread then you're not really dealing with player objects but objects that represent the input (arguably you're doing that now already). If so then you should have a delegate or callback implemented that allows the Game loop to react to a "card-chosen" event rather than blocking on a list of objects for each one to complete.  Hence, the game loop would maintain in the main thread the state of all the cards chosen and only 'process them' once all participants have responded.

Of the two, the latter is probably more what you're looking for if you aren't a fan of multi-threading.

Title: Method waits for user action


问:
which pattern is most intuitive for a calculator app?
The title says it all. I'm trying to build a calculator application (for self-learning purposes). The application is going to have a very common UI, with plus(+), minus(-), multiply(*) and a divide(/) button. Also, the app can do, real-number as well as complex-number calculations.

So, the situation here is, depending upon the mode(normal or complex), the same button should perform different calculation ? Which pattern should I be using for this situation ? I feel, strategy pattern should be a good fit, but then, I don't exactly know how to implement that - I mean, I'm just not sure about how to design my classes, what to have as Interfaces, and what as delegates.

CURRENTLY, MY DESIGN CONTAINS

```<code>IOperation
{
  Do();
}
Add:IOperation{}
Subtract:IOperation{}
Multiply:IOperation{}
Divide:IOperation{}
Root:IOperation{} //not supported by ComplexNumber
ISupportedOperation
{
   IList<IOperation> SupportedOps {get;}
}
INumber : ISupportedOperation {}
RealNumber:INumber{}
ComplexNumber : INumber {}
</code>```

Interface names starts with I

All others are concrete classes

BUT IT'S A MESS. And, I'm totally lost within my own classes, and interfaces.

PS: Of course, I can do this using if/else, but that's not what I want to do. Not because I forcefully want to use a pattern, but because, those if-else will be scattered everywhere in the program for eg. ReadInput, PlusButtonClick, MinusButtonClick, etc. And, as I understand, design patterns are supposed to avoid these kind of situations of code-repetitions, by clever/tricky re-organization of the existing code.

PPS: Sorry for being too verbose.

答:
I'll take a different approach actually. I'll suggest you use a strategy pattern (pseudo code - been a while since I used C#).

```<code>class CalculatorContext {
   private List<Number> numberHistory;
   private Number currentDisplay;
   private List<Operation> commandHistory;
   private Operation currentCommand;

   public void evaluateAnswer(Operation op) {
       currentCommand = op;
       commandHistory.put(op);
       Number returnVal = currentCommand.execute(this);
       numberHistory.put(currentDisplay);
       currentDisplay = returnVal;
   }

   //Getters/setters.
}

interface Operation {
   public Number execute(CalculatorContext ctx);
}

class AddOperation : Operation {
   public Number execute(CalculatorContext ctx) {
      //Current number to add
      Number a = ctx.getCurrentDisplay();

      //Previous number to add
      assert(ctx.getNumberHistory() != null && ctx.getNumberHistory().size() > 1);
      Number b = ctx.getNumberHistory().last();

      return a + b;
    }
}
</code>```

The reason I like that approach is you could modify it to handle parenthesis pretty easy but also it reflects how a real calculator works (a current state then modified via operations).  In the method where you don't use a queue-like approach you then need to manage that in a different and much more painful way from the UI.  Things like square root become a problem, whereas here you only get "A", not A + B.  You could use a 'power' like above but the problem with that is - presumably - you don't want the CalculatorContext or the UI to be aware of the specifics of that operation.  So I'd probably handle it in the operation and if it became burdensome collecting the parameters I'd build helper methods for it.

Body:
I'll take a different approach actually. I'll suggest you use a strategy pattern (pseudo code - been a while since I used C#).

class CalculatorContext {
   private List<Number> numberHistory;
   private Number currentDisplay;
   private List<Operation> commandHistory;
   private Operation currentCommand;

   public void evaluateAnswer(Operation op) {
       currentCommand = op;
       commandHistory.put(op);
       Number returnVal = currentCommand.execute(this);
       numberHistory.put(currentDisplay);
       currentDisplay = returnVal;
   }

   //Getters/setters.
}

interface Operation {
   public Number execute(CalculatorContext ctx);
}

class AddOperation : Operation {
   public Number execute(CalculatorContext ctx) {
      //Current number to add
      Number a = ctx.getCurrentDisplay();

      //Previous number to add
      assert(ctx.getNumberHistory() != null && ctx.getNumberHistory().size() > 1);
      Number b = ctx.getNumberHistory().last();

      return a + b;
    }
}

The reason I like that approach is you could modify it to handle parenthesis pretty easy but also it reflects how a real calculator works (a current state then modified via operations).  In the method where you don't use a queue-like approach you then need to manage that in a different and much more painful way from the UI.  Things like square root become a problem, whereas here you only get "A", not A + B.  You could use a 'power' like above but the problem with that is - presumably - you don't want the CalculatorContext or the UI to be aware of the specifics of that operation.  So I'd probably handle it in the operation and if it became burdensome collecting the parameters I'd build helper methods for it.


答:
I wouldn't store the serialized objects for long term.
As the others already stated: When you change a litte bit on your classes, (maybe you don't even notice it) maybe you can't load your data. It will be hell to fix it.

I'm not sure, why you need all the data in the memory. Is it, because it is used everytime and everywhere in your software (master data)? Looks like a "Yes"

What I would do:
I would store the data in a inmemory-database (hsqldb,...)
dump the file and provide the file on the machine
After the startup I would load the file (quite fast) and then use it like a "normal" database.

You can do this also with your serialized objects. But I wouldn't see a sense any more. The "normal" database can be cached and will be extremly fast. So query the object.

Title: Java Serialization for long-ish-term storage

Body:
I have an application that uses a database of about 15,000 Java objects, which I have to read every time the application starts.  Originally I've been using JSON to store the data, but that has a few issues, mostly that it's slow (it can take 8-10 seconds to read all the objects on my lower-end machine) and also, it's very common for the objects in my database to have fields that point to the same object.  Java serialization handles this by using references to the same object, whereas with JSON, I just have to write the state of each object and then intern them during reading.  This also bloats the file size.

The contents of this database will be updated fairly infrequently (maybe about once a month or so).  I've heard from pretty much every source that Java serialization is always a poor choice for long-term storage, and I understand why.  Given these conditions, however, is there a good reason not to use Java serialization here?


答:
You're doing this backwards. Forget about the design patterns for awhile.

Just build your calculator program. Build it from scratch, and just design it however it is intuitive to you. Think about it for a few minutes, come up with a few ideas, then roll with it, start to finish.

While you are trying to implement your calculator, you might not design it right the first time and will have to restructure it now and then as you learn more about what's involved in your design. This is the process of learning, and this will teach you about how you've structured your code to attack the problem at hand.

Then, after you've done that, then take a look at the design patterns described in the
GoF book, and see what patterns most closely describe how you ended up designing your calculator. Now you know what those patterns are used for, and now you'll know how to choose what pattern makes sense to apply when.

Design patterns are not building blocks, they are names for common structural paradigms, to improve communication with other developers.

Title: which pattern is most intuitive for a calculator app?

Body:
The title says it all. I'm trying to build a calculator application (for self-learning purposes). The application is going to have a very common UI, with plus(+), minus(-), multiply(*) and a divide(/) button. Also, the app can do, real-number as well as complex-number calculations.

So, the situation here is, depending upon the mode(normal or complex), the same button should perform different calculation ? Which pattern should I be using for this situation ? I feel, strategy pattern should be a good fit, but then, I don't exactly know how to implement that - I mean, I'm just not sure about how to design my classes, what to have as Interfaces, and what as delegates.

CURRENTLY, MY DESIGN CONTAINS

```<code>IOperation
{
  Do();
}
Add:IOperation{}
Subtract:IOperation{}
Multiply:IOperation{}
Divide:IOperation{}
Root:IOperation{} //not supported by ComplexNumber
ISupportedOperation
{
   IList<IOperation> SupportedOps {get;}
}
INumber : ISupportedOperation {}
RealNumber:INumber{}
ComplexNumber : INumber {}
</code>```

Interface names starts with I

All others are concrete classes

BUT IT'S A MESS. And, I'm totally lost within my own classes, and interfaces.

PS: Of course, I can do this using if/else, but that's not what I want to do. Not because I forcefully want to use a pattern, but because, those if-else will be scattered everywhere in the program for eg. ReadInput, PlusButtonClick, MinusButtonClick, etc. And, as I understand, design patterns are supposed to avoid these kind of situations of code-repetitions, by clever/tricky re-organization of the existing code.

PPS: Sorry for being too verbose.


问:
SaaS model, 1DB per client

The context

we're building a web-based system and one of the design decisions (database related) was whether to have 1 main DB manage all client data VS having 1 DB per client.
After reading a lot on the matter (especially in these forums), it appears that 1 DB per client is overall a better approach, especially on the mid to long-run and especially in our use-case.

The basic architecture

Our system is mostly a front-end system that pulls data from a RESTful webservice (where the client data is located), to access that webservice we use unique keys, each key belonging to a specific pair of CLIENT:DATABASE.

Where things get tricky

When a new client creates an account, the idea is to have the webservice auto-create a new DB, DB user and API key for that account. I've looked for a standard method of implementing this, but failed to find anything conclusive. Obviously, SaaS providers automate this stuff, but where I fail to understand is how they do this safely.

The only current solution I have is to create a sort of MASTER MySQL user, which has absolute total full über power over MySQL, which we would use to create these DB, DB user pairs. But this feels like such a dangerous set up that it CANT be the only solution. Any compromise to this user would be fatal. This is where I need your help...

Another side-question, is how to limit DB size with MySQL/innoDB. The only things that I have found is that MySQL can only limit TABLE SIZE. And, in more sophisticated contexts, that DBs are stored in separate directories which have a specific disk-quota (this seems to be used by some web hosting providers... but I can't confirm).
Does anyone know of any other way to control DB size?

答:
Have you considered pre-creating a number of databases prior to use and when a new client creates an account, record the mapping from the client account name to the pre-created DB? This way you can limit denial of service attacks that auto-create too many databases for the DBMS to manage (because the list of pre-created databases would run out) and you'd avoid the need for database create privs for day-to-day user interaction.

If you included in the mapping the database server at the same time i.e. used a 'client name' -> 'server:pre-created-db-name' mapping, you could manage sharding dynamically as well by simply moving the DB from server to server and updating the master map which could be stored either as a central lib/file somewhere, or even in a master DB.

If you populated the pre-created set of DBs each day (for example) you'd have an automatic throttle on the number at any one time.

Title: SaaS model, 1DB per client