问:
Architecture for a template-building, WYSIWIG application
I'm building a WYSIWYG designer in Ember.js. The designer will allow users to create campaigns - think MailChimp.

To build a campaign, users will choose an existing template. The template will have a defined layout. The user will then be taken to the designer, where he will be able to edit the text and style, and additionally change some layout options.

I've been thinking about how best to go about structuring this app, and there are a few hurdles. Specifically, the output of the campaign will be dynamic: eventually, it will be published somewhere, and when the consumers (not my users, but the people clicking on the campaign that my user created) visit the campaign, certain pieces of data will change, depending on the type of consumer viewing the campaign.

That means the ultimate output of the designer will be a dynamic site. The data that is dynamic for this site - the end product - will not be manipulated by the user in the designer. However, the data that will be manipulated by the user in the designer are things like copy, styles, layout options, etc. I'll call the first set of variables server-side data, and the second client-side data.

It seems, then, that the process will go something like this:

I'll need to create templates for this designer that have two dynamic segments. For instance, the server-side data could be Liquid expressions, and the client-side data Handlebars expressions.

When the user creates a campaign, I would compile the template on the back end using some dummy data for the server-side variables, and serve up a handlebars template to the Ember app.

The user would then edit the template, and the Ember app would save all his edits to the JS variables that were powering the template. This way he'd be able to preview the template.

When he saves, he'll send back the selected template, along with all the data and options he's made.

When it comes time to publish, the back-end system will have to do two things:

compile the template with Handlebars using the campaign data, and then

compile the template with Liquid using the server-side data

Is my thinking roughly accurate about this, or is there a simpler way?

答:
I think nobody has answered it because it sounds about right to them.  I'm going to paraphrase it to see if I understood it correctly.  I am making a slight modification with the Handlebars library.

You have a case where you have two people modifying a webpage.  The first person does some modifications (basically, it creates a web template, I think).

The second person will also be able to modify the website, but perhaps (but not necessarily) in different ways.  Those changes will also be saved to the server.  This is more like a client setting up a website, I think.

Finally, the third person will go to the website to view the results of the first two's work.  In this case, you first apply person 1's modifications, then person 2's modifications.  I'd recommend using the same technology for both of these.  I think it will make it easier to understand.  In fact, I'd further recommend merging the configurations from person 1 and 2 before running it through your template code, so you only process it once.  You can use whatever technology you want for this, on whatever side (server or client).

That's just how I would do it.  Feel free to modify according to your comfort level.


问:
Preferred way for dealing with customer-defined data in enterprise application
Let's say that we have a small enterprise web (intranet) application for managing data for car dealers. It has screens for managing customers, inventory, orders, warranties and workshops.

This application is installed at 10 customer sites for different car dealers.

First version of this application was created without any way to provide for customer-specific data. For example, if dealer A wanted to be able to attach a photo to a customer, dealer B wanted to add e-mail contact to each workshop, and dealer C wanted to attach multiple PDF reports to a warranty, each and every feature like this was added to the application, so all of the customers received everything on new update.

However, this will inevitably lead to conflicts as the number of customers grow as their usage patterns are unique, and if, for instance, a specific dealer requested to have an ability to attach (for some reason) a color of inventory item (and be able to search by this color) as a required item, others really wouldn't need this feature, and definitely will not want it to be a required item. Or, one dealer would like to manage e-mail contacts for their employees on a separate screen of the application.

I imagine that a solution for this is to use a kind of plugin system, where we would have a core of the application that provides for standard features like customers, inventory, etc, and all of the customer's installed plugins.

There would be different kinds of plugins - standalone screens like e-mail contacts for employees, with their own logic, and customer plugin which would extend or decorate inventory items (like photo or color).

Inventory (customer,order,...) plugins would require to have installation procedure, hooks for plugging into the item editor, item displayer, item filtering for searching, backup hook and such.

Is this the right way to solve this problem?

答:
Many systems have a "configuration" section for a dealer.  This is often a simple (dealer_id, name, value) truple in a database.  The code reads all this in and can show/hide (or, using server side technology, include/exclude) certain user interface options.  Often, a user_id is tied to the dealer_id, so you know who gets what.

You CAN do all this with user roles, but it can become confusing that way.

I have often found that custom code makes for distribution and testing nightmares.  I believe it can be done successfully, but it sure seems simpler to just turn stuff on and off in configurations.

Make sure your database columns are nullable or have decent default values, of course.

ContentLicense: CC BY-SA 3.0


问:
Designing javascript chart library
I started coding a chart library on top of d3js: My chart library.
I read Javascript API reusability and Towards reusable charts. However, I am NOT really following the suggestions because I am not really convinced about them.

This is how my library can be used to create a bubble chart:

```<code>    var chart = new XYBubbleChart();
    chart.data = [{"xValue":200,"yValue":300},{"xValue":400,"yValue":200},{"xValue":100,"yValue":310}];  //set data
    chart.dataKey.x = "xValue";
    chart.dataKey.y = "yValue";
    chart.elementId = "#chart";
    chart.createChart();
</code>```

Here are my questions:

It does not use chaining. Is it a big issue?

Every property and function is exposed publicly. (Example: width, height are exposed in Chart.js). OOP is all about abstraction and hiding, but I don't really see the point right now. I think exposing everything gives flexibility to change property and functionality inside subclasses and objects without writing a lot of code. What could be pitfalls of such exposure?

I have implemented functions like: zooming, "showing info boxes when data point is clicked" as "abilities". (example: XYZoomingAbility.js). Basically, such "abilities" accept "chart" object, play around with public variables of "chart" to add functionality. What this allows me to do is to add an ability by writing:

```<code>activateZoomAbility(chartObject);
</code>```

My goal is to separate "visualization" from "interactivity". I want "interactivity" like: zooming to be plugged into the chart rather than built inside the chart. Like, I don't want my bubble chart to know anything about "zooming". However, I do want zoomable bubble chart. What is the best way to do this?

How to test and what to test? I have written mixed tests: jasmine and actual html files so that I can test manually on browser.

答:
My opinions:

It does not use chaining. Is it a big issue?

Not a big issue, but it does make it harder for others to use.  Once a style gets implemented, people start to expect it, and when it doesn't work, some throw out your work as "broken".  People don't read documentation.

Every property and function is exposed publicly. (Example: width, height are exposed in Chart.js).

One of the big advantages of hiding details is that, once you expose something, you have to support it when you rewrite the code to make it better.  Another advantage is that, but making everything functions, you can react when a variable changes values without making the user change a variable and then call a function.

I have implemented functions like: zooming, "showing info boxes when data point is clicked" as "abilities". (example: XYZoomingAbility.js). Basically, such "abilities" accept "chart" object, play around with public variables of "chart" to add functionality. What this allows me to do is to add an ability by writing:

activateZoomAbility(chartObject);

One concept we are trying to avoid here is having conflicting function names in the global namespace.  Look at the libraries that have plugins but only expose one global variable (jQuery is one, but by far not the only one, although it may have the most documented on how to make plugins correctly).

How to test and what to test? I have written mixed tests: jasmine and actual html files so that I can test manually on browser.

Look to see what others test, and how they do it.  Honestly, there are a lot of broken libraries out there, so the better testing you do, the better chance you have of getting it right and not breaking anything on updates.

Thanks for offering code for others to use.  Together, all of us can make a better web.

Title: Designing javascript chart library


问:
Why are most GNU's software written in C
I am a Java developer, and I rarely write GUI program in C. However, I noticed that many GNU's projects, such as PSPP, R, Dia, etc., are written in C, instead of Java or C++.

I personally don't mind this, but I am really curious why GNU favors C so much. My understanding is that C is the one that supports the least in object-oriented programming, and today's CS education really emphasizes OOP, as OOP really makes codes more reusable. In this case, why would so many developers choose to develop in C instead of C++ or Java.

Does anyone know why GNU's software are so exclusively written in C? Do you think or GNU's software should be written in C++ or Java so that the source code could be more useful to people? Why or why not?

答:
The primary reason is because C is the lingua franca of software, the GNU project has been around for quite some time and the GNU project and FSF, above else, value freedom of their software over any other consideration. Performance, modularity, code 'elegance', bug fixes, etc, all take a back seat to software freedom as far as the GNU project is concerned.

For much of GNU's history, C was the only language available that could fulfill that goal. The GNU project began IIRC in 1984. One of the initial development efforts was to make a GNU toolchain, and C was the obvious choice. Depending on a proprietary compiler beyond the short-term was unacceptable, and C ia a simple yet very effective language that was suitable for general purpose software development, and thus a reasonable target for the initial GNU compiler.

In the meantime, C++ was only a year old, and it would still be many years until dependable compilers were even available, and it wasn't until 1987 that GCC came around, and it didn't have C++ capability until a year after that. For many years, Java was a "trap", in that all Java software required a non-free runtime in order to execute, so Java was not an option, even if it had existed at the time.


答:
You are on the right track. Plugins provide a clean mechanism for extending the core data and application with client specific data and business logic.

You have to architect your database such that client specific data can be added to any of the core data.

Let's say you want to provide an extension mechanism for customer data. Let's also say that core customer data consists of:

```<code>1. ID
2. Name (first, last, middle)
3. Address
</code>```

You could add to that:

```<code>4. Extension
</code>```

Extension could include the ID of the dealer and a list of database names where the extension data can be found.

In your example for client A, you could create a table for storing photographs of customers. That table and the logic for manipulating the photographs could be packaged into a plugin for client A. If another client requests for the same functionality, you could install the "customer photograph" package to them.

Since the extension data allows for multiple extensions, a client could request as many plugins as they want to use.

