问:
Algorithm for flattening overlapping ranges
I am looking for a nice way of flattening (splitting) a list of potentially-overlapping numeric ranges. The problem is very similar to that of this question: Fastest way to split overlapping date ranges, and many others.

However, the ranges are not only integers, and I am looking for a decent algorithm that can be easily implemented in Javascript or Python, etc.

Example Data:

Example Solution:

Apologies if this is a duplicate, but I am yet to find a solution.

答:
If the data really is similar in scope to your sample data, you could create a map like this:

```<code>map = [0 .. 150]

for each color:
    for loc range start * 10 to range finish * 10:
        map[loc] = color
</code>```

Then just walk through this map to generate the ranges

```<code>curcolor = none
for loc in map:
    if map[loc] != curcolor:
        if curcolor:
            rangeend = loc / 10
        make new range
        rangecolor = map[loc]
        rangestart = loc / 10
</code>```

To work, the values have to be in a relatively small range as in your sample data.

Edit: to work with true floats, use the map to generate a high level mapping and then refer to the original data to create the boundaries.

```<code>map = [0 .. 15]

for each color:
   for loc round(range start) to round(range finish):
        map[loc] = color

curcolor = none
for loc in map
    if map[loc] != curcolor:

        make new range
        if loc = round(range[map[loc]].start)
             rangestart = range[map[loc]].start
        else
             rangestart = previous rangeend
        rangecolor = map[loc]
        if curcolor:
             if map[loc] == none:
                 last rangeend = range[map[loc]].end
             else
                 last rangeend = rangestart
        curcolor = rangecolor
</code>```

Body:
If the data really is similar in scope to your sample data, you could create a map like this:

map = [0 .. 150]

for each color:
    for loc range start * 10 to range finish * 10:
        map[loc] = color

Then just walk through this map to generate the ranges

curcolor = none
for loc in map:
    if map[loc] != curcolor:
        if curcolor:
            rangeend = loc / 10
        make new range
        rangecolor = map[loc]
        rangestart = loc / 10

To work, the values have to be in a relatively small range as in your sample data.

Edit: to work with true floats, use the map to generate a high level mapping and then refer to the original data to create the boundaries.

map = [0 .. 15]

for each color:
   for loc round(range start) to round(range finish):
        map[loc] = color

curcolor = none
for loc in map
    if map[loc] != curcolor:

        make new range
        if loc = round(range[map[loc]].start)
             rangestart = range[map[loc]].start
        else
             rangestart = previous rangeend
        rangecolor = map[loc]
        if curcolor:
             if map[loc] == none:
                 last rangeend = range[map[loc]].end
             else
                 last rangeend = rangestart
        curcolor = rangecolor


问:
How can the following algorithm be optimized?
I am currently working on a tic tac toe auto-mover game. I have come upon a decent algorithm that allows the computer to easily build towards, and claim victory spots.
The problem however is that when the opponent is dangerously close to victory, the computer continues to build towards it's own victory instead of blocking the opponents, is there any way the following algorithm can be optimized to counter that?

The algorithm works as follows:

Initialize a 3x3 integer array

Loop over all possible combinations on the board (0|0, 1|1, 0|2... e.tc).

If combination is a immediate victory, stop and return this position.

Else initiate a loop (That loops either 1000, 10000 or 100000 times, depending on difficulty)

Continually move from both sides randomly till victory is achieved. If victory is by the computer, increment the score counter.

Select the board position with the highest score

