问:
Permuting and combining the values based on the key
I am trying to generate a table which would show all possible combinations based on the key. To make it more clear lets say I have a kind of Key, Value pair set(Its mentioned kind of because there are unique keys and different values).  I need to fill the table with all possible combinations of the values with different keys.

Now i need to make the key as the heading of the table and add the values accordingly so that there are no duplicate rows and all combinations are present. I am doing it in C#. I could only retrieve these key value pairs from my database based on conditions, but I have no idea how the table can be built.

Are there any examples someone could provide? Or a basic approach I should follow to achieve it?

So far my ideas:

To create an array with size equals number of distinct parameters of key. Add values to the array and then pass a list of the Array to the View.

P.S : My data model is complex. Reference to this question would give an idea of a part of my Data model. The value I am talking about comes from the SetValue described in the model and the key from another class which is not described (I feel this information is irrelevant as I have already the list of my Key value pairs). I think I have posted the question in the right forum, as I am not asking for any code. If not please let me know the right forum where this question will belong to.

答:
I have managed to do a more versatile version, that allows multiple properties with list of values to be permuted. It is rather silly (does not use LINQ, as input data is a OrderedDictionary) and can be improved if input data is in a more friendly format.</p>

```<code>// hold index data for permutations
class IndexData
{
    public int PropIndex { get; set; }
    public int MaxCount { get; set; }
}

// input data - OrderedDictionary helps with the key order, but has serious non-typed drawbacks
var propsValues = new OrderedDictionary()
{
    { "colour", new List<String>() { "red", "blue", "violet", "black", "yellow"}},
    { "fruit", new List<String>() { "apple", "mango", "banana", "banana"}},
    { "vegetable", new List<String>() { "onion", "potato", "tomato"}},
    { "shape", new List<String>() { "round", "oval" }}
};

// compute index containers to help with permutations
var propsIndexes = new Dictionary<String, IndexData>();
var propsKeys = new List<String>();
foreach (var key in propsValues.Keys)
{
    propsKeys.Add((String) key);
    propsIndexes.Add((String) key, new IndexData() { PropIndex = 0, MaxCount = (propsValues[key] as List<String>).Count});
}

int propCount = propsValues.Count;
String lastKey = propsKeys[propCount - 1];

// count the permutations until the "most significant" property (the one changing least often) has reached its count
for (int combinationIndex = 0; ; combinationIndex ++ )
{
    var sb = new StringBuilder();
    sb.AppendFormat("{0}: ", combinationIndex + 1);
    foreach (var key in propsValues.Keys)
    {
        int propIndex = propsIndexes[(String)key].PropIndex;
        sb.AppendFormat("{0} ", ((propsValues[(String)key] as List<String>)[propIndex]));
    }
    Console.WriteLine(sb.ToString());

    // incrementing indexes
    bool exit = false;
    propsIndexes[lastKey].PropIndex++;

    for (int i = propCount - 1; i >= 0; i--)
    {
        String propKey = (String)propsKeys[i];

        // current index has reached its count - incrementing previous one and resetting current one
        if (propsIndexes[propKey].PropIndex >= propsIndexes[propKey].MaxCount)
        {
            propsIndexes[propKey].PropIndex = 0;

            // "most significant" property has reached its count
            if (i == 0)
            {
                exit = true;
                break;
            }

            String prevPropKey = (String)propsKeys[i - 1];
            propsIndexes[prevPropKey].PropIndex++;
        }
    }

    if (exit)
        break;
}
</code>```

Body:
I have managed to do a more versatile version, that allows multiple properties with list of values to be permuted. It is rather silly (does not use LINQ, as input data is a OrderedDictionary) and can be improved if input data is in a more friendly format.

// hold index data for permutations
class IndexData
{
    public int PropIndex { get; set; }
    public int MaxCount { get; set; }
}

// input data - OrderedDictionary helps with the key order, but has serious non-typed drawbacks
var propsValues = new OrderedDictionary()
{
    { "colour", new List<String>() { "red", "blue", "violet", "black", "yellow"}},
    { "fruit", new List<String>() { "apple", "mango", "banana", "banana"}},
    { "vegetable", new List<String>() { "onion", "potato", "tomato"}},
    { "shape", new List<String>() { "round", "oval" }}
};

// compute index containers to help with permutations
var propsIndexes = new Dictionary<String, IndexData>();
var propsKeys = new List<String>();
foreach (var key in propsValues.Keys)
{
    propsKeys.Add((String) key);
    propsIndexes.Add((String) key, new IndexData() { PropIndex = 0, MaxCount = (propsValues[key] as List<String>).Count});
}

int propCount = propsValues.Count;
String lastKey = propsKeys[propCount - 1];

// count the permutations until the "most significant" property (the one changing least often) has reached its count
for (int combinationIndex = 0; ; combinationIndex ++ )
{
    var sb = new StringBuilder();
    sb.AppendFormat("{0}: ", combinationIndex + 1);
    foreach (var key in propsValues.Keys)
    {
        int propIndex = propsIndexes[(String)key].PropIndex;
        sb.AppendFormat("{0} ", ((propsValues[(String)key] as List<String>)[propIndex]));
    }
    Console.WriteLine(sb.ToString());

    // incrementing indexes
    bool exit = false;
    propsIndexes[lastKey].PropIndex++;

    for (int i = propCount - 1; i >= 0; i--)
    {
        String propKey = (String)propsKeys[i];

        // current index has reached its count - incrementing previous one and resetting current one
        if (propsIndexes[propKey].PropIndex >= propsIndexes[propKey].MaxCount)
        {
            propsIndexes[propKey].PropIndex = 0;

            // "most significant" property has reached its count
            if (i == 0)
            {
                exit = true;
                break;
            }

            String prevPropKey = (String)propsKeys[i - 1];
            propsIndexes[prevPropKey].PropIndex++;
        }
    }

    if (exit)
        break;
}


问:
Finding xor sum in a tree
I was trying to solve this problem on hackerearth where you have a tree with values on each node and you have to answer queries that ask what is the xor sum between two nodes. Also, there are updates that you have to make(the value of a node can change). I solved the easy part (dfs and lca) and for each node I saved the xor sum of the values of nodes on the path from node 1 to that node (including that node).

However, there's a part of the "editorial" for this problem I can't understand.

Consider the tree is rooted at node 1. Let F(i) be the XOR sum of all
  value associated with nodes in the path from root 1 to node i. Let
  LCA(u, v) be the lowest common ancestor of node u and node v. Let Q(u,
  v) be the XOR sum of all value associated with nodes in the single
  path from node u to node v. So Q(u, v) is answer for each query of
  type 2.

We have: Q(u, v) = F(u) XOR F(v) XOR A[LCA(u, v)] (why?) where A[i]
  denoting value associated with node i.

I don't understand where they got this formula:

Q(u, v) = F(u) XOR F(v) XOR A[LCA(u, v)]

What is the thought process behind this formula?

答:
The key to deriving that formula is seeing how the various paths overlap and remembering that any number XOR itself equals 0. In particular, Q(x, y) XOR Q(x, y) will also equal 0.

The Quick Derivation

F(u) is the path from the root node to u. F(v) is the path from the root node to v. Because any number XOR itself equals 0, F(u) XOR F(v) will "cancel out" all the nodes above the lowest common ancestor of u and v, LCA(u, v). So F(u) XOR F(v) = Q(LCA(u, v), u) XOR Q(LCA(u, v), v). This happens to be the XOR sum of all nodes on the unique path from u to v, except for LCA(u, v) itself, since it's currently counted twice. So if we simply count it a third time, then we get the sum of all the nodes in Q(u, v). Thus Q(u, v) = F(u) XOR F(v) XOR LCA(u, v).

I suspect this "proof" leaves out too many details for you or contains a few steps you're not already convinced of, so here's a much longer version:

The Thorough Derivation

We're assuming that our graph is a valid tree, and there is a unique single path between u and v. This ensures u and v have a single "lowest common ancestor", LCA(u, v), which I will refer to as a. I will call the root node r. Keep in mind that a may be the same node as u, v, a, or even all three. The argument I'm about to show should still work even in those degenerate cases.

So there are unique paths (possibly of length zero) between these four nodes, like this:

Following the "editorial", let Q(x, y) denote the XOR sum of the nodes on the unique path from x to y.

We're interested in Q(u, v). Clearly, the unique path from u to v passes through a. However, it would be wrong to say that Q(u, v) = Q(u, a) XOR Q(a, v) because that would count the value of a twice. Fortunately, because XOR'ing a value by itself results in zero, counting a three times is the same as counting it only once. So the correct statement is:

```<code>Q(u, v) = Q(u, a) XOR Q(a, v) XOR A[a]
</code>```

Next, F(i) is defined as Q(r, i). So we can follow the same logic as above and say:

```<code>F(u) = Q(r, u) = Q(r, a) XOR Q(a, u) XOR A[a]
F(v) = Q(r, v) = Q(r, a) XOR Q(a, v) XOR A[a]
</code>```

Now, what is F(u) XOR F(v)? Because the XOR operation is commutative and associative, we can safely rearrange a series of XORs like we would a series of +s, which lets us do this:

```<code>F(u) XOR F(v) = (Q(r, a) XOR Q(a, u) XOR A[a]) XOR (Q(r, a) XOR Q(a, v) XOR A[a])
              = (Q(r, a) XOR Q(r, a)) XOR (Q(a, u) XOR Q(a, v)) XOR (A[a] XOR A[a])
              = 0 XOR (Q(a, u) XOR Q(a, v)) XOR 0
              = Q(a, u) XOR Q(a, v)
</code>```