You have to manage packaging of the right set of plugins for each client.

Title: Preferred way for dealing with customer-defined data in enterprise application

Body:
Let's say that we have a small enterprise web (intranet) application for managing data for car dealers. It has screens for managing customers, inventory, orders, warranties and workshops.

This application is installed at 10 customer sites for different car dealers.

First version of this application was created without any way to provide for customer-specific data. For example, if dealer A wanted to be able to attach a photo to a customer, dealer B wanted to add e-mail contact to each workshop, and dealer C wanted to attach multiple PDF reports to a warranty, each and every feature like this was added to the application, so all of the customers received everything on new update.

However, this will inevitably lead to conflicts as the number of customers grow as their usage patterns are unique, and if, for instance, a specific dealer requested to have an ability to attach (for some reason) a color of inventory item (and be able to search by this color) as a required item, others really wouldn't need this feature, and definitely will not want it to be a required item. Or, one dealer would like to manage e-mail contacts for their employees on a separate screen of the application.

I imagine that a solution for this is to use a kind of plugin system, where we would have a core of the application that provides for standard features like customers, inventory, etc, and all of the customer's installed plugins.

There would be different kinds of plugins - standalone screens like e-mail contacts for employees, with their own logic, and customer plugin which would extend or decorate inventory items (like photo or color).

Inventory (customer,order,...) plugins would require to have installation procedure, hooks for plugging into the item editor, item displayer, item filtering for searching, backup hook and such.

Is this the right way to solve this problem?

Body:
You are on the right track. Plugins provide a clean mechanism for extending the core data and application with client specific data and business logic.

You have to architect your database such that client specific data can be added to any of the core data.

Let's say you want to provide an extension mechanism for customer data. Let's also say that core customer data consists of:

1. ID
2. Name (first, last, middle)
3. Address

You could add to that:

4. Extension

Extension could include the ID of the dealer and a list of database names where the extension data can be found.

In your example for client A, you could create a table for storing photographs of customers. That table and the logic for manipulating the photographs could be packaged into a plugin for client A. If another client requests for the same functionality, you could install the "customer photograph" package to them.

Since the extension data allows for multiple extensions, a client could request as many plugins as they want to use.

You have to manage packaging of the right set of plugins for each client.


问:
Should one always know what an API is doing just by looking at the code?
Recently I have been developing my own API and with that invested interest in API design I have been keenly interested how I can improve my API design.

One aspect that has come up a couple times is (not by users of my API but in my observing discussion about the topic): one should know just by looking at the code calling the API what it is doing.

For example see this discussion on GitHub for the discourse repo, it goes something like:

```<code>foo.update_pinned(true, true);
</code>```

Just by looking at the code (without knowing the parameter names, documentation etc.) one cannot guess what it is going to do - what does the 2nd argument mean? The suggested improvement is to have something like:

```<code>foo.pin()
foo.unpin()
foo.pin_globally()
</code>```

And that clears things up (the 2nd arg was whether to pin foo globally, I am guessing), and I agree in this case the later would certainly be an improvement.

However I believe there can be instances where methods to set different but logically related state would be better exposed as one method call rather than separate ones, even though you would not know what it is doing just by looking at the code. (So you would have to resort to looking at the parameter names and documentation to find out - which personally I would always do no matter what if I am unfamiliar with an API).

For example I expose one method SetVisibility(bool, string, bool) on a FalconPeer and I acknowledge just looking at the line:

```<code>falconPeer.SetVisibility(true, "aerw3", true);
</code>```

You would have no idea what it is doing. It is setting 3 different values that control the "visibility" of the falconPeer in the logical sense: accept join requests, only with password and reply to discovery requests. Splitting this out into 3 method calls could lead to a user of the API to set one aspect of "visibility" forgetting to set others that I force them to think about by only exposing the one method to set all aspects of "visibility". Furthermore when the user wants to change one aspect they almost always will want to change another aspect and can now do so in one call.

答:
Obviously, there are always exceptions to the rule, but as you explained well by yourself, there are certain advantages in having a readable API. Boolean arguments are particularly bothersome, as 1) they do not reveal an intent and 2) they imply that you call a function, where you actually should have two, because different things are going to happen depending on the boolean flag.

The main question is rather: how much effort do you want to invest into making your API more readable? The more outwards-facing it is, the more effort can easily be justified. If it is an API that is used only by one other unit, then it's not that big of a deal. If you're talking about a REST API where you plan to let the whole world lose upon it, then you may as well invest some more effort into making it more understandable.

As for your example, there is a simple solution: Apparently, in your case visibility is not just a true or false thing. Instead, you have a whole set of things that you consider "visibility". One solution may be to introduce something like a Visibility class, which covers all these different kinds of visibility. If you further apply the Builder-pattern for creating these, you may end up with code like the following:

```<code>Visibility visibility = Visibility.builder()
  .acceptJoinRequests()
  .withPassword("aerw3")
  .replyToDiscoveryRequests()
  .build();
falconPeer.setVisibility(visibility);
</code>```

Body:
Obviously, there are always exceptions to the rule, but as you explained well by yourself, there are certain advantages in having a readable API. Boolean arguments are particularly bothersome, as 1) they do not reveal an intent and 2) they imply that you call a function, where you actually should have two, because different things are going to happen depending on the boolean flag.

The main question is rather: how much effort do you want to invest into making your API more readable? The more outwards-facing it is, the more effort can easily be justified. If it is an API that is used only by one other unit, then it's not that big of a deal. If you're talking about a REST API where you plan to let the whole world lose upon it, then you may as well invest some more effort into making it more understandable.

As for your example, there is a simple solution: Apparently, in your case visibility is not just a true or false thing. Instead, you have a whole set of things that you consider "visibility". One solution may be to introduce something like a Visibility class, which covers all these different kinds of visibility. If you further apply the Builder-pattern for creating these, you may end up with code like the following:

Visibility visibility = Visibility.builder()
  .acceptJoinRequests()
  .withPassword("aerw3")
  .replyToDiscoveryRequests()
  .build();
falconPeer.setVisibility(visibility);


答:
Your desire not to split it out into three method calls is completely understandable, but you do have other options besides boolean parameters.

You could use enums:

```<code>falconPeer.SetVisibility(JoinRequestOptions.Accept, "aerw3", DiscoveryRequestOptions.Reply);
</code>```

Or even a flags enum (if your language supports it):

```<code>falconPeer.SetVisibility(VisibilityOptions.AcceptJoinRequests | VisibilityOptions.ReplyToDiscoveryRequests, "aerw3");
</code>```

Or you could use a Parameter Object:

```<code>var options = new VisibilityOptions();
options.AcceptJoinRequests = true;
options.ReplyToDiscoveryRequest = true;
options.Password="aerw3";
falconPeer.SetVisibility(options);
</code>```

The Parameter Object pattern gives you a few other advantages that you may find helpful. It makes it easy to pass around and serialize a set of parameters, and you can easily give unspecified parameters "default" values.

Or you could just use boolean parameters. Microsoft seems to do it all the time with the .NET Framework API, so you could just shrug and say "if it's good enough for them, it's good enough for me".

Title: Should one always know what an API is doing just by looking at the code?

Body:
Recently I have been developing my own API and with that invested interest in API design I have been keenly interested how I can improve my API design.

One aspect that has come up a couple times is (not by users of my API but in my observing discussion about the topic): one should know just by looking at the code calling the API what it is doing.

For example see this discussion on GitHub for the discourse repo, it goes something like:

```<code>foo.update_pinned(true, true);
</code>```

Just by looking at the code (without knowing the parameter names, documentation etc.) one cannot guess what it is going to do - what does the 2nd argument mean? The suggested improvement is to have something like:

```<code>foo.pin()
foo.unpin()
foo.pin_globally()
</code>```

And that clears things up (the 2nd arg was whether to pin foo globally, I am guessing), and I agree in this case the later would certainly be an improvement.

However I believe there can be instances where methods to set different but logically related state would be better exposed as one method call rather than separate ones, even though you would not know what it is doing just by looking at the code. (So you would have to resort to looking at the parameter names and documentation to find out - which personally I would always do no matter what if I am unfamiliar with an API).

For example I expose one method SetVisibility(bool, string, bool) on a FalconPeer and I acknowledge just looking at the line:

```<code>falconPeer.SetVisibility(true, "aerw3", true);
</code>```

You would have no idea what it is doing. It is setting 3 different values that control the "visibility" of the falconPeer in the logical sense: accept join requests, only with password and reply to discovery requests. Splitting this out into 3 method calls could lead to a user of the API to set one aspect of "visibility" forgetting to set others that I force them to think about by only exposing the one method to set all aspects of "visibility". Furthermore when the user wants to change one aspect they almost always will want to change another aspect and can now do so in one call.

Body:
Your desire not to split it out into three method calls is completely understandable, but you do have other options besides boolean parameters.

You could use enums:

falconPeer.SetVisibility(JoinRequestOptions.Accept, "aerw3", DiscoveryRequestOptions.Reply);

Or even a flags enum (if your language supports it):

falconPeer.SetVisibility(VisibilityOptions.AcceptJoinRequests | VisibilityOptions.ReplyToDiscoveryRequests, "aerw3");

Or you could use a Parameter Object:

var options = new VisibilityOptions();
options.AcceptJoinRequests = true;
options.ReplyToDiscoveryRequest = true;
options.Password="aerw3";
falconPeer.SetVisibility(options);

The Parameter Object pattern gives you a few other advantages that you may find helpful. It makes it easy to pass around and serialize a set of parameters, and you can easily give unspecified parameters "default" values.

