问:
Windows Firewall single rule with multiple IP addresses vs multiple rules with single IP address
I've tried finding some resources to help me on my dilemma, but wasn't successful in my approach. So here goes:

I am implementing an automated firewall manager for Windows Firewall which will ban some offending IP address for a certain port, for a certain period of time, after which the same firewall manager will remove the ban. My trouble is deciding whether I should just stick to creating a new rule for each IP/port pair or create one rule for each port and only edit the IP list to add/remove an IP address. My main consideration would be if one of the approach would yield better performance than the other. It would suit me better to use one rule for each IP/port pair, but I don't mind going for the other approach if it is significantly better.

I've tried asking this on security.stackexchange.com but it's been marked as off-topic there.

Thanks!

答:
Well this answer on ServerFault shows a single rule with many IP blocks works fine, but as he says it take a lot of CPU to process when updating, I imagine the rules are stored internally in an efficient format, and when the rule is changed WF will re-parse and store the IPs. In this case, it doesn't matter if you have 1 rule with a million IPs or a million rules with 1 IP, except that the time it takes to parse each rule will be different.

Personally I'd go with a half-way house, finding the sweet spot between management and rule size. Probably 1 rule per country or per netblock.


问:
SQL - Algorithm for finding availability of a resource
I'm having trouble creating a mysql compatible algorithm for this.

Background

App with mysql, perl and JS. It's a booking system where each booking is comprised of a start, end and qty.  Start and end are timestamps.

Schema simplified to a single table:

|  bookings
|-------------------
| id    | pkey
| start | timestamp
| end   | timestamp
| qty   | int
```

<h2>Question</h2>

<p>In SQL, how do you check how many resources are booked at once for a given <code>timeRange</code>? Code with explanation or an algorithm that is SQL compatible both work.</p>

<p>So, for the following schedule:</p>

<pre class="lang-none prettyprint-override"><code>09:00 -----               <-|
09:30 |   |                 | A maximum of 12 are booked at once during this range
10:00 |x7 |                 |
10:30 ----- ----- -----     |
11:00       |   | |   |     |
11:30       |x2 | |x10|   <-|
12:00       |   | |   |
12:30       ----- -----
</code>```

I should get 12 since the x2 and x10 bookings don't overlap with the x7 booking, so there are never more than 12 items booked at once between 9:00 and 11:30.

Progress

--It's been heavily shrunk to show just the relevant part, so it might have some errors
SELECT coalesce(max(qtyOverlap.sum),0) booked
FROM (
    SELECT coalesce(sum(b2.qty),0) sum
        FROM booking b1
        LEFT JOIN (
            SELECT b.qty, b.tStart, b.tEnd FROM booking b
        ) b2
        ON b1.tStart < b2.tEnd AND
           b1.tEnd > b2.tStart AND
           b2.tStart < '2015-02-19 16:30:00' AND
           b2.tEnd > '2015-02-19 06:00:00'
        WHERE
              b1.tStart < '2015-02-19 16:30:00' AND
              b1.tEnd > '2015-02-19 06:00:00'
        GROUP BY b1.id
) qtyOverlap
GROUP BY qtyOverlap.itemId
```

<p>Which is this algorithm:</p>

<pre class="lang-none prettyprint-override"><code>Max of
    For each booking that overlaps given timeRange
        return sum of
            each booking that overlaps this booking and given timeRange
</code>```

In the schedule above this would be:

```<code>max([7],[2+10],[10+2]) = 12
</code>```

But given a schedule like:

09:00 -----               <-|
09:30 |   |                 | A maximum of 17 are booked at once during this range, not 19
10:00 |x7 |                 |
10:30 |   |       -----     |
11:00 -----       |   |     |
11:30       ----- |x10|   <-|
12:00       |x2 | |   |
12:30       ----- -----
```

<p>This gives:</p>

```max([7+10],[2+10],[10+7+2]) = 19
```

<p>Which is wrong.</p>

<p>The only way I can think of to fix this is to use recursion (which isn't mysql compatible afaik).</p>

<p>It would look something like (in working JS code)</p>

```function getOverlaps(bookings,range) {
    return bookings.filter(function(booking){
        return isOverLapping(booking,range);
    });
}
function isOverLapping(a, b) {
    return (a.start  b.start);
}
function maxSum(booking, overlaps) { // main recursive function
    var currentMax = 0;
    var filteredOverlaps = getOverlaps(overlaps,booking);
    for (var i = 0; i < filteredOverlaps.length; i++) {
        currentMax = Math.max(
            maxSum(filteredOverlaps[i], removeElement(filteredOverlaps,i)),
            currentMax
        );
    }
    return currentMax + booking.qty;
}
function removeElement(array,i){
    var clone = array.slice(0)
    clone.splice(i,1);
    return clone;
}
var maxBooked = maxSum(timeRange, getOverlaps(bookings,timeRange));
```

Visual JSFiddle demo

Any way to do this in SQL? (any reasonable way, that is)

Update
I just tried to use a stored procedure recursion emulation method as documented here. But part way through implementing it, I tried it with the demo data and decided the performance was far too terrible. Actually, it just needed indexing. Now it's just 'kinda' bad.

答:
So Esoteric's solution worked but it still bothered me since it feels kinda bruteforce-ish. I knew there had to be a solution that only looked at the relevant data (start, end and qty) and didn't need to translate it into a different form.

Then I remembered order by and a solution hit me.

Ordered edge tally

Create a list of edges and their quantities (start U end). End edges get negated qtys.

Order them by date (for duplicate dates, end goes first).

Make a running total and combine any duplicate dates.

```<code>+---------------------+-----------+-------+
| edgedate            | qtyChange | tally |
+---------------------+-----------+-------+
| 2015-02-19 09:00:00 |         7 |     7 |
| 2015-02-19 10:30:00 |        10 |    17 |
| 2015-02-19 11:00:00 |        -7 |    10 |
| 2015-02-19 11:30:00 |         2 |    12 |
| 2015-02-19 12:30:00 |       -12 |    10 |
+---------------------+-----------+-------+
</code>```

4. Return max tally.

Actual SQL:

```<code>SET @i = 0;
SELECT max(edge.tally)
    FROM (
        SELECT sum(@i:= b1.qty + @i) AS tally /*Cumulative sum and combine any duplicate dates*/
            FROM ( /*Get every edge (start U end)*/
                SELECT tstart, qty, 1 as ord
                    FROM booking b
                    WHERE b.tstart < '2015-02-19 12:30:00' AND
                          b.tend   > '2015-02-19 08:00:00'
                UNION
                SELECT tend AS tstart, (qty*-1) AS qty, 0 as ord /*End edges have negative qtys*/
                    FROM booking b
                    WHERE b.tstart < '2015-02-19 12:30:00' AND
                          b.tend   > '2015-02-19 08:00:00'
                ORDER BY tstart, ord
            ) b1
            GROUP BY b1.tstart
    ) edge;
</code>```

Perfect precision, no joins, minimum complexity (my big O notation skills are lacking, maybe O(2*b) where b is the number of bookings?)

explain query:

```<code>+----+--------------+------------+-------+---------------+--------+---------+------+------+---------------------------------+
| id | select_type  | table      | type  | possible_keys | key    | key_len | ref  | rows | Extra                           |
+----+--------------+------------+-------+---------------+--------+---------+------+------+---------------------------------+
|  1 | PRIMARY      | <derived2> | ALL   | NULL          | NULL   | NULL    | NULL |    5 |                                 |
|  2 | DERIVED      | <derived3> | ALL   | NULL          | NULL   | NULL    | NULL |    6 | Using temporary; Using filesort |
|  3 | DERIVED      | b          | range | tstart,tend   | tstart | 9       | NULL |    2 | Using where                     |
|  4 | UNION        | b          | range | tstart,tend   | tstart | 9       | NULL |    2 | Using where                     |
| NULL | UNION RESULT | <union3,4> | ALL   | NULL          | NULL   | NULL    | NULL | NULL | Using filesort                  |
+----+--------------+------------+-------+---------------+--------+---------+------+------+---------------------------------+
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So Esoteric's solution worked but it still bothered me since it feels kinda bruteforce-ish. I knew there had to be a solution that only looked at the relevant data (start, end and qty) and didn't need to translate it into a different form.

Then I remembered order by and a solution hit me.

Ordered edge tally

Create a list of edges and their quantities (start U end). End edges get negated qtys.

Order them by date (for duplicate dates, end goes first).

Make a running total and combine any duplicate dates.

+---------------------+-----------+-------+
| edgedate            | qtyChange | tally |
+---------------------+-----------+-------+
| 2015-02-19 09:00:00 |         7 |     7 |
| 2015-02-19 10:30:00 |        10 |    17 |
| 2015-02-19 11:00:00 |        -7 |    10 |
| 2015-02-19 11:30:00 |         2 |    12 |
| 2015-02-19 12:30:00 |       -12 |    10 |
+---------------------+-----------+-------+

4. Return max tally.

Actual SQL:

SET @i = 0;
SELECT max(edge.tally)
    FROM (
        SELECT sum(@i:= b1.qty + @i) AS tally /*Cumulative sum and combine any duplicate dates*/
            FROM ( /*Get every edge (start U end)*/
                SELECT tstart, qty, 1 as ord
                    FROM booking b
                    WHERE b.tstart < '2015-02-19 12:30:00' AND
                          b.tend   > '2015-02-19 08:00:00'
                UNION
                SELECT tend AS tstart, (qty*-1) AS qty, 0 as ord /*End edges have negative qtys*/
                    FROM booking b
                    WHERE b.tstart < '2015-02-19 12:30:00' AND
                          b.tend   > '2015-02-19 08:00:00'
                ORDER BY tstart, ord
            ) b1
            GROUP BY b1.tstart
    ) edge;

Perfect precision, no joins, minimum complexity (my big O notation skills are lacking, maybe O(2*b) where b is the number of bookings?)

explain query:

