问:
Algorithm to assign edges to smallest possible polygons?
I'm designing a procedural city generator, and the first step of the generation process is the creation of city streets. These streets extend out in a straight line to a point, then they can either branch, rotate, or continue in the same direction. If a street would hit another street, it can either stop growing or attach to the nearest junction.

I've been thinking of the junctions as vertices and the streets as edges. From this, I should be able to break the network up into a collection of the smallest possible polygons -- i.e., a space enclosed on all sides by streets.

So long as a street has 2 junctions on either side, I would like to have that as the edge of a polygon. I remove streets that are "dead ends" (vertices that only have one edge attaching to them) from consideration before processing, so they're not an issue.

So given a collection of vertices and edges, what is a good way to break them up into the smallest possible polygons? It doesn't matter if the polygon is convex or concave, as it would primarily be used as a way to load in bits of the city and mark an area as loaded or unloaded and selectively choose bits of the city for simulation. It's also important that I am able to create new areas at runtime to allow for a semi-infinite map.

You'll have to pardon my hastily-thrown-together image, but say I have a network that looks like this:

I'd like the output to produce something like this:

I've tried to accomplish this on my own, but I had a few issues (mainly when it came to determining if an edge would be "shared" by 2 polygons -- in my above example, the edge F is shared by AEF and FGMOL, while A only belongs to AEF).

Since this seems like a problem that would be common in the graphics industry, I figured there should be a readily-accessible algorithm for it. I looked at Andrew's Monotone Chain Algorithm, but it seems like it does the opposite (returning the LARGEST polygon from a set of points).

It is entirely possible that I'm looking at this in completely the wrong way, so any help would be appreciated. My apologies if I posted this to the wrong section -- I tried posting this question to StackOverflow, and they redirected me here.

Thank you!

答:
See here for an algorithm.  Consider each undirected edge as actually two edges, one going in each direction.  Basically, if you order the edges around each vertex by angle, that will let you walk around each face in a clockwise direction, and you cross off each edge as you walk it.  Then you pick and edge that hasn't been crossed off, and walk around starting with it.

However, since you're the one generating the graph, it might be easier just to generate the faces in the first place.  When you get to a vertex on the edge of a map, take a left, and follow the outside edge by keeping taking the first right.  Then branch off to the right and keep going around clockwise until you get back to the original vertex, taking care not to create a loop that doesn't include the original vertex.  Then perhaps split the face once or twice.


问:
Should a scrum team estimate time for the user stories during Sprint Planning, or before it?
I am newbie for scrum. Lets say we have all the user stories for the product, and the product owner gave them the priorities. Now as a team, when we should estimate times for these stories? Should we estimate times for all the stories roughly before the sprint planning then updating them if it is necessary during sprint planning?

Actually I am curious which part of scrum first time estimation should be begin? During sprint planning or where?

答: Typically, teams hold backlog grooming meetings during a sprint to discuss and estimate the items in their backlog. Having at least the highest priority portion of the backlog estimated before the planning meeting makes planning for the next sprint go much more quickly. It lets the team focus on which items will be part of the next sprint rather than getting into the details of individual items.</p>

ContentLicense: CC BY-SA 3.0


问:
Most efficient way to generate all descendents of all nodes in a tree
I'm looking for the most efficient algorithm to take a tree (stored as either a list of edges; OR as a list of mappings from parent node to a list of child nodes); and produce, for EVERY node, a list of all nodes descended from it (leaf level and non-leaf level).

The implementation must be via loops instead of recusion, due to scale; and should ideally be O(N).

This SO question covers a standard reasonably obvious solution for finding the answer for ONE node in a tree. But obviously, repeating that algorithm on every tree node is highly inefficient ( off the top of my head, O(NlogN) to O(N^2) ).

The tree root is known. The tree is of absolutely arbitrary shape (e.g. not N-nary, not balanced in any way, shape or form, not uniform depth) - some nodes have 1-2 children, some have 30K children.