Or you could just use boolean parameters. Microsoft seems to do it all the time with the .NET Framework API, so you could just shrug and say "if it's good enough for them, it's good enough for me".


问:
Does my use of the strategy pattern violate the fundamental MVC pattern in iOS?
I'm about to use the 'strategy' pattern in my iOS app, but feel like my approach violates the somehow fundamental MVC pattern.

My app is displaying visual "stories", and a Story consists (i.e. has @properties) of one Photo and one or more VisualEvent objects to represent e.g. animated circles or moving arrows on the photo. Each VisualEvent object therefore has a eventType @property, that might be e.g. kEventTypeCircle or kEventTypeArrow. All events have things in common, like a startTime @property, but differ in the way they are being drawn on the StoryPlayerView.

Currently I'm trying to follow the MVC pattern and have a StoryPlayer object (my controller) that knows about both the model objects (like Story and all kinds of visual events) and the view object StoryPlayerView.

To chose the right drawing code for each of the different visual event types, my StoryPlayer is using a switch statement.

```<code>@implementation StoryPlayer

// (...)

- (void)showVisualEvent:(VisualEvent *)event onStoryPlayerView:storyPlayerView
{
    switch (event.eventType) {
        case kEventTypeCircle:
            [self showCircleEvent:event onStoryPlayerView:storyPlayerView];
            break;
    case kEventTypeArrow:
            [self showArrowDrawingEvent:event onStoryPlayerView:storyPlayerView];
            break;
    // (...)
}
</code>```

But switch statements for type checking are bad design, aren't they? According to Uncle Bob they lead to tight coupling and can and should almost always be replaced by polymorphism.

Having read about the "Strategy"-Pattern in Head First Design Patterns, I felt this was a great way to get rid of my switch statement.

So I changed the design like this:

All specialized visual event types are now subclasses of an abstract VisualEvent class that has a showOnStoryPlayerView: method.

```<code>@interface VisualEvent : NSObject

- (void)showOnStoryPlayerView:(StoryPlayerView *)storyPlayerView; // abstract
</code>```

Each and every concrete subclass implements a concrete specialized version of this drawing  behavior method.

```<code>@implementation CircleVisualEvent

- (void)showOnStoryPlayerView:(StoryPlayerView *)storyPlayerView
{
    [storyPlayerView drawCircleAtPoint:self.position
                 color:self.color
                 lineWidth:self.lineWidth
                radius:self.radius];
}
</code>```

The StoryPlayer now simply calls the same method on all types of events.

```<code>@implementation StoryPlayer

- (void)showVisualEvent:(VisualEvent *)event onStoryPlayerView:storyPlayerView
{
    [event showOnStoryPlayerView:storyPlayerView];
}
</code>```

The result seems to be great: I got rid of the switch statement, and if I ever have to add new types of VisualEvents in the future, I simply create new subclasses of VisualEvent.  And I won't have to change anything in StoryPlayer.

But of cause this approach violates the MVC pattern since now my model has to know about and depend on my view! Now my controller talks to my model and my model talks to the view calling methods on StoryPlayerView like drawCircleAtPoint:color:lineWidth:radius:. But this kind of calls should be controller code not model code, right??
Seems to me like I made things worse.

I'm confused! Am I completely missing the point of the strategy pattern? Is there a better way to get rid of the switch statement without breaking model-view separation?

答:
You are trying to merge two levels of functionality into a single class. That is almost guaranteed to cause a mess in your design. Instead, how about this:

Create another set of classes parallel to the Event classes. Each xxVisualEvent will have a corresponding xxVisualEventRenderer that encapsulates its rendering/display logic. These classes know about both the Model and the View and are essentially extensions of the Controller.

Create a Mapper class (basically a factory), which takes in a VisualEvent and creates a VisualEventRenderer based on the type. Yes, this means a type-based switch, but the class has no logic other than to construct Renderer instances.

Then you can call the Render/Draw method on these Renderer classes instead of on the Event classes. You will retain all the advantages of your approach, such as the loose coupling, etc.

ContentLicense: CC BY-SA 4.0


问:
Storing a looong lookup table

Background

The product i am working on has a very long lookup-table. the table contains static data and cannot be auto generated. there are about 500 rows and 10 columns. columns have mostly integers and strings. to complicate the matters, there are actually two such tables. every row in table-1 maps to zero-or-more rows in table-2.

we use an SQLite database with two tables. the product installer places the SQLite file in the installation directory. the application is written in dot-net and we use ADO to load the data once on startup.

now,

the lookup table grows. in each release a month, we add about 10 new entries

existing entries are adjusted. every release we fine tune existing entries.

The problem

a team of (10) developers work on the lookup table. Code goes in the SVN, but the little devil the SQLite does not. this prevents multiple developers to work on it. we do take regular backups of the file, but proper versioning is not possible. we never know who did the breaking change. the worse thing is we dont know if there is any change at all. diff'ing databases is tedious if not impossible.

the tables are expected to grow quite large in years to come and we would need developers to work in parallel on it. the data is business critical. we need to be able to audit changes made to it.

Question

What would be a solution for the problems outlines above? one idea was to transform the whole thing to XML and treat it like just another source file. that way SVN can do the versioning and we can work in parallel. but the data shows relational behavior. with XML we loose the unique and foreign-key constraints. also we cant query it with sql like ease.

any help here will be appreciated.

答:
Ideally, you develop a small program to do the editing, so you can edit the file (and maybe even do the svn update and commit as part of the program).  That may be more work then you have time for.  I have never had that time.

Instead, I had people edit in the database in place, and built a small script that they ran (maybe as an svn trigger, maybe not, I never tried) that loaded/dumped the database to one or more files.  The files then become the "master".  Any changes to the database are lost unless dumped and committed.  It's a slight culture change, but in my experience, after people lose their work once or twice, they get it.  Ideally, everyone has their own copy of the database built from the files they checked out, and you no longer have a development database (you do have a nightly build database, of course, etc.), so you don't have to worry about picking up others changes when you commit, and svn handles the parallelism.  Make sure you dump your database in a reasonable order of rows so you can easily see what was changed.

Good luck.  I wish there was a better answer (there is, of course, but it costs money).

Title: Storing a looong lookup table


问:
How to maintain encapsulation with composition in C++?
I am designing a class Master that is composed from multiple other classes, A, Base, C and D. These four classes have absolutely no use outside of Master and are meant to split up its functionality into manageable and logically divided packages. They also provide extensible functionality as in the case of Base, which can be inherited from by clients.

But, how do I maintain encapsulation of Master with this design?

So far, I've got two approaches, which are both far from perfect:

1. Replicate all accessors:

Just write accessor-methods for all accessor-methods of all classes that Master is composed of.
This leads to perfect encapsulation, because no implementation detail of Master is visible, but is extremely tedious and makes the class definition monstrous, which is exactly what the composition should prevent. Also, adding functionality to one of the composees (is that even a word?) would require to re-write all those methods in Master. An additional problem is that inheritors of Base could only alter, but not add functionality.

2. Use non-assignable, non-copyable member-accessors:

Having a class accessor<T> that can not be copied, moved or assigned to, but overrides the operator-> to access an underlying shared_ptr, so that calls like

```<code>Master->A()->niceFunction();
</code>```

are made possible. My problem with this is that it kind of breaks encapsulation as I would now be unable to change my implementation of Master to use a different class for the functionality of niceFunction(). Still, it is the closest I've gotten without using the ugly first approach. It also fixes the inheritance issue quite nicely. A small side question would be if such a class already existed in std or boost.

EDIT: Wall of code

I will now post the code of the header files of the classes discussed. It may be a bit hard to understand, but I'll give my best in explaining all of it.

1. GameTree.h

The foundation of it all. This basically is a doubly-linked tree, holding GameObject-instances, which we'll later get to. It also has it's own custom iterator GTIterator, but I left that out for brevity. WResult is an enum with the values SUCCESS and FAILED, but it's not really important.

```<code>class GameTree
{
public:
    //Static methods for the root. Only one root is allowed to exist at a time!
    static void ConstructRoot(seed_type seed, unsigned int depth);
    inline static bool rootExists(){ return static_cast<bool>(rootObject_); }
    inline static weak_ptr<GameTree> root(){ return rootObject_; }

    //delta is in ms, this is used for velocity, collision and such
    void tick(unsigned int delta);

    //Interaction with the tree
    inline weak_ptr<GameTree> parent() const { return parent_; }

    inline unsigned int numChildren() const{ return static_cast<unsigned int>(children_.size()); }
    weak_ptr<GameTree> getChild(unsigned int index) const;
    template<typename GOType>
    weak_ptr<GameTree> addChild(seed_type seed, unsigned int depth = 9001){
        GOType object{ new GOType(seed) };
        return addChildObject(unique_ptr<GameTree>(new GameTree(std::move(object), depth)));
    }
    WResult moveTo(weak_ptr<GameTree> newParent);
    WResult erase();

    //Iterators for for( : ) loop
    GTIterator& begin(){
        return *(beginIter_ = std::move(make_unique<GTIterator>(children_.begin())));
    }
    GTIterator& end(){
        return *(endIter_ = std::move(make_unique<GTIterator>(children_.end())));
    }

    //unloading should be used when objects are far away
    WResult unloadChildren(unsigned int newDepth = 0);
    WResult loadChildren(unsigned int newDepth = 1);

    inline const RenderObject& renderObject() const{ return gameObject_->renderObject(); }

    //Getter for the underlying GameObject (I have not tested the template version)
    weak_ptr<GameObject> gameObject(){
        return gameObject_;
    }
    template<typename GOType>
    weak_ptr<GOType> gameObject(){
        return dynamic_cast<weak_ptr<GOType>>(gameObject_);
    }

    weak_ptr<PhysicsObject> physicsObject() {
        return gameObject_->physicsObject();
    }

private:
    GameTree(const GameTree&); //copying is only allowed internally
    GameTree(shared_ptr<GameObject> object, unsigned int depth = 9001);

    //pointer to root
    static shared_ptr<GameTree> rootObject_;

    //internal management of a child
    weak_ptr<GameTree> addChildObject(shared_ptr<GameTree>);
    WResult removeChild(unsigned int index);

    //private members
    shared_ptr<GameObject> gameObject_;
    shared_ptr<GTIterator> beginIter_;
    shared_ptr<GTIterator> endIter_;

    //tree stuff
    vector<shared_ptr<GameTree>> children_;
    weak_ptr<GameTree> parent_;
    unsigned int selfIndex_; //used for deletion, this isn't necessary
    void initChildren(unsigned int depth); //constructs children
};
</code>```