+----+--------------+------------+-------+---------------+--------+---------+------+------+---------------------------------+
| id | select_type  | table      | type  | possible_keys | key    | key_len | ref  | rows | Extra                           |
+----+--------------+------------+-------+---------------+--------+---------+------+------+---------------------------------+
|  1 | PRIMARY      | <derived2> | ALL   | NULL          | NULL   | NULL    | NULL |    5 |                                 |
|  2 | DERIVED      | <derived3> | ALL   | NULL          | NULL   | NULL    | NULL |    6 | Using temporary; Using filesort |
|  3 | DERIVED      | b          | range | tstart,tend   | tstart | 9       | NULL |    2 | Using where                     |
|  4 | UNION        | b          | range | tstart,tend   | tstart | 9       | NULL |    2 | Using where                     |
| NULL | UNION RESULT | <union3,4> | ALL   | NULL          | NULL   | NULL    | NULL | NULL | Using filesort                  |
+----+--------------+------------+-------+---------------+--------+---------+------+------+---------------------------------+


问:
Constructor-only subclasses: Is this an anti-pattern?
I was having a discussion with a co-worker, and we ended up having conflicting intuitions about the purpose of subclassing. My intuition is that if a primary function of a subclass is to express a limited range of possible values of its parent, then it probably shouldn't be a subclass. He argued for the opposite intuition: that subclassing represents an object's being more "specific", and therefore a subclass relationship is more appropriate.