More intuitively: Whenever you XOR the XOR sums of two overlapping paths, the parts that overlap simply disappear, and we're left only with the XOR sums of the non-overlapping parts of the paths.

Finally, recall that Q(u, v) = Q(u, a) XOR Q(a, v) XOR A[a]. We now know that Q(a, u) XOR Q(a, v) is equal to F(u) XOR F(v), which means:

```<code>Q(u, v) = Q(u, a) XOR Q(a, v) XOR A[a]
        = F(u) XOR F(v) XOR A[a]
</code>```

And since I defined a as LCA(u, v), we're done.

ContentLicense: CC BY-SA 3.0

Title: Finding xor sum in a tree

Body:
The key to deriving that formula is seeing how the various paths overlap and remembering that any number XOR itself equals 0. In particular, Q(x, y) XOR Q(x, y) will also equal 0.

The Quick Derivation

F(u) is the path from the root node to u. F(v) is the path from the root node to v. Because any number XOR itself equals 0, F(u) XOR F(v) will "cancel out" all the nodes above the lowest common ancestor of u and v, LCA(u, v). So F(u) XOR F(v) = Q(LCA(u, v), u) XOR Q(LCA(u, v), v). This happens to be the XOR sum of all nodes on the unique path from u to v, except for LCA(u, v) itself, since it's currently counted twice. So if we simply count it a third time, then we get the sum of all the nodes in Q(u, v). Thus Q(u, v) = F(u) XOR F(v) XOR LCA(u, v).

I suspect this "proof" leaves out too many details for you or contains a few steps you're not already convinced of, so here's a much longer version:

The Thorough Derivation

We're assuming that our graph is a valid tree, and there is a unique single path between u and v. This ensures u and v have a single "lowest common ancestor", LCA(u, v), which I will refer to as a. I will call the root node r. Keep in mind that a may be the same node as u, v, a, or even all three. The argument I'm about to show should still work even in those degenerate cases.

So there are unique paths (possibly of length zero) between these four nodes, like this:

Following the "editorial", let Q(x, y) denote the XOR sum of the nodes on the unique path from x to y.

We're interested in Q(u, v). Clearly, the unique path from u to v passes through a. However, it would be wrong to say that Q(u, v) = Q(u, a) XOR Q(a, v) because that would count the value of a twice. Fortunately, because XOR'ing a value by itself results in zero, counting a three times is the same as counting it only once. So the correct statement is:

Q(u, v) = Q(u, a) XOR Q(a, v) XOR A[a]

Next, F(i) is defined as Q(r, i). So we can follow the same logic as above and say:

F(u) = Q(r, u) = Q(r, a) XOR Q(a, u) XOR A[a]
F(v) = Q(r, v) = Q(r, a) XOR Q(a, v) XOR A[a]

Now, what is F(u) XOR F(v)? Because the XOR operation is commutative and associative, we can safely rearrange a series of XORs like we would a series of +s, which lets us do this:

F(u) XOR F(v) = (Q(r, a) XOR Q(a, u) XOR A[a]) XOR (Q(r, a) XOR Q(a, v) XOR A[a])
              = (Q(r, a) XOR Q(r, a)) XOR (Q(a, u) XOR Q(a, v)) XOR (A[a] XOR A[a])
              = 0 XOR (Q(a, u) XOR Q(a, v)) XOR 0
              = Q(a, u) XOR Q(a, v)

More intuitively: Whenever you XOR the XOR sums of two overlapping paths, the parts that overlap simply disappear, and we're left only with the XOR sums of the non-overlapping parts of the paths.

Finally, recall that Q(u, v) = Q(u, a) XOR Q(a, v) XOR A[a]. We now know that Q(a, u) XOR Q(a, v) is equal to F(u) XOR F(v), which means:

Q(u, v) = Q(u, a) XOR Q(a, v) XOR A[a]
        = F(u) XOR F(v) XOR A[a]

And since I defined a as LCA(u, v), we're done.


问:
Declarative parser for JSON and DOM
I am parsing many JSONs and DOMs in PHP. The problem is that the my knowledge about the structure of the JSON/DOM is mixed with code. For example, suppose that I have few sources of first and last names. Each data source can look different and have its own tricks, for example:

```<code>[
  {"firstname": "FirstName1", "lastname": "LastName1"},
  {"firstname": "FirstName2", "lastname": "LastName2"}
]
</code>```

```<code>{
  "firstnames": ["FirstName1", "FirstName2"],
  "lastnames": ["LastName1", "LastName2"]
}
</code>```

```<code>{
  "firstnames":
  [
    {"firstname": "FirstName1", "id": 1},
    {"firstname": "FirstName2", "id": 2}
  ],
  "lastnames":
  [
    {"lastname": "LastName2", "id": 2},
    {"lastname": "LastName1", "id": 1}
  ]
}
</code>```

So for each data source I write code that turns the JSON into my objects. If the JSON is very complex then the code also is very complex and it is impossible to see the JSON structure in my code. Looking for bugs is very hard.

I want to solve the problem in declarative way, something like a JSON regex where I can tell "first names are in 'firstnames', second names are in 'secondnames', and they are linked by 'id'".

How can I achieve that? Does JSON have some kind of declarative transformation language (like XSLT/XPath for XML)? Are there any strategies or patterns that can be used to make this JSON → Model transformation more declarative?