2. GameObject.h

This is a bit hard to grasp, but GameObject basically works like this:

When constructing a GameObject, you construct its basic attributes and a CResult-instance, which contains a vector<unique_ptr<Construction>>. The Construction-struct contains all information that is needed to construct a GameObject, which is a seed and a function-object that is applied at construction by a factory. This enables dynamic loading and unloading of GameObjects as done by GameTree. It also means that you have to define that factory if you inherit GameObject. This inheritance is also the reason why GameTree has a template-function gameObject<GOType>.

GameObject can contain a RenderObject and a PhysicsObject, which we'll later get to.

Anyway, here's the code.

```<code>class GameObject;
typedef unsigned long seed_type;

//this declaration magic means that all GameObjectFactorys inherit from GameObjectFactory<GameObject>
template<typename GOType>
struct GameObjectFactory;

template<>
struct GameObjectFactory<GameObject>{
    virtual unique_ptr<GameObject> construct(seed_type seed) const = 0;
};

template<typename GOType>
struct GameObjectFactory : GameObjectFactory<GameObject>{
    GameObjectFactory() : GameObjectFactory<GameObject>(){}
    unique_ptr<GameObject> construct(seed_type seed) const{
        return unique_ptr<GOType>(new GOType(seed));
    }
};

//same as with the factories. this is important for storing them in vectors
template<typename GOType>
struct Construction;

template<>
struct Construction<GameObject>{
    virtual unique_ptr<GameObject> construct() const = 0;
};

template<typename GOType>
struct Construction : Construction<GameObject>{
    Construction(seed_type seed, function<void(GOType*)> func = [](GOType* null){}) :
        Construction<GameObject>(),
        seed_(seed),
        func_(func)
    {}

    unique_ptr<GameObject> construct() const{
        unique_ptr<GameObject> gameObject{ GOType::factory.construct(seed_) };
        func_(dynamic_cast<GOType*>(gameObject.get()));
        return std::move(gameObject);
    }

    seed_type seed_;
    function<void(GOType*)> func_;
};

typedef struct CResult
{
    CResult() :
        constructions{}
    {}

    CResult(CResult && o) :
        constructions(std::move(o.constructions))
    {}

    CResult& operator= (CResult& other){
        if (this != &other){
            for (unique_ptr<Construction<GameObject>>& child : other.constructions){
                constructions.push_back(std::move(child));
            }
        }
        return *this;
}

    template<typename GOType>
    void push_back(seed_type seed, function<void(GOType*)> func = [](GOType* null){}){
        constructions.push_back(make_unique<Construction<GOType>>(seed, func));
    }

    vector<unique_ptr<Construction<GameObject>>> constructions;
} CResult;

//finally, the GameObject
class GameObject
{
public:
    GameObject(seed_type seed);
    GameObject(const GameObject&);

    virtual void tick(unsigned int delta);

    inline Matrix4f trafoMatrix(){ return physicsObject_->transformationMatrix(); }

    //getter
    inline seed_type seed() const{ return seed_; }
    inline CResult& properties(){ return properties_; }
    inline const RenderObject& renderObject() const{ return *renderObject_; }
    inline weak_ptr<PhysicsObject> physicsObject() { return physicsObject_; }

protected:
    virtual CResult construct_(seed_type seed) = 0;

    CResult properties_;
    shared_ptr<RenderObject> renderObject_;
    shared_ptr<PhysicsObject> physicsObject_;
    seed_type seed_;
};
</code>```

3. PhysicsObject

That's a bit easier. It is responsible for position, velocity and acceleration. It will also handle collisions in the future. It contains three Transformation objects, two of which are optional. I'm not going to include the accessors on the PhysicsObject class because I tried my first approach on it and it's just pure madness (way over 30 functions). Also missing: the named constructors that construct PhysicsObjects with different behaviour.

```<code>class Transformation{
    Vector3f translation_;
    Vector3f rotation_;
    Vector3f scaling_;
public:
    Transformation() :
        translation_{ 0, 0, 0 },
        rotation_{ 0, 0, 0 },
        scaling_{ 1, 1, 1 }
    {};
    Transformation(Vector3f translation, Vector3f rotation, Vector3f scaling);

    inline Vector3f translation(){ return translation_; }
    inline void translation(float x, float y, float z){ translation(Vector3f(x, y, z)); }
    inline void translation(Vector3f newTranslation){
        translation_ = newTranslation;
    }
    inline void translate(float x, float y, float z){ translate(Vector3f(x, y, z)); }
    inline void translate(Vector3f summand){
        translation_ += summand;
    }

    inline Vector3f rotation(){ return rotation_; }
    inline void rotation(float pitch, float yaw, float roll){ rotation(Vector3f(pitch, yaw, roll)); }
    inline void rotation(Vector3f newRotation){
        rotation_ = newRotation;
    }
    inline void rotate(float pitch, float yaw, float roll){ rotate(Vector3f(pitch, yaw, roll)); }
    inline void rotate(Vector3f summand){
        rotation_ += summand;
    }

    inline Vector3f scaling(){ return scaling_; }
    inline void scaling(float x, float y, float z){ scaling(Vector3f(x, y, z)); }
    inline void scaling(Vector3f newScaling){
        scaling_ = newScaling;
    }
    inline void scale(float x, float y, float z){ scale(Vector3f(x, y, z)); }
    void scale(Vector3f factor){
        scaling_(0) *= factor(0);
        scaling_(1) *= factor(1);
        scaling_(2) *= factor(2);
    }

    Matrix4f matrix(){
        return WMatrix::Translation(translation_) * WMatrix::Rotation(rotation_) * WMatrix::Scale(scaling_);
    }
};

class PhysicsObject;

typedef void tickFunction(PhysicsObject& self, unsigned int delta);

class PhysicsObject{
    PhysicsObject(const Transformation& trafo) :
        transformation_(trafo),
        transformationVelocity_(nullptr),
        transformationAcceleration_(nullptr),
        tick_(nullptr)
    {}
    PhysicsObject(PhysicsObject&& other) :
        transformation_(other.transformation_),
        transformationVelocity_(std::move(other.transformationVelocity_)),
        transformationAcceleration_(std::move(other.transformationAcceleration_)),
        tick_(other.tick_)
    {}

    Transformation transformation_;
    unique_ptr<Transformation> transformationVelocity_;
    unique_ptr<Transformation> transformationAcceleration_;

    tickFunction* tick_;

public:
    void tick(unsigned int delta){ tick_ ? tick_(*this, delta) : 0; }

    inline Matrix4f transformationMatrix(){ return transformation_.matrix(); }
}
</code>```

4. RenderObject

RenderObject is a base class for different types of things that could be rendered, i.e. Meshes, Light Sources or Sprites. DISCLAIMER: I did not write this code, I'm working on this project with someone else.

```<code>class RenderObject
{
public:
    RenderObject(float renderDistance);
    virtual ~RenderObject();

    float renderDistance() const { return renderDistance_; }
    void setRenderDistance(float rD) { renderDistance_ = rD; }

protected:
    float renderDistance_;
};

struct NullRenderObject : public RenderObject{
    NullRenderObject() : RenderObject(0.f){};
};

class Light : public RenderObject{
public:
    Light() : RenderObject(30.f){};
};

class Mesh : public RenderObject{
public:
    Mesh(unsigned int seed) :
        RenderObject(20.f)
    {
        meshID_ = 0;
        textureID_ = 0;
        if (seed == 1)
            meshID_ = Model::getMeshID("EM-208_heavy");
        else
            meshID_ = Model::getMeshID("cube");
    };

    unsigned int getMeshID() const { return meshID_; }
    unsigned int getTextureID() const { return textureID_; }

private:
    unsigned int meshID_;
    unsigned int textureID_;
};
</code>```

I guess this shows my issue quite nicely: You see a few accessors in GameObject which return weak_ptrs to access members of members, but that is not really what I want.

Also please keep in mind that this is NOT, by any means, finished or production code! It is merely a prototype and there may be inconsistencies, unnecessary public parts of classes and such.

答:
The whole game industry switched to Component-based Design engines (for re-usable engines only) for the reason of composability with performance constraints (and allow also fully data-driven engines). You should look into it, it's the best way we know to have very heterogeneous kind of entities, defined by a set of different components.

There is a lot of different ways to setup a component system. I should point to the book Game Engine Architecture which have a whole chapter on the different kind of setup you can have to solve the problem you have, including different kind of component-based systems. Also there are a lot of articles about the subject like:

http://www.randygaul.net/2013/05/20/component-based-engine-design/