To put my intuition more concretely, I think that if I have a subclass that extends a parent class but the only code that subclass overrides is a constructor (yes, I know constructors don't generally "override", bear with me), then what was really needed was a helper method.

For example, consider this somewhat real-life class:

public class DataHelperBuilder
{
    public string DatabaseEngine { get; set; }
    public string ConnectionString { get; set; }

    public DataHelperBuilder(string databaseEngine, string connectionString)
    {
        DatabaseEngine = databaseEngine;
        ConnectionString = connectionString;
    }

    // Other optional "DataHelper" configuration settings omitted

    public DataHelper CreateDataHelper()
    {
        Type dataHelperType = DatabaseEngineTypeHelper.GetType(DatabaseEngine);
        DataHelper dh = (DataHelper)Activator.CreateInstance(dataHelperType);
        dh.SetConnectionString(ConnectionString);

        // Omitted some code that applies decorators to the returned object
        // based on omitted configuration settings

        return dh;
    }
}
```

<p>His claim is that it would be entirely appropriate to have a subclass like this:</p>

<pre class="lang-cs prettyprint-override"><code>public class SystemDataHelperBuilder
{
    public SystemDataHelperBuilder()
        : base(Configuration.GetSystemDatabaseEngine(),
               Configuration.GetSystemConnectionString())
    {
    }
 }
</code>```

So, the question:

Among people who talk about design patterns, which of these intuitions is correct? Is subclassing as described above an anti-pattern?

If it is an anti-pattern, what is its name?

I apologize if this turns out to have been an easily googleable answer; my searches on google mostly returned information about the telescoping constructor anti-pattern and not really what I was looking for.

答:
In the example you gave, your partner is right. The two data helper builders are strategies. One is more specific than the other, but they are both interchangeable once initialized.

Basically if a client of the datahelperbuilder was to receive the systemdatahelperbuilder, nothing would break. Another option would have been to have the systemdatahelperbuilder be a static instance of the datahelperbuilder class.


问:
Why would someone use @Native annotations?
link : http://download.java.net/jdk8/docs/api/java/lang/annotation/Native.html

In Java 8, there will be @Native annotations.

Indicates that a field defining a constant value may be referenced from native code. The annotation may be used as a hint by tools that generate native header files to determine whether a header file is required, and if so, what declarations it should contain.

Problem is: What for?
Do you have any idea on which problematics would be efficiently solved by this feature?

答:
A good example is the serialVersionUID which is @native for java 8 classes.

This way, we make sure that an extension of a java program is able to refer to the serial version uid easily hence make sure we refer to the right classes.


问:
Why are structs and classes separate concepts in C#?
While programming in C#, I stumbled upon a strange language design decision that I just can't understand.

So, C# (and the CLR) has two aggregate data types: struct (value-type, stored on the stack, no inheritance) and class (reference-type, stored on the heap, has inheritance).

This setup sounds nice at first, but then you stumble upon a method taking a parameter of an aggregate type, and to figure out if it is actually of a value type or of a reference type, you have to find its type's declaration. It can get really confusing at times.

The generally accepted solution to the problem seems to be declaring all structs as "immutable" (setting their fields to readonly) to prevent possible mistakes, limiting structs' usefulness.

C++, for example, employs a much more usable model: it allows you to create an object instance either on the stack or on the heap and pass it by value or by reference (or by pointer). I keep hearing that C# was inspired by C++, and I just can't understand why didn't it take on this one technique. Combining class and struct into one construct with two different allocation options (heap and stack) and passing them around as values or (explicitly) as references via the ref and out keywords seems like a nice thing.

The question is, why did class and struct become separate concepts in C# and the CLR instead of one aggregate type with two allocation options?

答:
By analogy, C# is basically like a set of mechanic's tools where somebody has read that you should generally avoid pliers and adjustable wrenches, so it doesn't include adjustable wrenches at all, and the pliers are locked in a special drawer marked "unsafe", and can only be used with approval from a supervisor, after signing a disclaimer absolving your employer of any responsibility for your health.

C++, by comparison, not only includes adjustable wrenches and pliers, but some rather odd-ball special purpose tools whose purpose aren't immediately apparent, and if you don't know the right way to hold them, they might easily cut off your thumb (but once you understand how to use them, can do things that are essentially impossible with the basic tools in the C# toolbox). In addition, it has a lathe, milling machine, surface grinder, metal-cutting band-saw, etc., to let you design and create entirely new tools any time you feel the need (but yes, those machinist's tools can and will cause serious injuries if you don't know what you're doing with them--or even if you just get careless).

That reflects the basic difference in philosophy: C++ attempts to give you all the tools you might need for essentially any design you might want. It makes almost no attempt at controlling how you use those tools, so it's also easy to use them to produce designs that only work well in rare situations, as well as designs that are probably just a lousy idea and nobody knows of a situation in which they're likely to work at all well. In particular, a great deal of this is done by decoupling design decisions--even those that in practice really are nearly always coupled. As a result, there's a huge difference between just writing C++, and writing C++ well. To write C++ well, you need to know a lot of idioms and rules of thumb (including rules of thumb about how seriously to reconsider before breaking other rules of thumb). As a result, C++ is oriented much more toward ease of use (by experts) than ease of learning. There are also (all too many) circumstances in which it's not really terribly easy to use either.

C# does a lot more to try to force (or at least extremely strongly suggest) what the language designers considered good design practices. Quite a few things that are decoupled in C++ (but usually go together in practice) are directly coupled in C#. It does allow for "unsafe" code to push the boundaries a little, but honestly, not a whole lot.

The result is that on one hand there are quite a few designs that can be expressed fairly directly in C++ that are substantially clumsier to express in C#. On the other hand, it's a whole lot easier to learn C#, and the chances of producing a really horrible design that won't work for your situation (or probably any other) are drastically reduced. In many (probably even most) cases, you can get a solid, workable design by simply "going with the flow", so to speak. Or, as one of my friends (at least I like to think of him as a friend--not sure if he really agrees) likes to put it, C# makes it easy to fall into the pit of success.

So looking more specifically at the question of how class and struct got how they are in the two languages: objects created in an inheritance hierarchy where you might use an object of a derived class in the guise of its base class/interface, you're pretty much stuck with the fact that you normally need to do so via some sort of pointer or reference--at a concrete level, what happens is that the object of the derived class contains something memory that can be treated as an instance of the base class/interface, and the derived object is manipulated via the address of that part of memory.

In C++, it's up to the programmer to do that correctly--when he's using inheritance, it's up to him to ensure that (for example) a function that works with polymorphic classes in a hierarchy does so via a pointer or reference to the base class.

In C#, what is fundamentally the same separation between the types is much more explicit, and enforced by the language itself. The programmer doesn't need to take any steps to pass an instance of a class by reference, because that'll happen by default.


答:
The strictest Object Oriented definition of a subclass relationship is known as «is-a».  Using the traditional example of a square and a rectangle, a square «is-a» rectangle.

By this, you should use subclassing for any situation where you feel a «is-a» is a meaningful relationship for your code.

In your specific case of a subclass with nothing but a constructor, you should analyze it from a «is-a» perspective.  It is clear that a SystemDataHelperBuilder «is-a» DataHelperBuilder, so the first pass suggests it is a valid use.

The question that you should answer is whether any of the other code leverages this «is-a» relationship.  Does any other code attempt to distinguish SystemDataHelperBuilders from the general population of DataHelperBuilders?  If so, the relationship is quite reasonable, and you should keep the subclass.

However, if no other code does this, then what you have is a relationshp that could be a «is-a» relationship, or it could be implemented with a factory.  In this case, you could go either way, but I would recommend a Factory rather than a «is-a» relationship.  When analyzing Object Oriented code written by another individual, the class hierarchy is a major source of information.  It provides the «is-a» relationships they will need to make sense of the code.  Accordingly, putting this behavior into a subclass promotes the behavior from "something someone will find if they dig into the superclass's methods" to "something everyone will look through before they even start diving into the code."  Quoting Guido van Rossum, "code is read more often than it is written," so decreasing readability of your code for upcoming developers is a stiff price to pay.  I would elect not to pay it, if I could use a factory instead.

Title: Constructor-only subclasses: Is this an anti-pattern?

Body:
I was having a discussion with a co-worker, and we ended up having conflicting intuitions about the purpose of subclassing. My intuition is that if a primary function of a subclass is to express a limited range of possible values of its parent, then it probably shouldn't be a subclass. He argued for the opposite intuition: that subclassing represents an object's being more "specific", and therefore a subclass relationship is more appropriate.

To put my intuition more concretely, I think that if I have a subclass that extends a parent class but the only code that subclass overrides is a constructor (yes, I know constructors don't generally "override", bear with me), then what was really needed was a helper method.

For example, consider this somewhat real-life class:

public class DataHelperBuilder
{
    public string DatabaseEngine { get; set; }
    public string ConnectionString { get; set; }

    public DataHelperBuilder(string databaseEngine, string connectionString)
    {
        DatabaseEngine = databaseEngine;
        ConnectionString = connectionString;
    }

    // Other optional "DataHelper" configuration settings omitted

    public DataHelper CreateDataHelper()
    {
        Type dataHelperType = DatabaseEngineTypeHelper.GetType(DatabaseEngine);
        DataHelper dh = (DataHelper)Activator.CreateInstance(dataHelperType);
        dh.SetConnectionString(ConnectionString);

        // Omitted some code that applies decorators to the returned object
        // based on omitted configuration settings

        return dh;
    }
}
```

<p>His claim is that it would be entirely appropriate to have a subclass like this:</p>

<pre class="lang-cs prettyprint-override"><code>public class SystemDataHelperBuilder
{
    public SystemDataHelperBuilder()
        : base(Configuration.GetSystemDatabaseEngine(),
               Configuration.GetSystemConnectionString())
    {
    }
 }
</code>```

So, the question:

Among people who talk about design patterns, which of these intuitions is correct? Is subclassing as described above an anti-pattern?

If it is an anti-pattern, what is its name?

I apologize if this turns out to have been an easily googleable answer; my searches on google mostly returned information about the telescoping constructor anti-pattern and not really what I was looking for.


问:
Sets of pair parameters
I have the following class, this class like many rely one parameters coming in as a pair.
Originally for convenience, I set them as params Object[] values and check if there is an even number of them if (values % 2 == 0).

Example Code:

```<code>using RVD = System.Web.Routing.RouteValueDictionary;

/// <summary>
/// Allows for quick building of similar RVDs.
/// </summary>
public class RVDBuilder
{
    public RVD Template { get; protected set; }

    public RVDBuilder(RVD template)
    {
        this.Template = template;
    }
    public RVDBuilder(params Object[] routeValues)
    {
        if (routeValues.Length % 2 != 0)
        {
            throw new Exception("parameters must come in pairs of two!");
        }
    }
}
</code>```

I can see two point of views here:

This adds great convience for the programmer: i.e. new RVDBuilder("Key1", 1, "Key2", "2", ...);

This is not as safe as it could be: i.e. new RVDBuilder(Tuple.Create("Key1", 1), ...);

I was hoping to get input on this subject/topic.

Should I force the programmer to use a 'pair' class? (How would this affect coupling?)

Should I make it safer even though It'll be an easy fix/catch if an error is made?

Is throwing an exception the best way to handle it or should I just truncate?

Would adding an event so the programmer can choose how to handle the situation be good practice?

Overall though, how do I identify and decide on a method for handling this situation? I know overall it depends on the setting of the project, but there's not really a mood/convention set for it on this subject. Are there any general rule-of-thumbs?

(Sorry if this isn't quite the right StackExchange for this question. It involves code, but I figured since it's purely for example to help better explain my design question it fit best here).

答: I read in "Effective C++" that APIs should always be easy to use correctly and hard to use incorrectly. Since you've stated that it can be used incorrectly, I would ditch it for a solution that can be safer. </p>

Title: Sets of pair parameters


答:
I had to tackle this recently in Java. My solution was to make the Pair class fairly painless to instantiate: Pair.of(..., ...). That's only 7 extra characters before the parentheses, and naming the factory method of seems to be a convention that value-based classes follow in Java 8.

But in my use case there were usually no more than 3-4 pairs, so I also provided overloads for up to 5 pairs of arguments, so the tuples rarely need to be used. It's mindless boilerplate to write, but it only needs to be done once and the callers benefit from it many times.

Should I force the programmer to use a 'pair' class? (How would this affect coupling?)

A "pair" class is a fairly harmless dependency. It has a small, well-defined interface and semantics, and a simple and straightforward implementation. It's very unlikely that its interface will ever change, or that someone will break it in the future. It's also very unlikely to depend on other classes.

Is throwing an exception the best way to handle it or should I just truncate?

Do not truncate. This is clearly an error on the programmer's part, and you can't even assume that the missing value is at the end: I once accidentally fused two strings around the middle of the argument list, e.g. "foo", "bar", "baz", "quux" became "foo", "bar baz", "quux". There's nothing for you to do but abort with an exception.

Would adding an event so the programmer can choose how to handle the situation be good practice?

There's no reason for the programmer to deliberately pass in a bad argument list, so if the error is handled at all, it'll probably happen at a high level "catch all" error handler, not at the method call. The caller can already catch the exception if he so wishes, so the event won't help.

Title: Sets of pair parameters

Body:
I have the following class, this class like many rely one parameters coming in as a pair.
Originally for convenience, I set them as params Object[] values and check if there is an even number of them if (values % 2 == 0).

Example Code:

```<code>using RVD = System.Web.Routing.RouteValueDictionary;

/// <summary>
/// Allows for quick building of similar RVDs.
/// </summary>
public class RVDBuilder
{
    public RVD Template { get; protected set; }

    public RVDBuilder(RVD template)
    {
        this.Template = template;
    }
    public RVDBuilder(params Object[] routeValues)
    {
        if (routeValues.Length % 2 != 0)
        {
            throw new Exception("parameters must come in pairs of two!");
        }
    }
}
</code>```

I can see two point of views here:

This adds great convience for the programmer: i.e. new RVDBuilder("Key1", 1, "Key2", "2", ...);

This is not as safe as it could be: i.e. new RVDBuilder(Tuple.Create("Key1", 1), ...);

I was hoping to get input on this subject/topic.

Should I force the programmer to use a 'pair' class? (How would this affect coupling?)

Should I make it safer even though It'll be an easy fix/catch if an error is made?

Is throwing an exception the best way to handle it or should I just truncate?

Would adding an event so the programmer can choose how to handle the situation be good practice?

Overall though, how do I identify and decide on a method for handling this situation? I know overall it depends on the setting of the project, but there's not really a mood/convention set for it on this subject. Are there any general rule-of-thumbs?

(Sorry if this isn't quite the right StackExchange for this question. It involves code, but I figured since it's purely for example to help better explain my design question it fit best here).


答:
Rather than thinking of value types deriving from Object, it would be more helpful to think of storage-location types existing in an entirely separate universe from class instance types, but for every value type to have a corresponding heap-object type.  A storage location of structure type simply holds a concatenation of the type's public and private fields, and the heap type is auto-generated according to a pattern like:

```<code>// Defined structure
struct Point : IEquatable<Point>
{
  public int X,Y;
  public Point(int x, int y) { X=x; Y=y; }
  public bool Equals(Point other) { return X==other.X && y==other.Y; }
  public bool Equals(Object other)
  { return other != null && other.GetType()==typeof(this) && Equals(Point(other)); }
  public bool ToString() { return String.Format("[{0},{1}", x, y); }
  public bool GetHashCode() { return unchecked(x+y*65531); }
}
// Auto-generated class
class boxed_Point: IEquatable<Point>
{
  public Point value; // Fake name; C++/CLI, though not C#, allow full access
  public boxed_Point(Point v) { value=v; }
  // Members chain to each member of the original
  public bool Equals(Point other) { return value.Equals(other); }
  public bool Equals(Object other) { return value.Equals(other); }
  public String ToString() { return value.ToString(); }
  public Int32 GetHashCode() { return value.GetHashCode(); }
}
</code>```

and for a statement like:
    Console.WriteLine("The value is {0}", somePoint);

to be translated as:
    boxed_Point box1 = new boxed_Point(somePoint);
    Console.WriteLine("The value is {0}", box1);

In practice, because storage location types and heap instance types exist in separate universes, it's not necessary to call the heap-instance types things like like boxed_Int32; since the system would know what contexts require the heap-object instance and which ones require a storage location.

Some people think that any value types which don't behave like objects should be considered "evil".  I take the opposite view: since storage locations of value types are neither objects nor references to objects, the expectation that they should behave like objects should be considered unhelpful.  In cases where a struct can usefully behave like an object, there's nothing wrong with having one do so, but each struct is at its heart nothing more than an aggregation of public and private fields stuck together with duct tape.

Title: Why are structs and classes separate concepts in C#?

Body:
While programming in C#, I stumbled upon a strange language design decision that I just can't understand.

So, C# (and the CLR) has two aggregate data types: struct (value-type, stored on the stack, no inheritance) and class (reference-type, stored on the heap, has inheritance).

This setup sounds nice at first, but then you stumble upon a method taking a parameter of an aggregate type, and to figure out if it is actually of a value type or of a reference type, you have to find its type's declaration. It can get really confusing at times.

The generally accepted solution to the problem seems to be declaring all structs as "immutable" (setting their fields to readonly) to prevent possible mistakes, limiting structs' usefulness.

C++, for example, employs a much more usable model: it allows you to create an object instance either on the stack or on the heap and pass it by value or by reference (or by pointer). I keep hearing that C# was inspired by C++, and I just can't understand why didn't it take on this one technique. Combining class and struct into one construct with two different allocation options (heap and stack) and passing them around as values or (explicitly) as references via the ref and out keywords seems like a nice thing.

The question is, why did class and struct become separate concepts in C# and the CLR instead of one aggregate type with two allocation options?

Body:
Rather than thinking of value types deriving from Object, it would be more helpful to think of storage-location types existing in an entirely separate universe from class instance types, but for every value type to have a corresponding heap-object type.  A storage location of structure type simply holds a concatenation of the type's public and private fields, and the heap type is auto-generated according to a pattern like:

// Defined structure
struct Point : IEquatable<Point>
{
  public int X,Y;
  public Point(int x, int y) { X=x; Y=y; }
  public bool Equals(Point other) { return X==other.X && y==other.Y; }
  public bool Equals(Object other)
  { return other != null && other.GetType()==typeof(this) && Equals(Point(other)); }
  public bool ToString() { return String.Format("[{0},{1}", x, y); }
  public bool GetHashCode() { return unchecked(x+y*65531); }
}
// Auto-generated class
class boxed_Point: IEquatable<Point>
{
  public Point value; // Fake name; C++/CLI, though not C#, allow full access
  public boxed_Point(Point v) { value=v; }
  // Members chain to each member of the original
  public bool Equals(Point other) { return value.Equals(other); }
  public bool Equals(Object other) { return value.Equals(other); }
  public String ToString() { return value.ToString(); }
  public Int32 GetHashCode() { return value.GetHashCode(); }
}

and for a statement like:
    Console.WriteLine("The value is {0}", somePoint);

to be translated as:
    boxed_Point box1 = new boxed_Point(somePoint);
    Console.WriteLine("The value is {0}", box1);

In practice, because storage location types and heap instance types exist in separate universes, it's not necessary to call the heap-instance types things like like boxed_Int32; since the system would know what contexts require the heap-object instance and which ones require a storage location.

Some people think that any value types which don't behave like objects should be considered "evil".  I take the opposite view: since storage locations of value types are neither objects nor references to objects, the expectation that they should behave like objects should be considered unhelpful.  In cases where a struct can usefully behave like an object, there's nothing wrong with having one do so, but each struct is at its heart nothing more than an aggregation of public and private fields stuck together with duct tape.


问:
Does modular programming refer to modules or programs?
As far as I can tell, the main idea in modular programming is:

program pieces that work well;

  complex behaviour results from piece_a and piece_b working together

Though, I am not sure if it means:

write multiple programs;

  compile each necessary program into executables;

  string together with pipes and shared files

or

write multiple functions;

  string together in the mainline of ONE program

答: Consider this: Aren't both "interaction through pipes and shared files" and "interaction through shared memory within a single process" just special cases of "working together"?</p>


问:
Is it poor decision making that using promises for GUI inputs?
So as you know the context: DOM with JavaScript, even though I think it is mostly a language agnostic issue (I know I put both language-agnostic and JavaScript tags, but it's only to let you see something I might not be able to see for myself).

I recently decided to use a promise mechanism to solve interactions with the user (clicks, keyboard input), and I was wondering if I was missing the point of promises.

For instance the algorithm would look like this

launch main menu (function that returns a promise)

then (takes a param input, sets some external data according to the input)

then (waits for a series of clicks)

then (navigate to another menu, also returning a promise)

catch (something was rejected -> then launch everything again from start)

It is a cycle, meaning that if it fails somewhere, it starts all again.
I'm wondering if made a total idiot of myself with this decision or if I'm actually doing promises right, or almost but not quite.

Can you enlighten me please?

答:
For what its' worth, the article you linked was discussing people who write promise libraries, not people who use them.

Your use case seems a bit larger than typical, but as far as I can tell from your description, it's a relatively good fit for promises.  Promises are designed to simplify sequencing and composition of asynchronous code.  That's certainly your situation here.  You're expecting several asynchronous actions in sequence, several of which might have subsequences.

Just make sure it's actually simplifying your code.  If you find yourself in a situation where you're having a lot of difficulty getting a promise to work, use something else for that part of the code.


问:
how to decide when to use database replication vs. custom REST applications vs. message brokers (pub / sub)
We have a distributed solution that's currently under design.  There are a few points of integration where some application needs data from someone else and vice versa.  We could solve by either writing REST interfaces and provide CRUD features so that apps can share data between themselves.  Or we can use something like nanomsg or zeroMQ to send messages back and forth.

We also have H/A requirements where we want to do master to master replication across primary and secondary db servers to ensure that if one goes down, the other one can kick in.

Here's the question.
Some on the team feel that we should choose one method of sharing data like master to master replication... and just use it across the board to "share" data.
It's true that we can do that, but I think each case should be analyzed and treated separately depending on specific criteria such as:

are the databases in question identical?  if they are, then master to master is appropriate such as in our High Availability scenario.

in the case of disparate systems, how much data are we shuttling back and forth? if it's a lot of data... maybe a message bus is better.  just send a notification to say "there's a change... here's the change id.  Go get it".

How often does data change?  Does this matter?  I *think both a REST api and a message bus will be able to handle many transactions.

I'm not sure what else to consider.  It feels like creating a message bus solution would be a lot more work than a REST api into each database.  But I could be wrong.
What other things should we take into consideration?

Thanks.

答:
If you need to share (read and write) all the data and use transactions, when just use shared access to the database. If you need high availability, consider using master-slave replication. Don't just blindly go with master-master, think carefully about disadvantages:

Most multi-master replication systems are only loosely consistent, i.e. lazy and asynchronous, violating ACID properties.

Eager replication systems are complex and increase communication latency.

Issues such as conflict resolution can become intractable as the number of nodes involved rises and latency increases.

REST cons:

You actually need to implement, test, and support it.

No transactions on multiple resource, unless you'll reinvent transactions on API layer, which is the worst possible idea.

Message queues cons:

Not suited for sharing data. MQs are good for asynchronous inter-process communication: invoking commands, firing events, etc.

Again, you need to implement, test, and support message handlers, since the data is not magically shared by just being put into queue.

However, if you need just some parts of your data to be shared, and multi-resource transactions are not needed, when REST (or maybe JSON-RPC) might be a better solution.

Still, MQ will be a bad solution, since it is, as I said, solves another set of problems.

The answer to your question depends on what you actually need:

Sharing all the data as it is, being able to use it in transactions - shared DB

Sharing some data in granular uniform fashion (CRUD) - REST

Operations which involve various parts of data and/or non-trivial logic - JSON-RPC

Asynchronous inter-process communication - Message queues


问:
Traverse a matrix using a linear index to get an evenly distributed values sample
I'm looking for an algorithm idea on how to traverse a matrix using a linear index while avoiding row/column based traversals to get a more diverse distribution of values.

To understand this better, think of an image that's split in blocks, with N rows & M columns. I need to process each image block sequentially (from 1 to NxM) but I don't know in advance what the processing time will be for each block ( blocks that are close together tend to have a similar processing time, with small variations).

During processing, I need to be able to estimate as best as possible the remaining processing time based on the number of blocks that have already been processed & their associated processing time. For this reason, traversing the blocks by columns or by rows will not give an accurate estimation so I need to find another way of traversing the matrix that would pick values from different zones of the image.

It's also important to be able to determine the blocks processing order based on a linear index (from 1 to NxM), without calculating them in advance. The algorithm that returns the row & column corresponding to the linear index should be as fast as possible.

Shorter version of the question

For a liner index named idx, I need to get a corresponding row & column pair from a matrix with N rows & M columns while avoiding a row/column based traversal.

For each idx between 1 and NxM, the algorithm would return a [row, column] pair so that all the rows & columns combinations are returned exactly once.

Example

(the values in the matrix represent the linear index's value that's associated with that row&column position)

```
 1 17 13  9  5
 6  2 18 14 10
11  7  3 19 15
16 12  8  4 20
```

The above example is for a diagonal traversal that would produce a better distribution of values that a row/column based traversal.

Another possible solution would be to split the matrix into smaller blocks & traverse those blocks in rows/columns. For example a 4x5 matrix could be virtually split into 2x2 blocks and those smaller blocks could be traversed by rows or columns (e.g. idx(1) = block1[1, 1], idx(2) = block2[1, 1], etc.). The traversal would look something like this:

```
 1 13 |  3 15 |  5
 7 17 |  9 18 | 11
------+-------+---
 2 14 |  4 16 |  6
 8 19 | 10 20 | 12
```

Any other traversal ideas are welcomed.

Ideally, this algorithm would translate to a math formula to calculate the row & column based on the linear index, possibly with a few conditions (IF statements) to compensate for missing values, etc.

答:
You indicated that you don't want to do row/column traversal, but that could be a useful method. Calculate an index change value for the array so each new index translates into a row/column position that samples a different area of the matrix. The only requirement is that the index change value must be coprime with the array length. This guarantees that each matrix position will be chosen once without calculating them in advance. The first index is 0 which is 0,0 , but could be calculated from m/2,n/2 to center it.</p>

```<code>// matrix dimensions are
// image height and width
var m = 600;
var n = 800;
// length of image array (number of matrix elements)
var l = m * n;
// potential coprime value
// for this expression
// number of rows is smaller of m and n
// while number of columns is larger of m and n
var p = floor( ( floor( min( m, n ) * 0.4) + 0.6) * max( m, n ) );
// greatest common denominator
// Euclidian algorithm
var gcd = function( a, b ){
    if( b === 0 ){
        return a;
    }
    return gcd( b, a % b );
}
// find coprime equal to or greater
while( p > 1 && gcd( l, p ) > 1 ){
    // increase coprime by 1
    p ++;
}
// starting index
var s = 0;
// center index
// center row plus center column
s = floor(m/2)*n + floor(n/2);
// loop through number of index positions
for( var j = 0; j < l; j ++ ){
    // index is start plus j times coprime mod array length
    var i = ( s + j * p ) % l;
    // row is index divided by number of columns rounded down
    var r = floor( i / n );
    // column is index mod number of columns
    var c = i % n;
}
</code>```

Body:
You indicated that you don't want to do row/column traversal, but that could be a useful method. Calculate an index change value for the array so each new index translates into a row/column position that samples a different area of the matrix. The only requirement is that the index change value must be coprime with the array length. This guarantees that each matrix position will be chosen once without calculating them in advance. The first index is 0 which is 0,0 , but could be calculated from m/2,n/2 to center it.

// matrix dimensions are
// image height and width
var m = 600;
var n = 800;
// length of image array (number of matrix elements)
var l = m * n;
// potential coprime value
// for this expression
// number of rows is smaller of m and n
// while number of columns is larger of m and n
var p = floor( ( floor( min( m, n ) * 0.4) + 0.6) * max( m, n ) );
// greatest common denominator
// Euclidian algorithm
var gcd = function( a, b ){
    if( b === 0 ){
        return a;
    }
    return gcd( b, a % b );
}
// find coprime equal to or greater
while( p > 1 && gcd( l, p ) > 1 ){
    // increase coprime by 1
    p ++;
}
// starting index
var s = 0;
// center index
// center row plus center column
s = floor(m/2)*n + floor(n/2);
// loop through number of index positions
for( var j = 0; j < l; j ++ ){
    // index is start plus j times coprime mod array length
    var i = ( s + j * p ) % l;
    // row is index divided by number of columns rounded down
    var r = floor( i / n );
    // column is index mod number of columns
    var c = i % n;
}


问:
What is the name/origin for this C code indentation style?
Look at the formatting of the variable declarations. I haven't encountered this indentation style in the past, but lately I stumbled upon two different code examples which use this style. Where does it come from? Is it still used today?

#include <stdio.h>
#include <stdarg.h>
#include <ctype.h>

void __cdecl odprintf(const char *format, ...)
{
char    buf[4096], *p = buf;
va_list args;
int     n;

        va_start(args, format);
        n = _vsnprintf(p, sizeof buf - 3, format, args); // buf-3 is room for CR/LF/NUL
        va_end(args);

        p += (n < 0) ? sizeof buf - 3 : n;

        while ( p > buf  &&  isspace(p[-1]) )
                *--p = '\0';

        *p++ = '\r';
        *p++ = '\n';
        *p   = '\0';

        OutputDebugString(buf);
}
```

©

答:
This is a variation on the kernel style or Allman style with the modification of variables within the block are outdented to the level of the open brace to set them clearly apart from the code that follows.

This also superficially resembles aspects of early C dialects where the parameters and types are declared outside the code block rather than in the code block:

int f(x)
int x;
{
    return x + 1;
}
```

There are nearly as many indent styles as there are programmers.  Occasionally two programmers might agree on a style within a project.  Sometimes they borrow elements of someone else's code style and use that.

This is just another personal choice for indent style.  Move along.

Body:
This is a variation on the kernel style or Allman style with the modification of variables within the block are outdented to the level of the open brace to set them clearly apart from the code that follows.

This also superficially resembles aspects of early C dialects where the parameters and types are declared outside the code block rather than in the code block:

int f(x)
int x;
{
    return x + 1;
}

There are nearly as many indent styles as there are programmers.  Occasionally two programmers might agree on a style within a project.  Sometimes they borrow elements of someone else's code style and use that.

This is just another personal choice for indent style.  Move along.


答:
The term is independent of any specific implementation.  Modular code is cohesive with a well-defined interface.  It doesn't particularly matter if that interface is a local function call or a call over the Internet to a REST API.

That being said, when you're talking with someone, you need to determine in context whether you're talking about the general abstract concept or one specific implementation.  For example, a C# developer might usually be talking specifically about a class that implements the IModule interface.

Title: Does modular programming refer to modules or programs?

Body:
As far as I can tell, the main idea in modular programming is:

program pieces that work well;

  complex behaviour results from piece_a and piece_b working together

Though, I am not sure if it means:

write multiple programs;

  compile each necessary program into executables;

  string together with pipes and shared files

or

write multiple functions;

  string together in the mainline of ONE program


问:
Should a bin directory be full of shell scripts?
New guy on the team so I figured I'd ask here in public than sound like a complete dweeb and ask elsewhere.  Without giving too much or anything away (please ask questions if you want), but should, or is it in any way traditional, to write code that rolls out a directory containing nothing but script files to /opt/bin?  Shouldn't bin contain... binaries?

I know that most distributions of linux or chock full of scripts in the /bin directory, but was that always the case?

答:
Though */bin seems to suggest by name that the contents therein are BINaries, the BSD hier man-page does not seem to suggest it. It only seems to suggest that the contents be executable. In particular:

```<code> /bin/         user utilities fundamental to both single-user and multi-user environ-
               ments

 /usr/         contains the majority of user utilities and applications

               bin/      common utilities, programming tools, and applications
</code>```

I've seen linux man pages that use similar language, explicitly calling out the executable nature of */bin folders. Here are a few hier man pages:

linux hier (7)

freebsd hier (7)

Mac OSX hier (7)

(The (7) in the man pages is indicating section 7 which is "Overviews of various topics, conventions and protocols, character set standards, and miscellaneous other things." separating it from a hypothetical hier library call, command, game, or configuration)

Body:
Though */bin seems to suggest by name that the contents therein are BINaries, the BSD hier man-page does not seem to suggest it. It only seems to suggest that the contents be executable. In particular:

 /bin/         user utilities fundamental to both single-user and multi-user environ-
               ments

 /usr/         contains the majority of user utilities and applications

               bin/      common utilities, programming tools, and applications

I've seen linux man pages that use similar language, explicitly calling out the executable nature of */bin folders. Here are a few hier man pages:

linux hier (7)

freebsd hier (7)

Mac OSX hier (7)

(The (7) in the man pages is indicating section 7 which is "Overviews of various topics, conventions and protocols, character set standards, and miscellaneous other things." separating it from a hypothetical hier library call, command, game, or configuration)


问:
Polymorphism Question
For the sake of the question I've taken this code from http://www.cplusplus.com/doc/tutorial/polymorphism/

```<code>class Polygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
};

class Rectangle: public Polygon {
  public:
    int area()
      { return width*height; }
};

class Triangle: public Polygon {
  public:
    int area()
      { return width*height/2; }
};

int main () {
  Rectangle rect;
  Triangle trgl;
  Polygon * ppoly1 = ▭
  Polygon * ppoly2 = &trgl;
  ppoly1->set_values (4,5);
  ppoly2->set_values (4,5);
  return 0;
}
</code>```

Is it possible to create a Polygon array and store Triangle and Rectangle objects in it and still be possible to access the functions associated with their respective classes?

For example:

```<code>Polygon *array[2];
array[0] = new Triangle;
array[1] = new Rectangle;
</code>```

Is there any way to call area() from the Polygon array?

答:
No, the access to the functions is restricted to base class functions only.

But there's easy way to fix this problem, by providing pure virtual function in the base class:

```<code>class Polygon {
public:
  virtual int area()=0;
};
</code>```

Then it'll just work fine.

Title: Polymorphism Question

Body:
No, the access to the functions is restricted to base class functions only.

But there's easy way to fix this problem, by providing pure virtual function in the base class:

class Polygon {
public:
  virtual int area()=0;
};

Then it'll just work fine.


问:
Should I focus on being deep or broad
I have been a professional developer for just over half a year and have been amazed at how big the world really is out of college. I have continued to learn in my free time but I am wondering where should I focus?

FOCUS 1) The development stack used by my company. Quickest payoff in my day to day development. #Deepest

FOCUS 2) A different language with the same paradigm. See if I can generalize my knowledge and way of thinking.

FOCUS 3) Different language, different paradigm. Expand my borders and learn new ways to do things. #Broadest

If anyone has a different focus feel free to put that out there.

答:
I think at your stage of development, getting some depth is the first priority. I see too many people who know a little bit about a bunch of things but can't get past doing entry level work because all their knowledge is entry level.

If I wanted to be a specialist, clearly, building depth is the best first choice.

If I want to be a generalist, build depth first (get to at least intermediate level) in one stack and then branch out to other languages. If you build some depth first, you may find it easier to build depth in multiple languages as you have more concepts available to you and know more of what you might want to learn. Then I would branch out a bit into something else. Then come back and build depth to the advanced level, then branch out again and learn more things that are very different from what you already know. Then expand that depth in a different area to an intermediate level, learn something else again, etc.

Caveat - I'm a specialst so I clearly favor depth of knowledge

ContentLicense: CC BY-SA 2.5

Title: Should I focus on being deep or broad


问:
Bad sign if nobody can comprehend one's code?
If a coder writes code that nobody other than he can understand, and code reviews always end with the reviewer scratching his head or holding their head in their hands, is this a clear sign that the coder is simply not cut-out for professional programming?  Would this be enough to warrant a career change?  How important is comprehensible code in this industry?

Consider these C examples, compare:

```<code>if (b)
  return 42;
else
  return 7;
</code>```

versus:

```<code>return (b * 42) | (~(b - 1) * 7);
</code>```

Is there ever an excuse to employ the latter example? if so, when and why?

EDIT: Leaving the original latter snippet for consideration, adding a correction:

```<code>return (b * 42) | ((b - 1) & 7);
</code>```

I think the other interesting observation is that it requires that b is 1 for true and 0 for false, any other values would render strange results.

答:
The first rule of any professional software engineer is to write code that is comprehensible. The second example looks like an optimized example for an older, non-optimizing compiler or just someone who happens to want to express themselves with bitwise operators. It's pretty clear what's going on if we are familiar with bitwise operations but unless you're in a domain where that's the case, avoid the second example. I should also point out that the curly braces are missing in the first example.

The coder may insist that his code is efficient, that may be the case but if it can't be maintained, it might as well not be written at all, since it will generate horrendous technical debt down the road.


问:
Lock object in base class: private or protected?
I have a base class that contains some lists, queues, and other fields which determine its state.  In the base class I only access these fields within a protected lock object since there could be multiple threads using it.  I provide methods for inheritors of this base class and these methods use the lock object to ensure the state remains valid.  (In other words, the classes that inherit from the base access the methods rather than the individual fields themselves so they don't need to know/remember to use the lock object).  So my inclination is to make the lock object and fields private so I never need to worry about inheritors using them wrong.  The downside to that approach is that anytime inheriting classes need new functionality with these fields I need to modify the base class to create a new method.

Is there a best practice I'm missing?  If not, which is the better option, private lock and fields or protected?

答:
It depends, is the state you're locking private or protected?

If it's protected, I recommend you reconsider.

Once you've reconsidered, make the lock object as public as the most public shared state. If you trust derived types to use the state properly, then you should trust them to handle the locking properly. If you don't provide the lock, they'll be tempted to have another locking mechanism leading to possible deadlock, concurrency bugs, and thermonuclear war.


问:
Quadtree with duplicates
I'm implementing a quadtree. For those who don't know this data structure, I am including the following small description:

A Quadtree is a data structure and is in the Euclidean plane
  what an Octree is in a 3-dimensional space. A common use of quadtrees
  is spatial indexing.

To summarize how they work, a quadtree is a collection — let's say of
  rectangles here — with a maximum capacity and an initial bounding box. When trying to insert an element into
  a quadtree which has reached its maximal capacity, the quadtree is
  subdivided into 4 quadtrees (a geometric representation of which will
  have a four times smaller area than the tree before insertion); each
  element is redistributed in the subtrees according to its position,
  ie. the top left bound when working with rectangles.

So a quadtree is either a leaf and has less elements than its capacity, or a tree with 4 quadtrees as children (usually north-west, north-east, south-west, south-east).

My concern is that if you try to add duplicates, may it be the same element several times or several different elements with the same position, quadtrees have a fundamental problem with handling the edges.

For instance, if you work with a quadtree with a capacity of 1 and the unit rectangle as the bounding box:

```<code>[(0,0),(0,1),(1,1),(1,0)]
</code>```

And you try inserting twice a rectangle the upper-left bound of which is the origin:
(or similarly if you try inserting it N+1 times in a quadtree with a capacity of N>1)

```<code>quadtree->insert(0.0, 0.0, 0.1, 0.1)
quadtree->insert(0.0, 0.0, 0.1, 0.1)
</code>```

The first insert will not be a problem:

But then the first insert will trigger a subdivision (because the capacity is 1):

Both rectangles are thus put in the same subtree.

Then again, the two elements will arrive in the same quadtree and trigger a subdivison…

And so on, and so forth, the subdivision method will run indefinitely because (0, 0) will always be in the same subtree out of the four created, meaning an infinite recursion problem occurs.

Is it possible to have a quadtree with duplicates? (If not, one may implement it as a Set)

How can we solve this problem without breaking completely the architecture of a quadtree?

答:
The common resolution I have come across (in visualisation problems, not in games) is to ditch one of the points, either always replacing or never replacing.

I suppose the main point in favour is that it is easy to do.

Title: Quadtree with duplicates


答:
There are several questions that you raise.

1) Is this a clear sign that the coder is not cut out for professional programming?

No.  Developers often go through stages where they learn about an idea and want to apply it.  Do they always apply these ideas efficiently and/or effectively.  No.  Mistakes are made, and it is part of the learning process.  If they are consistently writing incomprehensible code, better communication is required.  The reviewers must communicate what the expectations are for acceptable code, and the coder must communicate what the code is (supposed to be) doing and if necessary why it was done in a particular fashion.

2) Would this be enough to warrant a career change?