答:
Without recommending a specific tool or lib (since it's considered off topic), I would definitely recommend you to use the reference JSON parser for your language and try, if you can't normalize your inputs, to write specific code for each format.

In my humble opinion, parsing it by hand and/or trying to reuse code in each use case is likely to be worse in terms of readability, maintainability, or even security.

Title: Declarative parser for JSON and DOM


问:
How to build a product modeling framework
We have a legacy ASP.Net application (written in c# a few years ago) which allows a factory manufacture a number of custom-made products. Different attributes such as color, length, width, etc. are common for all product types, but each product type carries a set of attributes specific to type. The application currently has a base product class, followed by a number of classes each for each type.

Also, every type has its own set of web forms specific to the type. selection between the types is given by a switch statement which directs the code execution based on product type to the relevant web form. In addition, a single with some 70 fields is used to hold all products manufactured, with only the fields relevant to product type populated.

We are now trying to refactor this application, so as to be able to add new products without having to change the code extensively. Also we would like to not have to build new web forms for each new type of product but rather have the forms created dynamically (we are moving to MVC now). We would like if possible to move from development to configuration. Is there a "canonic approach" for this kind of task?

答:
Yes, But you dont say what you are doing with the products.

If you just need to record the information, then you only need a single Product with a dictionary of attributes.

Then a single view can loop through the collection and produce forms for any product 'type'

If however you have custom logic to implement per type any generic system will soon become too complex. You end up inventing a new programming language for your configuration which is a nightmare to maintain.

Rather than go down that route I would suck up the short term pain of a view per model.

edit -----

code example for simple dictionary model

```<code>using System.Collections.Generic;
    public class Product
    {
        public Dictionary<string, string> Attributes { get;set }
    }
    public class ProductFactory
    {
        public Product Create(string productType)
        {
            Product p  = new Product();
            if(productType == "chair")
            {
                p.Attributes.Add("legCount","4");
                p.Attributes.Add("material","pine wood");
            }
            return p;
        }
    }
</code>```

razor view snippet

```<code>@foreach(KeyValuePair kvp in Model.Attributes)
{
    <label>@kvp.Value<label> <input type="text" name="@kvp.Key" value="@kvp.Value"/>
}
</code>```

Views on EAV answer :

In my view this is the next level up. You replace the strings with objects and add meta data to tell the form how to render for specific types. However, (briefly) in my view this only pushes the requirement for custom forms down to the attribute level and you are better off just going for custom forms per product

Problems with this simple dictionary approach :

You no longer have strongly typed products. At some point you need to convert the string "4" legs into an actual number of legs. if the user has typed "four" you will get a run time error.

To clarify :

If you want my recommendation, it's "don't do autogenerated forms"

Body:
Yes, But you dont say what you are doing with the products.

If you just need to record the information, then you only need a single Product with a dictionary of attributes.

Then a single view can loop through the collection and produce forms for any product 'type'

If however you have custom logic to implement per type any generic system will soon become too complex. You end up inventing a new programming language for your configuration which is a nightmare to maintain.

Rather than go down that route I would suck up the short term pain of a view per model.

edit -----

code example for simple dictionary model

using System.Collections.Generic;
    public class Product
    {
        public Dictionary<string, string> Attributes { get;set }
    }
    public class ProductFactory
    {
        public Product Create(string productType)
        {
            Product p  = new Product();
            if(productType == "chair")
            {
                p.Attributes.Add("legCount","4");
                p.Attributes.Add("material","pine wood");
            }
            return p;
        }
    }

razor view snippet

@foreach(KeyValuePair kvp in Model.Attributes)
{
    <label>@kvp.Value<label> <input type="text" name="@kvp.Key" value="@kvp.Value"/>
}

Views on EAV answer :

In my view this is the next level up. You replace the strings with objects and add meta data to tell the form how to render for specific types. However, (briefly) in my view this only pushes the requirement for custom forms down to the attribute level and you are better off just going for custom forms per product

Problems with this simple dictionary approach :

You no longer have strongly typed products. At some point you need to convert the string "4" legs into an actual number of legs. if the user has typed "four" you will get a run time error.

To clarify :

If you want my recommendation, it's "don't do autogenerated forms"


问:
PHP: where to call helper class in MVC?
I've a helper class in Laravel 5.1 with static methods for calculating week numbers, dates in weeks, etc. (Why static? I need max. 1 instance of this helper class)

I need this logic in my views. I'm using MVC pattern. My question is quite simple:

May my view call the helper methods directly?

Or: is my controller responsible to call the helper and pass the results to the view?

答:
Having static methods because you only need one instance is an awful excuse. You are introducing global state, which is bad and messes up unit testing.

If you really need only one instance of the helper, make a container with a method like createAndReturnHelper which will act as a weak singleton, lazy loading the class if it is not preset and/or otherwise returning the already created instance. If you need the helper in your controller, be sure to inject it by using the container to obtain the helper from it.

That gets your static methods sorted out.

Whether you want the view to call helper's methods directly or not, that is mostly up to you, although it has proven to me that the better approach is to do all the logic inside the controller, filtering data, finding the right stuff, and include into the view only very simple PHP, such as the foreach loop and variables, of course. Variables, which contain the correct data.

The main point into making the view not contain any complicated php code is that frontend designers usually do not have deep knowledge of the programming language(s), and they are not really supposed to, they are focusing on frontend, so you can tell them if you iterate over the variable $x, it will contain all the data you need. The backend team will make sure the data is correct, so just style it for the end user in a nice way.

Title: PHP: where to call helper class in MVC?


问:
When using DDD and CRQS, should be exactly one event per command?
I am looking for a way to design a ddd application with convention over configuration.

Say an aggregate "Client" has a command defined "FillProfile". It will logically raise an event "ProfileFilled".

Are there cases when a command will raise more than an event, or where a command will raise different events based on some logic? Or is this always a 1 - 1 relationship (1 command will always raise none, or a single event of a given type).

I am asking this because if this is a fact, that a command will always raise the same event, I can build my convention system on that fact. I know that "RaiseEvent" will result in "EventRaised"...

答:
Usually one command will lead to one event. But in some cases it can also be more than one, it depends on your implementation.

Either your command calls other commands and each of them fire own events. Or your command does different tasks on it's own and issues multiple events. For example:

RegisterUserCommand

User.create(email, password) → UserCreatedEvent

User.updateProfile(firstName, lastName, location) → UserProfileUpdatedEvent

User.joinDefaultGroup() → UserJoinedGroupEvent


问:
How much should I be using 'let' vs 'const' in ES6?
I've been writing a lot of ES6 code for io.js recently. There isn't much code in the wild to learn from, so I feel like I'm defining my own conventions as I go.

My question is about when to use const vs let.

I've been applying this rule: If possible, use const. Only use let if you know its value needs to change. (You can always go back and change a const to a let if it later turns out you need to change its value.)

The main reason for this rule is it's easy to apply consistently. There are no grey areas.

The thing is, when I apply this rule, in practice 95% of my declarations are const. And this looks weird to me. I'm only using let for things like i in a for loop, or occasionally for things like accumulated Fibonacci totals (which doesn't come up much in real life). I was surprised by this – it turns out 95% of the 'variables' in my ES5 code to date were for values that do not vary. But seeing const all over my code feels wrong somehow.

So my question is: is it OK to be using const this much? Should I really be doing things like const foo = function () {...};?

Or should I reserve const for those kind of situations where you're hard-coding a literal at the top of a module – the kind you do in full caps, like const MARGIN_WIDTH = 410;?

答:
My personal approach, thought for helping code readability and understanding:

let is only for short-lived variables, defined at a single line and not changed after. Generally those variables which are there only to decrease the amount of typing. For example:

```<code>for (let key in something) {
  /* we could use `something[key]` for this entire block,
     but it would be too much letters and not good for the
     fingers or the eyes, so we use a radically temporary variable
  */
  let value = something[key]
  ...
}
</code>```

const for all names known to be constant across the entire module. Not including locally constant values. The value in the example above, for example, is constant in its scope and could be declared with const, but since there are many iterations and for each one there's a value with same name, "value", that could trick the reader into thinking value is always the same. Modules and functions are the best example of const variables:

```<code>const PouchDB = require('pouchdb')
const instantiateDB = function () {}
const codes = {
  23: 'atc',
  43: 'qwx',
  77: 'oxi'
}
</code>```

var for everything that may or not be variable. Names that may confuse people reading the code, even if they are constant locally, and are not suitable for let (i.e., they are not completed in a simple direct declaration) apply for being declared with var. For example:

```<code>var output = '\n'
lines.forEach(line => {
  output += '  '
  output += line.trim()
  output += '\n'
})
output += '\n---'

for (let parent in parents) {
  var definitions = {}
  definitions.name = getName(parent)
  definitions.config = {}
  definitions.parent = parent
}
</code>```

Further commentary and possible future updates here.

Body:
My personal approach, thought for helping code readability and understanding:

let is only for short-lived variables, defined at a single line and not changed after. Generally those variables which are there only to decrease the amount of typing. For example:

for (let key in something) {
  /* we could use `something[key]` for this entire block,
     but it would be too much letters and not good for the
     fingers or the eyes, so we use a radically temporary variable
  */
  let value = something[key]
  ...
}

const for all names known to be constant across the entire module. Not including locally constant values. The value in the example above, for example, is constant in its scope and could be declared with const, but since there are many iterations and for each one there's a value with same name, "value", that could trick the reader into thinking value is always the same. Modules and functions are the best example of const variables:

const PouchDB = require('pouchdb')
const instantiateDB = function () {}
const codes = {
  23: 'atc',
  43: 'qwx',
  77: 'oxi'
}

var for everything that may or not be variable. Names that may confuse people reading the code, even if they are constant locally, and are not suitable for let (i.e., they are not completed in a simple direct declaration) apply for being declared with var. For example:

var output = '\n'
lines.forEach(line => {
  output += '  '
  output += line.trim()
  output += '\n'
})
output += '\n---'

for (let parent in parents) {
  var definitions = {}
  definitions.name = getName(parent)
  definitions.config = {}
  definitions.parent = parent
}

Further commentary and possible future updates here.


问:
Helper methods of a particular class
Let's say I have a class that needs some helper methods to do its work. The number of helper methods starts to grow and the size of the class also starts to grow a lot.

How should I handle this problem?

Should I generalize the methods and create a static Helper class even though I know that, for now, only one class needs it?

Should I just let the class size grow? (I don't like this solution)

Any better solution?

答:
Speaking broadly, it sounds like your class has taken on too many responsibilities. It's impossible to say exactly how without knowing the details, but the fact that you're concerned about its growth is a smell/tell/canary-in-the-coalmine. It's likely that you simply need a new class.

Remember, "helpers" are problematic. If you think about it long and hard, there's probably a noun with related verbs that works on/with your original class. There's likely some thing that can stand on its own. If not, it might turn out that your original class is actually two or more classes. If it's not that, well, then you haven't had a chance to think about it enough. There's no such thing as something that does one and only one thing, but requires many, many, many methods to do it. That can't be just one thing.

Anticipating questions about the obnoxious HtmlHelper I'll say this: it could have been better named. Sure, its extension methods are all about rendering HTML, but is that really the best name? Also, it probably does more than it should. Is there really some big "thing" that knows about routing, rendering HTML, client-side validation modes, validation summary CSS, etc...? Mmmmm... my guess is there's more than one person on the MVC team who isn't crazy about the name and responsibilities. Sometimes, the best solutions aren't obvious until we've lived with the alternative for a while.

Did I tell you about the time I met Rod Stewart? It could have been one of the best days of my life. Instead, I went straight home and sold all of his vinyl. He smelled like baby wipes, bourbon, and cat pee. I couldn't understand a word he said. He pushed by me (the radio award winner) so he could hit on my girlfriend. We're not sure, but it sounded like he kept calling her "peanut butter" while pawing at her blouse. We left early.

My point is that just because you look up to someone doesn't mean they won't <s>hit on your girlfriend</s> occasionally make mistakes.

(Don't make the equivalent of a HtmlHelper.)

Related from SO: Is the word “Helper” in a class name a code smell?

Title: Helper methods of a particular class


问:
Development process used for the code on Apollo 11 missions?
The Apollo missions had technology no more complicated than a pocket calculator.

From link here, there's an information about Apollo Guidance Computer (AGC)

The on-board Apollo Guidance Computer (AGC) was about 1 cubic foot with 2K of 16-bit RAM and 36K of hard-wired core-rope memory with copper wires threaded or not threaded through tiny magnetic cores. The 16-bit words were generally 14 bits of data (or two op-codes), 1 sign bit, and 1 parity bit. The cycle time was 11.7 micro-seconds. Programming was done in assembly language and in an interpretive language, in reverse Polish.

So, I've stumbled upon some source code when I researched what was up there, and I've noticed great comments (eg. TEMPORARY, I HOPE HOPE HOPE)

```<code>VRTSTART    TS  WCHVERT
# Page 801
        CAF TWO     # WCHPHASE = 2 ---> VERTICAL: P65,P66,P67
        TS  WCHPHOLD
        TS  WCHPHASE
        TC  BANKCALL    # TEMPORARY, I HOPE HOPE HOPE
        CADR    STOPRATE    # TEMPORARY, I HOPE HOPE HOPE
        TC  DOWNFLAG    # PERMIT X-AXIS OVERRIDE
        ADRES   XOVINFLG
        TC  DOWNFLAG
        ADRES   REDFLAG
        TCF VERTGUID
</code>```

The actual programs in the spacecraft were stored in core rope memory, an ancient memory technology made by (literally) weaving a fabric/rope, where the bits were physical rings of ferrite material. "Core" memory is resistant to cosmic rays. The state of a core bit will not change when bombarded by radiation in Outer Space.

Virtual Apollo Guidance Computer (AGC) software is also on GITHUB!

Some part of documentation is here.

Another sample of source code with great comments.

```<code>033911,000064: 32,3017    06037        FLAGORGY        TC       INTPRET      #  DIONYSIAN FLAG WAVING

    034090,000243: 32,3241    13247        BZF      P63SPOT4               #  BRANCH IF ANTENNA ALREADY IN POSITION 1
    034091,000244:
    034092,000245: 32,3242    33254        CAF      CODE500                #  ASTRONAUT:     PLEASE CRANK THE
    034093,000246: 32,3243    04616        TC       BANKCALL               #                 SILLY THING AROUND
    034094,000247: 32,3244    20623        CADR     GOPERF1
    034095,000248: 32,3245    16001        TCF      GOTOP00H               #  TERMINATE
    034096,000249: 32,3246    13235        TCF      P63SPOT3               #  PROCEED        SEE IF HE'S LYING

    034101,000254: 32,3251    04635        TC       POSTJUMP               #  OFF TO SEE THE WIZARD ...
    034102,000255: 32,3252    74126        CADR     BURNBABY
</code>```

My question here is this:

How were the teams writing this much code able to make it functional given the tools at the time?

Because if you compile so much code that was used on Apollo 11... it'd take days, even weeks. I seriously doubt that programmers back then left everything to happen by chance.

答:
If I understand correctly, the development process was peer review and experimentation.

The team consisted of people like "Math Doctors" - extremely dedicated, intelligent, passionate, detail-oriented folks whose lives were dedicated to their work. So when I say peer review, I mean many peer reviews over the course of many months (more than a year).

These developers "ran the simulations in their heads", "debugged the software on paper" and worked in groups with many developers looking at the same code over and over until they were convinced it was correct. There were multiple teams - each working on a part of the whole.

My Numerical Methods professor at The Ohio State University (Spring '96) wrote the code that decided when to kick off a stage of the booster rocket. He described the printout being the size of the phone book (So, maybe 2.5 to 3.5 inches thick of 8.5 x 11 inch paper - he didn't describe the font size) of Fortran code.

When convinced, they launched an unmanned missile (rockets technically don't have gyroscopes) with a radio on board that emitted a beep at regular intervals. They listened to the beeps up to the point they expected the radio to impact the moon (crash into it and destroy itself) and stop beeping. They knew that if they missed, the radio would keep beeping long past the calculated time of impact. Impact occurred 15 seconds after the calculated time.

This admitedly anecdotal story are my recollections from an office visit with the doctor. He was very old, and it was a long time ago. This is my best recollection.


问:
How to best encapsulate features in software design?
I like domain driven design, and onion design.  However I would really like my features to be encapsulated.  If i check out some legacy code and I need to investigate some specific feature the best thing that I think could happen to me is that I see (lets say in java) is that there would be a package with featurename and all the feature functionality would reside in that package.  In a way that if i delete the package the feature would be gone.

While I understand its impossible because some of the feature might reside in other service I'm trying to at least think if its correct to do that in my own service.

My problem with this is that usually in DDD and in onion design you have the domain which contains a bunch of domain objects.  now some of these objects are of "my feature" and some of them are of other features.  lets say (user authentication is one feature and user twitter account details is another feature).

Is there any design methodology that does something with it? is what I'm suggesting makes sense?

Example: you have a project that manages users waiting in line.  You are asked to add a limit, max on the queue size.  you need to read that max queue size from configuration.  Then in your logic you need to apply that max queue size.  You also need to expose this configuration of max queue size in jmx, also you have an api to that service so you need to expose that max queue size as an api in that service.

Current app packages:

  --> conf (deals with reading configuration) // do change here.
  --> domain // do change here for that small subfeature.
  --> logic // do change also here for that small subfeature
  --> service (where api are) // do also a change here.

so in the above simplistic example for a simple subfeature addition i need to make changes to at least 4 packages.  Which means my subfeature is spread among these packages and classes.

I understand DDD mentions boundcontext but notice my feature here is very very small! just adding a max limitation on size.  So it does not seem appropriate to open a boundedcontext on each such small subfeature.

So the way I deal with it today I go conf i find there a class named Configuration which contains various configurations.  I add to that Configuration class a member named Configuration.maxQueueSize.

I go then to domain to model that new property I have there lets say Account I add to the Account class Account.maxQueueSize.

I go then to service an expose a new method named getMaxQueueSize

as you see I went to multiple packages and multiple classes already dealing with other functionality and extended them.

This is a very small feature, for one hand I cant imaging that for every small feauter I would open a whole new bounded context with its own service, domain, conf packages (and lets assume there are more) so that each feature is in its own package.

On the other way on each feature I need to extend configuration, domain, service, ... which means no single feature is encapsulated well enough so that I can just delete it or see a package which its fully resides in so that I can better understand the app.

答:
What you are looking for is called Bounded Context in DDD.

Now, as you are realizing in your question, bounded contexts might share data. The best way to implement it that I saw is simply to duplicate the entities. So Accounting context has Customer, and so does Production have Customer. But even though they have same name, they have completely different meaning. It then becomes responsibility of the layer above (most probably infrastructure layer) to save and load them into same table. But from the point of individual contexts, the customers are completely separate. This then allows you to completely remove any bounded context from the whole application without affecting any other part.

As it relates to Onion Architecture, I would design each "feature module" as a "slice" through the onion where each layer is single library. Imagine cutting out a piece round cake. So you could have libraries Feature1.Domain, Feature1.Database and Feature2.Domain, Feature2.Database, etc.. between which would be relationships according onion architecture.

But there is a problem. As you might know, some modules might want to communicate between each other. That's where Bridging libraries come in. Simply said, you could have library Feature1Feature2Bridge. This library would rely on Feature1.Domain and Feature2.Domain providing abstractions for communication, and this "Bridge" library would implement that communication. Then, this library would be loaded only if both features are loaded.


答:
What you are looking for is called "Entity Attribute Value" model. It will allow you to have a metamodel in your database, which describes the list of attributes of each entity (in your case the Product types). The metamodel can be changed at run time, so you can add new product types without changing your application. And you can provide additional information there like "datatype", "allowed range of values", "is the attibute mandatory or optional", "minimum width" and so on which is necessary for generating a useful form for this data.

To implement this, you will need to add some functionality to your application to manage the list of available product types and the list of attributes of each type.

Beware, EAV is often seen as an anti-pattern, because it can add more additional complexity to a program than one typically expects. So my recommendation is to use it only for product attributes where you really need that kind of flexibility, the "user defined attributes", not for the attributes common for all product types. It is perfectly possible to implement EAV only partial, or in a downsized variant which suits your needs. For example, you can provide a certain list of standard products, for instance, a "basic chair", a "basic table", builtin into the application, and each attribute a classic row in your database table. Then you let the user create something like a dining chair or an office chair as extensions of the "basic chair", by giving him add the ability to the missing attributes by himself (and only those attributes will become part of the EAV model).

Title: How to build a product modeling framework

Body:
We have a legacy ASP.Net application (written in c# a few years ago) which allows a factory manufacture a number of custom-made products. Different attributes such as color, length, width, etc. are common for all product types, but each product type carries a set of attributes specific to type. The application currently has a base product class, followed by a number of classes each for each type.

Also, every type has its own set of web forms specific to the type. selection between the types is given by a switch statement which directs the code execution based on product type to the relevant web form. In addition, a single with some 70 fields is used to hold all products manufactured, with only the fields relevant to product type populated.

We are now trying to refactor this application, so as to be able to add new products without having to change the code extensively. Also we would like to not have to build new web forms for each new type of product but rather have the forms created dynamically (we are moving to MVC now). We would like if possible to move from development to configuration. Is there a "canonic approach" for this kind of task?


问:
What is the meaning of bootstrapping in software development?
In some articles and books that I read, I some time see the term 'Bootstrapping'. For example I see this sentence "Bootstrapping X.JS" in angular js document: http://docs.angularjs.org/tutorial/step_00

Bootstrapping AngularJS apps automatically using the ngApp directive is very easy and suitable for most cases. In advanced cases, such as when using script loaders, you can use imperative / manual way to bootstrap the app...

What is the meaning of bootstrapping in software development?

答: Bootstrapping in web frameworks is pushed into index page (the bootstrapper), and then it loads the frameworks helpers, models, configuration, and then loads the controller and passes off control to it.</p>


答:
One command can raise multiple events. It is simply logical conclusion of one fact : Composite command exists.

Lets say you have two commands, each raising an event. Then, you create a composite command of those two. From the view of one using the composite command, it seems as if the command raised two events.

So there is nothing stopping you from having single command raising multiple (or even no) events.

Title: When using DDD and CRQS, should be exactly one event per command?

Body:
I am looking for a way to design a ddd application with convention over configuration.

Say an aggregate "Client" has a command defined "FillProfile". It will logically raise an event "ProfileFilled".

Are there cases when a command will raise more than an event, or where a command will raise different events based on some logic? Or is this always a 1 - 1 relationship (1 command will always raise none, or a single event of a given type).

I am asking this because if this is a fact, that a command will always raise the same event, I can build my convention system on that fact. I know that "RaiseEvent" will result in "EventRaised"...


问:
akka and futures, which ExecutionContext should be used
Following this blog by @Tomasz Nurkiewicz we can see that 4 different approaches are available for picking the ExecutionContext, when interacting with akka actors, for scala futures to run on.

```<code>import ExecutionContext.Implicits.global

//or

implicit val ec = ExecutionContext.fromExecutorService(Executors.newFixedThreadPool(50))

//or (inside actor)

import context.dispatcher

//or (explicitly)

val future = Future {
    //...
} (ec)
</code>```

Only one is akka specific, the rest are agnostic to the fact that concurrency is handled by actors, elsewhere.

Given that there are situations where handling concurrency with actors and futures is unavoidable (for example, my question on SO regarding slick), which paradigm would fit best? Running the future on the actor's dispatcher, or one of the other possibilities, as illustrated above?

BTW, rereading my question on SO, I see that I used Scala's global ExecutionContext, yet the logs log the threads handling the future code as belonging to the ActorSystem's default dispatcher... what's going on with that???

EDIT,

went back to the aforementioned SO question and recreated the example. The world makes more sense again, as the following logs appeared (we can see that the default global ForkJoinPool is invoked within the future while the default dispatcher is used for actors):

```<code>[INFO] [11/04/2015 09:29:06.267] [wtf-akka.actor.default-dispatcher-3] [akka://wtf/user/$a] ['wtf1] external block pre future
[INFO] [11/04/2015 09:29:06.287] [wtf-akka.actor.default-dispatcher-3] [akka://wtf/user/$a] ['wtf1] external block post future
[INFO] [11/04/2015 09:29:06.287] [ForkJoinPool-2-worker-7] [akka://wtf/user/$a] ['wtf1] internal block pre sleep
[INFO] [11/04/2015 09:29:06.461] [wtf-akka.actor.default-dispatcher-2] [akka://wtf/user/$a] ['wtf2] external block pre future
[INFO] [11/04/2015 09:29:06.471] [wtf-akka.actor.default-dispatcher-2] [akka://wtf/user/$a] ['wtf2] external block post future
[INFO] [11/04/2015 09:29:06.472] [ForkJoinPool-2-worker-5] [akka://wtf/user/$a] ['wtf2] internal block pre sleep
</code>```

答:
You say to consider Slick as an example. Slick will use JDBC, and thus will use blocking I/O, i.e. the thread will not be available to do other work while it waits for the response from the database. You don't want to use your default Akka dispatcher for that.

You could define a separate execution context for your database operations and use that. I think this documentation page might be helpful for you.

ContentLicense: CC BY-SA 4.0


问:
Is it OK to learn an algorithm from an open source project, and then implement it in a closed source project?
Reference The post that started it all

In order to clear up the original question I asked in a provocative manner, I have posed this question.

If you learn an algorithm from an open source project, is it OK to use that algorithm in a separate closed sourced project? And if not, does that imply that you cannot use that knowledge ever again? If you can use it, what circumstance could that be?

Just to clarify, I am not trying to evade a licence, otherwise I would not have asked the question in the first place.

答:
As I understand it the algorithm itself is not copyrightable but the expression of it in program code is. The problem you may face is if you write an implementation and parts of it up being similar to an implementation you have previously read then you may have an uphill battle to demonstrate that you didn't (knowingly or unknowingly) copy parts of the expression.

Patent issues are seperate, they apply to anyone who implements the algorithm regardless of if they have read a previous implementation.


答:
Since you tagged your question with "CQRS", I guess you mean events in a "CQRS & Event Sourcing" context, like it is described here. In this tutorial, the difference between events and commands is well explained:

events capture the elementary "things that happened" in your system, from the system's point of view,

commands are defined by what the user considers as an operation, from his point of view.

And though this often leads to a couple of commands and events with a 1:1 correspondence, these different points of view can lead to commands which fire more than one event, or different events depending on the command parameters. I can even imagine cases where a command does not raise an event at all, but that would be a very exceptional case, not a very typical one.

For example, the tutorial mentions events

TabOpened

DrinksOrdered

FoodOrdered

and commands

OpenTab

PlaceOrder

Here, the command "OpenTab" will lead to an event "TabOpened", but the command PlaceOrder will lead to the events "DrinksOrdered", "FoodOrdered", or both.

In fact, if you are designing a new system "from scratch", you can try to design it with a 1:1 correspondence between commands and events and look how well that scales when the system becomes bigger. You can even try a hybrid approach: a list of events and commands with a 1:1 correspondence, together with some additional, combined commands. Just try how far that leads you for the particular system you are designing.


问:
Data Oriented Design - impractical with more than 1-2 structure "members"?
The usual example of Data Oriented Design is with the Ball structure:

```<code>struct Ball
{
  float Radius;
  float XYZ[3];
};
</code>```

and then they make some algorithm that iterates a std::vector<Ball> vector.

Then they give you the same thing, but implemented in Data Oriented Design:

```<code>struct Balls
{
  std::vector<float> Radiuses;
  std::vector<XYZ[3]> XYZs;
};
</code>```

Which is good and all if you're going to iterate trough all radiuses first, then all positions and so on. However, how do you move the balls in the vector? In the original version, if you have a std::vector<Ball> BallsAll, you can just move any BallsAll[x] to any BallsAll[y].

However to do that for the Data Oriented version, you must do the same thing for every property (2 times in the case of Ball - radius and position). But it gets worse if you have a lot more properties. You'll have to keep an index for each "ball" and when you try to move it around, you have to do the move in every vector of properties.

Doesn't that kill any performance benefit of Data Oriented Design?

答:
Data-Oriented Mindset

Data-oriented design doesn't mean apply SoAs everywhere. It simply means designing architectures with a predominant focus on data representation -- specifically with a focus on efficient memory layout and memory access.

That could possibly lead to SoA reps when appropriate like so:

```<code>struct BallSoa
{
   vector<float> x;        // size n
   vector<float> y;        // size n
   vector<float> z;        // size n
   vector<float> r;        // size n
};
</code>```

... this is often suitable for vertical loopy logic that doesn't process a sphere center vector components and radius simultaneously (the four fields aren't simultaneously hot), but instead one at a time (a loop through radius, another 3 loops through individual components of sphere centers).

In other cases it might be more appropriate to use an AoS if the fields are frequently accessed together (if your loopy logic is iterating through all the fields of balls rather than individually) and/or if random-access of a ball is needed:

```<code>struct BallAoS
{
    float x;
    float y;
    float z;
    float r;
};
vector<BallAoS> balls;        // size n
</code>```

... in other cases it might be suitable to use a hybrid which balances both benefits:

```<code>struct BallAoSoA
{
    float x[8];
    float y[8];
    float z[8];
    float r[8];
};
vector<BallAoSoA> balls;      // size n/8
</code>```

... you might even compress the size of a ball to half using half-floats to fit more ball fields into a cache line/page.

```<code>struct BallAoSoA16
{
    Float16 x2[16];
    Float16 y2[16];
    Float16 z2[16];
    Float16 r2[16];
};
vector<BallAoSoA16> balls;    // size n/16
</code>```

... perhaps even the radius is not accessed nearly as often as the sphere center (perhaps your codebase often treats them like points and only rarely as spheres, e.g.). In that case, you might apply a hot/cold field splitting technique further.

```<code>struct BallAoSoA16Hot
{
    Float16 x2[16];
    Float16 y2[16];
    Float16 z2[16];
};
vector<BallAoSoA16Hot> balls;     // size n/16: hot fields
vector<Float16> ball_radiuses;    // size n: cold fields
</code>```

The key to a data-oriented design is to consider all of these kinds of representations early in making your design decisions, to not trap yourself into a sub-optimal representation with a public interface behind it.

It puts a spotlight on memory access patterns and accompanying layouts, making them a significantly stronger concern than usual. In a sense it may even somewhat tear down abstractions. I've found by applying this mindset more that I no longer look at std::deque, e.g., in terms of its algorithmic requirements quite as much as the aggregated contiguous blocks representation it has and how random-access of it works at the memory level. It is somewhat putting a focus on implementation details, but implementation details which tend to have just as much or more of an impact on performance as the algorithmic complexity describing scalability.

Premature Optimization

A lot of the predominant focus of data-oriented design will appear, at least at a glance, as dangerously close to premature optimization. Experience often teaches us that such micro-optimizations are best applied in hindsight, and with a profiler in hand.

Yet perhaps a strong message to take from data-oriented design is to leave room for such optimizations. That's what a data-oriented mindset can help allow:

Data-oriented design can leave breathing room to explore more effective  representations. It's not necessarily about achieving memory layout perfection in one go, but more about making the appropriate considerations in advance to allow increasingly-optimal representations.

Granular Object-Oriented Design

A lot of data-oriented design discussions will pit themselves against classical notions of object-oriented programming. Yet I would offer a way of looking at this which is not quite as hardcore as to dismiss OOP entirely.

The difficulty with object-oriented design is that it will often tempt us to model interfaces at a very granular level, leaving us trapped with a scalar, one-at-a-time mindset instead of a parallel bulk mindset.

As an exaggerated example, imagine an object-oriented design mindset applied to a single pixel of an image.

```<code>class Pixel
{
public:
    // Pixel operations to blend, multiply, add, blur, etc.

private:
    Image* image;          // back pointer to access adjacent pixels
    unsigned char rgba[4];
};
</code>```

Hopefully no one actually does this. To make the example really gross, I stored a back pointer to the image containing the pixel so that it can access neighboring pixels for image processing algorithms like blur.

The image back pointer immediately adds a glaring overhead, but even if we excluded it (making only the public interface of pixel provide operations that apply to a single pixel), we end up with a class just to represent a pixel.

Now there's nothing wrong with a class in the immediate overhead sense in a C++ context besides this back pointer. Optimizing C++ compilers are great at taking all the structure we built and obliterating it down to smithereens.

The difficulty here is that we're modeling an encapsulated interface at too granular of a pixel level. That leaves us trapped with this kind of granular design and data, with potentially a vast number of client dependencies coupling them to this Pixel interface.

Solution: obliterate away the object-oriented structure of a granular pixel, and start modeling your interfaces at a coarser level dealing with a bulk number of pixels (at the image level).

By modeling at the bulk image level, we have significantly more room to optimize. We can, for example, represent large images as coalesced tiles of 16x16 pixels which perfectly fit into a 64-byte cache line but allow efficient neighboring vertical access of pixels with a typically-small stride (if we have a number of image processing algorithms which need to access neighboring pixels in a vertical fashion) as a hardcore data-oriented example.

Designing at a Coarser Level

The above example of modeling interfaces at an image level is kind of a no-brainer example as image processing is a very mature field that's been studied and optimized to death. Yet less obvious might be a particle in a particle emitter, a sprite vs. a collection of sprites, an edge in a graph of edges, or even a person vs. a collection of people.

The key to allowing data-oriented optimizations (in foresight or hindsight) is often going to boil down to designing interfaces at a much coarser level, in bulk. The idea of designing interfaces for single entities becomes replaced by designing for collections of entities with big operations that process them in bulk. This especially and immediately targets sequential access loops that need to access everything and cannot help but have linear complexity.

Data-oriented design often begins with the idea of coalescing data to form aggregates modeling data in bulk. A similar mindset echoes to the interface designs that accompany it.

This is the most valuable lesson I've taken from data-oriented design, since I'm not computer architecture-savvy enough to often find the most optimal memory layout for something on my first try. It becomes something I iterate towards with a profiler in hand (and sometimes with a few misses along the way where I failed to speed things up). Yet the interface design aspect of data-oriented design is what leaves me room to seek more and more efficient data representations.

The key is to design interfaces at a coarser level than we're usually tempted to do. This also often has side benefits like mitigating the dynamic dispatch overhead associated with virtual functions, function pointer calls, dylib calls and the inability for those to be inlined. The main idea to take out of all of this is to look at processing in a bulk fashion (when applicable).

Body:
Data-Oriented Mindset

Data-oriented design doesn't mean apply SoAs everywhere. It simply means designing architectures with a predominant focus on data representation -- specifically with a focus on efficient memory layout and memory access.

That could possibly lead to SoA reps when appropriate like so:

struct BallSoa
{
   vector<float> x;        // size n
   vector<float> y;        // size n
   vector<float> z;        // size n
   vector<float> r;        // size n
};

... this is often suitable for vertical loopy logic that doesn't process a sphere center vector components and radius simultaneously (the four fields aren't simultaneously hot), but instead one at a time (a loop through radius, another 3 loops through individual components of sphere centers).

In other cases it might be more appropriate to use an AoS if the fields are frequently accessed together (if your loopy logic is iterating through all the fields of balls rather than individually) and/or if random-access of a ball is needed:

struct BallAoS
{
    float x;
    float y;
    float z;
    float r;
};
vector<BallAoS> balls;        // size n

... in other cases it might be suitable to use a hybrid which balances both benefits:

struct BallAoSoA
{
    float x[8];
    float y[8];
    float z[8];
    float r[8];
};
vector<BallAoSoA> balls;      // size n/8

... you might even compress the size of a ball to half using half-floats to fit more ball fields into a cache line/page.

struct BallAoSoA16
{
    Float16 x2[16];
    Float16 y2[16];
    Float16 z2[16];
    Float16 r2[16];
};
vector<BallAoSoA16> balls;    // size n/16

... perhaps even the radius is not accessed nearly as often as the sphere center (perhaps your codebase often treats them like points and only rarely as spheres, e.g.). In that case, you might apply a hot/cold field splitting technique further.

struct BallAoSoA16Hot
{
    Float16 x2[16];
    Float16 y2[16];
    Float16 z2[16];
};
vector<BallAoSoA16Hot> balls;     // size n/16: hot fields
vector<Float16> ball_radiuses;    // size n: cold fields

The key to a data-oriented design is to consider all of these kinds of representations early in making your design decisions, to not trap yourself into a sub-optimal representation with a public interface behind it.

It puts a spotlight on memory access patterns and accompanying layouts, making them a significantly stronger concern than usual. In a sense it may even somewhat tear down abstractions. I've found by applying this mindset more that I no longer look at std::deque, e.g., in terms of its algorithmic requirements quite as much as the aggregated contiguous blocks representation it has and how random-access of it works at the memory level. It is somewhat putting a focus on implementation details, but implementation details which tend to have just as much or more of an impact on performance as the algorithmic complexity describing scalability.

Premature Optimization

A lot of the predominant focus of data-oriented design will appear, at least at a glance, as dangerously close to premature optimization. Experience often teaches us that such micro-optimizations are best applied in hindsight, and with a profiler in hand.

Yet perhaps a strong message to take from data-oriented design is to leave room for such optimizations. That's what a data-oriented mindset can help allow:

Data-oriented design can leave breathing room to explore more effective  representations. It's not necessarily about achieving memory layout perfection in one go, but more about making the appropriate considerations in advance to allow increasingly-optimal representations.

Granular Object-Oriented Design

A lot of data-oriented design discussions will pit themselves against classical notions of object-oriented programming. Yet I would offer a way of looking at this which is not quite as hardcore as to dismiss OOP entirely.

The difficulty with object-oriented design is that it will often tempt us to model interfaces at a very granular level, leaving us trapped with a scalar, one-at-a-time mindset instead of a parallel bulk mindset.

As an exaggerated example, imagine an object-oriented design mindset applied to a single pixel of an image.

class Pixel
{
public:
    // Pixel operations to blend, multiply, add, blur, etc.

private:
    Image* image;          // back pointer to access adjacent pixels
    unsigned char rgba[4];
};

Hopefully no one actually does this. To make the example really gross, I stored a back pointer to the image containing the pixel so that it can access neighboring pixels for image processing algorithms like blur.

The image back pointer immediately adds a glaring overhead, but even if we excluded it (making only the public interface of pixel provide operations that apply to a single pixel), we end up with a class just to represent a pixel.

Now there's nothing wrong with a class in the immediate overhead sense in a C++ context besides this back pointer. Optimizing C++ compilers are great at taking all the structure we built and obliterating it down to smithereens.

The difficulty here is that we're modeling an encapsulated interface at too granular of a pixel level. That leaves us trapped with this kind of granular design and data, with potentially a vast number of client dependencies coupling them to this Pixel interface.

Solution: obliterate away the object-oriented structure of a granular pixel, and start modeling your interfaces at a coarser level dealing with a bulk number of pixels (at the image level).

By modeling at the bulk image level, we have significantly more room to optimize. We can, for example, represent large images as coalesced tiles of 16x16 pixels which perfectly fit into a 64-byte cache line but allow efficient neighboring vertical access of pixels with a typically-small stride (if we have a number of image processing algorithms which need to access neighboring pixels in a vertical fashion) as a hardcore data-oriented example.

Designing at a Coarser Level

The above example of modeling interfaces at an image level is kind of a no-brainer example as image processing is a very mature field that's been studied and optimized to death. Yet less obvious might be a particle in a particle emitter, a sprite vs. a collection of sprites, an edge in a graph of edges, or even a person vs. a collection of people.

The key to allowing data-oriented optimizations (in foresight or hindsight) is often going to boil down to designing interfaces at a much coarser level, in bulk. The idea of designing interfaces for single entities becomes replaced by designing for collections of entities with big operations that process them in bulk. This especially and immediately targets sequential access loops that need to access everything and cannot help but have linear complexity.

Data-oriented design often begins with the idea of coalescing data to form aggregates modeling data in bulk. A similar mindset echoes to the interface designs that accompany it.

This is the most valuable lesson I've taken from data-oriented design, since I'm not computer architecture-savvy enough to often find the most optimal memory layout for something on my first try. It becomes something I iterate towards with a profiler in hand (and sometimes with a few misses along the way where I failed to speed things up). Yet the interface design aspect of data-oriented design is what leaves me room to seek more and more efficient data representations.

The key is to design interfaces at a coarser level than we're usually tempted to do. This also often has side benefits like mitigating the dynamic dispatch overhead associated with virtual functions, function pointer calls, dylib calls and the inability for those to be inlined. The main idea to take out of all of this is to look at processing in a bulk fashion (when applicable).


问:
Are decorators/annotations the result of bad design decisions?
Talking generic, there are programming languages who make more or less use of annotations and decorators.

Be it to add type information to variables in  a dynamically typed language or to add "metadata" to methods and classes in a framework context. The "purpose" of them is always to in some way extend the language in it's abilities or to make it more flexible in a certain way.

Now this all seems nice right? Using a dynamically typed language and want to add some type information to your variables? - Just use them decorators. Need to make that class to be managed remotely by an app-server? Tell it by adding an annotation.

Those things look like symptoms to me. Symptoms being caused by an underlying design problem. Or am I massively wrong about that?

答:
You're massively wrong about that. ;)

A decorator in Python is more than just information. It's runnable code. That means you can apply concerns in a declarative manner. A declarative style keeps your code tidy -- there's no need to torture your plumbing/design to express relationships and intent. Decorators are absolutely brilliant at applying middleware.

In static type systems, annotations are information, but it's incredibly valuable information. If I can identify, though annotations, characteristics of a code unit, I can then generically assign/modify behaviors based on those characteristics. Again, this allows nice clean declarative modifications versus hacking up my software model to express the same intent.


问:
Legitimate "real work" in a constructor?
I am working on a design, but keep hitting a roadblock. I have a particular class (ModelDef) that is essentially the owner of a complex node tree built by parsing an XML schema (think DOM). I want to follow good design principles (SOLID), and ensure that the resulting system is easily testable. I have every intention of using DI to pass dependencies into the constructor of ModelDef  (so that these can easily be swapped out, if need be, during testing).

What I'm struggling with, though, is the creation of the node tree. This tree is going to be made up entirely of simple "value" objects which will not need to be independently tested. (However, I may still pass an Abstract Factory into ModelDef to assist with the creation of these objects.)

But I keep reading that a constructor should not do any real work (e.g. Flaw: Constructor does Real Work). This makes perfect sense to me if "real work" means constructing heavy-weigh dependent objects that one might later want to stub out for testing. (Those should be passed in via DI.)

But what about light-weight value objects such as this node tree? The tree has to be created somewhere, right? Why not via the constructor of ModelDef (using, say, a buildNodeTree() method)?

I don't really want to create the node tree outside of ModelDef and then pass it in (via constructor DI), because creating the node tree by parsing the schema requires a significant amount of complex code -- code that needs to be thoroughly tested. I don't want to relegate it to "glue" code (which should be relatively trivial, and will likely not be directly tested).

I have thought of putting the code to create the node tree in a separate "builder" object, but hesitate to call it a "builder", because it doesn't really match the Builder Pattern (which seem to be more concerned with eliminating telescoping constructors). But even if I called it something different (e.g. NodeTreeConstructor), it still feels like a bit of a hack just to avoid having the ModelDef constructor build the node tree. It has to be built somewhere; why not in the object that's going to own it?

答:
I've heard that "rule" before. In my experience it is both true and false.

In more "classic" object orientation we talk about objects encapsulating state and behaviour. Thus an objects constructor should ensure that the object is initialized to a valid state (and signal a fault if the provided arguments does not make the object valid). Ensuring that an object is initialized to a valid state sure sounds like real work to me. And this idea has merits, if you have an object that only allows initialization to  a valid state via the constructor and the object properly encapsulates it state so that each method that changes the state also checks that it doesn't change the state to something bad...then that object in essence guarantees that it is "always valid". That is a really nice property!

So the problem generally arrives when we try to break everything apart into small pieces to test and mock stuff. Because if an object is really properly encapsulated then you can't really get in there and replace the FooBarService with your mocked FooBarService and you (probably) can't just change values willy-nilly to suit your tests (or, it may take a lot more code than a simple assignment).

Thus we get the other "school of thought", which is SOLID. And in this school of thought it is most likely a lot more true that we shouldn't do real work in the constructor. SOLID code is often (but not always) more easy to test. But can also be harder to reason about. We break apart our code into small objects with a single responsibility, and thus most of our objects no longer encapsulate their state (and contain generally either state or behaviour). Validation code is generally extracted into a validator class and kept separate from the state. But now we've lost cohesion, we can no longer be sure that our objects are valid when we get them and to be completely sure we must always validate that the preconditions that we think that we have about the object is true before we attempt to do something with the object. (Of course, in general you do validation in one layer and then assume that the object is valid at lower layers.) But it's easier to test!

So who is right?

No one really. Both schools of thought have their merits. Currently SOLID is all the rage and everyone is talking about SRP and Open/Closed and all of that jazz. But just because something is popular doesn't mean that it is the correct design choice for every single application. So it depends. If you're working in a code base that is heavily following the SOLID principles then yes, real work in the constructor is probably a bad idea. But otherwise, look at the situation and try to use your judgement. What properties does your object gain from doing work in the constructor, what properties does it lose? How well does it fit with the overall architecture of your application?

Real work in the constructor isn't an antipattern, it can be quite the opposite when used in the correct places. But it should be documented clearly (along with which exceptions can be thrown, if any) and as with any design decision - it should fit within the general style used in the current code base.


答:
When I find that all the changes I'm asked to make require tiny changes to several different modules, that usually means that the way I've split the project into modules is inappropriate.

To give an example which I believe is similar to yours, one of the services I work on converts documents from an old format to a new format. Whenever a new feature becomes supported in the new format, I have to go back into this conversion service and:

Add the parameters representing this feature to the model objects for old and new documents.

Update the logic for fetching the old document from the old database, so it gets the old version of the feature.

Add logic to convert the old version of the feature into the new version.

Update a sort-of-config file to say that the service is now using model version 1.11 instead of version 1.10.

In my case, all of this is a single commit to a single repository that's deployed as a single package, simply because that's how we chose to split up our packages. Yes, it's still (roughly) four separate files, but I don't believe that's a problem as long as that set of changes can be conveniently committed, reviewed, deployed, etc as a single cohesive unit (which it can if you have decent tools).

For instance, it sounds like your model objects are in a separate package from the logic that operates on them, which is probably unnecessary unless said objects have to be shared among many other services. That's even more true for your configuration file, as I can't imagine that being reused by other services (unless the configuration is horridly overcomplicated). It's also difficult to think of any scenario where having a service's API and its logic in two separate packages would be a good idea. I can think of some derivative products like API documentation which perhaps belong in separate packages (though ideally those would be autogenerated as part of your build/deploy process), but the actual API/logic seem like they should normally go together.

Title: How to best encapsulate features in software design?

Body:
I like domain driven design, and onion design.  However I would really like my features to be encapsulated.  If i check out some legacy code and I need to investigate some specific feature the best thing that I think could happen to me is that I see (lets say in java) is that there would be a package with featurename and all the feature functionality would reside in that package.  In a way that if i delete the package the feature would be gone.

While I understand its impossible because some of the feature might reside in other service I'm trying to at least think if its correct to do that in my own service.

My problem with this is that usually in DDD and in onion design you have the domain which contains a bunch of domain objects.  now some of these objects are of "my feature" and some of them are of other features.  lets say (user authentication is one feature and user twitter account details is another feature).

Is there any design methodology that does something with it? is what I'm suggesting makes sense?

Example: you have a project that manages users waiting in line.  You are asked to add a limit, max on the queue size.  you need to read that max queue size from configuration.  Then in your logic you need to apply that max queue size.  You also need to expose this configuration of max queue size in jmx, also you have an api to that service so you need to expose that max queue size as an api in that service.

Current app packages:

  --> conf (deals with reading configuration) // do change here.
  --> domain // do change here for that small subfeature.
  --> logic // do change also here for that small subfeature
  --> service (where api are) // do also a change here.

so in the above simplistic example for a simple subfeature addition i need to make changes to at least 4 packages.  Which means my subfeature is spread among these packages and classes.

I understand DDD mentions boundcontext but notice my feature here is very very small! just adding a max limitation on size.  So it does not seem appropriate to open a boundedcontext on each such small subfeature.

So the way I deal with it today I go conf i find there a class named Configuration which contains various configurations.  I add to that Configuration class a member named Configuration.maxQueueSize.

I go then to domain to model that new property I have there lets say Account I add to the Account class Account.maxQueueSize.

I go then to service an expose a new method named getMaxQueueSize

as you see I went to multiple packages and multiple classes already dealing with other functionality and extended them.

This is a very small feature, for one hand I cant imaging that for every small feauter I would open a whole new bounded context with its own service, domain, conf packages (and lets assume there are more) so that each feature is in its own package.

On the other way on each feature I need to extend configuration, domain, service, ... which means no single feature is encapsulated well enough so that I can just delete it or see a package which its fully resides in so that I can better understand the app.


问:
Implementing a generic/dynamic custom property system in C#
I have an architecture design problem which I think is appropriate for this site.

Note that I have made an EDIT to this post below, reflecting my latest potential solution to this problem.

General problem description:

My primary goal is to design a software library/program (C#) to automate a very particular type of microscopy experiments. Our experimental setups consists of many distinct hardware devices that generally fall into a limited number of categories:

Point detector

XY sample stage

Autofocus device

...

The natural choice is to design an interface IDevice with some basic properties shared by all devices such as e.g. IDevice.Initialize(), IDevice.Name, ...

We can even design an abstract class, inheriting IDevice, e.g. DeviceBase implementing some functionalty common to all devices.

Likewise, we can also design interfaces for specific devices, each time implementing the common stuff (IXYSampleStage might hold e.g. IXYSampleStage.Move(posX, posY) or IXYSampleStage.AxisXStepSize).

Ultimately, I can implement all these interfaces in the final classes representing specific devices. I think I know what to do there.

However, not all devices of a class are exactly the same. Some manufacturers offer rich functionality on top of the standard stuff. An XY Stage might have e.g. any number of optional/non-standard parameters to set such as e.g. channel delays, PID control values or whatever.

To tackle this,

I need a mechanism to add additional properties (not methods,
  properties will suffice) to specific device classes. Higher level
  code, interacting with the devices should understand these added
  properties, be able to get/set them, however many there might be.

So much for the basic design problem.

What exists already

There is an OS software program, Micro Manager, which has such a system implemented, be it in C++ (full source here and no, I cannot use this SW directly for my purposes):

```<code>class PropertyBase
{
public:
   virtual ~PropertyBase() {}

   // property type
   virtual PropertyType GetType() = 0;

   // setting and getting values
   virtual bool Set(double dVal) = 0;
   virtual bool Set(long lVal) = 0;
   virtual bool Set(const char* Val) = 0;

   virtual bool Get(double& dVal) const = 0;
   virtual bool Get(long& lVal) const = 0;
   virtual bool Get(std::string& strVal) const = 0;

   // Limits
   virtual bool HasLimits() const = 0;
   virtual double GetLowerLimit() const = 0;
   virtual double GetUpperLimit() const = 0;
   virtual bool SetLimits(double lowerLimit, double upperLimit) = 0;

   // Some more stuff left out for brevity
   ...
};
</code>```

Subsequently, the Property class implements some of the pure virtual functions related to the limits.

Next, StringProperty, IntegerProperty and FloatProperty implement the Get()/Set() methods. These kinds of properties are defined in an enum which allows only these three kinds of property.

Properties can next be added to a PropertyCollection which is basically a kind of dictionary that is part of a device class.

This all works nicely. We use MM a lot in the lab for other types of experiments but when trying to do similar things in my C# solution I stumbled about a few more fundamental questions. Most of these have to do with not being quite sure how to leverage specific features offered by C#/.NET (generic but definitely also dynamics, ...) to perhaps improve the existing C++ implementation.

The questions:

First question:

To limit the types of properties allowed, MM defines an enum:

```<code>    enum PropertyType {
      Undef,
      String,
      Float,
      Integer
    };
</code>```

Whereas C# has reflection and a lot of built-in support for types/generics. I therefore considered this:

```<code>public interface IProperty<T>
{
   public T value { get; set; }

   ...
}
</code>```

I could next do an abstract PropertyBase<T> and ultimately

```<code>IntegerProperty : PropertyBase<int>
StringProperty : PropertyBase<string>
FloatProperty : PropertyBase<double>
</code>```

But this gets me in trouble when trying to put them into a collection because in .NET following is not possible:

```<code>PropertyCollection : Dictionary<string, IProperty<T>>
</code>```

Unless, perhaps, I adopt this strategy, i.e. have a non generic base class that only returns a type and then yet more base classes to actually implement my property system. However, this seems convoluted to me. Is there a better way?

I think that utilising the generic language features might allow me to do away with needing all these Get()/Set() methods in the MM example above, as I would be able to know the backing type of my property value.

I realise this is a very broad question but, there is a big gap between understanding the basics of some language features and being able to fully make the correct design decisions from the outset.

Second question

I am contemplating making my final device classes all inherit from a kind of DynamicDictionary (e.g. similar to the one from here):

```<code>    public class DynamicDictionary : DynamicObject
    {
        internal readonly Dictionary<string, object> SourceItems;

        public DynamicDictionary(Dictionary<string, object> sourceItems)
        {
            SourceItems = sourceItems;
        }
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (SourceItems.ContainsKey(binder.Name))
            {
                SourceItems[binder.Name.ToLower()] = value;
            }
            else
            {
                SourceItems.Add(binder.Name.ToLower(), value);
            }
            return true;
        }
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (SourceItems != null)
            {
                if (SourceItems.TryGetValue(binder.Name.ToLower(), out result))
                {
                    return true;
                }
            }
            result = null;
            return true;
        }
    }
}
</code>```

but instead of <string, object> I would then like to use <string, MyPropertyBase> where the string would be the alias for my property (which would correspond to the design choice from Q1).

Would doing such a thing make sense from a design standpoint?

I would actually only need to add custom properties to devices at design time (i.e. when writing a custom device driver). At runtime, I would only need to inspect my custom properties or get/set their values.

the C++ MM solves this by using a bunch of CreateProperty("alias", Property) methods in the device constructor, which again, works so maybe using dynamics here is overkill. But again, I am wondering if somebody could provide insight in possible advantages but certainly also disadvantages of going down the dynamic route.

To summarize

Are there .NET features (4.5) which I could leverage to implement some of the MM concepts in a more elegant way with a focus on the above mentioned specific matters?

Again, I do realise this is a very broad question and perhaps some of the possible answers are more a matter of taste/style than anything els but if so (this making the question unsuited for this platform), please provide feedback/comments such that I can adjust accordingly.

EDIT

I have spent some more thinking about this and tried to solve it in the following way:

First, an enum specifying the allowed propertytypes:

```<code>public enum PropertyType
{
    Undefined,
    String,
    Float,
    Integer
}
</code>```

Second, an interface IPropertyType that is responsible for checking values fed to a property of a specific type:

```<code>public interface IPropertyType
{
    Type BackingType { get; }

    PropertyType TypeAlias { get; }

    bool IsValueTypeValid(object value);
}
</code>```

Then, a base class implementing IPropertyType:

```<code>public bool IsValueTypeValid(object value)
    {
        if (value == null)
        {
            return true;
        }

        Type type = value.GetType();

        if (type == this.BackingType)
        {
            return true;
        }

        return false;
    }

...

public Type BackingType
    {
        get
        {
            switch (this.TypeAlias)
            {
                case PropertyType.Integer:
                    return typeof(long);
                case PropertyType.Float:
                    return typeof(double);
                case PropertyType.String:
                    return typeof(string);
                default:
                    return null;
            }
        }
    }
</code>```

I then have three IPropertyType: StringPropertyType, IntegerPropertyType and FloatPropertyType where each time, the property PropertyTypeAlias is set to one of the enum values.

I can now add my IPropertyType to IProperty types:

```<code>public interface IProperty
{
    string Alias { get; }

    /// If we want to limit the property to discrete values.
    Dictionary<string, object> AllowedValues { get; }

    bool HasLimits { get; }

    bool HasValue { get; }

    bool IsReadOnly { get; }

    /// Callback for HW operations using the property value.
    Func<PropertyFuncType, bool> PropertyFunction { set; }

    PropertyType TypeAlias { get; }

    object Value { get; set; }

    void AddAllowedValue(string alias, object value);

    void ClearAllowedValues();

    // On numeric properties, it might be usefull to limit the range of values.
    void SetLimits(object lowerLimit, object upperLimit);

    // These will do stuff on the HW...
    bool TryApply();

    bool TryUpdate();
}
</code>```

Here, the Value setter will run the validation on input value as defined by the IPropertyType.

IProperty is almost fully implemented in PropertyBase which also has a field of IPropertyType which gets set upon instance creation (and cannot be changed thereafter; a property cannot change type.

From the base class e.g.:

```<code>    enum PropertyType {
      Undef,
      String,
      Float,
      Integer
    };
</code>```0

That only leaves specific IProperty classes: StringProperty, IntegerProperty and FloatProperty where there is only one override, SetLimits() because it relies on comparison of values. Everything else can be in the base class:

```<code>    enum PropertyType {
      Undef,
      String,
      Float,
      Integer
    };
</code>```1

This way, I think I have a system that allows me to have a collection of IProperty that can actually hold data of different types (int, float or string) where for each type of IProperty I have the ability to implement value limits etc (i.e. stuff that is different, depending on the data type)...

However, I still have the impression that there are either better ways to do this sort of thing or that I am over engineering things.

Therefore, any feedback on this is still welcome.

EDIT 2

After more searching online I believe the last bits of code posted here in the previous edit are leaning towards the Adaptive Object Model "pattern" (if it really is that).

However, most resources on this topic seem to be quite old and I'm wondering if there are now better ways to achieve these types of things.

答:
I had the same kind of issue. I have a "simple" plugin system where I have a workspace where i can drag and drop widgets in the form of plugin. I wanted to give flexibility (still working on the full functionality) to the plugin creator to add a set of properties attached to the plugin. As i'm using an MVP approach I created an interface to access the property

```<code>public interface IPluginControlSettingsPropertyAccessors<T>
{
    bool Validator(T _Source);

    bool Setter(T _Source);

    bool Getter(out T _Result);
}
</code>```

and for each property the plugin exposes several accessors of different types with the constraint to at least expose a

```<code>IPluginControlSettingsPropertyAccessors<string>
</code>```

for each property.

Then it depends on the View to actually implement a way to handle certain types of properties e.g. you can have:

```<code>if (l_Property is IPluginControlSettingsPropertyAccessors<Enum>)
{
     View.AddEnumHandler(l_Property);
}
else if (l_Property is IPluginControlSettingsPropertyAccessors<String>)
{
    View.AddStringHandler(l_Property);
}
</code>```

As you can see this disconnects an object and its properties from how they are being shown on the GUI. With this approach a simple GUI could simply treat all properties in their string form for visualization purposes and defer string handling to the property setter and validator.
If an object has a property which exposes

```<code>IPluginControlSettingsPropertyAccessors<String>
IPluginControlSettingsPropertyAccessors<Color>
</code>```

and your GUI only support the string type property then it will have a textbox which (depending on the string validator) might accept only colors in the #FFFFFF format. A more complex GUI might instead support IPluginControlSettingsPropertyAccessors and provide a color pick.

I am quite new to C# too and I could not come up with a better solution than this regarding an MVP pattern but so far it has proven quite easy to maintain.

Body:
I had the same kind of issue. I have a "simple" plugin system where I have a workspace where i can drag and drop widgets in the form of plugin. I wanted to give flexibility (still working on the full functionality) to the plugin creator to add a set of properties attached to the plugin. As i'm using an MVP approach I created an interface to access the property

public interface IPluginControlSettingsPropertyAccessors<T>
{
    bool Validator(T _Source);

    bool Setter(T _Source);

    bool Getter(out T _Result);
}

and for each property the plugin exposes several accessors of different types with the constraint to at least expose a

IPluginControlSettingsPropertyAccessors<string>

for each property.

Then it depends on the View to actually implement a way to handle certain types of properties e.g. you can have:

if (l_Property is IPluginControlSettingsPropertyAccessors<Enum>)
{
     View.AddEnumHandler(l_Property);
}
else if (l_Property is IPluginControlSettingsPropertyAccessors<String>)
{
    View.AddStringHandler(l_Property);
}

As you can see this disconnects an object and its properties from how they are being shown on the GUI. With this approach a simple GUI could simply treat all properties in their string form for visualization purposes and defer string handling to the property setter and validator.
If an object has a property which exposes

IPluginControlSettingsPropertyAccessors<String>
IPluginControlSettingsPropertyAccessors<Color>

and your GUI only support the string type property then it will have a textbox which (depending on the string validator) might accept only colors in the #FFFFFF format. A more complex GUI might instead support IPluginControlSettingsPropertyAccessors and provide a color pick.

I am quite new to C# too and I could not come up with a better solution than this regarding an MVP pattern but so far it has proven quite easy to maintain.