http://gameprogrammingpatterns.com/component.html

(there are also a lot of experimentation on github about how to implement a component system in modern C++. I did one recently with no inheritance at all, using concept-based type-erasure)

The issues you have are related to the use of inheritance where it makes the architecture less flexible than it could. Remove inheritance and organize things in batches of components and you will have maximum flexibility.

Note that, of course, that flexibility is not always what you want in the end, but it should solve the problem you are presenting here.

OwnerDisplayName: iFreilicht


问:
How can Swift be so much faster than Objective-C in these comparisons?
Apple launched its new programming language Swift at WWDC14. In the presentation, they made some performance comparisons between Objective-C and Python. The following is a picture of one of their slides, of a comparison of those three languages performing some complex object sort:

There was an even more incredible graph about a performance comparison using the RC4 encryption algorithm.

Obviously this is a marketing talk, and they didn't go into detail on how this was implemented in each. I leaves me wondering though:

How can a new programming language be so much faster?

Are the Objective-C results caused by a bad compiler or is there something less efficient in Objective-C than Swift?

How would you explain a 40% performance increase? I understand that garbage collection/automated reference control might produce some additional overhead, but this much?

答:
I've struggled myself through the Swift tutorial, and it seems to me that Swift is more down to earth (makes me think of Visual Basic) with less 'object-ification' than Objective-C. Had they taken into account C or C++, I presume the latter would have won, since they are even more compile-time only.

In this case, I presume Objective-C is the victim of it's object oriented pureness (and overhead).


答:
Being 3.9 times faster than python, the language that consistently loses most benchmarks by considerable margin (ok, it's on par with Perl, Ruby and PHP; but it loses to anything statically typed), is nothing one should be boasting about.

The benchmarks game shows C++ programs that are more than order of magnitude faster than python programs in most cases. It is not much better when comparing with Java, C# (on Mono), OCaml, Haskell and even Clojure, which is not statically typed.

So the real question is how is Objective-C only 2.8 times faster than python. Apparently they carefully chose benchmark where the slow fully dynamic dispatch of ObjC hurts a lot. Any statically typed language should be able to do better. In complex object sort there are many method calls for comparing the objects and the actual comparison was probably not very complex itself. So if Swift takes at least some advantage of the type information, it can easily do better on the method calls and there is not enough other operations that ObjC could be better in.

Of course, as the benchmarks game clearly demonstrates, the relative performance on different tasks varies wildly, so one benchmark is not really representative. If they had benchmark where it had bigger advantage, they would have shown us that one instead, so on other tasks it probably isn't better or not so much.

Title: How can Swift be so much faster than Objective-C in these comparisons?

Body:
Apple launched its new programming language Swift at WWDC14. In the presentation, they made some performance comparisons between Objective-C and Python. The following is a picture of one of their slides, of a comparison of those three languages performing some complex object sort:

There was an even more incredible graph about a performance comparison using the RC4 encryption algorithm.

Obviously this is a marketing talk, and they didn't go into detail on how this was implemented in each. I leaves me wondering though:

How can a new programming language be so much faster?

Are the Objective-C results caused by a bad compiler or is there something less efficient in Objective-C than Swift?

How would you explain a 40% performance increase? I understand that garbage collection/automated reference control might produce some additional overhead, but this much?


问:
Are there advantages for using recursion over iteration - other than sometimes readability and elegance?
I am about to make two assumptions. Please correct me if they're wrong:

There isn't a recursive algorithm without an iterative equivalent.

Iteration is always cheaper performance-wise than recursion (at
least in general purpose languages such as Java, C++, Python etc.).

If it's true that recursion is always more costly than iteration, and that it can always be replaced with an iterative algorithm (in languages that allow it) - than I think that the two remaining reasons to use recursion are: elegance and readability.

Some algorithms are expressed more elegantly with recursion. E.g. scanning a binary tree.

However apart from that, are there any reasons to use recursion over iteration? Does recursion have advantages over iteration other than sometimes elegance and readability?

答:
Recursion uses the call stack to store function call returns.  Function state is stored in between calls.

Iteration must also use a stack or some similar mechanism to store intermediate states, except that you create the stack yourself.  Unless, of course, you can find a substitute algorithm that doesn't require such state storage.

Recursion is only more costly if you overflow the stack.  In a sense, iteration is going to be more costly (in those algorithms that lend themselves to recursion), because you're re-creating the state storage mechanism that recursion already provides.


问:
Why does Clang/LLVM warn me about using default in a switch statement where all enumerated cases are covered?
Consider the following enum and switch statement:

```<code>typedef enum {
    MaskValueUno,
    MaskValueDos
} testingMask;

void myFunction(testingMask theMask) {
    switch (theMask) {
        case MaskValueUno: {}// deal with it
        case MaskValueDos: {}// deal with it
        default: {} //deal with an unexpected or uninitialized value
    }
};
</code>```

I'm an Objective-C programmer, but I've written this in pure C for a wider audience.

Clang/LLVM 4.1 with -Weverything warns me at the default line:

Default label in switch which covers all enumeration values

Now, I can sort of see why this is there: in a perfect world, the only values entering in the argument theMask would be in the enum, so no default is necessary. But what if some hack comes along and throws an uninitialized int into my beautiful function? My function will be provided as a drop in library, and I have no control over what could go in there. Using default is a very neat way of handling this.

Why do the LLVM gods deem this behaviour unworthy of their infernal device? Should I be preceding this by an if statement to check the argument?

答:
I also prefer to have a default: in all cases.  I'm late to the party as usual, but... some other thoughts that I didn't see above:

The particular warning (or error if also throwing -Werror) is coming from -Wcovered-switch-default (from -Weverything but not -Wall). If your moral flexibility allows you to turn off certain warnings (i.e., excise some things from -Wall or -Weverything), consider throwing -Wno-covered-switch-default (or -Wno-error=covered-switch-default when using -Werror), and in general -Wno-... for other warnings you find disagreeable.

For gcc (and more generic behavior in clang), consult gcc manpage for -Wswitch, -Wswitch-enum, -Wswitch-default for (different) behavior in similar situations of enumerated types in switch statements.

I also don't like this warning in concept, and I don't like its wording; to me, the words from the warning ("default label ... covers all ... values") suggest that the default: case will be always be executed, such as

```<code>switch (foo) {
  case 1:
    do_something();
    //note the lack of break (etc.) here!
  default:
    do_default();
}
</code>```

On first reading, this is what I thought you were running into -- that your default: case would always be executed because there's no break; or return; or similar. This concept is similar (to my ear) to other nanny-style (albeit occasionally helpful) commentary that spews forth from clang. If foo == 1, both functions will be executed; your code above has this behavior. I.e., fail to break-out only if you want to possibly keep executing code from subsequent cases!  This appears, however, not to be your problem.

At the risk of being pedantic, some other thoughts for completeness:

I do however think this behavior is (more) consistent with aggressive type checking in other languages or compilers.  If, as you hypothesize, some reprobate does attempt to pass an int or something to this function, which is explicitly intending to consume your own specific type, your compiler should protect you equally well in that situation with an aggressive warning or error.  BUT it doesn't! (That is, it seems that at least gcc and clang don't do enum type-checking, but I hear that icc does). Since you aren't getting type-safety, you could get value-safety as discussed above. Otherwise, as suggested in TFA, consider a struct or something that can provide type-safety.

Another workaround could be creating a new "value" in your enum such as MaskValueIllegal, and not supporting that case in your switch.  That would be eaten by the default: (in addition to any other wacky value)

Long live defensive coding!

Body:
I also prefer to have a default: in all cases.  I'm late to the party as usual, but... some other thoughts that I didn't see above:

The particular warning (or error if also throwing -Werror) is coming from -Wcovered-switch-default (from -Weverything but not -Wall). If your moral flexibility allows you to turn off certain warnings (i.e., excise some things from -Wall or -Weverything), consider throwing -Wno-covered-switch-default (or -Wno-error=covered-switch-default when using -Werror), and in general -Wno-... for other warnings you find disagreeable.

For gcc (and more generic behavior in clang), consult gcc manpage for -Wswitch, -Wswitch-enum, -Wswitch-default for (different) behavior in similar situations of enumerated types in switch statements.

I also don't like this warning in concept, and I don't like its wording; to me, the words from the warning ("default label ... covers all ... values") suggest that the default: case will be always be executed, such as

switch (foo) {
  case 1:
    do_something();
    //note the lack of break (etc.) here!
  default:
    do_default();
}

On first reading, this is what I thought you were running into -- that your default: case would always be executed because there's no break; or return; or similar. This concept is similar (to my ear) to other nanny-style (albeit occasionally helpful) commentary that spews forth from clang. If foo == 1, both functions will be executed; your code above has this behavior. I.e., fail to break-out only if you want to possibly keep executing code from subsequent cases!  This appears, however, not to be your problem.

At the risk of being pedantic, some other thoughts for completeness:

I do however think this behavior is (more) consistent with aggressive type checking in other languages or compilers.  If, as you hypothesize, some reprobate does attempt to pass an int or something to this function, which is explicitly intending to consume your own specific type, your compiler should protect you equally well in that situation with an aggressive warning or error.  BUT it doesn't! (That is, it seems that at least gcc and clang don't do enum type-checking, but I hear that icc does). Since you aren't getting type-safety, you could get value-safety as discussed above. Otherwise, as suggested in TFA, consider a struct or something that can provide type-safety.

Another workaround could be creating a new "value" in your enum such as MaskValueIllegal, and not supporting that case in your switch.  That would be eaten by the default: (in addition to any other wacky value)

Long live defensive coding!