Not touching this one.

3) How important is comprehensible code in this industry?

Extremely.  If the code is not comprehensible, you can not be sure of what is doing, nor what it is NOT doing.  In other words, you have no way to know if it is working properly.

4a) The C examples:

The cited C examples are not equivalent.  The second case will give the same results as the first if and only if b is restricted to the values of 0 and 1.  However, if you throw in a value of say 173,406,926 for b, the results will NOT match.

4b) Is there ever an excuse to employ the latter example?

Yes.  Many processors employ branch prediction and pipelines.  The cost of an incorrectly predicted branch may introduce unacceptable delays.  To achieve a more deterministic response, bit twiddling might be used to smooth things out.

My own take on the 2nd example is that it is unnecessarily complicated and should be reworked for clarity.  Furthermore, I don't like the multiplication as (depending upon the architecture) it may be slow when compared to other operations.  Most likely, I would prefer to see something of the form:

```<code>return b ? 42 : 7;
</code>```

However, depending upon the circumstance (AND if it could be demonstrated that it provided better substantially better results in critical categories), I might accept a macro with an appropriately descriptive name when reviewing the code.  For example:

```<code>/*
 * APPROPRIATE_MACRO_NAME - use (x) if (condition) is 1, (y) if (condition) is 0
 *
 * Parameter Restrictions:
 * (condition) - must be either 1 or 0
 * (x) and (y) are of the same integer type
 *
 * This macro generates code that avoids branching (and thus incorrectly
 * predicted branches).  Its use should be restricted to <such and such>
 * because <why and why>.
 */
#define APPROPRIATE_MACRO_NAME(condition,x,y)  \
    (((condition - 1) & ((y) - (x))) + (x))
</code>```