This algorithm works fine and can build towards victory (example:

```<code>·|x|o    ·|x|o    ·|x|o
·|·|·    x|·|o    x|x|o
·|·|·    ·|·|·    ·|·|o
</code>```

However when confronted with a board like this

```<code>·|x|o
o|x|·
·|·|·
</code>```

The optimal move should be to break x's chain, but the computer builds towards raising it's own chain i.e moving at 1|2 (The board is 3x3, indexes start from zero. So that'd be the second row's third coloumn).

Is there any way to optimize this algorithm such that this weakness goes away?

答:
Tic-Tac-Toe is a solved game and quite 'easy' to fully program or expand (its even been done in books).  Pre-programming the entire game is the optimal approach.

If you were working with a larger game (such as a 20,20,5 game (these all belong to a set of games known as m,n,k games - Tic-Tac-Toe can be described as 3,3,3)) then matters of min-max trees and optimizations on them come into play.  For Tic-Tac-Toe, this is overkill.

Working with just 3,3,3; if the game is represented with 0 as the empty cell, +1 as X, and -1 as O, the board has some interesting properties:

```
·|x|o        0 | +1 | -1
o|x|·  -->  -1 | +1 |  0
·|·|·        0 |  0 |  0
```

For each row, column, and diagonal, take the absolute value of the sum of the elements:

```
             0
            /
 0 | +1 | -1 = 0
-1 | +1 |  0 = 0
 0 |  0 |  0 = 0
 =    =    =\
 1    2    1 1
```

Wherever there is a 2, you want to play in that remaining spot.  If there are two or more spots that can be played into, chose the one that has the sign match your own.  This way, you are always guaranteed to play to win or to block if possible.

This can be used as the basis for other heuristics.  Spots that have a value of 0 are rather uninteresting in that they are either blocked ( x | o | . ) or uncontested ( . | . | .).  The number of contested lines that pass through a given cell then would likely make it a better play.

ContentLicense: CC BY-SA 3.0

Body:
Tic-Tac-Toe is a solved game and quite 'easy' to fully program or expand (its even been done in books).  Pre-programming the entire game is the optimal approach.

If you were working with a larger game (such as a 20,20,5 game (these all belong to a set of games known as m,n,k games - Tic-Tac-Toe can be described as 3,3,3)) then matters of min-max trees and optimizations on them come into play.  For Tic-Tac-Toe, this is overkill.

Working with just 3,3,3; if the game is represented with 0 as the empty cell, +1 as X, and -1 as O, the board has some interesting properties:

·|x|o        0 | +1 | -1
o|x|·  -->  -1 | +1 |  0
·|·|·        0 |  0 |  0

For each row, column, and diagonal, take the absolute value of the sum of the elements:

             0
            /
 0 | +1 | -1 = 0
-1 | +1 |  0 = 0
 0 |  0 |  0 = 0
 =    =    =\
 1    2    1 1

Wherever there is a 2, you want to play in that remaining spot.  If there are two or more spots that can be played into, chose the one that has the sign match your own.  This way, you are always guaranteed to play to win or to block if possible.

This can be used as the basis for other heuristics.  Spots that have a value of 0 are rather uninteresting in that they are either blocked ( x | o | . ) or uncontested ( . | . | .).  The number of contested lines that pass through a given cell then would likely make it a better play.


答:
Walk from left to right, using a stack to keep track of what color you're on.  Instead of a discrete map, use the 10 numbers in your dataset as the break-points.

Starting with an empty stack, and setting start to 0, loop until we reach the end:

If stack is empty:

Look for the first color starting at or after start, and push it and all lower-ranked colors onto the stack.  In your flattened list, mark the beginning of that color.

else (If not empty):

Find next beginning point for any higher-ranked color at or after start, and find the end of the current color

If the next color starts first, push it and anything else on the way to it onto the stack.  Update the end of the current color as the beginning of this one, and add the start of this color to the flattened list.

If there are none and the current color ends first, set start to the end of this color, pop it off of the stack, and check the next-highest ranked color

If start is within the next color's range, add this color to the flattened list, starting at start.

If the stack empties, just continue the loop (go back to the first bullet point).

This is a mental run-through given your example data:

```<code># Initial data.
flattened = []
stack = []
start = 0
# Stack is empty.  Look for the next starting point at 0 or later: "b", 0 - Push it and all lower levels onto stack
flattened = [ (b, 0, ?) ]
stack = [ r, b ]
start = 0
# End of "b" is 5.4, next higher-colored start is "g" at 2 - Delimit and continue
flattened = [ (b, 0, 2), (g, 2, ?) ]
stack = [ r, b, g ]
start = 2
# End of "g" is 12, next higher-colored start is "y" at 3.5 - Delimit and continue
flattened = [ (b, 0, 2), (g, 2, 3.5), (y, 3.5, ?) ]
stack = [ r, b, g, y ]
start = 3.5
# End of "y" is 6.7, next higher-colored start is "o" at 6.7 - Delimit and continue
flattened = [ (b, 0, 2), (g, 2, 3.5), (y, 3.5, 6.7), (o, 6.7, ?) ]
stack = [ r, b, g, y, o ]
start = 6.7
# End of "o" is 10, and there is nothing starting at 12 or later in a higher color.  Next off stack, "y", has already ended.  Next off stack, "g", has not ended.  Delimit and continue.
flattened = [ (b, 0, 2), (g, 2, 3.5), (y, 3.5, 6.7), (o, 6.7, 10), (g, 10, ?) ]
stack = [ r, b, g ]
start = 10
# End of "g" is 12, there is nothing starting at 12 or later in a higher color.  Next off stack, "b", is out of range (already ended).  Next off stack, "r", is out of range (not started).  Mark end of current color:
flattened = [ (b, 0, 2), (g, 2, 3.5), (y, 3.5, 6.7), (o, 6.7, 10), (g, 10, 12) ]
stack = []
start = 12
# Stack is empty.  Look for the next starting point at 12 or later: "r", 12.5 - Push onto stack
flattened = [ (b, 0, 2), (g, 2, 3.5), (y, 3.5, 6.7), (o, 6.7, 10), (g, 10, 12), (r, 12.5, ?) ]
stack = [ r ]
start = 12
# End of "r" is 13.8, and there is nothing starting at 12 or higher in a higher color.  Mark end and pop off stack.
flattened = [ (b, 0, 2), (g, 2, 3.5), (y, 3.5, 6.7), (o, 6.7, 10), (g, 10, 12), (r, 12.5, 13.8) ]
stack = []
start = 13.8
# Stack is empty and nothing is past 13.8 - We're done.
</code>```

Title: Algorithm for flattening overlapping ranges

Body:
I am looking for a nice way of flattening (splitting) a list of potentially-overlapping numeric ranges. The problem is very similar to that of this question: Fastest way to split overlapping date ranges, and many others.

However, the ranges are not only integers, and I am looking for a decent algorithm that can be easily implemented in Javascript or Python, etc.

Example Data:

Example Solution:

Apologies if this is a duplicate, but I am yet to find a solution.

Body:
Walk from left to right, using a stack to keep track of what color you're on.  Instead of a discrete map, use the 10 numbers in your dataset as the break-points.

Starting with an empty stack, and setting start to 0, loop until we reach the end:

If stack is empty:

Look for the first color starting at or after start, and push it and all lower-ranked colors onto the stack.  In your flattened list, mark the beginning of that color.

else (If not empty):

Find next beginning point for any higher-ranked color at or after start, and find the end of the current color

If the next color starts first, push it and anything else on the way to it onto the stack.  Update the end of the current color as the beginning of this one, and add the start of this color to the flattened list.

If there are none and the current color ends first, set start to the end of this color, pop it off of the stack, and check the next-highest ranked color

If start is within the next color's range, add this color to the flattened list, starting at start.

If the stack empties, just continue the loop (go back to the first bullet point).

This is a mental run-through given your example data:

# Initial data.
flattened = []
stack = []
start = 0
# Stack is empty.  Look for the next starting point at 0 or later: "b", 0 - Push it and all lower levels onto stack
flattened = [ (b, 0, ?) ]
stack = [ r, b ]
start = 0
# End of "b" is 5.4, next higher-colored start is "g" at 2 - Delimit and continue
flattened = [ (b, 0, 2), (g, 2, ?) ]
stack = [ r, b, g ]
start = 2
# End of "g" is 12, next higher-colored start is "y" at 3.5 - Delimit and continue
flattened = [ (b, 0, 2), (g, 2, 3.5), (y, 3.5, ?) ]
stack = [ r, b, g, y ]
start = 3.5
# End of "y" is 6.7, next higher-colored start is "o" at 6.7 - Delimit and continue
flattened = [ (b, 0, 2), (g, 2, 3.5), (y, 3.5, 6.7), (o, 6.7, ?) ]
stack = [ r, b, g, y, o ]
start = 6.7
# End of "o" is 10, and there is nothing starting at 12 or later in a higher color.  Next off stack, "y", has already ended.  Next off stack, "g", has not ended.  Delimit and continue.
flattened = [ (b, 0, 2), (g, 2, 3.5), (y, 3.5, 6.7), (o, 6.7, 10), (g, 10, ?) ]
stack = [ r, b, g ]
start = 10
# End of "g" is 12, there is nothing starting at 12 or later in a higher color.  Next off stack, "b", is out of range (already ended).  Next off stack, "r", is out of range (not started).  Mark end of current color:
flattened = [ (b, 0, 2), (g, 2, 3.5), (y, 3.5, 6.7), (o, 6.7, 10), (g, 10, 12) ]
stack = []
start = 12
# Stack is empty.  Look for the next starting point at 12 or later: "r", 12.5 - Push onto stack
flattened = [ (b, 0, 2), (g, 2, 3.5), (y, 3.5, 6.7), (o, 6.7, 10), (g, 10, 12), (r, 12.5, ?) ]
stack = [ r ]
start = 12
# End of "r" is 13.8, and there is nothing starting at 12 or higher in a higher color.  Mark end and pop off stack.
flattened = [ (b, 0, 2), (g, 2, 3.5), (y, 3.5, 6.7), (o, 6.7, 10), (g, 10, 12), (r, 12.5, 13.8) ]
stack = []
start = 13.8
# Stack is empty and nothing is past 13.8 - We're done.

ContentLicense: CC BY-SA 4.0


答:
Just keep a set of ranges sorted by start.  Add range that covers everything (-oo..+oo).  To add a range r:</p>

```<code>let pre = last range that starts before r starts

let post = earliest range that starts before r ends

now iterate from pre to post: split ranges that overlap, remove ranges that are covered, then add r
</code>```

Body:
Just keep a set of ranges sorted by start.  Add range that covers everything (-oo..+oo).  To add a range r:

let pre = last range that starts before r starts

let post = earliest range that starts before r ends

now iterate from pre to post: split ranges that overlap, remove ranges that are covered, then add r


答:
This solution seems the simplest. (Or at least, the easiest to grasp)

All that is needed is a function to subtract two ranges. In other words, something that will give this:

```<code>A ------               A     ------           A    ----
B    -------    and    B ------        and    B ---------
=       ----           = ----                 = ---    --
</code>```

Which is simple enough. Then you can simply iterate through each of the ranges, starting from the lowest, and for each one, subtract from it all the ranges above it, in turn. And there you have it.

Here is an implementation of the range subtractor in Python:

```<code>def subtractRanges((As, Ae), (Bs, Be)):
    '''SUBTRACTS A FROM B'''
    # e.g, A =    ------
    #      B =  -----------
    # result =  --      ---
    # Returns list of new range(s)

    if As > Be or Bs > Ae: # All of B visible
        return [[Bs, Be]]
    result = []
    if As > Bs: # Beginning of B visible
        result.append([Bs, As])
    if Ae < Be: # End of B visible
        result.append([Ae, Be])
    return result
</code>```

Using this function, the rest can be done like this:
(A 'span' means a range, as 'range' is a Python keyword)

```<code>spans = [["red", [12.5, 13.8]],
["blue", [0.0, 5.4]],
["green", [2.0, 12.0]],
["yellow", [3.5, 6.7]],
["orange", [6.7, 10.0]]]

i = 0 # Start at lowest span
while i < len(spans):
    for superior in spans[i+1:]: # Iterate through all spans above
        result = subtractRanges(superior[1], spans[i][1])
        if not result:      # If span is completely covered
            del spans[i]    # Remove it from list
            i -= 1          # Compensate for list shifting
            break           # Skip to next span
        else:   # If there is at least one resulting span
            spans[i][1] = result[0]
            if len(result) > 1: # If there are two resulting spans
                # Insert another span with the same name
                spans.insert(i+1, [spans[i][0], result[1]])
    i += 1

print spans
</code>```

This gives [['red', [12.5, 13.8]], ['blue', [0.0, 2.0]], ['green', [2.0, 3.5]], ['green', [10.0, 12.0]], ['yellow', [3.5, 6.7]], ['orange', [6.7, 10.0]]], which is correct.

Body:
This solution seems the simplest. (Or at least, the easiest to grasp)

All that is needed is a function to subtract two ranges. In other words, something that will give this:

A ------               A     ------           A    ----
B    -------    and    B ------        and    B ---------
=       ----           = ----                 = ---    --

Which is simple enough. Then you can simply iterate through each of the ranges, starting from the lowest, and for each one, subtract from it all the ranges above it, in turn. And there you have it.

Here is an implementation of the range subtractor in Python:

def subtractRanges((As, Ae), (Bs, Be)):
    '''SUBTRACTS A FROM B'''
    # e.g, A =    ------
    #      B =  -----------
    # result =  --      ---
    # Returns list of new range(s)

    if As > Be or Bs > Ae: # All of B visible
        return [[Bs, Be]]
    result = []
    if As > Bs: # Beginning of B visible
        result.append([Bs, As])
    if Ae < Be: # End of B visible
        result.append([Ae, Be])
    return result

Using this function, the rest can be done like this:
(A 'span' means a range, as 'range' is a Python keyword)

spans = [["red", [12.5, 13.8]],
["blue", [0.0, 5.4]],
["green", [2.0, 12.0]],
["yellow", [3.5, 6.7]],
["orange", [6.7, 10.0]]]

i = 0 # Start at lowest span
while i < len(spans):
    for superior in spans[i+1:]: # Iterate through all spans above
        result = subtractRanges(superior[1], spans[i][1])
        if not result:      # If span is completely covered
            del spans[i]    # Remove it from list
            i -= 1          # Compensate for list shifting
            break           # Skip to next span
        else:   # If there is at least one resulting span
            spans[i][1] = result[0]
            if len(result) > 1: # If there are two resulting spans
                # Insert another span with the same name
                spans.insert(i+1, [spans[i][0], result[1]])
    i += 1

print spans

This gives [['red', [12.5, 13.8]], ['blue', [0.0, 2.0]], ['green', [2.0, 3.5]], ['green', [10.0, 12.0]], ['yellow', [3.5, 6.7]], ['orange', [6.7, 10.0]]], which is correct.


问:
Are there any concerns with using a static read-only unit of work so that it behaves like a cache?
Related question: How do I cache data that rarely changes?

I'm making an ASP.NET MVC4 application.

On every request the security details about the user will need to be checked with the area/controller/action that they are accessing to see if they are allowed to view it. The security information is stored in the database.

For example:

```<code>User
Permission
UserPermission
Action
ActionPermission
</code>```

A "Permission" is a token that is applied to an MVC action to indicate that the token is required in order to access the action. Once a user is given the permission (via the UserPermission table) then they have the token and can therefore access the action.

I've been looking in to how to cache this data (since it rarely changes) so that I'm only querying in-memory data and not hitting a database (which is a considerable performance hit at the moment).

I've tried storing things in lists, using a caching provider but I either run in to problems or performance doesn't improve.

One problem that I constantly run in to is that I'm using lazy loading and dynamic proxies with EntityFramework. This means that even if I ToList() everything and store them somewhere static, the relationships are never populated. For example, User.Permissions is an ICollection but it's always null. I don't want to Include() everything because I'm trying to keep things simple and generic (and easy to modify).

One thing I know is that an EntityFramework DbContext is a unit of work that acts with 1st-level caching. That is, for the duration of the unit of work, everything that is accessed is cached in memory.

I want to create a read-only DbContext that will exist indefinitely and will only be used to read about permission data. Upon testing this it worked perfectly; my page load times went from 200ms+ to 20ms. I can easily force the data to refresh at certain intervals or simply leave it to refresh when the application pool is recycled. Basically it will behave like a cache.

Note that the rest of the application will interact with other contexts that exist per request as normal.

Is there any disadvantage to this approach? Could I be doing something different?

答:
Yes, there are many problems with this approach.

First, The EF DBContext is not thread safe.  If you make it static, then multiple users hitting this DbContext at the same time can cause data corruption, particularly if you're saving any items to the database.  Even if it's read-only, you still have to deal with the fact that objects get inserted into the Local cache at runtime, and that's not thread-safe either.

Secondly, DbContexts are designed to be short-lived.  There is no mechanism for cleanup.  This means that if your app runs for months, it will contain this data for each user that has ever logged in, using more and more memory as it goes along until your worker process is restarted.

Third, You should really just cache your data you need in the Asp.NET Cache.  This has mechanisms to expire data after a period of time, and is designed to deal with these situations.


问:
Separate Action from Assertion in Unit Tests

Setup

Many years ago I took to a style of unit testing that I have come to like a lot. In short, it uses a base class to separate out the Arrangement, Action and Assertion of the test into separate method calls. You do this by defining method calls in [Setup]/[TestInitialize] that will be called before each test run.

```<code>[Setup]
public void Setup()
{
   before_each(); //arrangement
   because(); //action
}
</code>```

This base class usually includes the [TearDown] call as well for when you are using this setup for Integration tests.

```<code>[TearDown]
public void Cleanup()
{
   after_each();
}
</code>```

This often breaks out into a structure where the test classes inherit from a series of Given classes that put together the setup (i.e. GivenFoo : GivenBar : WhenDoingBazz) with the Assertions being one line tests with a descriptive name of what they are covering

```<code>[Test]
public void ThenBuzzSouldBeTrue()
{
   Assert.IsTrue(result.Buzz);
}
</code>```

The Problem

There are very few tests that wrap around a single action so you end up with lots of classes so recently I have taken to defining the action in a series of methods within the test class itself:

```<code>[Test]
public void ThenBuzzSouldBeTrue()
{
   because_an_action_was_taken();
   Assert.IsTrue(result.Buzz);
}

private void because_an_action_was_taken()
{
   //perform action here
}
</code>```

This results in several "action" methods within the test class but allows grouping of similar tests (i.e. class == WhenTestingDifferentWaysToSetBuzz)

The Question

Does someone else have a better way of separating out the three 'A's of testing? Readability of tests is important to me so I would prefer that, when a test fails, that the very naming structure of the tests communicate what has failed. If someone can read the Inheritance structure of the tests and have a good idea why the test might be failing then I feel it adds a lot of value to the tests (i.e. GivenClient : GivenUser : WhenModifyingUserPermissions : ThenReadAccessShouldBeTrue).

I am aware of Acceptance Testing but this is more on a Unit (or series of units) level with boundary layers mocked.

EDIT : My question is asking if there is an event or other method for executing a block of code before individual tests (something that could be applied to specific sets of tests without it being applied to all tests within a class like [Setup] currently does. Barring the existence of this event, which I am fairly certain doesn't exist, is there another method for accomplishing the same thing?

Using [Setup] for every case presents a problem either way you go. Something like [Action("Category")] (a setup method that applied to specific tests within the class) would be nice but I can't find any way of doing this.

答:
What you are doing looks a lot like BDD - Behavior Driven Development.

Maybe you should take a look at the SpecFlow.

There are also other options for doing BDD on C#, if you prefer code centric approach, there is NSpec, NBehave, StoryQ and many others.

Edit: To expand a little, it seems to me that you have reached the limitations of your chosen framework and programming language here and there is nothing more you can do to syntax wise that would allow this kind of separation of class roles.

The technique and style of naming tests suggests that you are already using Behaviour Driven testing style, so my suggestion is that instead of trying to fight your chosen testing framework and unnecessarily convolute the test code, just change the testing framework to something that is more suited to the tests you are writing.

OwnerDisplayName: DigitalMoss


问:
Inheritance vs containment while extending a large legacy project
I have got a legacy Java project with a lot of code. The code uses MVC pattern and is well structured and well written. It also has a lot of unit tests and it is still actively maintained (bug fixing, minor features adding). Therefore I want to preserve the original structure and code style as much as possible.

I aim to inject a new behavior into an existing class. Like a Duck that was trained to jump. Then I ask all my Ducks to jump. Those who can - jump. Those who cannot do nothing which is perfectly OK with me.

The new feature I am going to add is a conceptual one, so I have to make my changes all over the code. In order to minimize changes I decided not to extend existing classes but to use containment:

```<code>class ExistingClass
{
   // .... existing code

   //  my code adding new functionality
   private ExistingClassExtension extension = new ExistingClassExtension();
   public ExistingClassExtension getExtension() {return extension;}
}

...
// somewhere in code
ExistingClass instance = new ExistingClass();

...
// when I need a new functionality
instance.getExtension().newMethod1();
</code>```

All functionality that I am adding is inside a new ExistingClassExtension class.
Actually I am adding only these 2 lines to each class that needs to be extended.

By doing so I also do not need to instantiate new, extended classes all over the code and I may use existing tests to make sure there is no regression.

However my colleagues argue that in this situation doing so isn't a proper OOP approach, and I need to inherit from ExistingClass in order to add a new functionality.

What do you think? I am aware of numerous inheritance/containment questions here, but I think my question is different.

EDIT:
Most of people replying to my question presume that a containment relationship looks like that:

```<code>class NewClass
{
   OldClass instanceOfOldClass;
   void oldFunctionality() { instanceOfOldClass.oldFunctionality();}

   void newFunctionality() { // new code here }
}
</code>```

But isn't this a kind of a containment relationship too?

```<code>class OldClass
{
   void OldFunctionality();
   NewClass instanceOfNewClass;

   void NewFunctionality {instanceOfNewClass.NewFunctionality();}
}
</code>```

答:
Your approach is what Michael Feather's calls a sprout class, see "Working Effectively with legacy code". It is a well-known technique for avoiding to change too many things in your old class (which makes the risk of accidentally breaking something small). Furthermore, it gives you the ability of testing the extended functionality in isolation (by writing unit test for your ExistingClassExtension), and it keeps the responsibilities separated between the old and the new class.

The (probably worse) alternative to this approach is to modify ExistingClass directly, and implement the new functionality directly in there (and if you do this more than 5 times, you will easily end up with a big ball of mud).

Inheritance is most probably the wrong approach here, at least when your ExistingClassExtension does not need access to the inner workings of ExistingClass, and you would have to modify the code which uses the existing class in many places by replacing the old class name by the inherited class name (probably even if that code does not make use of the extended functionality). Obviously, inheritance prohibits tests in isolation. Furthermore, think of what will happen if you need not just one extension, but five. Are you going to construct an inheritance tree five levels deep? In which order?

So talk to your colleagues, tell them that there are right and wrong uses of inheritance, and this is most probably a very typical case of wrong use.


问:
Android -> Ruby Server Interface -> Mongodb
I've been wrecking my brain about this for a few days. I'll run my scenario by you and hopefully you can help me. In my head this is how it goes:

I have an Android App.

I want my Android App to make (function) calls to a MongoDB database via a Ruby Interface on the Server.

e.g. Android app sends a HTTP GET ? with the function name, let's say getFriends for this user

Ruby Interface receives this request from the app, grabs a thread from a thread pool and calls the appropriate function call implemented in Ruby, to the Mongodb.

Ruby Interface gets results from Mongodb and sends a HTML POST to the Android app.
So that's how I think it works.

I know about the ruby driver for mongo db, and interacting with the mongodb from ruby but, how do I make a ruby back end listen for incoming messages and should these messages be done through sockets or a http interface ala Net::http in ruby?

答:
I don't see much point in using sockets here - the HTTP protocol should suit your needs just fine. Also, the Ruby server should not send an HTTP POST with the results to the Android app - that's not how HTTP work! The android app sends the POST request to the server, and the Ruby server returns the result as a response, which is part of the HTTP POST sent by the app. Behind the scenes, the Android app opens the TCP socket to send the request and the server uses the same socket to send the response.

Anyways, to create a simple HTTP server in Ruby you can use the Rack gem. Alternatively, you can use a full blown Rails web application. Using Rails here is quite an overkill, but most of the setup is done automatically so it might end up easier to setup, and since Ruby on Rails is such a major part of the Ruby culture and influences most of it's ecosystem(enough for many people to confuse RoR with Ruby itself), you can find much more information and support about it online. It might also end up easier to develop due to Rails' automatic reloading mechanism.


问:
Is ok to leave untranslated advanced log?
I just had a little fight with my boss over this topic (well, the boss always wins so I will do what he wants to be done) but I'd like to have the opinion of others about this:

We are making a complex application that will be used by expert users (like the one who manages the company backups).

I made an Advanced log, which contains 3 types of log:

messages

alerts

errors

Every error is translated and handled by the GUI, so the user will always know why something went wrong. My concern is about the messages:

The main goal of those messages is to have a detailed idea of what is happening and help the expert user to solve problems by himself without calling for assistance.

To do this I log a message (that will remain in RAM only, with a max message count) for every little kind of stuff, like

Connecting to server
Connection successfully
Request file list from path XXX
Starting receiving file list
File list successfully received
```

This can help to know when a problem occurred and to determine who is guilty for it.

The main problem is: Our program is translated in more than 10 languages! Translating that HUGE amount of little messages will be expensive and it will be used only by some users. You can access to this messages list using an Advanced console panel, so it's clear it's for Advanced users.

My boss wants those messages to be translated, but he doesn't want to spend a lot in translation, so he asked me to limit myself in using those messages.

If I limit myself this message log can become useless, but if we don't translate it our program loses its "friendly, translated approach".

What is the best thing to do? Pay more and translate everything? Limit message usage? Try to convince my boss that Advanced Users SHOULD know English?

答:
What you need to do is to configure logging to serve both your needs and those of your boss. Thing is, you aren't really forced to do what your boss asks ("Limit message usage") in the code and completely deprive yourself of an option to do logging the way you want.

Any half-decent logging framework allows programmer to output log messages into different locations (if your current framework can't, you have much much bigger problems than translation).

Configure your logging so that what is supposed to be desirable by your boss outputs into one location (file) and what you consider necessary, goes to another.

After that, show example of supposedly "boss-compliant" output to them and verify if this fits their needs.

Also, point them to example of "internally necessary" output and explain that it can be turned completely off by config change (your logging framework should allow that, and if it doesn't, see above) and explain that turning it off would make it much harder and expensive to investigate issues that may occur during application use.

Logging configuration is the way to keep your options open: no matter what is decided initially, changing it later would involve only logging config, leaving the application untouched.


答:
Don't assume advanced users know English. I'm from France and spent a year working in a software development company where:

Many programmers were unable to read or write in English,

Most programmers hated to read or write in English.

Given that any programmer should know English, you easily see how expecting non-programmers to know English may become problematic (you can, on the other hand, expect that if your app is targeting, say, scientists).

Technical character of the messages may matter. I hardly see people I've told about above who were unable to read in English to dive in /var/log/ when a proxy server or bind9 don't behave as expected. Very probably, they won't even find the location of those logs, and even if those messages were localized, they are too technical for them.

On the other hand, I expect software such as Microsoft Word to have detailed, localized messages when the app fails, but is only able to show me a message box which is at the same time clear, detailed and extremely helpful: "Microsoft Word failed to start, because it encountered an unexpected error."

Don't assume the requirements of the app. It's not your job. It's not the job of your boss. It's your customers/end users who should be asked if they are fluent enough in English or if the log messages should be translated.

Shipping features you expect the users will use without letting them to decide is one of the reasons projects are late and above the originally expected cost, because you're spending time and money on features that maybe nobody needs.

Users tell their problems: "I'm an expert user but I don't know English very well."

People from your company who work with end users gather/predict the statistics. "On 12 000 users, there are 1 500 of our users who may be interested in translated log messages, and 400 users who are totally interested."

Developers evaluate the effort needed. "We have over twelve hundred error messages, and it would take two days to make them dependent on the language. It will take additional two hours to integrate the work of the translators, and will take thirty minutes every time we have to add or change a message."

Translators evaluate the effort needed. "It would take us three weeks to translate those messages to ten languages."

Project managers evaluate the cost and schedule. "We have no chances to ship the support for Oracle for September 1st if we need to localize the log messages meanwhile."

Business decide. "It's acceptable to spend a few months on translation, given that then, we will be able to assert that our product is 100% translated into ten languages. It may also boost our international sales by giving a strong benefit over our primary competitor."

Separate logs which are intended to be read by the users from the logs which are intended to be read by developers during debug. Gnat already described that.

This will help you to avoid limiting log entries. Having detailed logs when the app runs in verbose mode is crucial to mitigate the cost of debugging.

You'll also be able to write those messages differently. For example, log messages intended for the end user may contain information such as paths of the files, something you may consider too sensitive to include in developer-oriented logs. On the other hand, you shouldn't include stack trace in end-user log messages, since this is too technical.

Take in account that translating actual messages is only a part of the effort. What is more importantly is that you'll have to translate every new message and every change to the existent message. Given the ten languages factor, this involves a lot of effort and organization, and may quickly become overwhelming for a small team.

You may end up using more and more the developer-oriented log (since it takes minutes to create a message), and change log messages for end-user log only when you don't have a choice (since it may easily take weeks).

Title: Is ok to leave untranslated advanced log?

Body:
I just had a little fight with my boss over this topic (well, the boss always wins so I will do what he wants to be done) but I'd like to have the opinion of others about this:

We are making a complex application that will be used by expert users (like the one who manages the company backups).

I made an Advanced log, which contains 3 types of log:

messages

alerts

errors

Every error is translated and handled by the GUI, so the user will always know why something went wrong. My concern is about the messages:

The main goal of those messages is to have a detailed idea of what is happening and help the expert user to solve problems by himself without calling for assistance.

To do this I log a message (that will remain in RAM only, with a max message count) for every little kind of stuff, like

Connecting to server
Connection successfully
Request file list from path XXX
Starting receiving file list
File list successfully received
```

This can help to know when a problem occurred and to determine who is guilty for it.

The main problem is: Our program is translated in more than 10 languages! Translating that HUGE amount of little messages will be expensive and it will be used only by some users. You can access to this messages list using an Advanced console panel, so it's clear it's for Advanced users.

My boss wants those messages to be translated, but he doesn't want to spend a lot in translation, so he asked me to limit myself in using those messages.

If I limit myself this message log can become useless, but if we don't translate it our program loses its "friendly, translated approach".

What is the best thing to do? Pay more and translate everything? Limit message usage? Try to convince my boss that Advanced Users SHOULD know English?


问:
Should interface only be used for behavior and not to show logical data grouped together?
Should an interface only be used to specify certain behavior? Would it be wrong to use interface to group logically related data?

To me it looks like we should not use interface to group logically related data as structure seems a better fit. A class may be used but class name should indicate something like DTO so that user gets the impression that class does not have any behavior.

Please let me know if my assumption is correct.

Also, are there any exceptions where interface can be used to group logically related data?

答:
I don't know if I understood correct but interface can be used as generalization for something (hide details) and also can be used as type, which groups some other types.

I recently working on creating simple ORM (for graph database), and I created a lot of empty interfaces just for group specific values. There were simple nodes, extended nodes and special nodes. All of them derived from few interfaces like:

```<code>internal interface Node
{
    void SetLabel(string label);
    Dictionary<string, object> Properties {get; }
    void AddProperty(string propertyName, object propertyValue);
}

internal interface SpecificNode : Node {}
internal interface ExtendedNode : Node {}
</code>```

As you can see, SpecyficNode is just type and doesn't define any behavior.

Body:
I don't know if I understood correct but interface can be used as generalization for something (hide details) and also can be used as type, which groups some other types.

I recently working on creating simple ORM (for graph database), and I created a lot of empty interfaces just for group specific values. There were simple nodes, extended nodes and special nodes. All of them derived from few interfaces like:

internal interface Node
{
    void SetLabel(string label);
    Dictionary<string, object> Properties {get; }
    void AddProperty(string propertyName, object propertyValue);
}

internal interface SpecificNode : Node {}
internal interface ExtendedNode : Node {}

As you can see, SpecyficNode is just type and doesn't define any behavior.


问:
Inserting data to database from Android
I have to build an application where the requirement is that my clients will send data from their Android device and I have to save that data to a database.

I have done the part of coding that inserts data from Android emulator to my XAMPP database on localhost, now I have to implement the real thing.

How can I connect the devices where my application will be installed to the XAMPP database I have created so that the data they send can be inserted into it?

答:
Presumably your android application sends a request to a web application.  In this case it is localhost, but when you deploy it, localhost will be replaced by the name or IP of the server that has xampp installed.  If only it were this simple.  There are some other things to consider:

Firewall - Computer housing xampp must be accessible from the outside world, and windows firewall by default stands at the doorway.  Do be sure to allow all the ports you require (default mysql port is 3306, and default http port is 80).

DNS - Would be nice to access this server with a name rather than an IP address.  If a thousand people install your application and the IP changes, a thousand people will have to change the configuration in order to make it work.  Better to give it a name.

Security - Not only does all this have to work, but it also must be secure.  And no, windows firewall does not make it secure.  Suppose you allowed just anyone to access your mysql database and hackers filled it up with trash (consequently filling up your disk).  In your case, you may be accessing the database through Apache, but you still must ensure that a reasonable amount of protection exists.

For what concerns the firewall, you must know how to fix this since you must get it up and running.  The last two are a job for a systems administrator, not you.  You need to know only to know what problems may arise, but you should not have to also know everything there is to know about security (consider liability for a moment).

Most importantly, try it before you try to install it.  By that I mean, buy an android phone, install your application, and configure it to point to your server and see if it works.  I can guarantee there will be problems.  The trick is to start with the assumption that there will be problems, and it will make your life easier.

Hope that helps!

Title: Inserting data to database from Android


问:
How can I work out how many IP addresses there are in a given range?
I'm wondering if there is a formula to work out the amount of IP addresses in a given range.

I have a system that takes either a single IP address or a start and and end IP address:

A single one might be: 145.16.23.241

A range might be: 145.16.23.122 - 145.16.23.144

The people inputting these aren't technical, nor are they receiving these details from technical people, so suggesting using CIDR notation isn't an answer for me.

I want to be able to highlight that when entering a range such as: 122.100.10.12 - 128.10.200.140 it might not actually be a range and rather 2 singular IP addresses since such a range would comprise of x (large number of) IP addresses.

Is there a basic formula to help me highlight this?

答: IP addresses are a 32 bit integer which we typically express as four octets for human purposes. You could get the number of addresses in a range by turning both into their 32 bit integer representations and subtracting. </p>


问:
How to use unit tests as a source of information?
A colleague of mine was once at a seminar about agile development, where he heard it is possible to use unit tests as technical documentation. Something like using unit tests as an example of how to use the class.

A quick Google search provided TDD and Documentation, which proves it should be possible. But looking at our code, I see that we obviously failed to implement unit tests in such a way.

In my opinion unit tests are there to test code as a minimal unit, even with help of mock and fake classes and functions.

So, the questions are:

Isn't it the task of functional tests to show how a class (or set of classes) should be used?

If it is possible to use unit tests as technical documentation, are there some guidelines on how to implement such unit tests?

答:
Testing today is all a mess of terminology where different people mean slightly different things, and definitions have changed over time.

For example, TDD used to be something that is now called BDD. The distinction is because what was unit-testing through test-driven development is now a much finer grained approach to testing methods (usually generated by automated tools). What used to be TDD was a slightly coarser way of testing units the size of classes, which I think is now called functional testing.

The idea that you can use (some form of) testing is that you can write a test that looks like how the user would use a unit of your code. It becomes an example for the docs, and a test at the same time.

So if you had a simple network class (for example). Rather than test each method individually, you'd approach testing that the class is the unit that needs testing.
Then your unit test would exercise the whole unit by calling the method to initialise the object, setting the host and port, and calling a method to send data, possibly calling a method to receive too.

All that can fit into a single 'unit test' that would test the object by setting it into a configured state, and making it do some work. Further unit tests would exercise it with bad data, but you don't need to put those in the documentation.

This isn't considered unit testing today, but it all comes down to your definition of a unit.


答:
You won't be able to get an accurate count without any information about whether the range crosses subnet boundaries and what those subnets are.  For example, 10.10.7.0 - 10.10.8.255 is a contiguous range of 512 addresses in the context of a /16.  If that range covers two /24 blocks, the count is 508 because each block has a network address and a broadcast address.

Making sure the entered upper bound is greater than or equal to the lower bound and using subtraction to measure the distance between them is good for a quick sanity check.  You'll need to decide what's a reasonable difference before you raise the red flag.

After you've converted each octet to an 8-bit integer, converting the lot of them to a single 32-bit integer is a matter of doing this:

```<code>(octet1 << 24) | (octet2 << 16) | (octet3 << 8) | octet4
</code>```

Title: How can I work out how many IP addresses there are in a given range?

Body:
I'm wondering if there is a formula to work out the amount of IP addresses in a given range.

I have a system that takes either a single IP address or a start and and end IP address:

A single one might be: 145.16.23.241

A range might be: 145.16.23.122 - 145.16.23.144

The people inputting these aren't technical, nor are they receiving these details from technical people, so suggesting using CIDR notation isn't an answer for me.

I want to be able to highlight that when entering a range such as: 122.100.10.12 - 128.10.200.140 it might not actually be a range and rather 2 singular IP addresses since such a range would comprise of x (large number of) IP addresses.

Is there a basic formula to help me highlight this?

Body:
You won't be able to get an accurate count without any information about whether the range crosses subnet boundaries and what those subnets are.  For example, 10.10.7.0 - 10.10.8.255 is a contiguous range of 512 addresses in the context of a /16.  If that range covers two /24 blocks, the count is 508 because each block has a network address and a broadcast address.

Making sure the entered upper bound is greater than or equal to the lower bound and using subtraction to measure the distance between them is good for a quick sanity check.  You'll need to decide what's a reasonable difference before you raise the red flag.

After you've converted each octet to an 8-bit integer, converting the lot of them to a single 32-bit integer is a matter of doing this:

(octet1 << 24) | (octet2 << 16) | (octet3 << 8) | octet4


问:
Storing primary keys of objects in Redis and then querying them in Postgres through Django
This is probably my second time posting in programmers. I'm usually on stackoverflow but this question is more fit for the community here.

All suggestions, advice and insight on this matter is extremely appreciated. I require you're brutal honesty as well. If you think what I'm currently doing in terms of design is really stupid, TELL ME! because I'm a self-taught back-end software engineer and I can use all the advice I can get.

I use Django, Redis & PostgreSQL. Let's say for example I have a User, Post & Location model.

```<code>#models.py
from django.db import models
from django.contrib.auth.models import User

class Post(models.Model):
        user = models.ForeignKey(User)
        media_url = models.CharField(max_length=255, blank=True)
        related_location = models.ForeignKey('Location')

class Location(models.Model):
        name = models.CharField(max_length=200, blank=True)
        address = models.CharField(max_length=255, blank=True)
        city = models.CharField(max_length=140, blank=True)
</code>```

Great, now that's out of the way, let's say users wanted to see all the posts tagged at a certain location. This location has an ID of 1812. The normal way of doing this is to make a simple query and return posts where the related_location has an ID of 1812. I would paginate the results so that user will see 10 objects at a time. If they want to see more, they need to make another request.

I used to do things this way, until recently I've had the scare of databases growing potentially large and queries becoming really slow. So I decided to create indexes on Redis for each Location object. For example, let's say posts 7, 33, 18, 12, 89, 56500, 34000, 30 we're all tagged at location 1812. I would create a Redis List called 'location:1812' and in that list, it would contain the IDs of all the posts that we're tagged there, in this case redislist = [7, 33, 18, 12, 89, 56500, 34000, 30].

I would then take this list and query against it:

```<code>queryset = Post.objects.filter(pk__in = redislist).order_by('-pk')
</code>```

Is this a smart thing to do? Immediately I began to think of the pros and cons of the approach. For one, queries to the DB would be faster since I already know which objects I need to grab. However, in terms of design, is it worth it? For something like unique location objects, that table in postgres alone can grow infinitely large (Can have over a billion rows). Storing a list for each location object in Redis can be costly (memory running out).

So it all comes down to this. Is the DB good enough, or should I continue doing what I am doing?

答:
There are many things for which Redis is the best choice available.  Replacing basic RDBMS functionality is not one of them.

Not only PostgreSQL is far faster than your Python app to do this, it has a lot of debugging behind its back.  It also manages consistency no matter which client code you use to access/update the data.

Keep Redis for what it does best, like a cache system, or to keep some analysis of the data that is either too slow or would demand denormalization if done directly on the datastore.

A typical example is keeping a scoreboard.  Normalizing the data makes complex to calculate and might be prohibitively slow.  Denormalizing on DB tables can make it slightly better, but doing it in Redis is a huge improvement in the algorithms you can apply.

In short, keep the database clean and as normalized as practical, and do extra things in Redis, not because it's "better" than the DB (it's not), but because it's different, so it applies better to the task at hand.

You'll also save a lot of headaches if you declare one storage as the "authoritative" data store, and everything else could be rebuilt from there in a single operation.


问:
What algorithms would suit image colour summarization?
I would like to analyse a set of hundreds of thousands of product images (clothing, electronic goods etc) and retrieve the dominant colours in each. I'm only interested in the top 3 or 4 colours. The aim is to achieve a degree of certainty that x image is mostly red or image y is mostly orange and blue.

The images are likely to be colour jpegs of reasonable quality and approximately 100kb in size.

I would like to use C# and the solution should run on a Linux server, preferably using open source libraries. What image processing algorithms or techniques might help me achieve this?

答:
The general method for this sort of thing is called an "Image Histogram". You generate a set of color values and a count of each of those values. In your particular case, you'd want a "Color Histogram".

Your chief challenge will be less a matter of actual collection and more one of segmentation as the definitions of various colors vary. So you'd need to decide what values "red" is for instance. From there it's easy enough to use a sorting algorithm to determine the majority colors, if any. You'd thus want to use a ordered collection unless you want to use Moore's voting algorithm instead. If you want more than one color, you'd have to remove each majority color and run the algorithm again. It also can't recognize tied colors in one pass.


问:
How to unit test models in MVC / MVR app?
I'm building a node.js web app and am trying to do so for the first time in a test driven fashion. I'm using nodeunit for testing, which I find allows me to write tests quickly and painlessly. In this particular app, the heavy lifting primarily involves translating SQL data into complex Javascript object and serving them to the front-end via json. Likewise, the app also spends a great deal of code validating and translating complex, multidimensional Javascript objects it receives from the front-end into SQL rows. Hence I have used a fat model design for the app -- most of the real code resides in the models, where the data translation happens.

What's the best approach to test such models with unit tests? I mean in particular the methods that have create javascript objects from the SQL rows and serve them to the front-end. Right now what I'm doing is making particular requests of my models with the unit tests and checking the returned data for all of the fields that should be there. However I have a suspicion that this is not the most robust kind of testing I could be doing. My current testing design also means I have to package my app code with some dummy data so that my tests can anticipate the kind of data that the app should be returning when tests run.

UPDATED QUESTION:

Specific question:

Does it make sense to inject a testing layer between my model and my database? Or would it be better to let the models work on a real database with pre-defined test data inserted into it?

The second option I imagine will probably result in more accurate testing, but the first model seems more versatile in terms of granularity and makes the testing and development more portable (no db required)

答:
Create a Repository or Service layer that acts as a go-between for your model and frontend, and write mock objects for that Repository or Service layer.

The Service Layer provides an interface surface that you can mock.  You can either inject a fake or stub that mimics the behavior of the Service Layer, or use a library to create mock objects.  Data layers don't do this well because, while they do adequately represent your data domain, they don't adequately model business processes and, well, who wants to mock a DAL anyway?

So, if you create a Service Layer or Repository Layer, this will afford you a layer of abstraction between your database classes and your frontend.  You can then mock that service layer and mimic some business domain-specific service behavior for testing your frontend classes.


问:
What is the most cross-browser/system compatible option for 3d graphics on a web page?
I would like to develop a bit of functionality for a web site that involves a bit of 3D - the user can move around objects, rotate them and texture them.

So far I've looked into:

WebGL (in particular three.js) and it looks great, but it's not supported in IE nor IOS.

IOS supports the <canvas> tag, but only 2d. It looks like three.js has an unsupported hack to make a 3d thing use the 2d canvas instead without textures, but this looks like a hack.

I also considered resorting to Flash which works on most browsers, but that won't work on IOS.

What's my best option for doing 3d web graphics on the vast array of browsers and interfaces?

At the moment I'm thinking WebGL for web (and ask people to use chrome or firefox, and take the hit on IE) and then maybe write a native app for IOS, but I am not sure if there are better alternatives available that I don't know of.

答:
I've had some luck in the past using this: https://code.google.com/p/jsc3d/ It worked on everything i tried on, i just had to change some javascript to make it interactive with mobile devices but i think now they took my changes and it should work for touch events.

That rendered with Chrome, Safari, Firefox, IE<9, IE>=9, Android Phone, Android Tablet, iPad, iPhone.

However performance is poor. But its cool i created a model in google sketchup, exported the obj file and then rendered it multiplatform with textures.


问:
How to refactor code to some common code?
Background

I'm working on an ongoing C# project. I'm not a C# programmer, primarily a C++ programmer. So I was assigned basically easy and refactoring tasks.

The code is a mess. It's a huge project. As our customer demanded frequent releases with new features and bug fixes, all other developers were forced to take brute force approach while coding. The code is highly unmaintainable and all other developers agree with it.

I'm not here to debate whether they did it right. As I'm refactoring, I'm wondering if I'm doing it in the right way as my refactored code seems complex! Here is my task as simple example.

Problem

There are six classes: A, B, C, D, E and F. All of the classes have a function ExecJob(). All six implementations are very similar. Basically, at first A::ExecJob() was written. Then a slightly different version was required which was implemented in B::ExecJob() by copy-paste-modification of A::ExecJob(). When another slightly different version was required, C::ExecJob() was written and so on. All six implementations have some common code, then some different lines of code, then again some common code and so on. Here is a simple example of the implementations:

```<code>A::ExecJob()
{
    S1;
    S2;
    S3;
    S4;
    S5;
}

B::ExecJob()
{
    S1;
    S3;
    S4;
    S5;
}

C::ExecJob()
{
    S1;
    S3;
    S4;
}
</code>```

Where SN is a group of exact same statements.

To make them common, I've created another class and moved the common code in a function. Using parameter to control which group of statements should be executed:

```<code>Base::CommonTask(param)
{
    S1;
    if (param.s2) S2;
    S3;
    S4;
    if (param.s5) S5;
}

A::ExecJob() // A inherits Base
{
    param.s2 = true;
    param.s5 = true;
    CommonTask(param);
}

B::ExecJob() // B inherits Base
{
    param.s2 = false;
    param.s5 = true;
    CommonTask(param);
}

C::ExecJob() // C inherits Base
{
    param.s2 = false;
    param.s5 = false;
    CommonTask(param);
}
</code>```

Note that, this example only employs three classes and oversimplified statements. In practice, the CommonTask() function looks very complex with all those parameter checking and there are many more statements. Also, in real code, there are several CommonTask()-looking functions.

Though all the implementations are sharing common code and ExecJob() functions are looking cuter, there exists two problems that are bothering me:

For any change in CommonTask(), all six (and may be more in the future) features are needed to be tested.

CommonTask() is already complex. It will get more complex over time.

Am I doing it in the right way?

答:
I agree with the other answers that your approach is along the right lines although I don't think that inheritance is the best way to implement common code - I prefer composition. From the C++ FAQ which can explain it far better than I ever could:
http://www.parashift.com/c++-faq/priv-inherit-vs-compos.html</p>


答:
Here's a relatively straightforward solution in Scala.  It shouldn't be too difficult to port to another language.

```<code>case class Range(name: String, left: Double, right: Double) {
  def overlapsLeft(other: Range) =
    other.left < left && left < other.right

  def overlapsRight(other: Range) =
    other.left < right && right < other.right

  def overlapsCompletely(other: Range) =
    left <= other.left && right >= other.right

  def splitLeft(other: Range) =
    Range(other.name, other.left, left)

  def splitRight(other: Range) =
    Range(other.name, right, other.right)
}

def apply(ranges: Set[Range], newRange: Range) = {
  val left     = ranges.filter(newRange.overlapsLeft)
  val right    = ranges.filter(newRange.overlapsRight)
  val overlaps = ranges.filter(newRange.overlapsCompletely)

  val leftSplit  =  left.map(newRange.splitLeft)
  val rightSplit = right.map(newRange.splitRight)

  ranges -- left -- right -- overlaps ++ leftSplit ++ rightSplit + newRange
}

val ranges = Vector(
  Range("red",   12.5, 13.8),
  Range("blue",   0.0,  5.4),
  Range("green",  2.0, 12.0),
  Range("yellow", 3.5,  6.7),
  Range("orange", 6.7, 10.0))

val flattened = ranges.foldLeft(Set.empty[Range])(apply)
val sorted = flattened.toSeq.sortBy(_.left)
sorted foreach println
</code>```

apply takes in a Set of all the ranges that have already been applied, finds the overlaps, then returns a new set minus the overlaps and plus the new range and the newly split ranges.  foldLeft repeatedly calls apply with each input range.

Body:
Here's a relatively straightforward solution in Scala.  It shouldn't be too difficult to port to another language.

case class Range(name: String, left: Double, right: Double) {
  def overlapsLeft(other: Range) =
    other.left < left && left < other.right

  def overlapsRight(other: Range) =
    other.left < right && right < other.right

  def overlapsCompletely(other: Range) =
    left <= other.left && right >= other.right

  def splitLeft(other: Range) =
    Range(other.name, other.left, left)

  def splitRight(other: Range) =
    Range(other.name, right, other.right)
}

def apply(ranges: Set[Range], newRange: Range) = {
  val left     = ranges.filter(newRange.overlapsLeft)
  val right    = ranges.filter(newRange.overlapsRight)
  val overlaps = ranges.filter(newRange.overlapsCompletely)

  val leftSplit  =  left.map(newRange.splitLeft)
  val rightSplit = right.map(newRange.splitRight)

  ranges -- left -- right -- overlaps ++ leftSplit ++ rightSplit + newRange
}

val ranges = Vector(
  Range("red",   12.5, 13.8),
  Range("blue",   0.0,  5.4),
  Range("green",  2.0, 12.0),
  Range("yellow", 3.5,  6.7),
  Range("orange", 6.7, 10.0))

val flattened = ranges.foldLeft(Set.empty[Range])(apply)
val sorted = flattened.toSeq.sortBy(_.left)
sorted foreach println

apply takes in a Set of all the ranges that have already been applied, finds the overlaps, then returns a new set minus the overlaps and plus the new range and the newly split ranges.  foldLeft repeatedly calls apply with each input range.


问:
What are the benefits of using a 'decorator factory' that decorates objects?
In a project I decided to implement the Decorator pattern.

I have a class Thing with methodA(), and a class AbstractDecorator that inherits from Thing and that all decorators inherit from: ConcreteDecorator1, ConcreteDecorator2, etc. All of them of course override methodA() to add some functionality before delegating to the wrapped Thing. Usual Decorator implementation.

I decided to implement a WrappingFactory (for a lack of a better name): it receives Thing objects and wraps them with a specified decorator. Some of the decorators require a parameter in the constructor, and WrappingFactory takes care of that too. Here it is:

```<code>public class WrappingFactory{

    public static void addSomeFunctionality(Thing thing){
        thing = new SomeDecorator(thing);
    }

    public static void addFunctionalityWithParameter(Thing thing, int param){
        thing = new DecoratorWithParameter(thing, param);
    }

    public static void addSomeAwesomeFunctionality(Thing thing){
        thing = new AwesomeDecorator(thing);
    }

}
</code>```

I did this but actually I don't know why. Does this have benefits as opposed to having the client instantiate decorators directly?

If this has benefits, please explain them to me.

答:
As always with the static factory pattern, you get the benefit of being able to easily change creation-implementation.

For example - let's say you have a decorator that takes a type as an argument:

```<code>public enum Type{TYPE_A,TYPE_B}

public class ThingWithType implements Thing{
    private Type type;
    private Thing thing;

    public ThingWithType(Thing thing,Type type){
        this.thing=thing;
        this.type=type;
    }
}

public class WrappingFactory{
    public Thing addType(Thing thing,Type type){
        return new ThingWithType(thing,type);
    }
}
</code>```

Now let's say you want to separate ThingWithType into two classes, one for TYPE_A and one for TYPE_B. Now you can do:

```<code>public enum Type{TYPE_A,TYPE_B}

public class ThingWithTypeA implements Thing{
    private Thing thing;

    public ThingWithTypeA(Thing thing){
        this.type=type;
    }
}

public class ThingWithTypeB implements Thing{
    private Thing thing;

    public ThingWithTypeB(Thing thing){
        this.type=type;
    }
}

public class WrappingFactory{
    public Thing addType(Thing thing,Type type){
        switch(type){
            case TYPE_A: return new ThingWithTypeA(thing,type);
            case TYPE_B: return new ThingWithTypeB(thing,type);
            default: throw new Error(String.format("Can't handle type %s",type));
        }
    }
}
</code>```

And you don't have to alter the actual places where you call WrappingFactory.addType. If you didn't have WrappingFactory, you would have to hunt for places in your code where you wrap Thing with ThingWithType and replace it there.

Edit:

I've read MichaelT's comment and I have to agree. Design patterns are solutions, and you sound like you have a solution and are now looking for a problem.

Body:
As always with the static factory pattern, you get the benefit of being able to easily change creation-implementation.

For example - let's say you have a decorator that takes a type as an argument:

public enum Type{TYPE_A,TYPE_B}

public class ThingWithType implements Thing{
    private Type type;
    private Thing thing;

    public ThingWithType(Thing thing,Type type){
        this.thing=thing;
        this.type=type;
    }
}

public class WrappingFactory{
    public Thing addType(Thing thing,Type type){
        return new ThingWithType(thing,type);
    }
}

Now let's say you want to separate ThingWithType into two classes, one for TYPE_A and one for TYPE_B. Now you can do:

public enum Type{TYPE_A,TYPE_B}

public class ThingWithTypeA implements Thing{
    private Thing thing;

    public ThingWithTypeA(Thing thing){
        this.type=type;
    }
}

public class ThingWithTypeB implements Thing{
    private Thing thing;

    public ThingWithTypeB(Thing thing){
        this.type=type;
    }
}

public class WrappingFactory{
    public Thing addType(Thing thing,Type type){
        switch(type){
            case TYPE_A: return new ThingWithTypeA(thing,type);
            case TYPE_B: return new ThingWithTypeB(thing,type);
            default: throw new Error(String.format("Can't handle type %s",type));
        }
    }
}

And you don't have to alter the actual places where you call WrappingFactory.addType. If you didn't have WrappingFactory, you would have to hunt for places in your code where you wrap Thing with ThingWithType and replace it there.

Edit:

I've read MichaelT's comment and I have to agree. Design patterns are solutions, and you sound like you have a solution and are now looking for a problem.


问:
Why do XML namespace URIs use the http scheme?
A XML namespace should be a URI, but it can use any URI scheme, including those that are not URLs.

Then why do all widely used XML namespaces use the http scheme (e.g. http://www.w3.org/XML/1998/namespace), considering that trying to use the URI as an URL by retrieving that document using the HTTP protocol is not guaranteed to do anything useful (and often doesn't)?

I understand the usefulness of DNS domains in namespace names to help guarantee uniqueness. But that doesn't require the http scheme, there could be a separate scheme for that (something like namespace:w3.org/XML/1998/namespace). This would avoid the confusion between URIs and URLs, while maintaining domain-based uniqueness.

答:
In most cases, I think that it's "because we've always done it that way." If you look at the Namespace spec you'll see that the examples all use HTTP URLs, but do not give a reason.

On the other hand, if you have control over your public-facing web-service, it can be very useful to actually put documentation at the namespace URL. For example, any of the Spring namespaces (eg: http://www.springframework.org/schema/beans/) take you to a page that contains the relevant XML schema documents for each version.

Personally, I prefer using namespaces that begin with urn:x-, followed by the domain name of whatever company I'm working for. That makes it very clear that this is a namespace, and has no other meaning.


答:
First, MichaelT's comments are spot-on. And there's absolutely no reason to create an AbstractDecorator class.

That said, here is an example of a "decorator factory": the factory determines, based on the input filename, whether or not to add a GZip decoder into the stack of decorated streams.

```<code>public static InputStream openFile(File file)
throws IOException
{
    InputStream stream = null;
    try
    {
        stream = new FileInputStream(file);
        stream = new BufferedInputStream(stream);
        if (file.getName().endsWith(".gz"))
            stream = new GZIPInputStream(stream);
        return stream;
    }
    catch (IOException ex)
    {
        closeQuietly(stream);
        throw ex;
    }
}
</code>```

The other -- main -- reason that this factory is useful is that it properly handles cleanup in case one of the constructors fails. Which is something that (1) many programmers (myself included) won't get right if they make explicit calls, and (2) eliminates boilerplate code.

Title: What are the benefits of using a 'decorator factory' that decorates objects?

Body:
In a project I decided to implement the Decorator pattern.

I have a class Thing with methodA(), and a class AbstractDecorator that inherits from Thing and that all decorators inherit from: ConcreteDecorator1, ConcreteDecorator2, etc. All of them of course override methodA() to add some functionality before delegating to the wrapped Thing. Usual Decorator implementation.

I decided to implement a WrappingFactory (for a lack of a better name): it receives Thing objects and wraps them with a specified decorator. Some of the decorators require a parameter in the constructor, and WrappingFactory takes care of that too. Here it is:

```<code>public class WrappingFactory{

    public static void addSomeFunctionality(Thing thing){
        thing = new SomeDecorator(thing);
    }

    public static void addFunctionalityWithParameter(Thing thing, int param){
        thing = new DecoratorWithParameter(thing, param);
    }

    public static void addSomeAwesomeFunctionality(Thing thing){
        thing = new AwesomeDecorator(thing);
    }

}
</code>```

I did this but actually I don't know why. Does this have benefits as opposed to having the client instantiate decorators directly?

If this has benefits, please explain them to me.

Body:
First, MichaelT's comments are spot-on. And there's absolutely no reason to create an AbstractDecorator class.

That said, here is an example of a "decorator factory": the factory determines, based on the input filename, whether or not to add a GZip decoder into the stack of decorated streams.

public static InputStream openFile(File file)
throws IOException
{
    InputStream stream = null;
    try
    {
        stream = new FileInputStream(file);
        stream = new BufferedInputStream(stream);
        if (file.getName().endsWith(".gz"))
            stream = new GZIPInputStream(stream);
        return stream;
    }
    catch (IOException ex)
    {
        closeQuietly(stream);
        throw ex;
    }
}

The other -- main -- reason that this factory is useful is that it properly handles cleanup in case one of the constructors fails. Which is something that (1) many programmers (myself included) won't get right if they make explicit calls, and (2) eliminates boilerplate code.


问:
What are the steps to grouping related classes into packages
What are the steps needed to be taken to group related classes into packages in Java?

In my case, I have about a number of .java files that I'd like to group into 3 packages according to the MVC pattern. One package for Model classes, one package for View classes and one package for Controller classes. I've identified which belong in what package, but not sure of the next step.

I want to know how to seperate them into packages, do I make 3 folders and place the .java files in the folder that represents the package they belong in?

答:
I like to organize my packages using the same technique I use to evaluate cohesion in a class: think back to Sesame Street! "One of these things is not like the others..." :)

It may seem silly or even flippant, but it works surprisingly well. Once you start thinking about ways where things are the same or different, it gives a good context for deciding how to organize. There usually isn't a "right" way to do it, but java (and a number of other languages) are flexible enough that it doesn't matter too much.

With packages specifically, I also ask myself how many import statements will be needed by clients of the module/library I'm writing (both with or without using * wildcards).


问:
Are short identifiers bad?
Are short identifiers bad? How does identifier length correlate with code comprehension? What other factors (besides code comprehension) might be of consideration when it comes to naming identifiers?

Just to try to keep the quality of the answers up, please note that there is some research on the subject already!

Edit

Curious that everyone either doesn't think length is relevant or tend to prefer larger identifiers, when both links I provided indicate large identifiers are harmful!

Broken Link

The link below pointed to a research on the subject, but it's now broken, I don't seem to have a copy of the paper with me, and I don't recall what it was. I'm leaving it here in case someone else figure it out.

http://evergreen.loyola.edu/chm/www/Papers/SCP2009.pdf

答:
They are not as bad as the misleading identifiers. I don't mind debugging code in which the identifiers are only one letter, but the moment different naming conventions come into the picture it becomes annoying. E.g., if somewhere you see strPersonID, and then somewhere else you see s_EmployeeID, then it's confusing to tell if are these both strings and whether there is any difference. Also if the variables are copy-pasted (pmapIntString = new std::map<int,int>) and are totally wrong, I will worry.

When it comes to me, I add comments in the code for the important variables used and try to maintain the standard given in development guideline. If there is no standard then I try to maintain the same naming convention throughout the code.

Title: Are short identifiers bad?


问:
MVC Communication Pattern
This is kind of a follow up question to this https://stackoverflow.com/questions/23743285/model-view-controller-and-callbacks, but I wanted to post it separately, because its kind of a different topic.

I'm working on a multiplayer cardgame for the Android platform. I split the project into MVC which fits the needs pretty good, but I'm currently stuck because I can't figure out a good way to communicate between the different parts.

I have everything setup and working with the controller being a big state machine, which is called over and over from the gameloop, and calls getter methods from the GUI and the android/network part to get the input. The input itself in the GUI and network is set by inputlisteners that set a local variable which I read in the getter method.

So far so good, this is working. But my problem is, the controller has to check every input separately,so if I want to add an input I have to check in which states its valid and call the getter method from all these states. This is not good, and lets the code look pretty ugly, makes additions uncomfortable and adds redundance.

So what I've got from the question I mentioned above is that some kind of command or event pattern will fit my needs. What I want to do is to create a shared and threadsafe queue in the controller and instead of calling all these getter methods, I just check the queue for new input and proceed it. On the other side, the GUI and network don't have all these getters, but instead create an event or command and send it to the controller through, for example, observer/observable.

Now my problem: I can't figure out a way, for these commands/events to fit a common interface (which the queue can store) and still transport different kind of data (button clicks, cards that are played, the player id the command comes from, synchronization data etc.).

If I design the communication as command pattern, I have to stick all the information that is needed to execute the command into it when its created, that's impossible because the GUI or network has no knowledge of all the things the controller needs to execute stuff that needs to be done when for example a card is played.

I thought about getting this stuff into the command when executing it. But over all the different commands I have, I would need all the information the controller has, and thus give the command a reference to the controller which would make everything in it public, which is real bad design I guess.

So, I could try some kind of event pattern. I have to transport data in the event. So, like the command, I would have an interface, which all events have in common, and can be stored in the shared queue. I could create a big enum with all the different events that a are possible, save one of these enums in the actual event, and build a big switch case for the events, to proceed different stuff for different events.

The problem here: I have different data for all the events. But I need a common interface, to store the events in a queue. How do I get the specific data, if I can only access the event through the interface?

Even if that wouldn't be a problem, I'm creating another big switch case, which looks ugly, and when i want to add a new event, I have to create the event itself, the case, the enum, and the method that's called with the data.

I could of course check the event with the enum and cast it to its type, so I can call event type specific methods that give me the data I need, but that looks like bad design too.

答:
It seems to me like you are missing the Model portion of your MVC pattern.

Your controller would be generally be responsible for gathering any relevant input for making a request to the model..  IE:

I want to draw a card..
I'm going to discard a card..
I want to bet 250 dollars.

Then the model then would be responsible for making sure they are valid requests, processing them, and notifying the clients that state has been updated.  The model shouldn't need to know anything about specific clicks, or the player since that should be inferred from the connection the request comes from.  The controller won't actually do anything other than ship a well formed request to the model.

Once you are at the model it is up to you want to encapsulate each request handler into a different object, or if you just want to do a big case statement, but any code that actually changes the game state will belong to the model.

As far as storing the requests in some sort of queue, you will generally just use a tag interface with no implementation. The handler for each request will check the type, doing any casting and handle all of the implementation dependent logic.

Title: MVC Communication Pattern


问:
If Scheme is untyped, how can it have numbers and lists?
Scheme is said to be just an extension of the Untyped Lambda Calculus (correct me if I am wrong). If that is the case, how can it have Lists and Numbers? Those, to me, look like 2 base types. So I'd say Racket is actually an extension of the Simply Typed Lambda Calculus. No?

Question:

Is Scheme's type system actually based or more similar to Simply Typed or Untyped Lambda Calculus?

In what ways does it differ from Untyped and or Simply Typed Lambda Calculus?

(The same question is valid for "untyped" languages such as Python and JavaScript - all of which look like they have base types to me.)

答:
When type theorists say "typed", they mean a what most programmers call statically typed. This is due to a fundamental divide: Type theorists care about proofs and related beasts, and hence care about statements that apply to all possible executions of a program. The mere notion of a "runtime type tag" doesn't make sense to them. If a type theorist says "this has type int" they mean "I can formally proof that this only ever takes on int values".

In contrast, an untyped language is one where you can't create such a proof, because the language doesn't give you enough guarantees/information.
This is the original meaning of "untyped" and it's actively used by (a minority of) people talking about type systems online. An alternative term is "unityped", because if you have to assign a type, you only have the trivial type "any value whatsoever" available.

The simply typed lambda calculus is typed in this sense, it has a static type system as you'd say. In the same sense, both Scheme and the untyped lambda calculus are untyped.

Programmers, on the other hand, primarily want to know what kind of value is in some memory location; whether this knowledge is innate in the source code for a compiler to explore and make use of, or whether it is determined at run time, is a separate decision.

In accordance with their understanding of "type", programmers have a different definition of "untyped": A system that has neither static information nor runtime tags, because there is effectively only "one type" to choose from (e.g. in Tcl, everything is a string). In this sense, the untyped lambda calculus is still untyped (everything is a function), but Scheme is, as you note, typed (though dynamically).

OwnerDisplayName: Dokkat


问:
Should REST APIs be context independent or dependent?
Let's say I have several users and each one has a user_id and also friends

To access their friends, they should be logged in, so a session will be established with the server.

Should the REST API for their friends be user/:user_id/friends or just friends

答:
The URL should be the same whether user is logged in or not.

The whole point of REST is to be as stateless as possible.  Holding a stateful session so that you can say friends instead of user/:user_id/friends is not stateless, and the URL pointing to a particular resource should always be the same.


答:
Untyped Lambda Calculus is untyped, because it doesn't concern itself with types.  Untyped Lambda Calculus is not a practical programming language, but merely a foundation for a practical programming language.

Scheme is typed, because in the real world we have to store and manipulate real data, rather than mathematical symbols. That Scheme is based on the Untyped Lambda Calculus just means that it likes some of its features.

If you want to find out more about Scheme's dynamic type system, you can read http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-2.html#node_toc_node_sec_1.1

Title: If Scheme is untyped, how can it have numbers and lists?

Body:
Scheme is said to be just an extension of the Untyped Lambda Calculus (correct me if I am wrong). If that is the case, how can it have Lists and Numbers? Those, to me, look like 2 base types. So I'd say Racket is actually an extension of the Simply Typed Lambda Calculus. No?

Question:

Is Scheme's type system actually based or more similar to Simply Typed or Untyped Lambda Calculus?

In what ways does it differ from Untyped and or Simply Typed Lambda Calculus?

(The same question is valid for "untyped" languages such as Python and JavaScript - all of which look like they have base types to me.)


问:
Simplicity-efficiency tradeoff
The CTO called to inform me of a new project and in the process told me that my code is weird.

He explained that my colleagues find it difficult to understand due to the overly complex, often new concepts and technologies used, which they are not familiar with. He asked me to maintain a simple code base and to think of the others that will inherit my changes.

I've put considerable time into mastering LINQ and thread-safe coding. However, others don't seem to care nor are impressed by anything other than their paycheck.

Do I have to keep it simple (stupid), just because others are not familiar with best practices and efficient coding? Or should I continue to do what I find best and write code my way?

答:
This is a difficult situation.

First, do not get into a negative relationship with your boss, or with your co-workers.
Above all, be positive, recognizing their valuable traits, and being helpful.

Then, see what you can do to expose your co-workers to newer techniques.
If necessary, include explanations in your code, so people can follow you.
Appeal to their higher motives.
Don't say "You should do such-and-so", say "This is what I do, and why I do it."
Don't preach.

And when it's the right thing to do - Compromise.

In other words, be a leader.

Title: Simplicity-efficiency tradeoff


问:
How are the conceptual pairs Abstract/Concrete, Generic/Specific, and Complex/Simple related to one another in software architecture?
```<code>(= 2 (+ 1 1))
</code>```

take the above. The requirement of the '=' predicate is that its arguments be comparable. Any two structures are comparable in this case, and so the contract/requirement is pretty generic. The '+' predicate requires that its arguments be numbers. That's more specific.

```<code>(socket domain type protocol)
</code>```

the arguments here are much more specific (even though the arguments are still just numbers and the function itself returns a file descriptor, which is itself an int), but the arguments are more abstract, and the implementation is built up from other functions whose abstractions are less abstract, which are themselves built from less and less abstract abstractions. To the point where the requirements are something like move from one location to another, observe whether the switch at that location is on or off, turn the switch on or off, or leave it the same, etc.

But are functions also less and less complex the less abstract they are? And is there a relationship between the number and range of arguments of a function and the complexity of its implementation, as you go from more abstract to less abstract, and vice versa?

```<code>(= 2 (+ 1 1) 2r10)
</code>```

the '=' predicate is more generic than the '+' predicate, and thus could be more complex in its implementation. The '+' predicate's contract is less generic, and so could be less complex in its implementation. Is this even a little correct? What about the 'socket' function? Each of those arguments is a number of some kind. What they represent, though, is something more elaborate. It also returns a number (just like the others do), which is also a representation of something conceptually much more elaborate than a number.

To boil it down, I'm asking if there is a relationship between the following dimensions, and why:

Abstract/Concrete

Complex/Simple

Generic/Specific

And more specifically, do different configurations of these dimensions have a specific, measurable impact on the number and range of the arguments (i.e., the contract) of a function?

答:
Generic/Specific and Abstract/Concrete are the same axes. They're synonymous, just different terms - when you make something generic, you're making it non-concrete, rather abstract. When you make something specific, you're making it non-abstract, rather concrete.

Complex/Simple is an unrelated axes to the above one you describe. You can show that they do not track together by simply drawing the quadrant of the two axes and fill it in to display the constraints that a relationship would confer.

```<code>            Abstract/Generic
                    |
                    |
          Possible  |  Possible
                    |
Complex_____________|______________Simple
                    |
          Possible  |  Possible
                    |
                    |
            Concrete/Specific
</code>```

All four quadrants are possible and therefore unconstrained. These axes profer no constraints upon eachother, therefore there's no relation.

And more specifically, do different configurations of these dimensions
  have a specific, measurable impact on the number and range of the
  arguments (i.e., the contract) of a function?

My experience tells me that individually these axes effect the design of any given bit of code, as such to say in combination they also effect the design is pretty clear. As for what precisely that impact is? Well it impacts how the code lays on these axes for one, so you can measure that I guess if you can come up with a measurement system for it.

That said, I really don't think you'll get any description of how these dimensions effect code, I've no knowledge of studies that talk about these necessarily. Though subjective opinions are a plenty, you likely can't get any objective info on how these subjective axes objectively effect code.

Body:
Generic/Specific and Abstract/Concrete are the same axes. They're synonymous, just different terms - when you make something generic, you're making it non-concrete, rather abstract. When you make something specific, you're making it non-abstract, rather concrete.

Complex/Simple is an unrelated axes to the above one you describe. You can show that they do not track together by simply drawing the quadrant of the two axes and fill it in to display the constraints that a relationship would confer.

            Abstract/Generic
                    |
                    |
          Possible  |  Possible
                    |
Complex_____________|______________Simple
                    |
          Possible  |  Possible
                    |
                    |
            Concrete/Specific

All four quadrants are possible and therefore unconstrained. These axes profer no constraints upon eachother, therefore there's no relation.

And more specifically, do different configurations of these dimensions
  have a specific, measurable impact on the number and range of the
  arguments (i.e., the contract) of a function?

My experience tells me that individually these axes effect the design of any given bit of code, as such to say in combination they also effect the design is pretty clear. As for what precisely that impact is? Well it impacts how the code lays on these axes for one, so you can measure that I guess if you can come up with a measurement system for it.

That said, I really don't think you'll get any description of how these dimensions effect code, I've no knowledge of studies that talk about these necessarily. Though subjective opinions are a plenty, you likely can't get any objective info on how these subjective axes objectively effect code.


答:
We write code for other humans to read.  New technologies are intended to make code easier to read, not harder.  There are good and bad ways to use new technologies.  If you're trying to write "impressive" code, you're doing it wrong.

I suspect it's not just the use of the technologies that is concerning people.  If the way you're using LINQ made a huge difference in readability, then your peers most likely wouldn't be whining to the CTO.  They would say, "Wow, that looks really clean, even though I don't fully understand it.  That makes me want to learn it better."  Don't just assume you can throw in a new technology and automatically get code of a higher caliber.  Make it a challenge to make using the new technology look clean and appealing.

Take this answer of mine, for example.  I wanted to highlight a functional-style solution since no one else did.  I think functional programming often produces superior code, but my first draft was terribly unreadable, even though it was concise and well-commented.  That bothered me, so I took another crack at it.  My second draft still requires basic understanding of functional programming, but is much nicer, if I may say so myself.

My point is if you put more effort into writing cleaner code, your colleagues are going to be more excited about the new technology.  If you can't write LINQ code that is easier to read than the "old-fashioned" way, you shouldn't use it in that situation.  If you can't tell if it's easier to read, ask for a code review.

Title: Simplicity-efficiency tradeoff

Body:
The CTO called to inform me of a new project and in the process told me that my code is weird.

He explained that my colleagues find it difficult to understand due to the overly complex, often new concepts and technologies used, which they are not familiar with. He asked me to maintain a simple code base and to think of the others that will inherit my changes.

I've put considerable time into mastering LINQ and thread-safe coding. However, others don't seem to care nor are impressed by anything other than their paycheck.

Do I have to keep it simple (stupid), just because others are not familiar with best practices and efficient coding? Or should I continue to do what I find best and write code my way?


答:
Three things come into my mind.

First: 'simple' is not 'stupid'. Simplicity is the predecessor of elegance.

Second: in your job, the most important thing to do is to be is a team player. Your boss is a team player. Is job is to keep the team together, and that means making your code understandable to your team mates and by that making you a part of the team. It is good that you try to educate yourself and lift up your skills. But within a team that also means: Take over responsibility and share your knowledge.

Third: If you think that the overall knowledge and level of skills of your team mates is not sufficient, talk to your boss about it, offer help, training, code reviews, presentations etc. Discuss possibilities, pros and cons of your additional skills.

Never forget: Keep it simple. Always. Never sophisticated. This ruins efficient work.
Your main goal must be: Combine high level skills and simplicity. That is the art of programming. In fact, it's the art of everything.

Title: Simplicity-efficiency tradeoff


问:
What is a real-world use case of using a Chomsky Type-I (context-sensitive) grammar
I have been having some fun lately exploring the development of language parsers in the context of how they fit into the Chomsky Hierarchy.

What is a good real-world (ie not theoretical) example of a context-sensitive grammar?

答:
Context sensitive grammars are sometimes used in descriptions of programming language semantics. Perhaps the most comprehensive use of context sensitive grammars was the Algol68 language definition. It used a two-level context free grammer (see http://en.wikipedia.org/wiki/Two-level_grammar) to describe both the syntax and semantics of Algol68 programs.

A couple of my colleagues used the van Wijngaarden grammar to direct their implementation of Algol68 (see http://en.wikipedia.org/wiki/FLACC).