问:
REST Service and CQRS
I am struggling with architecture on a new project. I am using the following patterns/technology.

CQRS - anything going in goes through a command

REST - using WebAPI

MVC - asp.net mvc

Angular - building a spa

nhibernate

I belive this provides some great separation and should help keep a very complex domain from growing into a giant set of services that mix queries with other business logic.

The REST services have become non restful. They are putting methods in rest that are "SearchByDate", "SearchByItem" etc.

Service Methods that execute commands are called with a "web" model class, a new command is built in the service and executed, I feel like there is a lot of extra code.

I expected this to be much different but I wasn't around to keep things on track.

Finally my questions are this...

I would have liked to see PUT Person (CreatePersonCommand) but then I realized that isn't restful either is it? the put should be a person entity not a command.

Can I make CQRS and REST service work together or am I going about this all wrong?

How do I handle service methods that don't fit into a REST model. I am not performing CRUD on the object but rather executing some business logic. I.E. I don't want the UI to be responsible for how a shipment is "unshipped" I want the service layer to worry about that.

答: You probably need Event Sourcing then. Basically you store each event in something that resembles a serial queue and have some service process pick up the events on the queue and execute them. That way you can separate the code that submits the events from the code that executes their effects. You also get the benefit of being able to replay the events to reconstitute object state. I suggest you do some googling for Event Sourcing. It's a common companion to CQRS. </p>

Title: REST Service and CQRS


问:
Callbacks: when to return value, and when to modify parameter?
When writing a callback, when is best to have the callback return a value, and when is it best to have the callback modify a parameter? Is there a difference?

For example, if we wanted to grab a list of dependencies, when would you do this:

```<code>function GetDependencies(){
    return [{"Dep1" : 1.1},
            {"Dept2": 1.2},
            {"Dep3" : 1.3}];
}
</code>```

And when would you do this?

```<code>function RegisterDependencies(register){
    register.add("Dep1", 1.1);
    register.add("Dep2", 1.2);
    register.add("Dep3", 1.3);
}
</code>```

答:
Callbacks fall into the following broad categories:

Those that produce a side effect but the dispatch mechanism doesn't care about the side effects. They usually don't return anything. Everything they need to operate properly are provided through arguments to the function. That may involve modifying the contents of the arguments as well.

Those that may or may not produce a side effect but the dispatch mechanism cares whether they succeeded or not. These functions usually return an integer that indicates the status of the callback function's execution. Callback functions that fall into this category also expect that everything they need to operate properly are provided through arguments to the function. That may involve modifying the contents of the arguments as well.

Those that return more complex or different data than the first two are unusual. I don't recall having seen any in my work or other places. If you are contemplating using callbacks of this category, you probably have thought through this well and your team, if you are in a team, is convinced this is the correct approach.

If you haven't thought through this, I would go with using callback functions that belong to the first two categories.


答: I don't like functions modifying my variables so I prefer to use the return value and then I can decide what to do with that value. Occasionally it is convenient to say return a boolean indicating if a value was modified and have the function modify the value. That can save time and code but in general I would prefer to drop those two pieces of information in a container and return that.</p>

Title: Callbacks: when to return value, and when to modify parameter?

Body:
When writing a callback, when is best to have the callback return a value, and when is it best to have the callback modify a parameter? Is there a difference?

For example, if we wanted to grab a list of dependencies, when would you do this:

```<code>function GetDependencies(){
    return [{"Dep1" : 1.1},
            {"Dept2": 1.2},
            {"Dep3" : 1.3}];
}
</code>```

And when would you do this?

```<code>function RegisterDependencies(register){
    register.add("Dep1", 1.1);
    register.add("Dep2", 1.2);
    register.add("Dep3", 1.3);
}
</code>```


答:
Since your example uses a JavaScript-like language (duck-typed), my answer will be specific to duck-typed languages.

From a usability standpoint, parameters are a tad more self-documenting then return values. If someone was crawling through code and saw:

```<code>function callback( model, rootElement )
{
    //TODO: implement editor UI
}
</code>```

It's a bit more obvious what should be done then:

```<code>function callback( model )
{
    //TODO: implement editor UI
    // ... okay, where?
}
</code>```

In addition, curious programmers have a bit more to work with if given parameters. For example, imagine an Options object with 20 configurable options. Providing that Options object as a parameter (pre-loaded with defaults) gives the programmer a chance to poke into the object and explore a bit:

```<code>function callback( options )
{
    console.log( options );
}
</code>```

While a callback that must return an options object requires the programmer to find your documentation:

```<code>function callback()
{
    // umm... return what?
}
</code>```

In addition, if you want a value returned but the user doesn't return a value, what happens? I've seen many cases where this condition has produced "cannot read property of undefined" errors... which usually breaks the page.

If the user is handed a parameter and given permission to modify it, then you aren't depending on them doing anything. For example, perhaps the user just wants to log that something has happened and your callback is a convenient place to do that. Requiring that they return something just makes the code more complicated.

```<code>function setOptionsCallback( options )
{
    console.log( 'object created' );
}
</code>```

Versus:

```<code>function setOptionsCallback()
{
    console.log( 'object created' );
    return {};
}
</code>```

In the end, though, most of these problems can be overcome with some good defensive programming and solid documentation.

Body:
Since your example uses a JavaScript-like language (duck-typed), my answer will be specific to duck-typed languages.

From a usability standpoint, parameters are a tad more self-documenting then return values. If someone was crawling through code and saw:

function callback( model, rootElement )
{
    //TODO: implement editor UI
}

It's a bit more obvious what should be done then:

function callback( model )
{
    //TODO: implement editor UI
    // ... okay, where?
}

In addition, curious programmers have a bit more to work with if given parameters. For example, imagine an Options object with 20 configurable options. Providing that Options object as a parameter (pre-loaded with defaults) gives the programmer a chance to poke into the object and explore a bit:

function callback( options )
{
    console.log( options );
}

While a callback that must return an options object requires the programmer to find your documentation:

function callback()
{
    // umm... return what?
}

In addition, if you want a value returned but the user doesn't return a value, what happens? I've seen many cases where this condition has produced "cannot read property of undefined" errors... which usually breaks the page.

If the user is handed a parameter and given permission to modify it, then you aren't depending on them doing anything. For example, perhaps the user just wants to log that something has happened and your callback is a convenient place to do that. Requiring that they return something just makes the code more complicated.

function setOptionsCallback( options )
{
    console.log( 'object created' );
}

Versus:

function setOptionsCallback()
{
    console.log( 'object created' );
    return {};
}

In the end, though, most of these problems can be overcome with some good defensive programming and solid documentation.


答:
REST works OK with a command model... the commands basically become nouns, or worker resources.

So instead of using

/blah/blah/SearchByName

You'd have a "search" (noun) resource

/blah/blah/search?Name=

I've always felt that's kind of a word game, but it does has the benefit of keeping your semantics resource oriented.

In the case where the verb directly mirrors an HTTP verb, just omit it.

Instead of

/blah/blah/CreatePerson

it's just PUT to

/blah/blah/Person

...the call is the same, it's just that you're using the HTTP verb (PUT) instead of duplicating that in the resource name.

Also, just stylistically, I don't think you need to add "Command" to all your URI's ;) It's kind of like having a "PersonResource", "CarResource", "CompanyResource", etc. Or like adding "Page" to all the URLs on the web: http://google.com/SearchPage, http://cnn.com/NewsPage, http://twitter.com/TweetsPage

CQRS is about splitting up your writers from your readers. It would be fair game under both CQRS and REST to add some resources that only accept POST -- using the "data processing" clause for POST provided in the HTTP spec. POST data for processing, then GET the resulting resources.

But as long as your resource names boil down to nouns rather than verbs, you can keep all the purists happy.

...

A Command name is just a combination of action + target. You're concatenating those to create your Command names "ActionTargetCommand".

In REST:

the target goes in the base URI

the action becomes the method or else implied from the query string

and Command just goes away as redundant

"ACTION htpp://blah/Target?ActionParameter=".

You either need to make your action one of the HTTP methods, or else turn the resource into a processor noun.

One one level, it's just renaming to suit a resource-oriented paradigmn, but on a deeper level is a matter of splitting the commands into those covered by the HTTP methods, and others into processing nouns.

Title: REST Service and CQRS

Body:
I am struggling with architecture on a new project. I am using the following patterns/technology.

CQRS - anything going in goes through a command

REST - using WebAPI

MVC - asp.net mvc

Angular - building a spa

nhibernate

I belive this provides some great separation and should help keep a very complex domain from growing into a giant set of services that mix queries with other business logic.

The REST services have become non restful. They are putting methods in rest that are "SearchByDate", "SearchByItem" etc.

Service Methods that execute commands are called with a "web" model class, a new command is built in the service and executed, I feel like there is a lot of extra code.

I expected this to be much different but I wasn't around to keep things on track.

Finally my questions are this...

I would have liked to see PUT Person (CreatePersonCommand) but then I realized that isn't restful either is it? the put should be a person entity not a command.

Can I make CQRS and REST service work together or am I going about this all wrong?

How do I handle service methods that don't fit into a REST model. I am not performing CRUD on the object but rather executing some business logic. I.E. I don't want the UI to be responsible for how a shipment is "unshipped" I want the service layer to worry about that.


答:
First, while it is true that there always exists an equivalent iterative equivalent to any recursive algorithm, it is not necessarily the case that the iterative equivalent is better, for any reasonable definition of "better".

For some algorithms, the iterative equivalent winds up just simulating the recursive algorithm, complete with simulated parameter and local variable stacking and unstacking.  Consider Ackermann's Function.  Consider Huffman coding.  In these cases, there is very little gained by (re)writing the explicit stack operations.