Hope this helps.

Title: Bad sign if nobody can comprehend one's code?

Body:
If a coder writes code that nobody other than he can understand, and code reviews always end with the reviewer scratching his head or holding their head in their hands, is this a clear sign that the coder is simply not cut-out for professional programming?  Would this be enough to warrant a career change?  How important is comprehensible code in this industry?

Consider these C examples, compare:

```<code>if (b)
  return 42;
else
  return 7;
</code>```

versus:

```<code>return (b * 42) | (~(b - 1) * 7);
</code>```

Is there ever an excuse to employ the latter example? if so, when and why?

EDIT: Leaving the original latter snippet for consideration, adding a correction:

```<code>return (b * 42) | ((b - 1) & 7);
</code>```

I think the other interesting observation is that it requires that b is 1 for true and 0 for false, any other values would render strange results.

Body:
There are several questions that you raise.

1) Is this a clear sign that the coder is not cut out for professional programming?

No.  Developers often go through stages where they learn about an idea and want to apply it.  Do they always apply these ideas efficiently and/or effectively.  No.  Mistakes are made, and it is part of the learning process.  If they are consistently writing incomprehensible code, better communication is required.  The reviewers must communicate what the expectations are for acceptable code, and the coder must communicate what the code is (supposed to be) doing and if necessary why it was done in a particular fashion.