On a practical level (though it shouldn't affect the algorithm) the tree has ~100K-200K nodes.

答:
Normally, you would just use a recursive approach, because it allows you to switch your execution order around such that you can calculate the number of leaves starting from the leaves upwards. Since, you would have to use the result of your recursive call to update the current node, it would take special effort to get a tail recursive version. If you do not take that effort, then of course, this approach would simply explode your stack for a large tree.

Given that we realized the main idea is to get a looping order starting at the leaves and going back up towards the root, the natural idea that comes to mind is to perform a topological sort on the tree. The resulting sequence of nodes can be traversed linearly in order to sum the number of leaves (assuming you can verify a node is a leaf in O(1)). The overall time complexity of the topological sort is O(|V|+|E|).

I assume that your N is the number of nodes, which would be |V| typically (from the DAG nomenclature). The size of E on the other hand highly depends on your tree's arity. For example, a binary tree has at most 2 edges per node, therefore O(|E|) = O(2*|V|) = O(|V|) in that case, which would result in an overall O(|V|) algorithm. Note that due to the overall structure of a tree, you cannot have something like O(|E|) = O(|V|^2). In fact, since each node has a unique parent, you can have at most one edge to count per node when you consider only parent-relations, so for trees we have a guarantee that O(|E|) = O(|V|). Therefore, the above algorithm is always linear in the size of the tree.


问:
Doing the same thing from different views
I have an MVC app, which has multiple views that give overviews (from different angles) on items.

For now, let's just call these views

View1

View2

...

ViewX

They all use the same Model Collection as a basis

As of now I have one controller per view (View1Controller, View2Controller, ...), and furthermore, I have ItemEditView and ItemEditController for the item edit window.

When certain interactions occur inside the numbered views, the same actions have to be done:

Action Chain 1: Boil down the clicked position/button to two values, check whether these two values allow to make a new item, if so, open the ItemEditView to create a new item.

Action Chain 2: Check whether this item may be shown, if so, open ItemEditView to edit the item.

Action Chain 3: Check whether this item may be changed, if so, update it based on the position it was dragged to.

How would I best split this into functions and controllers?

As of now, the function View2Controller.ItemClicked() calculates some additional parameters required by View1Controller, and then calls View1Controller.ItemClicked()... I guess this is a terrible mess, but where would I put common functions of all ViewXControllers?

Or should I put all functions of all the Views into a common controller?

答:
If I understand this correctly, you are describing a composition rather than distinct views.

There is a item which can be clicked and which opens a edit view.

There is a view which contains the item and decides if editing of the item is allowed.

There is a view which contains the item and performs model modifications without opening a edit view.

I don't know if the framework you work with allows this kind of composition, but this is how I would design this: The item itself consists of a view and controller and handles the clicking and opening a edit view. The second view enables/disables the item based on rules if the item may be edited. The third view disables editing for the item and only uses it for displaying data.


问:
What can slow a developer down?
What things tend to slow a developer down?

Please try to refrain from posting answers that:

are slow now but useful in the feature. (TDD, Refactoring, ...)

list a distraction.

答: Anything that causes context switching.</p>

ContentLicense: CC BY-SA 2.5

Title: What can slow a developer down?

Body: Anything that causes context switching.


问:
Model-View-Controller: who creates whom?
In "Pattern Oriented Software Architecture - Vol 1" (p. 131), the author said that View is responsible for creating Controller. But in "Head First Design Patterns" (p. 562) it is the Controller that creates the View. In some other references I see that nor View niether Controller create each other. Only Controller has a reference of View and/or vice versa.
What's your opinion about this? Does this depend?

答:
Well, I can only assume this changes along different platforms.
On the android library, you create the view from the controller.

i.e., in your Activity you call setContentView... to "awake" you XML (The view) and create it.

On the other hand, in the iOS world, you would ask the View (storyboard or .xib file) to awake (Actually you ask the system to go to the app's bundle, get the View and create it) itself up, than it will awake your controller (e.g., myView) and awakeFromNib will be called...

I might not be precise about the small details, but you can see that different platforms would create this connection in slightly different ways, depends on the architecture.


问:
How to make significant technical decisions given very little time
I have got 2 days for making a very serious decision about the tools and platforms that my company is going to use in order to port its WPF application to Linux / Android / iOS whatnot.

Obviously I can point to my seniors that 2 days is hardly enough for reading about all possible options, and what about trying, making prototypes etc. I can say it, it won't help me a bit, I have got 2 days, and after 2 days the decision would be made. Period.

From one side I am frustrated, from other side I think there is a grain of truth in this approach, otherwise I can easily find myself buried under dozens of downloaded SDKs, frameworks,  APIs, blog articles etc etc doing bench-works, running samples and forgetting in the process what it all was for.

Still I am afraid that a wrong decision will cost the company dearly.
So what do you think is an "ideal" process for making such decisions?

答:
As much as I like to learn and experiment new stuff, under time constraints the best option is always to go for whatever is or feels more comfortable to work with. Stick to what you know.

Even if in the long run it becomes clear you didn't choose the best option, anything you developed meanwhile continues being valuable and wraps a kind of field knowledge that is still completely usable and portable. And that's exactly because the comfortable context, tools, platform you chose to use stay out of the way and make you see what really matters.


问:
Is address 0000000C a special address?
When programming sometimes things break. You made a mistake and your program tries to read from a wrong address.

One thing that stands out to me that often those exceptions are like :

```<code>Access violation at address 012D37BC in module 'myprog.exe'. Read of address 0000000C.
</code>```

Now I see a lot of error logs and what stands out to me is the : 0000000C. Is this a "special" address? I see other access violations with bad reads but the addresses just seem random, but this one keeps coming back in totally different situations.

答:
As for why 0x0C seems more common than 0x08 (is it really? I don't know; and in what kinds of applications?), this might have to do with virtual method table pointers. This is really more of a comment (wild mass guessing :), but it's somewhat larger, so here goes... If you've got a class with virtual methods, its own fields are going to be shifted by 0x04. For example, a class that inherits from another virtual class might have a memory layout like this:

```<code>0x00 - VMT pointer for parent
0x04 - Field 1 in parent
0x08 - VMT pointer for child
0x0C - Field 1 in child
</code>```

Is this a common scenario, or even close? I'm not sure. However, note that in a 64-bit application, this could get even more interestingly shifted towards the 0x0C value:

```<code>0x00 - VMT parent
0x08 - Field 1 parent
0x0C - VMT child
0x14 - Field 2 child
</code>```

So there's actually a lot of cases where applications might have significant overlap in null-pointer offsets. It might be the first field in a child class, or its virtual method table pointer - needed whenever you call any virtual method on an instance, so if you're calling a virtual method on a null pointer, you'll get access violation on its VMT offset. The prevalence of this particular value might then have something to do with some common API that provides a class which has a similar inheritance pattern, or more likely, a particular interface (quite possible for some classes of applications, like DirectX games). It might be possible to track some simple common cause like this, but I tend to get rid of applications that do null dereferencing pretty quickly, so...

Title: Is address 0000000C a special address?

Body:
As for why 0x0C seems more common than 0x08 (is it really? I don't know; and in what kinds of applications?), this might have to do with virtual method table pointers. This is really more of a comment (wild mass guessing :), but it's somewhat larger, so here goes... If you've got a class with virtual methods, its own fields are going to be shifted by 0x04. For example, a class that inherits from another virtual class might have a memory layout like this:

0x00 - VMT pointer for parent
0x04 - Field 1 in parent
0x08 - VMT pointer for child
0x0C - Field 1 in child

Is this a common scenario, or even close? I'm not sure. However, note that in a 64-bit application, this could get even more interestingly shifted towards the 0x0C value:

0x00 - VMT parent
0x08 - Field 1 parent
0x0C - VMT child
0x14 - Field 2 child

So there's actually a lot of cases where applications might have significant overlap in null-pointer offsets. It might be the first field in a child class, or its virtual method table pointer - needed whenever you call any virtual method on an instance, so if you're calling a virtual method on a null pointer, you'll get access violation on its VMT offset. The prevalence of this particular value might then have something to do with some common API that provides a class which has a similar inheritance pattern, or more likely, a particular interface (quite possible for some classes of applications, like DirectX games). It might be possible to track some simple common cause like this, but I tend to get rid of applications that do null dereferencing pretty quickly, so...


答: Does it really matter what creates what though? It depends imo, as long as business logic and view are separated it's alright. Controller should have a reference to both of them and provide means to translate data from the logic to the view and vice versa. But honestly, in real world applications, no matter how hard you try you will put some of the logic inside of the controller too.</p>

Title: Model-View-Controller: who creates whom?

Body:
In "Pattern Oriented Software Architecture - Vol 1" (p. 131), the author said that View is responsible for creating Controller. But in "Head First Design Patterns" (p. 562) it is the Controller that creates the View. In some other references I see that nor View niether Controller create each other. Only Controller has a reference of View and/or vice versa.
What's your opinion about this? Does this depend?


答:
The inefficient part is not traversing the tree, but building the lists of nodes. It would seem sensible to create the list like this:

```<code>descendants[node] = []
for child in node.childs:
    descendants[node].push(child)
    for d in descendants[child]:
        descendants[node].push(d)
</code>```

Since each descendant node is copied into the list of each parent, we end up with O(n log n) complexity on average for balanced trees, and O(n²) worst case for degenerate trees that are really linked lists.

We can drop to O(n) or O(1) depending on whether you need to do any setup if we use the trick of calculating the lists lazily. Assume we have a child_iterator(node) that gives us the childs of that node. We can then trivially define a descendant_iterator(node) like this:

```<code>def descendant_iterator(node):
  for child in child_iterator(node):
    yield from descendant_iterator(child)
  yield node
</code>```

A non-recursive solution is much more involved, since iterator control flow is tricky (coroutines!). I'll update this answer later today.

Since traversal of a tree is O(n) and iteration over a list is linear as well, this trick completely defers the cost until it is paid anyway. For example, printing out the list of descendants for each node has O(n²) worst case complexity: Iterating over all nodes is O(n) and so is iterating over each node's descendants, whether they are stored in a list or calculated ad hoc.

Of course, this won't work if you need an actual collection to work on.

Title: Most efficient way to generate all descendents of all nodes in a tree

Body:
I'm looking for the most efficient algorithm to take a tree (stored as either a list of edges; OR as a list of mappings from parent node to a list of child nodes); and produce, for EVERY node, a list of all nodes descended from it (leaf level and non-leaf level).

The implementation must be via loops instead of recusion, due to scale; and should ideally be O(N).

This SO question covers a standard reasonably obvious solution for finding the answer for ONE node in a tree. But obviously, repeating that algorithm on every tree node is highly inefficient ( off the top of my head, O(NlogN) to O(N^2) ).

The tree root is known. The tree is of absolutely arbitrary shape (e.g. not N-nary, not balanced in any way, shape or form, not uniform depth) - some nodes have 1-2 children, some have 30K children.

On a practical level (though it shouldn't affect the algorithm) the tree has ~100K-200K nodes.

Body:
The inefficient part is not traversing the tree, but building the lists of nodes. It would seem sensible to create the list like this:

descendants[node] = []
for child in node.childs:
    descendants[node].push(child)
    for d in descendants[child]:
        descendants[node].push(d)

Since each descendant node is copied into the list of each parent, we end up with O(n log n) complexity on average for balanced trees, and O(n²) worst case for degenerate trees that are really linked lists.

We can drop to O(n) or O(1) depending on whether you need to do any setup if we use the trick of calculating the lists lazily. Assume we have a child_iterator(node) that gives us the childs of that node. We can then trivially define a descendant_iterator(node) like this:

def descendant_iterator(node):
  for child in child_iterator(node):
    yield from descendant_iterator(child)
  yield node

A non-recursive solution is much more involved, since iterator control flow is tricky (coroutines!). I'll update this answer later today.

Since traversal of a tree is O(n) and iteration over a list is linear as well, this trick completely defers the cost until it is paid anyway. For example, printing out the list of descendants for each node has O(n²) worst case complexity: Iterating over all nodes is O(n) and so is iterating over each node's descendants, whether they are stored in a list or calculated ad hoc.

Of course, this won't work if you need an actual collection to work on.


问:
What should be the structure of a person to person store database?
I am going to create a person to person store with Laravel, a website where its users can share and sell their product or their mobile, TV, Computer, Shoes, Shirts, Books, Cars, Bags, Animal, etc.

I am going to create a table named products and other tables about products are, for example, bugs, Animals, Cars, Shirts, Shoes, Computers.

products table:

```<code>product_id   |   cat_id     |   title    |   cost    |    timestamp
</code>```

cars table:

```<code>      id     |  product_fk  |     brand   |   model   |    type    |  Fuel  | ...
</code>```

computers table:

```<code>     id     |  product_fk  |     brand   |   type     |    CPU     |  GPU    |  hard_disk  |  ...
</code>```

I will create other tables with this way.

I want to search database by titles and their type , I mean I just search the products table

I want to know

Is there any other way (better and easier) to do this?

What do you think about this structure?

答:
You can use this structure too...</p>

```<code>Products:
--------
ProductID | CategoryID | Title | Cost | TimeStamp
1         | 1          | Audi  | $0   | -----

Specifications
--------------
SpecificationID | Specification
1               | Model
2               | Fuel
3               | HardDisk

ProductSpecifications:
----------------------
ProductSpecificationID | ProductID | SpecificationID | Value
1                      | 1         | 1               | xyz
1                      | 1         | 2               | abc
</code>```

Body:
You can use this structure too...

Products:
--------
ProductID | CategoryID | Title | Cost | TimeStamp
1         | 1          | Audi  | $0   | -----

Specifications
--------------
SpecificationID | Specification
1               | Model
2               | Fuel
3               | HardDisk

ProductSpecifications:
----------------------
ProductSpecificationID | ProductID | SpecificationID | Value
1                      | 1         | 1               | xyz
1                      | 1         | 2               | abc


答: This should take place in the planning game. Armed with the estimates and business priorities, stories are selected for the upcoming sprint.</p>

Title: Should a scrum team estimate time for the user stories during Sprint Planning, or before it?

Body:
I am newbie for scrum. Lets say we have all the user stories for the product, and the product owner gave them the priorities. Now as a team, when we should estimate times for these stories? Should we estimate times for all the stories roughly before the sprint planning then updating them if it is necessary during sprint planning?

Actually I am curious which part of scrum first time estimation should be begin? During sprint planning or where?


问:
How much logic can be put into a command? Or differently: What kind of logic is command pattern for?
I have been using the command pattern for quite some time but I'm never really sure how much logic I can actually put in the Execute method.

My current implementation of the command pattern looks similar to this:

```<code>public abstract class Command
{
    public static event EventHandler Completed = delegate { };

    public bool Success { get; private set; }

    public Exception Exception {get; private set; }

    public abstract bool Execute();

    protected bool OnCompleted(bool success, Exception ex = null)
    {
        Success = success;
        Exception = ex;
        Completed(this, EventArgs.Empty)
        return success;
    }
}
</code>```

and these are the questions that I ask myself (and practice in my commands):

Is it OK to show messege boxes or file open dialogs etc.?

Is it OK to set properties of any object?

Can a command contain business logic?

Can a command modify GUI controls in anyway?

Which layer commands belong to? View or data layer? Can I have commands in both layers?

Can a command do all that what previously was in the button1_Click?

Should a command by unit-testable?

Can a command be seen as a user that makes use of the APIs and that builds the last layer of an application and also the last resort of catching exceptions?

Can commands be executed also by code (command calls api, api runs and finally some other api calls a command) or can only the user invoke it and the APIs must not know about ther existence?

Is there a place for commands in MVC or MVVC or any other design pattern with a controller? They seem to be mutually exclusive. What's preferable?

There are plenty of tutorials showing how to implement the command pattern but none actually discusses how to apply it in a real wold application.

答:
Most of the benefit of commands is that they make it easy to undo an action, redo an action, perform an action in multiple places (over a network connection), or perform it at a later date, and so on.

With that in mind:

Probably not. It's hard to imagine any situation where "undoing" a dialog box makes sense, and this is the sort of thing I'd rather put in the UI code.

As long as that object is accessible from everywhere that may want to execute the command, then of course it's fine to change its properties.

Absolutely. This ties into whether your model should "contain" business logic; it's actually considered an anti-pattern ("anemic domain model") to have too little business logic in there.

If the GUI controls are part of your model, absolutely. If not, it's questionable.

Definitely not the view. The view should be informed that the data or the model has changed and react accordingly, but the actual change should take place in the data or the model.

In principle, probably yes. Being able to undo commands is one of the best things about the pattern.

The execute() function of the command definitely should be unit tested. Again, if commands are tied to a model of some kind, they're among the easiest parts of an application to test.

I'm not quite sure what you mean, but:

It's perfectly fine for an external API to use commands as input or output. Assuming you validate them, of course.

"last layer" sounds like a View to me. In MVC, the commands probably should be generated by the controller and handled by the model, so it would be sensible to say the view is built "above" the command stuff, if that's what you were going for.

As for exceptions, probably not. In MVC, I'd expect the controller to be the one catching exceptions and turning them into the right kind of dialog box. Not the model/commands.

Absolutely. Most of the benefits of commands are kind of impossible to implement if code never executes them.

It's probably obvious by now, but I do not see them as mutually exclusive at all. On my team at work, the controller translates user-generated events into commands, the model receives and executes the commands (and saves "undo" commands somewhere), and when it's done the controller tells the view to update itself based on the new model. The commands also get sent over the network to any copies of the model being viewed by other users, so they see it as well. It works brilliantly.

And the title question: How much logic to put in one command? I wouldn't put any minimum or maximum on it. What I would say is that it's a very good idea to implement more complex commands using a series of simpler commands, and refactor commands the same way you'd refactor functions.


答:
In the scrum process the tasks are estimated at the sprint planning meeting,

Product owner presents the top priority items from the backlog

Team does the effort estimations for each item

Depending on the time box certain items may be moved to the next sprint or more items may be added to the current sprint.

Read more from : http://www.mountaingoatsoftware.com/agile/scrum/overview


问:
Why is it a good practice to keep Javascript code in separate files?
In web development we are commonly used to keep Javascript code in separate files, but sometimes we need this Javascript code to manipulate server side data locally.

For example, making an Ajax Call to a dynamically created URL server side.

But some programmers My colleagues keep saying that plain Javascript in the JSP file is a sign of bad code, and wrong practices.

To what extent are they right ? Assuming that those blocks of code are not reusable in other pages, why is this practice perceived as a bad thing?

Edit :

Thanks for the quick answers, I'm still wondering how can I manage Dynamically created Javascript code (which cannot be cached, obviously). For example making an ajax call with an URL like this :

```<code>url : ${some_url_coming_from_server},
</code>```

In my case the code is huge, and I have server-data everywhere, am I doing it wrong ?

答:
First thing : A pure JS code in a separate file will be cached, reducing the amount of data transfered on each request.

Unless you have a very small, page specific JS code, you shouldn't inline it.

Other valid reasons are already pointed in Mike's answer.

If you have to pass some values from the server to the JS, what you can do instead of injecting JSP code directly in your JS is to create a function in your external file, and call it from your page, passing your dynamic values as parameters :

JSP:

```<code><script>
    yourFunction(${param1}, ${param2}...);
</script>
</code>```

JS external file:

```<code>function yourFunction (param1, param2...) {
    // do your stuff
}
</code>```

Or even better, especially if you have a large amount of variables, create an object to pass as a parameter instead of passing a bunch of params :

JSP:

```<code><script>
    var obj = {
        param1: ${param1},
        param2: ${param2}
        ...
    }
    yourFunction(obj)
</script>
</code>```

JS external file:

```<code>function yourFunction (obj) {
    // do your stuff using obj.param1, obj.param2...
}
</code>```

Body:
First thing : A pure JS code in a separate file will be cached, reducing the amount of data transfered on each request.

Unless you have a very small, page specific JS code, you shouldn't inline it.

Other valid reasons are already pointed in Mike's answer.

If you have to pass some values from the server to the JS, what you can do instead of injecting JSP code directly in your JS is to create a function in your external file, and call it from your page, passing your dynamic values as parameters :

JSP:

<script>
    yourFunction(${param1}, ${param2}...);
</script>

JS external file:

function yourFunction (param1, param2...) {
    // do your stuff
}

Or even better, especially if you have a large amount of variables, create an object to pass as a parameter instead of passing a bunch of params :

JSP:

<script>
    var obj = {
        param1: ${param1},
        param2: ${param2}
        ...
    }
    yourFunction(obj)
</script>

JS external file:

function yourFunction (obj) {
    // do your stuff using obj.param1, obj.param2...
}


答:
Command Pattern is generally used to decouple WHAT from WHO, and WHAT from WHEN. This is the benefit of having a simple interface as simple as:

```<code>public abstract class Command {
    public abstract void execute();
}
</code>```

Lets imagine that you have a class EngineOnCommand. You can pass this Command to other objects which accept instances of Command. So this means that the class which receives this EngineOnCommand, could also receive a different Command to be executed by it and it should never know it. This means you decoupled WHAT from WHO.

Now, the second case for the Command Patterm is to decouple WHAT from WHEN. Let's imagine that you want to create a system in which the actions in the Database should only be executed at night, but following the sequence in which they were requested. With a queue of Commands in which you can execute one by one you could have achieved this. The idea is that the invocation of the command actually only triggers a enqueue of the command on a list to be executed later.

I hope my examples above helps to understand what is the idea of the pattern. Now I will try to answer some of your questions using the above as basis.

Can a command contain business logic?

yes, I believe it should contain it. It it will contain it in a decoupled way of WHO and WHEN.

Can a command modify GUI controls in anyway?

This means you are coupling it to the GUI. This means it is not being used for the intent of decoupling WHAT from WHO. The command ideally should not know who is invoking it, if it is GUI or a batch functionality.

Should a command by unit-testable?

It should not, it must be unit testable. All the code should be unit testable, but ideally all commands must be unit testable.

Sorry for not answering all your questions, but I believe you should check the GOF book. It contains some good examples.

Title: How much logic can be put into a command? Or differently: What kind of logic is command pattern for?

Body:
I have been using the command pattern for quite some time but I'm never really sure how much logic I can actually put in the Execute method.

My current implementation of the command pattern looks similar to this:

```<code>public abstract class Command
{
    public static event EventHandler Completed = delegate { };

    public bool Success { get; private set; }

    public Exception Exception {get; private set; }

    public abstract bool Execute();

    protected bool OnCompleted(bool success, Exception ex = null)
    {
        Success = success;
        Exception = ex;
        Completed(this, EventArgs.Empty)
        return success;
    }
}
</code>```

and these are the questions that I ask myself (and practice in my commands):

Is it OK to show messege boxes or file open dialogs etc.?

Is it OK to set properties of any object?

Can a command contain business logic?

Can a command modify GUI controls in anyway?

Which layer commands belong to? View or data layer? Can I have commands in both layers?

Can a command do all that what previously was in the button1_Click?

Should a command by unit-testable?

Can a command be seen as a user that makes use of the APIs and that builds the last layer of an application and also the last resort of catching exceptions?

Can commands be executed also by code (command calls api, api runs and finally some other api calls a command) or can only the user invoke it and the APIs must not know about ther existence?

Is there a place for commands in MVC or MVVC or any other design pattern with a controller? They seem to be mutually exclusive. What's preferable?

There are plenty of tutorials showing how to implement the command pattern but none actually discusses how to apply it in a real wold application.

Body:
Command Pattern is generally used to decouple WHAT from WHO, and WHAT from WHEN. This is the benefit of having a simple interface as simple as:

public abstract class Command {
    public abstract void execute();
}

Lets imagine that you have a class EngineOnCommand. You can pass this Command to other objects which accept instances of Command. So this means that the class which receives this EngineOnCommand, could also receive a different Command to be executed by it and it should never know it. This means you decoupled WHAT from WHO.

Now, the second case for the Command Patterm is to decouple WHAT from WHEN. Let's imagine that you want to create a system in which the actions in the Database should only be executed at night, but following the sequence in which they were requested. With a queue of Commands in which you can execute one by one you could have achieved this. The idea is that the invocation of the command actually only triggers a enqueue of the command on a list to be executed later.

I hope my examples above helps to understand what is the idea of the pattern. Now I will try to answer some of your questions using the above as basis.

Can a command contain business logic?

yes, I believe it should contain it. It it will contain it in a decoupled way of WHO and WHEN.

Can a command modify GUI controls in anyway?

This means you are coupling it to the GUI. This means it is not being used for the intent of decoupling WHAT from WHO. The command ideally should not know who is invoking it, if it is GUI or a batch functionality.

Should a command by unit-testable?

It should not, it must be unit testable. All the code should be unit testable, but ideally all commands must be unit testable.

Sorry for not answering all your questions, but I believe you should check the GOF book. It contains some good examples.


答:
There are two primary reasons:

Separation of concerns - by having the code in a separate file it is separate from the HTML and may be changed without touching the HTML file. If used in multiple places it allows for a single place to make the change.

DRY - Don't Repeat Yourself By having it in a separate file you don't have to repeat the code in several HTML files.

Title: Why is it a good practice to keep Javascript code in separate files?

Body:
In web development we are commonly used to keep Javascript code in separate files, but sometimes we need this Javascript code to manipulate server side data locally.

For example, making an Ajax Call to a dynamically created URL server side.

But some programmers My colleagues keep saying that plain Javascript in the JSP file is a sign of bad code, and wrong practices.

To what extent are they right ? Assuming that those blocks of code are not reusable in other pages, why is this practice perceived as a bad thing?

Edit :

Thanks for the quick answers, I'm still wondering how can I manage Dynamically created Javascript code (which cannot be cached, obviously). For example making an ajax call with an URL like this :

```<code>url : ${some_url_coming_from_server},
</code>```

In my case the code is huge, and I have server-data everywhere, am I doing it wrong ?


问:
class in OOP language and type
In programming language theory, a type is a set of values. E.g. the type "int" is the set of all integer values.

In OOP languages, a class is a type, is it?

When a class is defined with more than one members, e.g.

```<code>class myclass{
    int a;
    double b;
}
</code>```

When we talk about a class, do we mean

"(a,b) where a is an int and b is a double", or

"{(x,y) | x is any int, y is any double}"?

What does an instance of myclass mean?

"(a,b) where a is an int and b is a double", or

an object which occupies a memory space and which can (not necessarily, i.e. can be empty) store (x,y), where x is any int and y is any double?

答:
Neither.

I take it you're asking whether having the same set of field types is enough to classify as being the same class, or whether they have to be named identically as well. The answer is: "Not even having the same types and the same names is sufficient!" Structurally equivalent classes are not necessarily type-compatible.

For instance, if you have a CartesianCoordinates and a PolarCordinates class, they might both have two numbers as their fields, and they might even have the same Number type and the same names, but they would still not be compatible, and an instance of PolarCoordinates would not be an instance of CartesianCoordinates. The ability to separate types by their intended purpose and not their current implementation is a very useful part of writing safer, more maintainable code.

Title: class in OOP language and type


问:
Architectural / Application Practices to guard against 'breaking changes'
We have an application where the customer has changed their mind about a large area of functionality and this area requires a large amount of re-work.

Whilst the re-work itself is not an issue, it has introduced a situation where the impact of the changes is wide ranging including:

Data

Query Logic / Table structure

Business logic

Display / Presentation

Ideally we'd like to incorporate these changes at the same time as several other development streams, but we're worried that the impact of the changes will have a negative impact on how frequently we can deliver. We can cater for some of this through branches, but it made me wonder what the possibilities are for guarding against this kind of thing from an application architecture or development practice point of view.

Things we currently do:

Abstract query logic into repositories - This is great for small changes, but when the overall logic in an area changes, e.g. instead of getting a list of users which meet a certain criteria, we now need to get a list of organisations which joined to locations.

Abstract business logic into services - This is exactly the same as the repositories in that we can't really guard against entire logic shifts, but small changes can be accommodated with limited impact.

Ensure configuration is kept out of code which needs re-deployment, a combination of database rows or web.config values.

Other patterns which promote aspects of flexibility like factories where appropriate etc.

Feature flagging for selection of functionality if two approaches were developed originally. etc

Are there any other current best practices to guard against changes, without incorporating branches etc?

答:
The only thing you can do to help reduce the impact of a change is to split your overall project up into many components, so while a major change will impact several of them, many will not be affected.

eg if the customer decides they need a new button that sends data through the middletier to be stored in a new column in the DB, you're going to have to change every layer in your system. However, if the system is also split 'horizontally' too then the UI impact will only affect part of the UI layer, the rest will not be changed. Similarly, if you have a lot of services in your middle tier that each process certain parts of the data, you'll only have to change one of them - the rest will be unaffected. the DB too, can be partitioned into independant schemas.

So for example, you need to get a list of users, so you have a service that manages user data. When you need to get a list of organisations too, you add a new service that deals with this and merge the data together in the UI (for example) which means you have not had to alter your user-access code at all. I think this kind of approach is termed microservices, though obviously 'micro' doesn't have to mean tiny, just logically separated.

I would not try to introduce abstractions as all that will happen is these will tie your layers together (eg a DB change will still require the underlying table change, but now the wrapping DAL layer will need change too, and having a DAL will not necessarily let you split the DB into sections, unless you get into a lot more complexity).


问:
Initialize physical resources in constructor
Is it an acceptable practice to initialize physical/external resources from a constructor when the resource is needed for the object to do it's work?

For instance, let's say I wanted to create an object that proxies a durable message queue and that the message queue is a physical database table.

Would that make sense to create an idempotent constructor which physically create the table if it doesn't exist yet?

E.g.

```<code>IMessageQueue queue = new SQLTableMessageQueue('table_name', dataSource);
</code>```

Perhaps a static factory method would be more appropriate? In that case, the table creation would occur in the factory method and the constructor would be free of such behavior.

```<code>IMessageQueue queue = SQLTableMessageQueue.create('table_name', dataSource);
</code>```

I'm not too sure what would be an appropriate approach? Another idea I had was to use the Repository Pattern.

答:
Google's C++ Style Guide asks you to refrain from doing work in constructors. Their arguments may or may not be applicable to your language. Testing on the Toilet's six-year-old advice #3 on how to write testable code by not doing work in the constructor still holds though.

If you search for it online you'll find tons, /*Programmers*/ is one place to start.


问:
Why is binary search,which needs sorted data, considered better than linear search?
I have always heard that linear search is a naive approach and binary search is better than it in performance due to better asymptotic complexity. But I never understood why is it better than linear search when sorting is required before binary search?

Linear search is O(n) and binary search is O(log n). That seems to be the basis of saying that binary search is better. But binary search requires sorting which is O(n log n) for the best algorithms. So binary search shouldn't be actually faster as it requires sorting.

I am reading CLRS in which the author implies that in insertion sort instead of using the naive linear search approach it is better to use binary search for finding the place where item has to be inserted.  In this case this seems to be justified as at each loop iteration there is a sorted list over which the binary search can be applied. But in the general case where there is no guarantee about the data set in which we need to search isn't using binary search actually worse than linear search due to sorting requirements?

Are there any practical considerations that I am overlooking which make binary search better than linear search? Or is binary search considered better than linear search without considering the computation time required for sorting?

答:
Like many others have answered, binary search is indeed preferable because the sorting step can be done only once and the actual searching can then be done as many times as you like. However, for certain values of n (i.e. certain input sizes), binary search is always more performing than linear search (even for one single run).

The "tipping point" is computed by solving the asymptotical complexity equation:

```<code>n log n + log n = n
</code>```

As you can see on Wolfram Alpha there is a numerical value for n that ensures that binary search and sorting is always faster than linear search alone. Of course the actual value of n that works in your case depends on many factors which may be difficult to estimate.

According to this interesting article by Mark Probst, which includes some nice in depth performance measurements on current processors:

If you need to search through a sorted array of integers and
  performance is really, really important, use linear search if your
  array is below around 64 elements in size, binary search if it’s
  above.

Body:
Like many others have answered, binary search is indeed preferable because the sorting step can be done only once and the actual searching can then be done as many times as you like. However, for certain values of n (i.e. certain input sizes), binary search is always more performing than linear search (even for one single run).

The "tipping point" is computed by solving the asymptotical complexity equation:

n log n + log n = n

As you can see on Wolfram Alpha there is a numerical value for n that ensures that binary search and sorting is always faster than linear search alone. Of course the actual value of n that works in your case depends on many factors which may be difficult to estimate.

According to this interesting article by Mark Probst, which includes some nice in depth performance measurements on current processors:

If you need to search through a sorted array of integers and
  performance is really, really important, use linear search if your
  array is below around 64 elements in size, binary search if it’s
  above.


问:
Where does the Liskov Substitution Principle generally lie in different constructor parameter lists?
There are two other questions I've posted that dealt with specific cases of this:

Where does the Liskov Substitution Principle lie in a subclass passing extra arguments to similar, tightly-related callbacks?

Matching the superclass's constructor's parameter list, is treating a null default value as a non-null value within a constructor a violation of LSP?

but these have kind of left me a little lost on the general case.  A basic summary of what I've gotten out of the answers to these questions is as follows:

The Liskov Substitution Principle does not apply to constructors; it only applies post-construction.  You can change parameter lists all you want, and you can even make matching parameters exhibit very different behaviors.

An exception to this rule is that if a callback is passed in to the constructor of both the base class and the superclass, and if it cannot be set at a later time, then the subclass's version, in normal situations, must be backwards-compatible with superclass's version.  The reason for this is that, in normal situations, outside code cannot otherwise enter into a state in which it would behave in the same way.

Even though this statement doesn't necessarily contradict itself, it comes close, yet only on a halfway fine-grained point.  So at this point, it's probably a good idea for me to ask about the subprinciple of LSP that deals specifically with constructors, particularly with their parameter lists.

What is the general application of LSP here?

Example

Consider the following example, which only illustrates certain specific points (this question is still about the general case though, not this example):

BasicButton:

```<code>public class BasicButton extends Sprite
{
    private var m_fOnClick:Function;
    private var m_fOnPress:Function;
    private var m_fOnRelease:Function;

    private var m_iColorPressed:uint;
    private var m_iColorReleased:uint;

    public function BasicButton(pColorPressed:uint, pColorReleased:uint, pOnClick:Function
            = null, pOnPress:Function = null, pOnRelease:Function = null)
    {
        m_iColorPressed = pColorPressed;
        m_iColorReleased = pColorReleased;
        m_fOnClick = pOnClick;
        m_fOnPress = pOnPress;
        m_fOnRelease = pOnRelease;
        drawBackground(pColorReleased);
    }

    private function drawBackground(pColor:uint):void
    {
        // completely fill the entire rectangular area of the button with one solid color
    }

    .
    .
    .
        // when the button has been pressed:
        if (m_fOnPress)
        {
            m_fOnPress();
        }
    .
    .
    .
}
</code>```

DirectionalButton:

```<code>// This class illustrates several different points.
public final class DirectionalButton extends BasicButton
{
    private var m_eDirection:int;

    private var m_fOnPress:Function;

    // Multiple parameters are omitted.  Two are just uint configurations to decide a color
    // with, and one is a callback that, if a non-null value had been included, would have
    // interacted directly with outside code.  Furthermore the pOnPress callback is treated
    // differently throughout this class.  Finally, pOnPress and pOnRelease are no longer
    // optional.
    public function DirectionalButton(pDirection:int, pOnPress:Function,
            pOnRelase:Function)
    {
        m_eDirection = pDirection;
        m_fOnClick = pOnClick;

        // pOnPress is nullified; the superclass won't even try to call it.
        // The colors are hard-coded.
        super(0x858585, 0xCCCCCC, null, onPress, pOnRelease);

        addArrowSprite(pDirection);
    }

    private function addArrowSprite(pDirection:int):void
    {
        // Add a new Sprite instance as a child, which will take the form of an arrow
        // pointing in the specified direction, using a different color than the
        // background.  Whereas the you could always assume that the superclass maintained
        // one color throughout at all times, this assumption will now be broken in the
        // subclass.  That means that, depending on how you interpret things, the
        // background color specified in the superclass's constructor uses either differing
        // or equivalent behavior.
    }

    private function onPress():void
    {
        m_fOnPress(m_eDirection); // pOnPress from before has had its parameter
                                  // list interfered with.  Also it is now assumed to be
                                  // non-null.
    }
}
</code>```

Remember that this example is still only dealing with the constructors' parameters, not with regular public functions or anything.  Furthermore you have several different so-called "properties" that are suppliable to the constructors, but which have no way to be configured afterward.

Whether dealing with these sorts of cases, or with different types of cases, what is the LSP rule about constructors, especially with their parameter lists?

答:
It depends on what language you're working with.

Let's look at the informal definition of the Liskov Substitution Principle (herafter LSP):

You should be able to use an instance of a subtype anywhere you could use the base type.

That only tangentially impacts constructors. LSP doesn't particularly care how instances are created, only that once created they play nice. Constructors obviously can impact if the instances play nice when used, but that's not really different from other object state impacting their behavior.

In a few more esoteric languages though, the types (and their constructors) can be treated like objects. Having the constructors behave differently in that sort of context would be a violation of LSP, but of the type objects, not the actual class instances.


问:
Why is it said that a class represents an abstraction?
I think that abstraction represents only the essential things needed for the purpose as there are so many unnecessary properties. So why is it said that a class represents an abstraction?</p>

答:
It's an abstraction as long as you work with it without knowing how its internal work. For the developer of a class, it's not an abstraction until he works on something different (maybe a client of that class). For an integrator who has to make it work with a related class in the same project, it's sometimes an abstraction (when he only uses its API and not its internals). As long as the API is well-designed and does all the client needs, that works fine.

In other words, a class bundles a lot of things that belong together and publishes them under one name. As long as it's enough to know the name in order to think about that component of a system, that constitutes a reduction in complexity. Whenever you have to open up the bundle and look inside, the abstraction breaks down, and the reduction is lost. Since most classes are successful at doing their job through their API some of the time, abstraction is still a net win for computer people - an indispensable one, for systems of the size that is now common.


答:
Sorry but I don't know about the "raw" theory. I can only provide a practical approach. I hope this is acceptable at programmers.SE; I'm not familiar with the etiquette here.

A central theme of OOP is information hiding. What the data members of a class are, exactly, should be of no interest to its clients. A client sends messages to (calls methods / member functions of) an instance, which might or might not modify internal state. The idea is that the internals of a class might change, without the client being affected by it.

A corrolary to this is that the class is responsible for ensuring that its internal representation remains "valid". Let's assume a class that stores a (simplified) phone number in two integers:

```<code>    int areacode;
    int number;
</code>```

These are the data members of the class. However, the class will probably be much more than just its data members, and it is certainly not definable as "set of all possible values of int x int". You shouldn't have direct access to the data members.

Construction of an instance might deny any negative numbers. Perhaps the construction would also normalize the areacode in some way, or even verify the whole number. You would thus end up much closer to your "(a,b) where a is an int and b is a double", because it's certainly not any two int stored in that class.

But that doesn't really matter as far as the class is concerned. It is neither the type of the data members, nor the range of their possible values that defines the class, it's the methods that are defined for it.

As long as those methods remain the same, the implementor could change the data types to floating point, BIGNUMs, strings, whatever, and for all practical purposes, it would still be the same class.

There are design patters to ensure that such changes of internal representation can be made without the client even being aware of it (e.g. the pimpl idiom in C++, which hides any data members behind an opaque pointer).

Title: class in OOP language and type

Body:
In programming language theory, a type is a set of values. E.g. the type "int" is the set of all integer values.

In OOP languages, a class is a type, is it?

When a class is defined with more than one members, e.g.

```<code>class myclass{
    int a;
    double b;
}
</code>```

When we talk about a class, do we mean

"(a,b) where a is an int and b is a double", or

"{(x,y) | x is any int, y is any double}"?

What does an instance of myclass mean?

"(a,b) where a is an int and b is a double", or

an object which occupies a memory space and which can (not necessarily, i.e. can be empty) store (x,y), where x is any int and y is any double?

Body:
Sorry but I don't know about the "raw" theory. I can only provide a practical approach. I hope this is acceptable at programmers.SE; I'm not familiar with the etiquette here.

A central theme of OOP is information hiding. What the data members of a class are, exactly, should be of no interest to its clients. A client sends messages to (calls methods / member functions of) an instance, which might or might not modify internal state. The idea is that the internals of a class might change, without the client being affected by it.

A corrolary to this is that the class is responsible for ensuring that its internal representation remains "valid". Let's assume a class that stores a (simplified) phone number in two integers:

    int areacode;
    int number;

These are the data members of the class. However, the class will probably be much more than just its data members, and it is certainly not definable as "set of all possible values of int x int". You shouldn't have direct access to the data members.

Construction of an instance might deny any negative numbers. Perhaps the construction would also normalize the areacode in some way, or even verify the whole number. You would thus end up much closer to your "(a,b) where a is an int and b is a double", because it's certainly not any two int stored in that class.

But that doesn't really matter as far as the class is concerned. It is neither the type of the data members, nor the range of their possible values that defines the class, it's the methods that are defined for it.

As long as those methods remain the same, the implementor could change the data types to floating point, BIGNUMs, strings, whatever, and for all practical purposes, it would still be the same class.

There are design patters to ensure that such changes of internal representation can be made without the client even being aware of it (e.g. the pimpl idiom in C++, which hides any data members behind an opaque pointer).


问:
Is it an abuse of SOA to use it as a database abstraction layer?
I have a question whether it is a good or bad practice to use an SOA layer for the application servers to talk to the database. A web application server can obviously directly connect to a database, but in the hype to make everything SOA, the architects are mandating that everything has to make an SOA call to midtier servers that connect to the database.

To me, this seems terribly wasteful that you have an application in the same datacenter as the database and the applications can directly access the database server, but they don't. There is already a level of abstraction on the application servers which looks identical to what we eventually end up with SOA, so this isn't a matter of a better interface.

By using SOA you are adding a lot of steps to build up the request, send it out, have it received and then decoded and then finally make the database call and then you have to package that up, send it out, have it received, decoded and finally you can use the data.

From what I have read about SOA, it is useful when you have geographically spread out systems where a server in Boston needs information from a server in Seattle and there is no way that a direct database connection could be possible. This is also useful when you have many different customers that need to call a central point to receive data according to a fixed contract.

However, to use SOA as the means for just directly communicating with your database from your application seems to be a complete abuse of the concept and seems to provide little advantage while significantly slowing down the transactions. A typical usage would be to call a stored proc and instead of calling it directly, you have to use a SOA call to a midtier server to get the exact same information.

So, am I crazy or what? Is everyone just drinking the SOA Kool Aid and applying SOA to absolutely everything until the point of absurdity? Or is there really some advantage to doing this?

答:
There are many factors about your application stack that may indicate or contra-indicate use of SOA, so it will be very hard to tell you if everything they are asking for is appropriate.

I will say that I don't think you should specifically not use SOA just because the machines happen to be in the same data-center.  What if you need to enforce a new security scheme, or need to move some of the servers, or support servers in different data-centers for DR-1 implementation, or you want to switch to new database software, or ...

One of the advantages of SOA is that it abstracts away those issues for you the front-end developer or even middle-tier developer(unless you are responsible for the db api).


问:
Scala and exception handling
I am curious why exception handling is a topic often ignored in Scala. Is it the goal of the language (or the style) to not rely on exception handling except for external input/code?

I was hoping the style guide had some discussion on exception checking/handling. Is there a good reference that I could consult to understand if there are any differences in handling exceptions in Scala vs. languages I'm more used to (C++/C#/Java/Ruby/etc)?

Would someone with some Scala years under their belt be willing to write down guidelines for exception handling that are Scala specific? or is the answer simply "do as you would in Java"? What is "the functional way"?

答:
Good functional style does not need defensive coding nearly as much as the imperative style.  try and catch is not the only control structure which is neglected in Scala (and other functional languages); for and while loops are endangered species and even if...else is used more selectively (although much more effectively, since it returns a value).

In the functional world, you match your code to the shape of the data.  Or you choose a shape which gives your code the structure you want.  This is true not only with Option and Either but List and Set and Map and more.  All of them are paired with powerful Higher Order Functions - map, fold, filter etc.

To take a trivial example, if a Java or C++ coder wants to fetch the first (or all) of the items in a list and manipulate it, they either have to first check that the list is not empty or wrap it in  try/catch to handle the error.  If they have to deal with a collection of lists, the latter option is more likely to be chosen (and even less likely to match the context which might generate an error).

In Scala you can simply do this to the list of Ints called xs:

```<code>  xs.headOption map (_ * 2)
  // Returns twice the first item - if there is one - as an Option
</code>```

or

```<code>  xs map (_ * 2)
  // Doubles everything in the list.  Returns a list.
</code>```

If there is nothing in the list, nothing will happen.  If you want something to happen, you can detect the failure and react.

```<code>  xs.headOption map (_ * 2) orElse Some(0)
  // Returns Some(twice the head item) if there is one or Some(0)
  xs.headOption map (_ * 2) getOrElse 0
  // Returns twice the head item or 0 if there is none
</code>```

Even better, if you are dealing with a lists of lists, any one of which might be empty, mapping over each of them will produced results for every populated list and no problem at all with any empty ones.  That is very powerful when dealing with large collections of unpredictable data.

What these functional types (Option and Either and List and Map and all the other - sorry to use the ugly word - monads) also offer, very importantly, is separation of concerns.  Notice how I used map in all the above examples.  In two examples it is Option.map, while in the other it is List.map.  In all cases, map is doing the same thing: ¨Apply my function to the data inside that container, preserving the context¨.  If it is a list context, you get a list of transformed data back.  If it is a ¨may or may not exist¨ context, you may get your transformed object.  If it is a ¨this could really go badly wrong¨ context, you either get your object or a chance to complain.  And so on.

So you get a separation of concerns between the action you want to perform and the context in which it is applied.  The big advantage is that if you decide to change the context (e.g. Set of unique objects rather than arbitrary List of objects), the rest of the code doesn´t need to change at all.  map will still do the right thing (as will filter, fold and the rest).

Built-in imperative keywords like try..catch or if...else...if...else do not have that power.  For a start, they have no real meaning of their own and have to be bodged together (distorting the code tangled within them) and they offer no guarantee.  Imagine having used those to manage an arbitrary list of objects and then deciding you want to guarantee uniqueness.  How much of that imperative code will you have to change?  How can you be confident it will work?

Leave exceptions to deal with the truly unexpected and unsolveable.  Functional types can be confident about their guarantees, to help you avoid the common and predictable errors.

Title: Scala and exception handling

Body:
Good functional style does not need defensive coding nearly as much as the imperative style.  try and catch is not the only control structure which is neglected in Scala (and other functional languages); for and while loops are endangered species and even if...else is used more selectively (although much more effectively, since it returns a value).

In the functional world, you match your code to the shape of the data.  Or you choose a shape which gives your code the structure you want.  This is true not only with Option and Either but List and Set and Map and more.  All of them are paired with powerful Higher Order Functions - map, fold, filter etc.

To take a trivial example, if a Java or C++ coder wants to fetch the first (or all) of the items in a list and manipulate it, they either have to first check that the list is not empty or wrap it in  try/catch to handle the error.  If they have to deal with a collection of lists, the latter option is more likely to be chosen (and even less likely to match the context which might generate an error).

In Scala you can simply do this to the list of Ints called xs:

  xs.headOption map (_ * 2)
  // Returns twice the first item - if there is one - as an Option

or

  xs map (_ * 2)
  // Doubles everything in the list.  Returns a list.

If there is nothing in the list, nothing will happen.  If you want something to happen, you can detect the failure and react.

  xs.headOption map (_ * 2) orElse Some(0)
  // Returns Some(twice the head item) if there is one or Some(0)
  xs.headOption map (_ * 2) getOrElse 0
  // Returns twice the head item or 0 if there is none

Even better, if you are dealing with a lists of lists, any one of which might be empty, mapping over each of them will produced results for every populated list and no problem at all with any empty ones.  That is very powerful when dealing with large collections of unpredictable data.

What these functional types (Option and Either and List and Map and all the other - sorry to use the ugly word - monads) also offer, very importantly, is separation of concerns.  Notice how I used map in all the above examples.  In two examples it is Option.map, while in the other it is List.map.  In all cases, map is doing the same thing: ¨Apply my function to the data inside that container, preserving the context¨.  If it is a list context, you get a list of transformed data back.  If it is a ¨may or may not exist¨ context, you may get your transformed object.  If it is a ¨this could really go badly wrong¨ context, you either get your object or a chance to complain.  And so on.

So you get a separation of concerns between the action you want to perform and the context in which it is applied.  The big advantage is that if you decide to change the context (e.g. Set of unique objects rather than arbitrary List of objects), the rest of the code doesn´t need to change at all.  map will still do the right thing (as will filter, fold and the rest).

Built-in imperative keywords like try..catch or if...else...if...else do not have that power.  For a start, they have no real meaning of their own and have to be bodged together (distorting the code tangled within them) and they offer no guarantee.  Imagine having used those to manage an arbitrary list of objects and then deciding you want to guarantee uniqueness.  How much of that imperative code will you have to change?  How can you be confident it will work?

Leave exceptions to deal with the truly unexpected and unsolveable.  Functional types can be confident about their guarantees, to help you avoid the common and predictable errors.


答:
SOA has many advantages other than increasing efficiency over a raw database confection.

The most important benefit is that it provides a layer of abstraction that can be used to allow an underlying database to evolve its design without the need to synchronise releases with all consumers of the data it stores (this is particularly important if the database is maintained by a different team to its consumers, but is still helpful even if they are both managed by the same team, as it allows the team to concentrate on changes to one aspect of the system at a time)

*

Title: Is it an abuse of SOA to use it as a database abstraction layer?

Body:
I have a question whether it is a good or bad practice to use an SOA layer for the application servers to talk to the database. A web application server can obviously directly connect to a database, but in the hype to make everything SOA, the architects are mandating that everything has to make an SOA call to midtier servers that connect to the database.

To me, this seems terribly wasteful that you have an application in the same datacenter as the database and the applications can directly access the database server, but they don't. There is already a level of abstraction on the application servers which looks identical to what we eventually end up with SOA, so this isn't a matter of a better interface.

By using SOA you are adding a lot of steps to build up the request, send it out, have it received and then decoded and then finally make the database call and then you have to package that up, send it out, have it received, decoded and finally you can use the data.

From what I have read about SOA, it is useful when you have geographically spread out systems where a server in Boston needs information from a server in Seattle and there is no way that a direct database connection could be possible. This is also useful when you have many different customers that need to call a central point to receive data according to a fixed contract.

However, to use SOA as the means for just directly communicating with your database from your application seems to be a complete abuse of the concept and seems to provide little advantage while significantly slowing down the transactions. A typical usage would be to call a stored proc and instead of calling it directly, you have to use a SOA call to a midtier server to get the exact same information.

So, am I crazy or what? Is everyone just drinking the SOA Kool Aid and applying SOA to absolutely everything until the point of absurdity? Or is there really some advantage to doing this?


答:
Its not an abuse if your organization demands it.  If there are security concerns or architectural guidance/governance that dictates it then it is warranted.

We went through this with a 3rd party audit a while back and one of the 3rd party audit concerns was that our service layer directly interacted with the database.  We had a web application layer and service layer.  The service had a data access layer and interacted to the database via stored procedures.  The data and service layer were in the same network zone.

Basically, the architecture team reviewed the 3rd party finding and asked what would be need to be done.

The response was to add another service that would only interact with the database.  This meant more cost to the project and raised a performance risk.  Our SLAs were less than 100ms per call.  Neither the additional cost or performance risk was acceptable to the business.

Because of the cost and risk, the team decided it was not necessary to do this.  But your situation may be different.

Taking all things into account, your right it's over kill.  I've seen SOA tken to the extreme where is takes 1/2 dozen service callouts to get the data that is required.  Data is scattered to the four winds.  You want a happy medium.


答:
A type is a description of a category/range of values, compound structures, or what have you.  OOPwise, it is akin to an "interface".  (In the language-agnostic sense.  The language-specific sense, not so much.  In Java, for example, int is a type, but has no relation to an interface.  Public/protected field specifications, as well, are not part of an interface, but are part of an "interface" or type.)

Main point being, it's much more a semantic definition than a concrete one.  Structure only factors in inasmuch as the exposed fields/behaviors and their defined purposes align.  If you don't have both, you don't have type compatibility.

A class is the realization of a type.  It's a template that actually defines the internal structure, attached behavior, etc.

Title: class in OOP language and type


问:
RavenDb - Get data through a REST Web API
I would like to build a RESTful API where I need to get data from a RavenHQ-cloud-database. First of all, is this possible?

The idea is to have multiple applications (xamarin-app, mvc-app, etc.) and use the API I'm building to pass the data to those applications.

For example, say I have a mobile-app with one button:

User clicks a button

Client connects to my API's Get() endpoing

Through the API, return the specific data I requested from RavenDB

Send the data from the API to my mobile-app (over JSON for example)

Use that data in my app.

Every time a do a Get() through the API to the db, I just need to get a small amount of data. But the db is really huge in all, so I don't think it is a good approach to store the whole db in the mobile-app. Better to get the small amounts of data when it's needed through the API I guess.

And as I need to use the db-data in many different application, I though this would be the best approach.

Is this architecture a good way to solve it?

答:
If you're asking does RavenDB (RavenHQ is just hosted RavenDB) work as persistent storage for any data system, including an API you write, of course it does. It's a document database. That's its job.

I'm not exactly sure what you're asking, unless you are asking "what is RavenDB?" If so, I recommend reading through the marketing materials and documentation at ravendb.net.

Since RavenHQ is just hosted RavenDB, it's no different than hosting a RavenDB instance directly on Amazon, Azure, or any other cloud provider.

Best I can tell is the reason you are really asking, is that you want to know if you can write a system (an API in this case) that uses cloud-hosted storage? If so, the answer is yes.

Cloud hosted storage works like local storage, with some extra latency. As long as you plan for longer response times in your design, and handle network connection failures gracefully (both of which should also be concerns even for the more common scenario of storage on a SAN or separate machines on the same LAN) then it should work just fine.

Regarding REST:

How strict you follow REST design guidelines in your custom API is completely up to you and the design of your API. It has nothing to do with your back-end storage system because you will never be exposing that directly over your API.

Regarding your mobile client design:

Yes, only requesting the data that is necessary for a client to have if they only ever need a small subset of a very large data system is a good plan.

But even though a mobile application that relies on queries over the network due to direct user actions can work, but I would discourage that exact approach for the following reasons:

UI latency; mobile networks aren't fast, so the UI will stay blocked waiting for a response no matter how fast your API and back-end storage is. Even if that response cycle and client processing is completed in under 500ms, that's still not fast enough for a UI.

network access is required at all times; mobile apps often need to work offline and this solution will prohibit that

battery life and data use; if the user requests that same data over and over it would require keeping the radio on and possibly use more of the user's data plan than you should

load; server load would be very 'bursty' depending on users usage patterns. Depending on how well designed your system is, the shape of the data, and the queries you build, timeliness of when users use it, etc. your API could get overwhelmed easily without warning

A way to fix a lot of the above issues are to use background tasks that make requests through a caching layer of your app. Then make sure your API returns responses than may be cached properly by that layer, and that it handles keeping that cache fresh.

(When implementing that caching in your API, the RavenDB, and therefore RavenHQ, caching system is very good, so you'll have no problems there, if you use it correctly. It will be more a question of "can you design your own caching out of your API correctly?")

And to enable offline usage (assuming the user can get the data once online first), you could add a 2nd layer cache that further caches to a local database, using the same caching system the first layer cache uses.

None of the above client design issues care about your back-end storage choice. It's up to the designers of the various client designs and your API design with how well those systems work together.


答:
Types are not sets.

You see, set theory has a number of features which simply don't apply to types, and vice-versa.  For instance, an object has a single canonical type.  It may be an instance of several different types, but only one of those types was used to instantiate it.  Set theory has no notion of "canonical" sets.

Set theory allows you to create subsets on the fly, if you have a rule that describes what belongs to the subset.  Type theory generally does not allow this.  While most languages have a Number type or something similar, they do not have an EvenNumber type, nor would it be straightforward to create one.  I mean, it's easy enough to define the type itself, but any existing Numbers which happen to be even will not be magically transformed into EvenNumbers.

Actually, saying that you can "create" subsets is somewhat disingenuous, because sets are a different kind of animal altogether.  In set theory, those subsets already exist, in all the infinite ways you can define them.  In type theory, we usually expect to be dealing with a finite (if large) number of types at any given time.  The only types which are said to exist are those we've actually defined, not every type we could possibly define.

Sets are not allowed to directly or indirectly contain themselves.  Some languages, such as Python, provide types with less regular structures (in Python, type's canonical type is type, and object is considered an instance of object).  On the other hand, most languages do not allow user-defined types to engage in this sort of trickery.

Sets are commonly allowed to overlap without being contained in one another.  This is uncommon in type theory, though some languages do support it in the form of multiple inheritance.  Other languages, such as Java, only allow a restricted form of this or disallow it entirely.

The empty type exists (it's called the bottom type), but most languages do not support it, or do not regard it as a first-class type.  The "type that contains all other types" also exists (it's called the top type) and is widely supported, unlike set theory.

NB: As some commenters previously pointed out (before the thread was moved to chat), it is possible to model types with set theory and other standard mathematical constructs.  For instance, you could model type membership as a relation rather than modeling types as sets.  But in practice, this is much simpler if you use category theory instead of set theory.  This is how Haskell models its type theory, for example.

The notion of "subtyping" is really quite different from the notion of "subset."  If X is a subtype of Y, it means we can substitute instances of Y for instances of X and the program will still "work" in some sense.  This is behavioral rather than structural, though some languages (e.g. Go, Rust, arguably C) have chosen the latter for reasons of convenience, either to the programmer or the language implementation.

Title: class in OOP language and type


问:
XSLT equivalent for JSON
I was interested in finding (or if necessary developing) an XSLT equivalent for JSON.

As I have not found any, I was considering the possible query language to use for matching JSON paths so as to apply templates (from JavaScript) when there was a match (probably just checking an array of matching patterns in order, and stopping at the first template which matches, though allowing for the equivalent of xsl:apply-templates to keep templates going for children).

I am aware of JSONPath, JSONQuery, and RQL as JSON query languages (though I was not fully clear on whether RQL supported absolute and relative paths). Any suggestions on factors to consider and relative advantages of each toward such a usage.

答:
I don't think you will ever get an JSON variant for JSON per se. There exist several templating engines such as Python's Jinja2, JavaScripts Nunjucks, the Groovy MarkupTemplateEngine, and many others that should be well suited for what you want. .NET has T4 and JSON serialization/deserialization support so you have that also.

Since the derserialized JSON data would be basically a dictionary or map structure, that would just get past to your templating engine and you would iterate over the desired nodes there. The JSON data then gets transformed by the template.

Title: XSLT equivalent for JSON


问:
Domain Analysis vs System Analysis
I am trying to determine the differences between systems analysis and domain analysis.  It seems that any systems analysis occurs within a domain--so are there techniques, concepts, tools, etc. that a domain analyst would use and a systems analyst would not?</p>

答:
Systems Analysis concerns itself with the design and behavior of the entire data processing system (including both computer hardware and software), whereas Domain Analysis concerns itself primarily with software design within the context of a business domain.

Note the differences in analysis techniques cited in the Wikipedia articles I linked.

Title: Domain Analysis vs System Analysis


问:
Factors for choosing between using a wrapper library or issuing command line process from my web application
I have a Java web application that makes use of certain libraries for example: Ghost Script for converting PDFs to TIFFs and Tesseract for OCR. There are java wrappers for both of these: Ghost4J and Tess4J.

What are some things I should think about when deciding whether to use the libraries or issue a command line process from my web application?

Off the bat what I'm noticing is that command line operations are slightly faster and don't take a toll on my application. For example 100 users sending PDFs that need to be converted to TIFFs using Ghost4j makes Java run at more that 100% CPU which makes the entire web application unresponsive.

答:
I agree to all the comments and the answer above on the Non-functional requirements that will influence whether to go with solution A or B.

Additional information regarding whether you want the conversions to be done offline or in realtime (e.g. User sends PDF, and gets Tiff back as soon its done) would be useful.

Regardless lets assume that at this point you are constrained by the available system resources (Conversion consuming all of the available CPU) and from personal experience i can say that the command-line tooling will be much efficient here. I do recommend to use that over pure java.

I can name a number of known java based systems out there that use imagemagick to do similar conversion (Create, resize, convert PDFs). it also comes with a nice Java api to work with. Reference: http://www.imagemagick.org/script/api.php

Next to that if your main app's performance is getting a huge hit because of the conversion, then i would also recommend to move the whole conversion to dedicated node(s) / cluster.


问:
Tracking internal builds versus public builds
At our office, we use JIRA to track issues reported by our QA teams. We also have Bamboo which builds each time we commit to our Git (Stash) repository. QA picks a build from Bamboo and they work with that build for about a week. Once all of the issues they filed on that build are resolved, they pick another build and regress/smoke test again until they find a fully passing build (i.e. no issues reported).

The problem is they want to be able to track changelogs between the internal builds they choose (the build they pick from bamboo) and our public release version which has been planned.

So for example, if our "public release" version is 1.0, then our internal builds will be 1.0.1, 1.0.2, and so on. They might pick a build in Bamboo 50 builds later and mark that as the public release. So even though we marketed our product to be version 1.0, the actual version is 1.0.50 (50 being our internal build number).

They want to track changelogs between each internal round of testing and also track changelogs on the public release as a whole. So let's say they picked the following builds for their weekly rounds of testing:

```<code>1.0.1 -> 1.0.25 -> 1.0.50
</code>```

They want to see which JIRA issues are resolved between 1.0.1 and 1.0.25, and likewise between 1.0.25 and 1.0.50. The only solution I can think of for this problem is to add 4 versions to our project in JIRA:

```<code>1.0
1.0.1
1.0.25
1.0.50
</code>```

1.0 would be unreleased, and each time QA adds an internal build, it will be immediately marked as released. This will allow them to assign 2 affects or fix versions per issue: 1.0 and 1.0.25 (or whatever internal build it was reported on)

This seems clunky, I don't like the idea of adding versions in JIRA for internal builds. It seems like JIRA should only care about public releases (i.e. 1.0 in this case). Is there a better way to handle this type of continuous integration / continuous delivery?

答:
Issues can be filtered by type, fixed version, affected version, status etc in JIRA and one can save the filter, share it with others and attach it to a dashboard for a quick overview.

All the information you need is already there in Jira, if its not then QA probably shouldn't be concerned about it. Lets assume your QA team is testing one build at a time from Dev branch CI builds and run through a scenario.

Issue is found and logged by QA in JIRA along with the Affected build version under test

Issue goes through the triage, it gets assigned to a Developer

Developer reproduces the issue, starts working on it and once the fix
has been tested locally, it is pushed to the dev branch, and the CI build passes.

Developers puts the status of the Issue to FIXED and sets
the fix version to be same as the build version in CI (Bamboo) !Important

Developer assigns the issue back to QA

QA uses JIRA filters to filter all the issues that have been fixed and assigned to them and potentially also checks whether the fix version is same as what they are testing at the moment and or its a number higher, in both cases they can start retesting the issue. If the issue passes their test then the ticket is set to CLOSED.

Once a build version has been reached which is ready for production. it takes QA half a minute to create a Jira filter which filters the changes that are going into the build.

In either way, QA has all the tooling they need within Jira, if its not then i'd suggest to review the current process of tracking and align it to the recommendations by Atlassian on their wiki.


问:
What is the efficient way to eliminate duplication? Design patterns?
I have a helper class which has a method that perform some checks against a field in a model. I have two models, ModelA and ModelB, they have some similarities but not all. One of them is they both have a field, lets say string ProductCheckField. The ProductCheckMethod returns back the Model, because of that it has created duplication of methods which does the same thing but returns a different model. Even the extracted methods are duplicates. Is there a good design pattern or any other good practice/technique I can use to eliminate duplication of having to create two methods?

N.B I can't use a shared Interface as the models are not the same.

Currently I have..

```<code>public class ModelA
   string blah..
   int blah
   .....
   string ProductCheckField

public class ModelB
   string xyz
   int xyz
   .....
   string ProductCheckField

public class HelperClass
{

    public ModelA ProductCheckMethod(ModelA model)
    {
       /// do somthing
       performX(model);
       checkY(model);
       return model;
    }

    public ModelB ProductCheckMethod(ModelB model)
    {
       /// do somthing
       performXDuplicate(model);
       checkYDuplicate(model);
       return model;
    }
}
</code>```

答:
What you have shown of the Models shows the same interface. So your protestations of differences are unsupported by the example you give. I suggest you wrap the fields you check in performX and checkY with accessor methods that are commonly named across model A and B and extract a common interface for the use of your Helper class.</p>

```<code>public interface CheckModel
{
    public String getStringValue();
    public void setStringValue(String blahs);
    public int getIntValue();
    public void setIntValue(int blah);
    public String getProductCheckField();
    public void setProductCheckField(String productCheckField);
}

public class ModelA implements CheckModel
{
    String blahs;
   int blah;

   String ProductCheckField;

   public String getStringValue()
    {
        return blahs;
    }

    public void setStringValue(String blahs)
    {
        this.blahs = blahs;
    }

    public int getIntValue()
    {
        return blah;
    }

    public void setIntValue(int blah)
    {
        this.blah = blah;
    }

    public String getProductCheckField()
    {
        return ProductCheckField;
    }

    public void setProductCheckField(String productCheckField)
    {
        ProductCheckField = productCheckField;
    }

}

public class ModelB implements CheckModel
{
    String xyzs;
   int xyz;

   String ProductCheckField;

public String getStringValue()
{
    return xyzs;
}

public void setStringValue(String xyzs)
{
    this.xyzs = xyzs;
}

public int getIntValue()
{
    return xyz;
}

public void setIntValue(int xyz)
{
    this.xyz = xyz;
}

public String getProductCheckField()
{
    return ProductCheckField;
}

public void setProductCheckField(String productCheckField)
{
    ProductCheckField = productCheckField;
}
}

public class HelperClass
{

    public CheckModel ProductCheckMethod(CheckModel model)
    {
       /// do somthing
       performX(model);
       checkY(model);
       return model;
    }

    private void checkY(CheckModel model)
    {
        // ...
    }

    private void performX(CheckModel model)
    {
        // ...
    }

}
</code>```

Body:
What you have shown of the Models shows the same interface. So your protestations of differences are unsupported by the example you give. I suggest you wrap the fields you check in performX and checkY with accessor methods that are commonly named across model A and B and extract a common interface for the use of your Helper class.

public interface CheckModel
{
    public String getStringValue();
    public void setStringValue(String blahs);
    public int getIntValue();
    public void setIntValue(int blah);
    public String getProductCheckField();
    public void setProductCheckField(String productCheckField);
}

public class ModelA implements CheckModel
{
    String blahs;
   int blah;

   String ProductCheckField;

   public String getStringValue()
    {
        return blahs;
    }

    public void setStringValue(String blahs)
    {
        this.blahs = blahs;
    }

    public int getIntValue()
    {
        return blah;
    }

    public void setIntValue(int blah)
    {
        this.blah = blah;
    }

    public String getProductCheckField()
    {
        return ProductCheckField;
    }

    public void setProductCheckField(String productCheckField)
    {
        ProductCheckField = productCheckField;
    }

}

public class ModelB implements CheckModel
{
    String xyzs;
   int xyz;

   String ProductCheckField;

public String getStringValue()
{
    return xyzs;
}

public void setStringValue(String xyzs)
{
    this.xyzs = xyzs;
}

public int getIntValue()
{
    return xyz;
}

public void setIntValue(int xyz)
{
    this.xyz = xyz;
}

public String getProductCheckField()
{
    return ProductCheckField;
}

public void setProductCheckField(String productCheckField)
{
    ProductCheckField = productCheckField;
}
}

public class HelperClass
{

    public CheckModel ProductCheckMethod(CheckModel model)
    {
       /// do somthing
       performX(model);
       checkY(model);
       return model;
    }

    private void checkY(CheckModel model)
    {
        // ...
    }

    private void performX(CheckModel model)
    {
        // ...
    }

}


答:
Algebraic data types are the way to discuss this.

There are three fundamental ways you can combine types:

Product. That's basically what you're thinking of:

```<code>struct IntXDouble{
  int a;
  double b;
}
</code>```

is a product type; its values are all possible combinations (i.e. tuples) of one int and one double. If you consider the number types as sets, then the cardinality of the product type is in fact the product of the fields' cardinalities.

Sum. In procedural languages this is a bit awkward to express directly (classically it's done with tagged unions), so for better understanding, here is a sum type in Haskell:

```<code>data IntOrDouble = AnInt Int
                 | ADouble Double
</code>```

the values of this type have either the form AnInt 345, or ADouble 4.23, but there's always only one number involved (unlike for the product type, where each value has two numbers). So the cardinality: you first enumerate all Int values, each must be combined with the AnInt constructor. Plus, all Double values, each combined with ADouble. Hence sum type.

Exponentiation1. I'll not discuss that in detail here because it has no clear OO correspondence at all.

So what about classes? I deliberately used the keyword struct rather than class for IntXDouble. The thing is, a class as a type isn't really characterised by its fields, those are merely implementation details. The crucial factor is rather, what distinguishable values can the class have.

What is relevant though is, a class's value can be values of any of it's subclasses! So a class is actually a sum type rather than a product type: if A and B would both be derived from myClass, the myClass would essentially be the sum of A and B. Regardless of actual implementation.

1This is functions (in the mathematical sense!); a function type Int -> Double is represented by the exponential DoubleInt. To bad if your language doesn't have proper functions...

Title: class in OOP language and type

Body:
Algebraic data types are the way to discuss this.

There are three fundamental ways you can combine types:

Product. That's basically what you're thinking of:

struct IntXDouble{
  int a;
  double b;
}

is a product type; its values are all possible combinations (i.e. tuples) of one int and one double. If you consider the number types as sets, then the cardinality of the product type is in fact the product of the fields' cardinalities.

Sum. In procedural languages this is a bit awkward to express directly (classically it's done with tagged unions), so for better understanding, here is a sum type in Haskell:

data IntOrDouble = AnInt Int
                 | ADouble Double

the values of this type have either the form AnInt 345, or ADouble 4.23, but there's always only one number involved (unlike for the product type, where each value has two numbers). So the cardinality: you first enumerate all Int values, each must be combined with the AnInt constructor. Plus, all Double values, each combined with ADouble. Hence sum type.

Exponentiation1. I'll not discuss that in detail here because it has no clear OO correspondence at all.

So what about classes? I deliberately used the keyword struct rather than class for IntXDouble. The thing is, a class as a type isn't really characterised by its fields, those are merely implementation details. The crucial factor is rather, what distinguishable values can the class have.

What is relevant though is, a class's value can be values of any of it's subclasses! So a class is actually a sum type rather than a product type: if A and B would both be derived from myClass, the myClass would essentially be the sum of A and B. Regardless of actual implementation.

1This is functions (in the mathematical sense!); a function type Int -> Double is represented by the exponential DoubleInt. To bad if your language doesn't have proper functions...