Second, it is not necessarily the case that recursion is always more expensive than iteration.  Consider tail recursion, and read the "Lambda: The Ultimate..." papers.

(Yes, I know this needs expansion.  I have to go to a doctor's appointment right now.)

OK, there are some things that can be said.

Tony Hoare originally described Quicksort iteratively, and he reported that it was very difficult to explain.  Explained recursively, it is SIMPLE.  See Quicksort in Haskell for the details.  If the array has length equal to one, you are finished, otherwise, you actually have to sort it.  First, you pick a pivot element.  Traditionally, this is the first element, but any element can be used.
 Next, you take a pass over the array, to form three subarrays.  The first is all elements less than the pivot, the second is all elements equal to the pivot, and the third is all elements greater than the pivot.  (If the array element values are required to be unique, then the length of the second subarray is equal to one.)  Now quicksort the first subarray, and then quicksort the second subarray.

Binary search is easiest to understand when presented recursively, and it is in fact tail-recursive.  You probe the middle element of the array.  If it is equal to the value you are looking for, you are done.  If the middle element is greater than the value you seek, then you know that the desired value must lie "to the left", and you search the subarray before the middle element, otherwise you search the subarray after the middle element.  In both cases, you know that the middle element is not the target, so you leave it out.  You either find your target, or you run out of array to search.  At that point, you bail all the way out, and you're done.  In the year 2014, never mind 2019, any self-respecting compiler knows how to do tail recursion optimization, even Java compilers.  (Note: The classic Java virtual machine does not support general tail call optimization, for lack of a general GOTO operation, but that does not affect tail recursion optimization.)

The real problem, a lot of places, is that the people running the show never learned about tail recursion optimization, and so they ban all recursion.  I ran into this at Nortel Networks, and had to write a full page of comments explaining it and some related concepts AND show them the assembly language listings that proved the compiler was NOT actually generating recursive calls.  Nortel is gone now, but those managers still exist in a lot of places.

Hope this helps.

Title: Are there advantages for using recursion over iteration - other than sometimes readability and elegance?

Body:
I am about to make two assumptions. Please correct me if they're wrong:

There isn't a recursive algorithm without an iterative equivalent.

Iteration is always cheaper performance-wise than recursion (at
least in general purpose languages such as Java, C++, Python etc.).

If it's true that recursion is always more costly than iteration, and that it can always be replaced with an iterative algorithm (in languages that allow it) - than I think that the two remaining reasons to use recursion are: elegance and readability.

Some algorithms are expressed more elegantly with recursion. E.g. scanning a binary tree.

However apart from that, are there any reasons to use recursion over iteration? Does recursion have advantages over iteration other than sometimes elegance and readability?


答:
Well, it's usually less code.

And to the extent that it's less code, it's less error-prone.

In particular, recursion is very beneficial when the iterative solutions requires that you simulate recursion with a stack. Recursion acknowledges that the compiler already manages a stack to accomplish precisely what you need. When you start managing your own, not only are you likely re-introducing the function call overhead you intended to avoid; but you're re-inventing a wheel (with plenty of room for bugs) that already exists in a pretty bug-free form.

IMO, only eschew recursion if it can be done naturally and easily without a stack. (Or other non-scalar state and/or scope management structure.)


问:
How should I refactor switch statements like this (Switching on type) to be more OO?
I'm seeing some code like this in our code base, and want to refactor it:

(Typescript psuedocode follows):

```<code>class EntityManager{

private findEntityForServerObject(entityType:string, serverObject:any):IEntity {

    var existingEntity:IEntity = null;

    switch(entityType) {
      case Types.UserSetting:
            existingEntity = this.getUserSettingByUserIdAndSettingName(serverObject.user_id, serverObject.setting_name);
                break;

        case Types.Bar:
            existingEntity = this.getBarByUserIdAndId(serverObject.user_id, serverObject.id);
            break;

        //Lots more case statements here...
    }
    return existingEntity;
 }

 }
</code>```

The downsides of switching on type are self-explanatory. Normally, when switching behavior based on type, I try to push the behavior into subclasses so that I can reduce this to a single method call, and let polymorphism take care of the rest.

However, the following two things are giving me pause:

1) I don't want to couple the serverObject with the class that is storing all of these objects. It doesn't know where to look for entities of a certain type. And unfortunately, the identity of a type of ServerObject varies with the type of ServerObject. (So sometimes it's just an ID, other times it's a combination of an id and a uniquely identifying string, etc). And this behavior doesn't belong down there on those subclasses. It is the responsibility of the EntityManager and its delegates.

2) In this case, I can't modify the ServerObject classes since they're plain old data objects. It should be mentioned that I've got other instances of the above method that take a parameter like "IEntity" and proceed to do almost the same thing (but slightly modify the name of the methods they're calling to get the identity of the entity). So, we might have:

```<code>        case Types.Bar:
            existingEntity = this.getBarByUserIdAndId(entity.getUserId(), entity.getId());
            break;
</code>```

So in that case, I can change the entity interface and subclasses, but this isn't behavior that belongs in that class.

So, I think that points me to some sort of map. So eventually I will call:

```<code>private findEntityForServerObject(entityType:string, serverObject:any):IEntity {

    return aMapOfSomeSort[entityType].findByServerObject(serverObject);

}

private findEntityForEntity(someEntity:IEntity):IEntity {
    return aMapOfSomeSort[someEntity.entityType].findByEntity(someEntity);
}
</code>```

Which means I need to register some sort of strategy classes/functions at runtime with this map. And again, I darn well better remember to register one for each my my types, or I'll get a runtime exception.

Is there a better way to refactor this? I feel like I'm missing something really obvious here.

答:
I would map between entityTypes and an object that knows what to do with that entity type. So you might have something like

```<code>private findEntityForServerObject(entityType:string, serverObject:any):IEntity {
    EntityFinder entityFinder = EntityFinder.getForEntity(entityType);
    return entityFinder.find(serverObject);
}
</code>```

You will then be pushing the switch into EntityFinder which will have a static method along the following lines

```<code>class EntityFinder {
    public static EntityFinder getForEntity(String entityType) {
        switch (entityType) {
            case Types.UserSetting:
               return new UserSettingsFinder();
            case Types.Bar:
               return new BarSettingsFinder();
            default:
               // Possibly better than a null pointer
               return new UnknownSettingsFinder();
        }
    }
}
</code>```

If you introduce a new type, you will have to remember to include it in the switch but hopefully, you will only have one place to do this.

Body:
I would map between entityTypes and an object that knows what to do with that entity type. So you might have something like

private findEntityForServerObject(entityType:string, serverObject:any):IEntity {
    EntityFinder entityFinder = EntityFinder.getForEntity(entityType);
    return entityFinder.find(serverObject);
}

You will then be pushing the switch into EntityFinder which will have a static method along the following lines

class EntityFinder {
    public static EntityFinder getForEntity(String entityType) {
        switch (entityType) {
            case Types.UserSetting:
               return new UserSettingsFinder();
            case Types.Bar:
               return new BarSettingsFinder();
            default:
               // Possibly better than a null pointer
               return new UnknownSettingsFinder();
        }
    }
}

If you introduce a new type, you will have to remember to include it in the switch but hopefully, you will only have one place to do this.


答:
Whenever you start switching by type (or providing if's based on type), then you're going against the OO model. In a good OO design, the implementation class should be hidden from the calling code.

(That said, there are times when it's easier to do a quick instanceof, but I try to make it rare).

Polymorphism is the answer here.

Really, what you're doing is calling some common action on some classes. So spin off an interface that defines that common call, and then reference the objects through that interface.

In other words, whenever I see myself writing "if xxx.class" or "xxx instanceof" or "switch (xxx.class)", I ask myself is there's a common interface I can pull out.

Now, it can be tricky. If the different classes require different parameters, you might need to use some sort of Builder pattern. It can get complicated.

But the short answer, anyway, is: if you're switching or iffing based on class type, you should really be using polymorphism instead.

Title: How should I refactor switch statements like this (Switching on type) to be more OO?

Body:
I'm seeing some code like this in our code base, and want to refactor it:

(Typescript psuedocode follows):

```<code>class EntityManager{

private findEntityForServerObject(entityType:string, serverObject:any):IEntity {

    var existingEntity:IEntity = null;

    switch(entityType) {
      case Types.UserSetting:
            existingEntity = this.getUserSettingByUserIdAndSettingName(serverObject.user_id, serverObject.setting_name);
                break;

        case Types.Bar:
            existingEntity = this.getBarByUserIdAndId(serverObject.user_id, serverObject.id);
            break;

        //Lots more case statements here...
    }
    return existingEntity;
 }

 }
</code>```

The downsides of switching on type are self-explanatory. Normally, when switching behavior based on type, I try to push the behavior into subclasses so that I can reduce this to a single method call, and let polymorphism take care of the rest.

However, the following two things are giving me pause:

1) I don't want to couple the serverObject with the class that is storing all of these objects. It doesn't know where to look for entities of a certain type. And unfortunately, the identity of a type of ServerObject varies with the type of ServerObject. (So sometimes it's just an ID, other times it's a combination of an id and a uniquely identifying string, etc). And this behavior doesn't belong down there on those subclasses. It is the responsibility of the EntityManager and its delegates.

2) In this case, I can't modify the ServerObject classes since they're plain old data objects. It should be mentioned that I've got other instances of the above method that take a parameter like "IEntity" and proceed to do almost the same thing (but slightly modify the name of the methods they're calling to get the identity of the entity). So, we might have:

```<code>        case Types.Bar:
            existingEntity = this.getBarByUserIdAndId(entity.getUserId(), entity.getId());
            break;
</code>```

So in that case, I can change the entity interface and subclasses, but this isn't behavior that belongs in that class.

So, I think that points me to some sort of map. So eventually I will call:

```<code>private findEntityForServerObject(entityType:string, serverObject:any):IEntity {

    return aMapOfSomeSort[entityType].findByServerObject(serverObject);

}

private findEntityForEntity(someEntity:IEntity):IEntity {
    return aMapOfSomeSort[someEntity.entityType].findByEntity(someEntity);
}
</code>```

Which means I need to register some sort of strategy classes/functions at runtime with this map. And again, I darn well better remember to register one for each my my types, or I'll get a runtime exception.

Is there a better way to refactor this? I feel like I'm missing something really obvious here.


问:
If you had to go back and re-learn your skill set, how would you do it?
My younger brother is looking to start programming. He's 14, and technically-inclined, but no real experience programming. He's looking to me for guidance, and I don't feel as if my experience is enough, so I figured I'd ask here.

He's more interested in web programming, but also has an interest in desktop/mobile/server applications.

What would be a good learning path for him to take? I'm going to buy him a bunch of books for Christmas to get him started; the question is, what should he learn, and in which order?

The way I see it, he needs to learn theory and code. I'd like to start him off with Python or Ruby or PHP. If he wants to get in to web, he's also going to need to learn HTML, CSS, Javascript, etc.

Out of those three domains (Languages, Theory, Markup/Etc.), what is the best order do you think to learn in? Also, am I missing anything?

Thanks!

答:
I never thought I'd say this, but get him Alice 3.0.

I hate Alice with the burning fury of a thousand suns, but it definitely does do a good job of teaching the fundamentals of programming (loops, statements, functions, etc.) when coupled with a decent tutorial.

Once he's solid on the basics, move on to a more practical text-based language.

ContentLicense: CC BY-SA 2.5


答:
Short Answer:

When you have to call a lot of functions down the line, it better callbacks modify state of an object, rather than return something.

When you don't really need to call a lot of functions, its okay if the callback return something back.

Long Answer:

When the framework in concern is involved with dispatching a chain of messages (or in other words, call a lot of routines/functions) which control the application's behaviour, then we'd go for modifying the value of a variable or an object's state rather than returning something back.

A good example of this is windows forms.

A detailed article about it will be linked to later.

In brief however,

windows forms is a framework which abstracts all the low-level message handling, characteristic of a gui-based app.

Through out the application's lifetime the app receives messages from the OS (reads it off a queue) and sends messages (to the OS).

Usually when a message is consumed, it results in an "event" in our application.

In classic windows application (using pure API or winapi) we only concern about some messages (like close, click, etc).

The windows forms framework however handles "all" the messages.

A windows forms app typically subscribes to a subset of the events; so essentially the apps responds to a subset of the messages

Most of these events modify the state of an object passed to it as argument based on which the framework decides how to respond. The framework needs to send messages to the OS, and receive messages from the queue. There are standard functions for this (defined by the API of course).

In this case, reading the state of a mutated object (and then deciding what message to send to the OS) serves to be "faster". (Imagine this in terms of how pure assembly instructions would execute).

Now when would you actually want to use a return?

In a few words, I'd say, when you don't have to call so many different functions down the line. Good example is jQuery's each iterator.

```<code>$.each([1, 2, 3, 4], function foo(_, v) {
   if(v === 2) return false;
   console.log(v);
});
</code>```

In this case jQuery simply calls function foo (name given for reference sake), and not anything else, so a callback returning something is "affordable" here. It also makes up for better understanding of code.

Body:
Short Answer:

When you have to call a lot of functions down the line, it better callbacks modify state of an object, rather than return something.

When you don't really need to call a lot of functions, its okay if the callback return something back.

Long Answer:

When the framework in concern is involved with dispatching a chain of messages (or in other words, call a lot of routines/functions) which control the application's behaviour, then we'd go for modifying the value of a variable or an object's state rather than returning something back.

A good example of this is windows forms.

A detailed article about it will be linked to later.

In brief however,

windows forms is a framework which abstracts all the low-level message handling, characteristic of a gui-based app.

Through out the application's lifetime the app receives messages from the OS (reads it off a queue) and sends messages (to the OS).

Usually when a message is consumed, it results in an "event" in our application.

In classic windows application (using pure API or winapi) we only concern about some messages (like close, click, etc).

The windows forms framework however handles "all" the messages.

A windows forms app typically subscribes to a subset of the events; so essentially the apps responds to a subset of the messages

Most of these events modify the state of an object passed to it as argument based on which the framework decides how to respond. The framework needs to send messages to the OS, and receive messages from the queue. There are standard functions for this (defined by the API of course).

In this case, reading the state of a mutated object (and then deciding what message to send to the OS) serves to be "faster". (Imagine this in terms of how pure assembly instructions would execute).

Now when would you actually want to use a return?

In a few words, I'd say, when you don't have to call so many different functions down the line. Good example is jQuery's each iterator.

$.each([1, 2, 3, 4], function foo(_, v) {
   if(v === 2) return false;
   console.log(v);
});

In this case jQuery simply calls function foo (name given for reference sake), and not anything else, so a callback returning something is "affordable" here. It also makes up for better understanding of code.


问:
POST and PUT requests – is it just the convention?
I've read quite a few articles on the difference between POST and PUT and in when the two should be used. But there are still few things confusing me ( hopefully questions will make some sense ):

1) We should use PUT to create resources when we want clients to specify the URI of the newly created resources and we should use POST to create resources when we let service generate the URI of the newly created resources.

a) Is it just by convention that POST create request doesn't contain an URI of the newly created resource or POST create request actually can't contain the URI of the newly created resource?

b) PUT has idempotent semantics and thus can be safely used for absolute updates ( ie we send entire state of the resource to the server ), but not also for relative updates ( ie we send just changes to the resource state ), since that would violate its semantics.

But I assume it's still possible for PUT to send relative updates to the server, it's just that in that case the PUT update won't be idempotent?

2) I've read somewhere that we should "use POST to append a resource to a collection identified by a service-generated URI".

a) What exactly does that mean? That if URIs for the resources were generated by a server ( thus the resources were created via POST ), then ALL subsequent resources should also be created via POST? Thus, in such situation no resource should be created via PUT?

b) If my assumption under a) is correct, could you elaborate why we shouldn't create some resources via POST and some via PUT ( assuming server already contains a collection of resources created via POST )?

答:
Read the HTTP spec that defines those methods. Seriously. It will clarify a lot of questions for you going forward.

http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

In HTTP, PUT is specifically the create / update method. Create if it doesn't exist, or update it if it does.

POST is sort of the grab-bag method. As Roy Fielding has said, it's the method to use when you don't want to generalize your operation.

Their usage has broken down this way in RESTish services:

Usually, create has fallen into the POST camp, because of the idea of "appending to a collection." It's become the way to append a resource to a list of resources.

However, POST is also the "data processing" method, so it's also applicable for ANYTHING ELSE YOU WANT TO DO. If you want to drive a battleship through a loophole in REST, use POST.

Taken together, POST is useful for create, because you can say "process this (incomplete) data, and append it to this list resource".

The semantics of PUT are much more specific. PUT is the "make it so" method. So if you have a complete representation, and a complete URL, then you PUT it and "make it so". If it doesn't already exist, the service will create it.

So, yes, both PUT and POST can be appropriate for create. Even for update, you might want to POST a piece of data for the resource to process. You can't draw a bright-line definition between CREATE / UPDATE and PUT / POST.

I've seen lots and lots of people try to map CRUD explicitly to the HTTP methods, but it always breaks down, because a) HTTP follows a "update or create" model and not a separate create and update model, and b) the breadth of POST is so large. Also, there are subtleties in the way data is processed that CRUD misses -- like identifier generation.

...

For example, let's say the Galactic Police Academy has a REST service. They have a Cadet resource & you can GET a Cadet by their helmet # for their service details.

GET http://galacticpoliceacademy/cadets/12345

All the Cadets are another resource that retrieves a list or collection of cadets:

GET http://galacticpoliceacademy/cadets/

Notice that the individual GET just adds information to the collection resource.

Now, if I get accepted to the Galactic Police Academy, I don't have my helmet # yet, so we'll POST my information to the collection.

POST http://galacticpoliceacademy/cadets/

{ info: "my info" }

Which will process my information, assign me a helmet number, and add me to the collection. Now the collection of cadets has 1 more item (i.e. me), and I can GET my details using my newly assigned helmet #. I can also pull the list of cadets, and I will be there in the list.

Some cadets transfer from the Provisional Frontier Militia, and already have their own helmets. They can just be PUT into the /cadets/ collection directly, since they already have a helmet number. The helmet numbers are unique, so they won't collide with another cadet, and they'll just be put straight into the list, as-is.

(!) If the asteroid that the academy is on gets blown up by space criminals, and we need to rebuild on a new asteroid, then I could PUT a copy of the existing list, or PUT a record for each of the survivors, and in the end I'd have a list of cadets that looks exactly like the data I have. Then I could start POSTing as I refill the ranks.

There's a surge of patriotism after the attack on the Academy, resulting in a large number of new recruits. We can POST a list of new recruits (without helmets) and the New Academy service will append each to the list and assign each of them a helmet #.

So your example of 10 / 11 items in a resource collection is right on -- that's correct behavior. Usually I don't mix PUT and POST for create for a particular resource, but the HTTP semantics allow it.