2) Would this be enough to warrant a career change?

Not touching this one.

3) How important is comprehensible code in this industry?

Extremely.  If the code is not comprehensible, you can not be sure of what is doing, nor what it is NOT doing.  In other words, you have no way to know if it is working properly.

4a) The C examples:

The cited C examples are not equivalent.  The second case will give the same results as the first if and only if b is restricted to the values of 0 and 1.  However, if you throw in a value of say 173,406,926 for b, the results will NOT match.

4b) Is there ever an excuse to employ the latter example?

Yes.  Many processors employ branch prediction and pipelines.  The cost of an incorrectly predicted branch may introduce unacceptable delays.  To achieve a more deterministic response, bit twiddling might be used to smooth things out.

My own take on the 2nd example is that it is unnecessarily complicated and should be reworked for clarity.  Furthermore, I don't like the multiplication as (depending upon the architecture) it may be slow when compared to other operations.  Most likely, I would prefer to see something of the form:

return b ? 42 : 7;

However, depending upon the circumstance (AND if it could be demonstrated that it provided better substantially better results in critical categories), I might accept a macro with an appropriately descriptive name when reviewing the code.  For example:

/*
 * APPROPRIATE_MACRO_NAME - use (x) if (condition) is 1, (y) if (condition) is 0
 *
 * Parameter Restrictions:
 * (condition) - must be either 1 or 0
 * (x) and (y) are of the same integer type
 *
 * This macro generates code that avoids branching (and thus incorrectly
 * predicted branches).  Its use should be restricted to <such and such>
 * because <why and why>.
 */
#define APPROPRIATE_MACRO_NAME(condition,x,y)  \
    (((condition - 1) & ((y) - (x))) + (x))

Hope this helps.


答:
If the branches in the if/then/else are a problem, then it's probably easiest to just switch to something like:

```<code>static const int values[] = {6, 42};

return values[b!=0];
</code>```

This actually works and although some may find it marginally less readable than the if/then/else, it certainly shouldn't be a noticeable obstruction to anybody who knows C or C++ at all.

For anybody who should think that this is a dirty trick, or depends on particularly loose type checking in one particular language: yes and no. As written the code depends upon "false" converting to 0 and "true" to 1 in C and C++.

The basic idea, however, can be applied equally well in other languages though, including those that have substantially tighter type systems. For example, in Pascal the same basic idea would look like:

```<code>var
    values : array [boolean] of Integer;

(* ... *)
values[false] = 6;
values[true] = 42;

(* ... *)
f = values[b<>0];
</code>```

The Pascal User Manual and Report (2nd Edition) by Kathleen Jensen and Niklaus Wirth shows the use of a Boolean as an index into an array in a number of places, such as §6.2.1 and §7. Although Pascal (as originally defined) doesn't include the notion of initialized variables, if it did, the initializers would end up in the same order they do in C and C++ (as it does define the fact that false < true).

Ada uses slightly different syntax, but provides the same basic capability:

```<code>Temp    : array(Boolean) of Integer := (false => 7, true=>42);

-- ...

Return_Value = Temp( 0 /= i);
</code>```

So no, we're not dealing with something that's just an accident of one language that happens to use particularly loose type checking. Pascal and (especially) Ada are well known for being particularly strongly typed, yet both support the same basic construct as C and C++, and do so in essentially the same way at that.

Body:
If the branches in the if/then/else are a problem, then it's probably easiest to just switch to something like:

static const int values[] = {6, 42};

return values[b!=0];

This actually works and although some may find it marginally less readable than the if/then/else, it certainly shouldn't be a noticeable obstruction to anybody who knows C or C++ at all.

For anybody who should think that this is a dirty trick, or depends on particularly loose type checking in one particular language: yes and no. As written the code depends upon "false" converting to 0 and "true" to 1 in C and C++.

The basic idea, however, can be applied equally well in other languages though, including those that have substantially tighter type systems. For example, in Pascal the same basic idea would look like:

var
    values : array [boolean] of Integer;

(* ... *)
values[false] = 6;
values[true] = 42;

(* ... *)
f = values[b<>0];

The Pascal User Manual and Report (2nd Edition) by Kathleen Jensen and Niklaus Wirth shows the use of a Boolean as an index into an array in a number of places, such as §6.2.1 and §7. Although Pascal (as originally defined) doesn't include the notion of initialized variables, if it did, the initializers would end up in the same order they do in C and C++ (as it does define the fact that false < true).

Ada uses slightly different syntax, but provides the same basic capability:

Temp    : array(Boolean) of Integer := (false => 7, true=>42);

-- ...

Return_Value = Temp( 0 /= i);

So no, we're not dealing with something that's just an accident of one language that happens to use particularly loose type checking. Pascal and (especially) Ada are well known for being particularly strongly typed, yet both support the same basic construct as C and C++, and do so in essentially the same way at that.


答:
The second code does not return 42 or 7.

```<code>for b = 1:
  (1 * 42) | (~(1 - 1) * 7)
  42 | (~(0) * 7)
  42 | (-1 * 7)
  42 | -7
  -5

for b = 0:
  (0 * 42) | (~(0 - 1) * 7)
  0 | (~(-1) * 7)
  0 | (0 * 7)
  0 | 0
  0
</code>```

And yet when you posted it, you thought it did, which is exactly why you should avoid convoluted code.

However, take some "correct" code for example like:

```<code>return ((b - 1) & (7 ^ 42)) ^ 42;
</code>```

There are two reasons I can think of that it may be useful.
- The architecture you are writing for does not support branching or predicated instructions.
- The architecture you are writing for has a pipeline that either does not work past a branch operation or has a prohibitive cost associated with a branch prediction miss.

In which case you would write something along these lines:

```<code>/*
   This code is equivalent to:

   if (b)
      return 42;
   else
      return 7;

   when b=0 or b=1

   But does not include a branch instruction since a branch prediction
   miss here would cause an unacceptable impact to performance.
*/

return ((b - 1) & (7 ^ 42)) ^ 42;
</code>```

If however you just see some code like that with no explanation or rationale, then it's probably a sign of source code obfuscation. Source code obfuscation (as opposed to binary code obfuscation, which many would consider to have legitimate purposes) tends to be nefarious. Some programmers can be territorial for varying reasons, sometimes for job security and sometimes for greater control over what is done and how things are done because of ego, insecurity or distrust. However, it is almost always against the interests of one's peers and one's employer. It is the responsibility of whoever is in charge of the team to stamp out such behaviour sooner rather than later, whether it is by building mutual trust or instilling fear, depending on the management style of the leader and what methods the individual programmer responds to.

Body:
The second code does not return 42 or 7.

for b = 1:
  (1 * 42) | (~(1 - 1) * 7)
  42 | (~(0) * 7)
  42 | (-1 * 7)
  42 | -7
  -5

for b = 0:
  (0 * 42) | (~(0 - 1) * 7)
  0 | (~(-1) * 7)
  0 | (0 * 7)
  0 | 0
  0

And yet when you posted it, you thought it did, which is exactly why you should avoid convoluted code.

However, take some "correct" code for example like:

return ((b - 1) & (7 ^ 42)) ^ 42;

There are two reasons I can think of that it may be useful.
- The architecture you are writing for does not support branching or predicated instructions.
- The architecture you are writing for has a pipeline that either does not work past a branch operation or has a prohibitive cost associated with a branch prediction miss.

In which case you would write something along these lines:

/*
   This code is equivalent to:

   if (b)
      return 42;
   else
      return 7;

   when b=0 or b=1

   But does not include a branch instruction since a branch prediction
   miss here would cause an unacceptable impact to performance.
*/

return ((b - 1) & (7 ^ 42)) ^ 42;

If however you just see some code like that with no explanation or rationale, then it's probably a sign of source code obfuscation. Source code obfuscation (as opposed to binary code obfuscation, which many would consider to have legitimate purposes) tends to be nefarious. Some programmers can be territorial for varying reasons, sometimes for job security and sometimes for greater control over what is done and how things are done because of ego, insecurity or distrust. However, it is almost always against the interests of one's peers and one's employer. It is the responsibility of whoever is in charge of the team to stamp out such behaviour sooner rather than later, whether it is by building mutual trust or instilling fear, depending on the management style of the leader and what methods the individual programmer responds to.


答:
Odds are, someone writing (b * 42) | (~(b - 1) * 7) is either someone who knows very little about programming trying to pretend to be experienced/knowledgeable/etc, or is someone trying to sabotage a project (i.e. they're too experienced/knowledgeable/intelligent and want job security).

The first type of person wants to show that they know how to use NOT, OR, order of operations, etc. They're showing off their knowledge, but, alas, they are writing code that's far less efficient, because this requires two multiplications, a subtraction, a not, and an or, which is clearly less efficient than a compare, a couple jumps, and a return.

If that's the case, they don't deserve to be in the industry (yet), but their demonstration proves they know basic computer logic and could be a valuable resource one day, once they get past showboating and start writing efficient code. Also, there's the distinct possibility that b won't necessarily be 0 or 1, which would result in a completely different value being returned. This could introduce subtle bugs that may be hard to find.

The second type of person hopes to slip in code like this (or many other devious types of code), so that people will keep asking them questions about the code, so they are deemed too valuable to lose. This type of sabotage will eventually hurt a project, and they should be let go immediately until they learn their lesson and write optimized, easy-to-read code. There's also the possibility that b won't be 1 or 0, as before, which means it will return a different value than expected (42 or 7), which may work correctly until some hapless programmer changes it back to if(b) ... else ... and the code suddenly stops working. For example, maybe this is a pseudo-number generator disguised as a very expensive if statement.

Legible code is important, as well as code free (as much as practical) from logic bugs such as this one. Anyone that's seriously written code for a while knows how important this is. Write a fully functional game of Tic Tac Toe. Now, set this code aside for a year, then come back to it and try to read the code. If you wrote it offhandedly, without regards for coding standards, commenting, documentation, etc, you would probably not even recognize that the code you wrote was typed by you, much less how to fix it or add a new feature if something was broken or needed to be updated.

When multiple developers work together, it's even more important that code be legible, because odds are, you won't be maintaining that code. You'll have moved on to other things, and someone else will have to maintain your code. Conversely, you may inherit another project and you'll hope that the developers before you left comments and clean code for you to work with. Programmers working on reliable code write the code to be maintainable, including legibility and comments.

Performance, while also important, should not trump legibility. At minimum, if someone did use the second code block here, I'd expect a lengthy comment block that clearly explains why they did it this way instead of a more conventional manner. At that point, I'd probably decide to replace it with more conventional code if there was no good reason for it. If, indeed, it were a logic bomb, I'd re-write it in a longer fashion so it's understood that the function has to be that way to avoid bugs, along with clear documentation of what it really does.

As it turns out, I'm pretty sure that there is a legitimate use for some specialized problem that coincidentally works out to need this precise algorithm. If so, though, I'd expect comments explaining the algorithm that uses this logic, and it had better be for something better than an if-else block. The only two appropriate if-else blocks for the specific example are: if(b) return 42; return 7; (else is optional) and return b? 42: 7; (ternary operators are okay for small branch logic, unless coding standards forbid it entirely). Anything else is overly complicated and should be reduced a simpler statement.

I do occasionally find myself writing "tricky" code that more junior developers may not immediately understand, and I usually comment that code so they can understand why it was written the way it was. Sometimes optimized code can be hard to read, and yet is necessary, but these should be the exception rather than the rule.

There is, coincidentally, a perfectly acceptable place for code like this. Obfuscation contests. In that case, I'd reserve judgement for the function until I determined that the code was just a really clever, CPU-wasting branch, or if it was a more devious device for generating pseudo-random numbers, the value for PI (or some other magical number), or maybe even a weak encryption algorithm.


答:
Something like the following would go a way toward making the INTENT of the code more apparent:

```<code>manifoldPressureFloor = (b * 42) | (~(b - 1) * 7);

return manifoldPressureFloor;
</code>```

manifoldPressureFloor is totally made up, of course I have no clue what the original code is actually about.

But without some kind of explanation or justification for the obfuscated code, the code reviewer and/or maintenance programmer is in the position of having no clear idea what the original programmer really meant to accomplish, which in turn makes it next to impossible to prove that the code actually works (that it actually does what it is SUPPOSED to do). And it makes maintenance programming both painful and much more likely to introduce bugs.

I don't believe (without qualifications) that code can be completely self-commenting. However; I do totally believe it is possible to lean heavily in that direction.

If there is some uncommon (or edge, performance or other heretofore unspecified) reason why that (b * 42) | (~(b - 1) * 7) syntax is justified, the code reviewer wasn't able to easily grasp that fact because the INTENT of the code is not easily deciphered, and there were apparently no comments explaining why that was done.

Code that is clever just for the sake of being clever should be avoided. One of the primary purposes of writing clear code is to ensure human comprehension and proactively prevent bugs from being introduced in the future. Clever code that isn't clearly comprehensible is a time bomb. Even if it works today, it's going to stop working after code maintenance tomorrow, or a year from now. And the bugs will be esoteric and difficult to find and fix.

How can anybody other than the original programmer prove that the code works if the intent and syntax isn't clear? How can even the original programmer prove that the code works in that case?

Comments should be required in screwy, clever edge case code. But its better if the code is simple enough not to require the comments. Those comments also end up out-of-date or irrelevant if the code is updated and the maintenance programmer doesn't update or remove the comments. Programmers routinely update code without updating comments. They shouldn't, they just do.

All of these factors lead to the conclusion that this programmer needs to address the issues of being able to prove that the code works, make the code comprehensible by other human beings, and make the code robust. Code that is highly susceptible to the introduction of new bugs during maintenance is fragile. No employer wants to pay a lot of money for the development of fragile, bug-prone code.

Fragile code, the behavior of which is unprovable, is much more expensive than clean, clear, provable (testable), easy-to-comprehend, easy-to-maintain code. The programmer is being paid by somebody else to be a professional and produce a reasonably clean, robust, maintainable product at a reasonable cost. Right?

So in conclusion, the programmer who came up with that code is obviously smart, and therefore full of potential. But the issues of being able to prove code correctness, make the code robust and comprehensible need to be taken seriously. If that change can take place, the programmer is probably worth keeping on. If not, and the programmer insists on continuing to do things this way, it could become difficult to justify keeping them on the team, because they'll almost certainly cost you more than they'll make you in the long run. And that's the real issue, isn't it?

IMHO.

Body:
Something like the following would go a way toward making the INTENT of the code more apparent:

manifoldPressureFloor = (b * 42) | (~(b - 1) * 7);

return manifoldPressureFloor;

manifoldPressureFloor is totally made up, of course I have no clue what the original code is actually about.

But without some kind of explanation or justification for the obfuscated code, the code reviewer and/or maintenance programmer is in the position of having no clear idea what the original programmer really meant to accomplish, which in turn makes it next to impossible to prove that the code actually works (that it actually does what it is SUPPOSED to do). And it makes maintenance programming both painful and much more likely to introduce bugs.

I don't believe (without qualifications) that code can be completely self-commenting. However; I do totally believe it is possible to lean heavily in that direction.

If there is some uncommon (or edge, performance or other heretofore unspecified) reason why that (b * 42) | (~(b - 1) * 7) syntax is justified, the code reviewer wasn't able to easily grasp that fact because the INTENT of the code is not easily deciphered, and there were apparently no comments explaining why that was done.

Code that is clever just for the sake of being clever should be avoided. One of the primary purposes of writing clear code is to ensure human comprehension and proactively prevent bugs from being introduced in the future. Clever code that isn't clearly comprehensible is a time bomb. Even if it works today, it's going to stop working after code maintenance tomorrow, or a year from now. And the bugs will be esoteric and difficult to find and fix.

How can anybody other than the original programmer prove that the code works if the intent and syntax isn't clear? How can even the original programmer prove that the code works in that case?

Comments should be required in screwy, clever edge case code. But its better if the code is simple enough not to require the comments. Those comments also end up out-of-date or irrelevant if the code is updated and the maintenance programmer doesn't update or remove the comments. Programmers routinely update code without updating comments. They shouldn't, they just do.

All of these factors lead to the conclusion that this programmer needs to address the issues of being able to prove that the code works, make the code comprehensible by other human beings, and make the code robust. Code that is highly susceptible to the introduction of new bugs during maintenance is fragile. No employer wants to pay a lot of money for the development of fragile, bug-prone code.

Fragile code, the behavior of which is unprovable, is much more expensive than clean, clear, provable (testable), easy-to-comprehend, easy-to-maintain code. The programmer is being paid by somebody else to be a professional and produce a reasonably clean, robust, maintainable product at a reasonable cost. Right?

So in conclusion, the programmer who came up with that code is obviously smart, and therefore full of potential. But the issues of being able to prove code correctness, make the code robust and comprehensible need to be taken seriously. If that change can take place, the programmer is probably worth keeping on. If not, and the programmer insists on continuing to do things this way, it could become difficult to justify keeping them on the team, because they'll almost certainly cost you more than they'll make you in the long run. And that's the real issue, isn't it?

IMHO.


问:
How to design a solution that needs dynamism using Inheritance
I have below code/classes/interfaces:

An Interface:

```<code> public interface Animal<A extends Animal<A>>{
 void fight(A otherAnimal);
 }
</code>```

2.Tiger class which is implementing Animal

```<code>    public class Tiger implements Animal{
    @Override
    public void fight(Tiger otherAnimal) {
        System.out.println("Tiger Fights");
    }
}
</code>```

3. I have a Lion class which also implements Animal

```<code>  Public class Lion implements Animal{
 @Override
 public void fight(Lion otherAnimal) {
    System.out.println("Lion Fights");
}
</code>```

I have a test class which is going to call fight:

```<code>public class TestClass{
public static void main(String[] args){
   Animal tiger = new Tiger();
   Animal lion = new Lion();
   tiger.fight(lion);
   }
}
</code>```

Now when I run the test class the obvious output is "Tiger Fights".

How should I redesign so that when I call fight on tiger with anything other than tiger should call their respective classes.

So in the example above it should invoke lion's fight even if the fight is called on object of tiger.

I need output as "lion fights" even if I am invoking an object of tiger. Meaning actually I want developer to have freedom to pass any type of object to to any class. My expectation is based on type of object the respective overridden method has to be called.

I need this dynamism because there can be N number of different animals (cat, dog, wolf etc) which might get added in near future.

Is it possible to design in such a way that My Animal interface will decide which class to call depending of type of object passed?

答:
From what you wrote, it is still a little bit unclear what you are after, but I guess when a "Tiger" fights a "Lion", you do not want to have printed "Tiger fights" or "Lions fights", but something like "Tiger fights Lion". And that is nothing for which you need double dispatch or the visitor pattern.

Just separate the "output part" from the "who fights" part:

```<code>public interface Animal {
   String Race();
   int Strength();
}

public class Tiger implements Animal{
  @Override
  public String Race() {
      return "Tiger";
  }
  @Override
  public int Strength() {
      return 10;
  }
</code>```

(yes, the Race part could be more elegantly implemented by using this.getClass().getName(), but this is for demonstration purposes). I have added an additional Strength method to make clearer how this works and how to implement actual logic with it. Place the fight method (the output part) somewhere else, and implement it in terms of "Animals":

```<code>public class Arena {
public void fight(Animal a1, Animal a2) {
    System.out.println(a1.Race() + " fights " + a2.Race());
    if(a1.Strength()>a2.Strength)
    {
         System.out.println(a1.Race() + " wins");
    }
    else if(a1.Strength()<a2.Strength)
    {
         System.out.println(a2.Race() + " wins");
    }
    else
    {
         System.out.println("Tie.");
    }
}
</code>```

Now you can easily add more different animals, without touching any of the existing animal classes or touching the fight method.

Body:
From what you wrote, it is still a little bit unclear what you are after, but I guess when a "Tiger" fights a "Lion", you do not want to have printed "Tiger fights" or "Lions fights", but something like "Tiger fights Lion". And that is nothing for which you need double dispatch or the visitor pattern.

Just separate the "output part" from the "who fights" part:

public interface Animal {
   String Race();
   int Strength();
}

public class Tiger implements Animal{
  @Override
  public String Race() {
      return "Tiger";
  }
  @Override
  public int Strength() {
      return 10;
  }

(yes, the Race part could be more elegantly implemented by using this.getClass().getName(), but this is for demonstration purposes). I have added an additional Strength method to make clearer how this works and how to implement actual logic with it. Place the fight method (the output part) somewhere else, and implement it in terms of "Animals":

public class Arena {
public void fight(Animal a1, Animal a2) {
    System.out.println(a1.Race() + " fights " + a2.Race());
    if(a1.Strength()>a2.Strength)
    {
         System.out.println(a1.Race() + " wins");
    }
    else if(a1.Strength()<a2.Strength)
    {
         System.out.println(a2.Race() + " wins");
    }
    else
    {
         System.out.println("Tie.");
    }
}

Now you can easily add more different animals, without touching any of the existing animal classes or touching the fight method.


答:
Your class is called RVDBuilder. The point of the builder pattern is to avoid ridiculously complex constructors and instead allow you to gradually collect all necessary information via ordinary method calls. Therefore, the best solution would be to add a fluent interface to add pairs of information:

```<code>class RVDBuilder {
  public RVDBuilder Add(string key, Object value) { … }
  public RVD Instantiate() { … }
}
</code>```

Then: new RVDBuilder().Add("foo", 42).Add("bar", "baz").Instantiate().

Title: Sets of pair parameters

Body:
Your class is called RVDBuilder. The point of the builder pattern is to avoid ridiculously complex constructors and instead allow you to gradually collect all necessary information via ordinary method calls. Therefore, the best solution would be to add a fluent interface to add pairs of information:

class RVDBuilder {
  public RVDBuilder Add(string key, Object value) { … }
  public RVD Instantiate() { … }
}

Then: new RVDBuilder().Add("foo", 42).Add("bar", "baz").Instantiate().


问:
SOA, Java EE and data organization
At the company I work for, we're currently splitting up our monolith solution into a number of small services (SOA).

The purpose of this is to make the developers working on each chunk of code (service) more independent, and on the whole to make the code base more manageable. When a change in code is introduced, only one part (i.e. a whole service) needs to be deployed, instead of having to deploy everything. This also helps with testing, there's less of a need to test everything when something is deployed.

Many of the services are small, so we'd like to deploy a number of these services on the same application server, JBoss 7.1 in this case.

As per the SOA philosophy, the independence of each service and the teams working on them is very important. What would be the best way to organize the data?

Use one schema per service

Would you use one datasource per schema in the application server?

Or use one datasource, prefixing all DB object names with the schema name in some transparent manner?

Use a shared schema, but evading any naming collisions by requiring each service to use a distinct prefix for all DB objects

Other options?

Am I maybe thinking this completely wrong here? :)

Edit: Explained why the code base is being split up from a monolith to smaller services.

答:
You are restructuring your application architecture from a monolith to a more modular approach:

At the company I work for, we're currently splitting up our monolith solution into a number of small services (SOA).

But why still rely on an application server?

Many of the services are small, so we'd like to deploy a number of these services on the same application server, JBoss 7.1 in this case.

There are other options today available:

Spring Boot

Dropwizard

Vert.x

Play - as standalone
etc.

Each Service would manage its own DB-connection.

For the scenario given:

I would opt for the case with one service - one datasource - one schema. This gives you flexibility: if you restructure your architecture in the future, you could easily move complete schemas to different servers (including the respctive services). Say you are developing in an e-commerce-scenario, possible parts were:

login-infrastructure

customer-data (e.g. address)

order-data

data for storage information (location of storage)

product catalog
...

These are all different concerns in the sense of SoC, which could be splitted up.

Depending on how large you grow, it might be necessary to implement an separated login-infrastructure.

On the other hand:

Since I do not know your business, nor your current architecture, there is YAGNI and Premature Optimization. It might be possible, that you refactor your current model to a use case, which will never happen (e.g. not every e-commerce-shop is the next Amazon).

Analyzing your (monolithic) architecture, a possible restructuring should emerge by itself. You know best, which subsystems are used how.

Here a nice read.

Title: SOA, Java EE and data organization


问:
Adding permanent objects to a vector
I'm relatively new to C++ (coming from Java) and I've got a little problem regarding lifetime of objects.
My situation is like this: I'm having a class A in which I'm trying to add elements to an vector in class B. This vector itself shall hold objects (not pointers) of class C.
However, since the objects are created in class As function, the are supposed to be deleted after the end of this function. So when I try to access these objects it gives me weird results. I'm currently passing the created objects as call by reference (using references instead of pointers).
My question is, what can I do / use to have the vectors elements not deleted but saved for later use?</p>

答:
You need to use a smart pointer to own them. Which one you choose and how you manage their lifetime depends on your application. The most common one is unique_ptr but there's also shared_ptr and a couple others if you have a more specialist need.

Do not ever use new and delete to manage their lifetime. Only use new if you have to implement make_unique- otherwise never use it. Never use new[], delete, delete[], or any strategy that requires them.

Title: Adding permanent objects to a vector