问:
Avoid too complex method - Cyclomatic Complexity
Not sure how to go about this method to reduce Cyclomatic Complexity. Sonar reports 13 whereas 10 is expected. I am sure nothing harm in leaving this method as it is, however, just challenging me how to go about obeying Sonar's rule. Any thoughts would be greatly appreciated.

```<code> public static long parseTimeValue(String sValue) {

    if (sValue == null) {
        return 0;
    }

    try {
        long millis;
        if (sValue.endsWith("S")) {
            millis = new ExtractSecond(sValue).invoke();
        } else if (sValue.endsWith("ms")) {
            millis = new ExtractMillisecond(sValue).invoke();
        } else if (sValue.endsWith("s")) {
            millis = new ExtractInSecond(sValue).invoke();
        } else if (sValue.endsWith("m")) {
            millis = new ExtractInMinute(sValue).invoke();
        } else if (sValue.endsWith("H") || sValue.endsWith("h")) {
            millis = new ExtractHour(sValue).invoke();
        } else if (sValue.endsWith("d")) {
            millis = new ExtractDay(sValue).invoke();
        } else if (sValue.endsWith("w")) {
            millis = new ExtractWeek(sValue).invoke();
        } else {
            millis = Long.parseLong(sValue);
        }

        return millis;

    } catch (NumberFormatException e) {
        LOGGER.warn("Number format exception", e);
    }

    return 0;
}
</code>```

All ExtractXXX methods are defined as static inner classes. For example, like one below -

```<code>    private static class ExtractHour {
      private String sValue;

      public ExtractHour(String sValue) {
         this.sValue = sValue;
      }

      public long invoke() {
         long millis;
         millis = (long) (Double.parseDouble(sValue.substring(0, sValue.length() - 1)) * 60 * 60 * 1000);
         return millis;
     }
 }
</code>```

UPDATE 1

I am going to settle down with a mix of suggestions here to satisfy Sonar guy. Definitely room for improvements and simplification.

Guava Function is just a unwanted ceremony here. Wanted to update the question about current status. Nothing is final here. Pour your thoughts please..

```<code>public class DurationParse {

private static final Logger LOGGER = LoggerFactory.getLogger(DurationParse.class);
private static final Map<String, Function<String, Long>> MULTIPLIERS;
private static final Pattern STRING_REGEX = Pattern.compile("^(\\d+)\\s*(\\w+)");

static {

    MULTIPLIERS = new HashMap<>(7);

    MULTIPLIERS.put("S", new Function<String, Long>() {
        @Nullable
        @Override
        public Long apply(@Nullable String input) {
            return new ExtractSecond(input).invoke();
        }
    });

    MULTIPLIERS.put("s", new Function<String, Long>() {
        @Nullable
        @Override
        public Long apply(@Nullable String input) {
            return new ExtractInSecond(input).invoke();
        }
    });

    MULTIPLIERS.put("ms", new Function<String, Long>() {
        @Nullable
        @Override
        public Long apply(@Nullable String input) {
            return new ExtractMillisecond(input).invoke();
        }
    });

    MULTIPLIERS.put("m", new Function<String, Long>() {
        @Nullable
        @Override
        public Long apply(@Nullable String input) {
            return new ExtractInMinute(input).invoke();
        }
    });

    MULTIPLIERS.put("H", new Function<String, Long>() {
        @Nullable
        @Override
        public Long apply(@Nullable String input) {
            return new ExtractHour(input).invoke();
        }
    });

    MULTIPLIERS.put("d", new Function<String, Long>() {
        @Nullable
        @Override
        public Long apply(@Nullable String input) {
            return new ExtractDay(input).invoke();
        }
    });

    MULTIPLIERS.put("w", new Function<String, Long>() {
        @Nullable
        @Override
        public Long apply(@Nullable String input) {
            return new ExtractWeek(input).invoke();
        }
    });

}

public static long parseTimeValue(String sValue) {

    if (isNullOrEmpty(sValue)) {
        return 0;
    }

    Matcher matcher = STRING_REGEX.matcher(sValue.trim());

    if (!matcher.matches()) {
        LOGGER.warn(String.format("%s is invalid duration, assuming 0ms", sValue));
        return 0;
    }

    if (MULTIPLIERS.get(matcher.group(2)) == null) {
        LOGGER.warn(String.format("%s is invalid configuration, assuming 0ms", sValue));
        return 0;
    }

    return MULTIPLIERS.get(matcher.group(2)).apply(matcher.group(1));
}

private static class ExtractSecond {
    private String sValue;

    public ExtractSecond(String sValue) {
        this.sValue = sValue;
    }

    public long invoke() {
        long millis;
        millis = Long.parseLong(sValue);
        return millis;
    }
}

private static class ExtractMillisecond {
    private String sValue;

    public ExtractMillisecond(String sValue) {
        this.sValue = sValue;
    }

    public long invoke() {
        long millis;
        millis = (long) (Double.parseDouble(sValue));
        return millis;
    }
}

private static class ExtractInSecond {
    private String sValue;

    public ExtractInSecond(String sValue) {
        this.sValue = sValue;
    }

    public long invoke() {
        long millis;
        millis = (long) (Double.parseDouble(sValue) * 1000);
        return millis;
    }
}

private static class ExtractInMinute {
    private String sValue;

    public ExtractInMinute(String sValue) {
        this.sValue = sValue;
    }

    public long invoke() {
        long millis;
        millis = (long) (Double.parseDouble(sValue) * 60 * 1000);
        return millis;
    }
}

private static class ExtractHour {
    private String sValue;

    public ExtractHour(String sValue) {
        this.sValue = sValue;
    }

    public long invoke() {
        long millis;
        millis = (long) (Double.parseDouble(sValue) * 60 * 60 * 1000);
        return millis;
    }
}

private static class ExtractDay {
    private String sValue;

    public ExtractDay(String sValue) {
        this.sValue = sValue;
    }

    public long invoke() {
        long millis;
        millis = (long) (Double.parseDouble(sValue) * 24 * 60 * 60 * 1000);
        return millis;
    }
}

private static class ExtractWeek {
    private String sValue;

    public ExtractWeek(String sValue) {
        this.sValue = sValue;
    }

    public long invoke() {
        long millis;
        millis = (long) (Double.parseDouble(sValue) * 7 * 24 * 60 * 60 * 1000);
        return millis;
    }
}
</code>```

}

UPDATE 2

Though I added my update, it is only that much worth the time. I am going to move on since Sonar now does not complains. Don't worry much and I am accepting the mattnz answer as it is the way to go and don't want to set a bad example for those who bumps on to this question. Bottom line -- Don't over engineer for the sake of Sonar (or Half Baked Project Manager) complains about CC. Just do what's worth a penny for the project. Thanks to all.

答:
Related to your comment of:

Bottom line -- Don't over engineer for the sake of Sonar (or Half Baked Project Manager) complains about CC. Just do what's worth a penny for the project.

Another option to consider is to change your team's coding standards for situations like this.  Perhaps you can add in some sort of team-vote to provide a measure of governance and avoid short-cut situations.

But changing the team's standards in response to situations that don't make sense is a sign of a good team with the right attitude about standards.  The standards are there to help the team, not get in the way of writing code.


问:
Optimal way to implement this specific lookup table in C#?
I want to create a lookup table for this data:

The "input variables" (what is used to "lookup") are 4 different doubles that can each take on 1 of 200 numbers (the numbers range from 1-1000 but there are only 200 possible numbers that each can be (these 200 possible numbers that each of them can be are known to me)) the doubles are all 2 decimal places. If any one of the four were changed it would slightly change the output variables. There is also 1 integer (enum really) that can take on a value from 1-5.

There is a condition on 3 of the input variables that (1/x + 1/y + 1/z must be less than 1.02). Could this be used in a hashing algorithm?

The "output variables" (what is returned) are ~30 doubles (mostly 2 decimal places but one has 10 decimal places). (will be packaged in an object) ranging from 1 to 1000 (2 decimal places).

I expect there to be ~150 million records.

Should I use a big dictionary and load it into memory then I start the program?

Would a Database and LINQ be best?

Can I use Trees or Hashing in some way to speed it up?

I've never had to make a LUT this big before, where speed is a major factor.

Clarification: Because of the condition that (1/x + 1/y + 1/z must be less than 1.02, see above) there is only ~150 million combinations of input variables. Not ~(200)^4.

Update:

I have looked at some stats (min and max observed values and discovered some relationships) for my input variables and have found that if we call the 4 input doubles A, B, C, D: A and B have ~200 possible values each,

C has ~50 possible values, and

D has ~120 possible values

Of these, there are several relationships that mean that there are only ~27 million combinations of these rather than the ~150 million I originally thought. So there will be ~27 million records in the LUT. There is also definitely a relationship that I haven't been able to figure out between (A, B, C) and D which will also bring down the number of combinations.

Would it be optimal to run the LUT from RAM now that I have reduced the entries from 150 to 27 million (and probably lower)?

Now that it's down to 27 million would storing them as ints by multiplying them by 100 (2 decimal places) still be optimal?

As DocBrown suggested, I should store the doubles as ints (multiply by 100 because they have 2 decimal places) and then combine the 5 different ints (4 doubles (see above) and 1 enum (value:1-5)) into a key for the LUT.

How to do this such that I will have a unique value for each combination of my 5 input variables (the 5 ints) AND this method is open to expansion of each of the input variables, i.e. should I need to expand the double C's combinations to 70 instead of 50 I will need unique key values for the new entries that are result of the expanded number of total combinations of the input variables.

答:
Doubles with 2 decimal places can easily be stored in an integer (just multiply each one by 100). If you map your 5 input variables to an index from 0 to 200 (or 1-5 for the fifth), you will need at most 5 bytes to store them all. For your output records, from what you write I estimate you will need around 4 bytes per value, maybe 8 for the last one, giving you a total of 29*4+8=124 bytes. Add the former 5 bytes, and add some internal overhead, you will need roundabout 150 bytes per record in total. Multiply this with 150 million records shows that you will need at least 22GB to hold the full data in memory. And that won't differ if you are using a hash structure or a tree structure.

If you have a 64 bit machine for your processing at hand with so much main memory, you can try to handle this without a database, but if you are using a typical standard PC, I would tend to use a database for that (at least, nowadays, in 5 or ten years when the "standard PC" comes with >64GB RAM the situation may be different). And don't use the doubles directly for indexing, map them first to integers in the 0,...,200 interval, combine them into a 5 byte integer and use that value as an indexed key.

ContentLicense: CC BY-SA 3.0


问:
What is the difference between 'code readability' and 'language conventions' used within a community?
When I'm looking at questions asked on sites like stackoverflow on how to make a particular piece of code "more pythonic" there are usually suggestions offered to use complex list comprehensions or generators or other python features that aren't available in, say, Java.

I am a casual Python programmer, and sometimes I can't follow what's going on without carefully unwrapping the logic in my head. Sometimes the list comprehensions are nested in ways that I'm thinking "you probably should just write it out using loops".

Of course, veteran Python users probably won't have an issue with this, but I'm increasingly getting the impression that "pythonic code" is preferred over writing code that would be readable for the "average programmer" that may not be very proficient in Python.

In general, what are some guidelines and heuristics to follow when choosing between the readability of the code and following the conventions used in a specific programming language community?

答:
Sometimes the list comprehensions are nested in ways that I'm thinking "you probably should just write it out using loops".

If you would refactor the code really that way, it would most probably lead to a replacement of one evil by another. IMHO it is better not to replace too deeply nested list comprehensions by (still too deeply nested) loops. Instead, replace too deeply nested lists comprehensions by not so deeply nested list comprehensions. This gives you a chance to add "explaining variables" with clear names for intermediate results, and you can still think in "sets", which produces much less "noise" than loops, and is still "pythonic".


问:
What is idiomatic use of arbitrary blocks in C?
A block is a list of statements to be executed.  Examples of where blocks come up in C are after a while statement and in if statements

```<code>while( boolean expression)
    statement OR block

if (boolean expression)
    statement OR block
</code>```

C also allows a block to be nested in a block.  I can use this to reuse variable names, suppose I really like 'x'

```<code>int x = 0;
while (x < 10)
{
    {
        int x = 5;
        printf("%d",x)
    }
    x = x+1;
}
</code>```

will print the number 5 ten times.  I guess I could see situations where keeping the number of variable names low is desirable.  Perhaps in macro expansion.  However, I cannot see any hard reason to need this feature.  Can anyone help me understand uses of this feature by supplying some idioms where it is used.

答:
In general, the reuse of variable names in this manner causes too much confusion to future readers of your code.  It's better to simply name the inside variable something else.  In fact, the C# language specifically disallows the use of variables in this manner.

I could see how the use of nested blocks in macro expansions would be useful for preventing variable naming collisions.


答:
I wouldn't look at it as "arbitrary" blocks. It's not a feature meant so much for developer use, but the way C uses blocks allows the same block construct to be used in a number of places with the same semantics. A block (in C) is a new scope, and variables that leave it are eliminated. This is uniform regardless of how the block is used.

In other languages, this is not the case. This has the advantage of allowing less abuse like you show, but the disadvantage that blocks behave differently depending on what context they are in.

I've rarely seen standalone blocks used in C or C++ - often when there's a large structure or an object that represents a connection or something that you want to force destruction of. Usually this is a hint that your function is doing too many things and/or is too long.

Title: What is idiomatic use of arbitrary blocks in C?

Body:
A block is a list of statements to be executed.  Examples of where blocks come up in C are after a while statement and in if statements

```<code>while( boolean expression)
    statement OR block

if (boolean expression)
    statement OR block
</code>```

C also allows a block to be nested in a block.  I can use this to reuse variable names, suppose I really like 'x'

```<code>int x = 0;
while (x < 10)
{
    {
        int x = 5;
        printf("%d",x)
    }
    x = x+1;
}
</code>```

will print the number 5 ten times.  I guess I could see situations where keeping the number of variable names low is desirable.  Perhaps in macro expansion.  However, I cannot see any hard reason to need this feature.  Can anyone help me understand uses of this feature by supplying some idioms where it is used.


答:
The idea isn't to keep the number of variable names low or otherwise encourage reuse of names, but rather to limit the scope of variables. If you have:

```<code>int x = 0;
//...
{
    int y = 3;
    //...
}
//...
</code>```

then the scope of y is limited to the block, which means that you can forget about it either before or after the block. You see this used most often in connection with loops and conditionals. You also see it more often in C-like languages such as C++, where a variable going out of scope causes it's destruction.

Body:
The idea isn't to keep the number of variable names low or otherwise encourage reuse of names, but rather to limit the scope of variables. If you have:

int x = 0;
//...
{
    int y = 3;
    //...
}
//...

then the scope of y is limited to the block, which means that you can forget about it either before or after the block. You see this used most often in connection with loops and conditionals. You also see it more often in C-like languages such as C++, where a variable going out of scope causes it's destruction.


答:
Because in ye olden days of C new variables could only be declared in a new block.

This way programmers could introduce new variables in the middle of a function without leaking it and minimizing stack use.

With todays optimizers it is useless and a sign that you need to consider extracting the block in its own function.

In a switch statement, it is useful to enclose the cases in their own blocks to avoid double declaration.

In C++ it is very useful for example for RAII lock guards and ensuring the destructors run the release lock when execution goes out of scope and still doing other stuff outside of the critical section.


答:
It's for scoping things that normally don't have scope at that level.  This is extremely rare, and in general refactoring is a better choice, but I have run across it once or twice in the past in switch statements:

```<code>switch(foo) {
   case 1:
      {
         // bar
      }
   case 2:
   case 3:
      // baz
      break;
   case 4:
   case 5:
      // bang
      break;
}
</code>```

When you consider maintenance, refactoring these should be balanced with having all the implementations in a row, as long as each is only a couple lines long.  It can be easier to have them all together, rather than a list of function names.

In my case, if I recall correctly, most of the cases were slight variations of the same code - except that one of them was identical to another, just with extra preprocessing.  A switch ended up being the simplest form for the code to take, and the extra scope allowed use of extra local variables that it and further cases didn't have to worry about (such as variable names accidentally overlapping with one defined before the switch but used later).

Note that the switch statement is simply the use of it that I've run across.  I'm sure it can apply elsewhere as well, but I don't recall seeing them used effectively that way.

Body:
It's for scoping things that normally don't have scope at that level.  This is extremely rare, and in general refactoring is a better choice, but I have run across it once or twice in the past in switch statements:

switch(foo) {
   case 1:
      {
         // bar
      }
   case 2:
   case 3:
      // baz
      break;
   case 4:
   case 5:
      // bang
      break;
}

When you consider maintenance, refactoring these should be balanced with having all the implementations in a row, as long as each is only a couple lines long.  It can be easier to have them all together, rather than a list of function names.

In my case, if I recall correctly, most of the cases were slight variations of the same code - except that one of them was identical to another, just with extra preprocessing.  A switch ended up being the simplest form for the code to take, and the extra scope allowed use of extra local variables that it and further cases didn't have to worry about (such as variable names accidentally overlapping with one defined before the switch but used later).

Note that the switch statement is simply the use of it that I've run across.  I'm sure it can apply elsewhere as well, but I don't recall seeing them used effectively that way.


问:
why no native compiler of C# or other “productive” language?
I've been reading about D and Go and how they aim at being compiled to machine code yet be convenient (like garbage collection, no need to manipulate pointers unless needed) and I agree that there is a need for such a language. However designers of both Go and D for some reason decided to invent a new language. Why? Why not take existing language which is popular, proven to be productive but is not compiled to native code like C#? What are technological reasons for that? Would it be hard to implement garbage collection (D does), linq or something entirely else?</p>

答:
In the case of Java, its because they wanted it to run on many different architectures (remembers its roots were for an embedded system). Becuase of this they thought it would be better to provide an intermediate layer (the VM) so the java code could be written for the layer, so you wouldn't need to provide different implementations for each platform. Instead the layer would be constructed for each platform.

When Microsoft started to make .NET, its was so heavily designed to be Java (in fact it used much of the old J++ code they already had, and the chief designer was the guy who worked on their Java implementation) so its understandable they kept it as little changed as possible in order to produce something quicker. I think they also assumed that they could do more optimisations in the JIT at runtime so it wouldn't be so much slower.

Why they don't have a native compiler for it now is debatable. Probably they decided its not necessary, .NET code simply has the VM installed along with the runtime library so making it generate "pure" native code would be a waste of time for them.

Compare this to Mono that does generate native code however.

I think the guys who made D and Go didn't want to restrict themselves to using Microsoft technology (understandable), and possibly just because they like to create new language (there's enough languages about already, 2 new ones hardly matter!!).


问:
If statements vs switch cases? in a JavaScript game and if to use a function
I am developing a game in JavaScript where you start with a user input, stored in the variable "controller". The options for the user consists of start to start the game or about to learn about the game. I was going to use the following code

```<code>if(controller === "start"){
    // Game code sitting here
}
else if(controller === "about"){
    // All about the Game
}
else{
    // Tells the user again to type start to start or about to learn about the game
}
</code>```

when I realized that I should maybe use switch cases instead...

So, my question is when to use switch cases instead of if statements and which I should use in this case. I would also like to know if you think I should store my game code in a function and call it if controller is equal to "start" or just have it sitting inside the if statement/switch case as it is atm?

答:
Cases fit this operation nicely. You could also instantiate a singleton dictionary and then populate it with all the functions that you'd need the controller to perform and then simply go through the dictionary each time the controller is activated.

Using if/then would prove problematic since it'd be much hard to maintain than a case statement or a dictionary.


答:
In all the usual implementations of C# and Java, at least part of the code is eventually compiled to native code.

The most widely used Java implementations are Oracle JDK / OpenJDK, which consist of an ahead-of-time compiler which compiles Java to JVM byte code and a mixed-mode VM, which starts interpreting the JVM byte code and JIT-compiles the performance-sensitive parts to native machine code.

In .NET, no code is ever interpreted, all code is compiled to native machine code before it is executed.

Title: why no native compiler of C# or other “productive” language?

Body: I've been reading about D and Go and how they aim at being compiled to machine code yet be convenient (like garbage collection, no need to manipulate pointers unless needed) and I agree that there is a need for such a language. However designers of both Go and D for some reason decided to invent a new language. Why? Why not take existing language which is popular, proven to be productive but is not compiled to native code like C#? What are technological reasons for that? Would it be hard to implement garbage collection (D does), linq or something entirely else?</p>


答:
Semantics, semantics, semantics.

Personally, in a situation like this, I make a judgement call as to which one will be easier to understand.

What influences the ease of understanding, again, in my opinion, is maybe a combination of several factors:

Collectively exhaustive - Is there a specific way to handle each legal value?  If so, a switch may be in order.

Dependency / mutual exclusive - Do any conditions depend on each other?  If so, an if statement may be more flexible.

More than 2 cases - switch/case has some cognitive overhead for me, so I would be annoyed to see a switch/case for true/false.  Possibly because if (x) { } else { } is leaner.

How similar are the actions?  Do they fall in the same domain?  If one case sets or returns a variable, while another case executes a function that mutates some state and another case prints / outputs a piece of information, I would not make that a case because the cases are not related at all.  If they all, however, switch on a menu selection and execute a different function as the next step, that is a good switch because all cases choose a "next step".

The first two, collectively exhaustive and mutually exclusive, come to me by thinking about a physical switch.  Let's say I have a switch that can be in 5 states.  To really be a switch, it can only be in one state at any given time.  It can never not have a state and it cannot co-exist with another state.  In software, this is like saying that for any input, at least one of the case statements must match (including the default)..

Again, this is my personal preference.  I do not know if there is any official guideline on this.

Title: If statements vs switch cases? in a JavaScript game and if to use a function

Body:
I am developing a game in JavaScript where you start with a user input, stored in the variable "controller". The options for the user consists of start to start the game or about to learn about the game. I was going to use the following code

```<code>if(controller === "start"){
    // Game code sitting here
}
else if(controller === "about"){
    // All about the Game
}
else{
    // Tells the user again to type start to start or about to learn about the game
}
</code>```

when I realized that I should maybe use switch cases instead...

So, my question is when to use switch cases instead of if statements and which I should use in this case. I would also like to know if you think I should store my game code in a function and call it if controller is equal to "start" or just have it sitting inside the if statement/switch case as it is atm?


答:
You have to realize, programming principles that seem obvious now were not always so.  C best practices greatly depends on how old your examples are.  When C was first introduced, breaking your code into small functions was considered too inefficient.  Dennis Ritchie basically lied and said function calls were really efficient in C (they weren't at the time), which was what got people started using them more, although C programmers somehow never really got completely past a culture of premature optimization.

It is a good programming practice even today to limit the scope of your variables as small as possible.  Nowadays, we usually do that by creating a new function, but if functions are considered expensive, introducing a new block is a logical way to limit your scope without the overhead of a function call.

However, I started programming in C over 20 years ago, back when you had to declare all your variables at the top of a scope, and I don't recall variable shadowing like that ever being considered good style.  Redeclaring in two blocks one after another like in a switch statement, yes, but not shadowing.  Maybe if the variable was already used and the specific name was highly idiomatic for the API you're calling, like dest and src in strcpy, for example.


答:
When to use switch instead of if statements?

Use switch instead of if when:

You are comparing multiple possible conditions of an expression and the expression itself is non-trivial.

You have multiple values that may require the same code.

You have some values that will require essentially all of another value's execution, plus only a few statements.

Use if instead of switch when:

You want to test for the truthiness of an expression.

You only have a single affirmative test.

You need to evaluate different expressions for each branch.

which I should use in this case?

Whichever you are more comfortable with.  For a state engine evaluation, you would gain a slight bit of flexibility with a switch statement, in that you could slightly more easily add synonyms latter on.  But the difference is too minor to matter.

Should [I] store my game code in [seperate] functions, or just have
  it sitting inside the if statement/switch case as it is atm?

You should definitely move the inner code of each branch to distinct functions.  You cannot easily unit-test the functionality if it's sitting in the middle of a thousand-line function.


答:
I'm assuming here that the problem is read-only and that if something changes you can stop and programmatically rebuild your index.
First, I would look at coding your input space as a series of permutations, just like Doc Brown is talking about. However, I would look at changing the output to be an address. This has a few advantages. If the output length varies, this makes for fixed widths on lookups because address width doesn't vary. It also allows the output to be pushed to secondary storage like disk etc. so that the OS can handle caching for lookups. It does add a layer of indirection, which is not so good in some ways but if your output is ever repeated it can also allow you to point at the same answer.
So let's look at some numbers. First, your input space has something like 200*200*50*120 = 240,000,000 entries in the full space, not just the used space. Second, your output space is roughly 27,000,000 * 30 * 8 (for a full double - but this could maybe get better), which gives us 6.48 GB of data. This can be addressed with room to spare by 5 bytes.
So now we come to a sticking point: trees? arrays? Trees are great for many things and depending on your usage pattern may be great. But it's really hard to beat arrays if they fit in memory. If we use trees, we only need to store entries for the actually used 27 million inputs. However, the hidden cost of trees is the multiple lookups for layers of indirection. (But B-Trees may be a good option if you don't like what I say next...) But if we use arrays for speed, we need to store pointers to our data for all 240 million entries. BUT to be fair, 5 bytes * 240 million gives ~1.2GB which can fit into memory on even a modest machine for your main lookup to secondary storage.

So the full system would look like this.

To build the lookup table, do the following:

1) Scan all your data and create lists of each unique input for each variable, say maybe 200 for A, 198 for B, etc.

2) For each input variable, build a dictionary that takes the input to an increasing int. These dictionaries should be the fastest data structures you can come up with for small lookups. Given the small number of values, a sorted array using binary search may not be a bad choice. Using this versus a tree may allow for better cache locality, but you may want to conduct some experiments on this.

3) Create your lookup array and output file. For each input, drop in the current output file offset (5 bytes) and append your output to the output file. The key is just created by doing something like this (A value)*(number of B's*number of C's*number of D's) + (B value)*(number of C's * number of D's) + (C value)(number of D's) + (D value)

To do a lookup:

1) Calculate the key from the inputs as explained above by using the small dictionaries for each individual input variable and then computing the key through math.

2) Index into the array.

3) Load object from disk/secondary storage. If you can fit it into RAM, good for you. If not, we'll just have to trust the OS disk cache.

I'm sure there's a more clever answer out there for sure. But what I like about this approach is that I could code it up quickly and get it to run on my box at home without a server. That secondary storage can be whatever is available to you, and that's worth a lot.

Also, given the type of work being done here, I would definitely recommend an unmanaged language over a managed language for allowing fast unsafe memory access - unmanaged languages are not the answer for all problems but it seems like a good fit here. Similarly, the problem seems specialized and constrained enough that a database is probably not the best fit, since with a little tweaking we can more or less guarantee that at least the primary lookup can fit in RAM.

Title: Optimal way to implement this specific lookup table in C#?

Body:
I want to create a lookup table for this data:

The "input variables" (what is used to "lookup") are 4 different doubles that can each take on 1 of 200 numbers (the numbers range from 1-1000 but there are only 200 possible numbers that each can be (these 200 possible numbers that each of them can be are known to me)) the doubles are all 2 decimal places. If any one of the four were changed it would slightly change the output variables. There is also 1 integer (enum really) that can take on a value from 1-5.

There is a condition on 3 of the input variables that (1/x + 1/y + 1/z must be less than 1.02). Could this be used in a hashing algorithm?

The "output variables" (what is returned) are ~30 doubles (mostly 2 decimal places but one has 10 decimal places). (will be packaged in an object) ranging from 1 to 1000 (2 decimal places).

I expect there to be ~150 million records.

Should I use a big dictionary and load it into memory then I start the program?

Would a Database and LINQ be best?

Can I use Trees or Hashing in some way to speed it up?

I've never had to make a LUT this big before, where speed is a major factor.

Clarification: Because of the condition that (1/x + 1/y + 1/z must be less than 1.02, see above) there is only ~150 million combinations of input variables. Not ~(200)^4.

Update:

I have looked at some stats (min and max observed values and discovered some relationships) for my input variables and have found that if we call the 4 input doubles A, B, C, D: A and B have ~200 possible values each,

C has ~50 possible values, and

D has ~120 possible values

Of these, there are several relationships that mean that there are only ~27 million combinations of these rather than the ~150 million I originally thought. So there will be ~27 million records in the LUT. There is also definitely a relationship that I haven't been able to figure out between (A, B, C) and D which will also bring down the number of combinations.

Would it be optimal to run the LUT from RAM now that I have reduced the entries from 150 to 27 million (and probably lower)?

Now that it's down to 27 million would storing them as ints by multiplying them by 100 (2 decimal places) still be optimal?

As DocBrown suggested, I should store the doubles as ints (multiply by 100 because they have 2 decimal places) and then combine the 5 different ints (4 doubles (see above) and 1 enum (value:1-5)) into a key for the LUT.

How to do this such that I will have a unique value for each combination of my 5 input variables (the 5 ints) AND this method is open to expansion of each of the input variables, i.e. should I need to expand the double C's combinations to 70 instead of 50 I will need unique key values for the new entries that are result of the expanded number of total combinations of the input variables.


问:
Is it OK to use email as an identifier in a RESTful URI?
I'm working with a team building a RESTful web service, and our current implementation utilizes the user's email as a unique identifier for the user resource, yielding URIs like the following:

https://www.domain.com/users/example@gmail.com/resource

Emails are guaranteed to be unique in our system, and we've handled when the user changes his/her email, so it seems OK. But is it correct? The debate is whether we should use an immutable user ID instead, which in our case would look more like:

https://www.domain.com/users/a36571b87be464728c8d/resource

Or perhaps something else altogether. For instance, several Google APIs simply use /users/me/resource and identify the user via auth data.

In a nutshell, is it acceptable to use a unique but mutable identifier in our URIs, or should we use an immutable one?

Thanks!

答:
The idea seems fine, as long as it handles various valid types of email addresses one might encounter. I, for one, routinely use emails like account+purpose@domain; there are many more cases.

Maybe using canonicalization and then URL-encoding or even base64 on the email before using in URLs is a good idea.


答:
To expand on Jorg's remark -

http://msdn.microsoft.com/en-us/library/ht8ecch6(v=vs.90).aspx

If one looks at the rather vast collection of variations in CPU architectures that .NET runs on, one can see some value in converting to machine code at the last possible instant.  Looking at the permutations of Pentiums, Atoms, Xeons, Opterons, etc. one finds various instruction subsets present or absent, variations in front side busses, graphics co-processors, etc. Is it a good idea for developers writing CRUD to spend even a second thinking about this stuff?


答:
users/me feels like a bad idea because REST prefers to have one url per resource. You will then have:

users/me
users/123myId

Which point to the same resource. If you work with hateos better supply a link to your own resource.

Then about the e-mails: An URL should, in my opinion, not have confidential or private data in it. For example: The url can be used for logging, caching etc. That creates a place where one or more e-mailaddresses are listed.

Those could be used for spam, login attempts, etc.

See also:
https://stackoverflow.com/questions/499591/are-https-urls-encrypted

So, no I would not do that.

2016: Answer to comment:

Let's agree that we walk about urls / uris at this point. Not exactly the same, lookup the difference. Roy Fielding is mentioned a few times below, he is the inventor of REST https://en.wikipedia.org/wiki/Roy_Fielding and other related technologies.

In general it's written as: Url to identify a resource. I take that as: One resource one url but it's not a hard rule.

https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm part 5.2.1.1 is interesting on this topic. "REST relies instead on the author choosing a resource identifier that best fits the nature of the concept being identified". So you have the freedom to choose, so why not chose multiple urls for the same resource?

For this specific case:

https://www.ics.uci.edu/~fielding/pubs/dissertation/evaluation.htm#sec_6_2

Part: 6.2.5 "One form of abuse is to include information that identifies the current user within all of the URI referenced by a hypermedia response representation."

I got lucky and found a quite specific answer to this case as you can see above. The same part also discusses some of the caching issues which might occur.

In general on REST and urls: I did not find proof that one resource === 1 url. But, in practice, I don't like it. You will have multiple urls which is less clear: "Here you can find that resource, but also here, and here.". In HATEOAS what will you define as the link to _self? An array of urls?

W3 posted an interesting post on the use of urls: http://www.w3.org/TR/cooluris/#intro

Stability. Once you set up a URI to identify a certain resource, it
should remain this way as long as possible. Think about the next ten
years. Maybe twenty. [...]

Much more interesting to read in that post where you can find numerous argument to keep urls stable.

And: http://www.w3.org/Provider/Style/URI on "I didn't think URLs have to be persistent - that was URNs."

BUT: Now let's just focus specifically on REST, because urls are much wider used as seen in the previous articles.

http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven

A REST API must not define fixed resource names or hierarchies (an
obvious coupling of client and server). Servers must have the freedom
to control their own namespace. Instead, allow servers to instruct
clients on how to construct appropriate URIs, such as is done in HTML
forms and URI templates, by defining those instructions within media
types and link relations. [Failure here implies that clients are
assuming a resource structure due to out-of band information, such as
a domain-specific standard, which is the data-oriented equivalent to
RPC’s functional coupling].

So, server informs the client on the right urls to use. No guessing around what the url should be, server tells. Either by supplying hard urls or by providing url templates: https://www.rfc-editor.org/rfc/rfc6570. So in that sense it doesn't matter too much, your clients will still work even when the server changes url structure.

That also removed part of the advantage of having 2 urls for the same resource, say /customers/1 and /user/123/customer/1 because it's not something a human should interpret and/or change by himself.

Then in the comments on that post by Roy Fielding:

A truly RESTful API looks like hypertext. Every addressable unit of
information carries an address, either explicitly (e.g., link and id
attributes) or implicitly (e.g., derived from the media type
definition and representation structure).

and:

Any important resource in a RESTful system must have an identifier [...]

That, to me, is kind of enough direction into keeping one url per resource. So to summarize: I did not find a strict hard rule but the intention and advantages of having one resource === one url to me are enough to stick to it. Advantages of having multiple urls don't seem to be available a lot except when you start to manually craft urls which does not seem to be the intention.

For more answer you might pose this question to Roy Fielding himself.

Title: Is it OK to use email as an identifier in a RESTful URI?

Body:
I'm working with a team building a RESTful web service, and our current implementation utilizes the user's email as a unique identifier for the user resource, yielding URIs like the following:

https://www.domain.com/users/example@gmail.com/resource

Emails are guaranteed to be unique in our system, and we've handled when the user changes his/her email, so it seems OK. But is it correct? The debate is whether we should use an immutable user ID instead, which in our case would look more like:

https://www.domain.com/users/a36571b87be464728c8d/resource

Or perhaps something else altogether. For instance, several Google APIs simply use /users/me/resource and identify the user via auth data.

In a nutshell, is it acceptable to use a unique but mutable identifier in our URIs, or should we use an immutable one?

Thanks!


答:
Arbitrary blocks are useful to introduce intermediary variables that
are only used in special cases of a computation.

This is a common pattern in scientific computing, where numeric
procedures typically:

rely on a lot of parameters or intermediary quantities;

have to deal with a lot of special cases.

Because of the second point, it is useful to introduce temporary
variables of limited scope, which is achieved wether by using an
arbitrary block or by introducing an auxiliary function.

While introducing an auxiliary function may look like a no brainer
or a best practice to blindly follow, there is actually little
benefits to do so in this particular situation.

Because there is a lot of parameters and intermediary quantities, we
want to introduce a structure to pass these to the auxilary
function.

But, since we want to be consequent with our practices, we will not
introduce only one auxiliary function but several.  So, wether we
introduce ad-hoc structures conveying parameters for each function,
which introduce a lot of code-overhead to move parameters back and
forth, or we introduce a one will rule them all worksheet structure,
which contains all our variables but looks like a grabpack of bits
without consistence, where at any time only the half of parameters
have an interesting meaning.

Therefore these auxiliary structures are typically cumbersome and
using them means choosing between code-bloat or introduce an
abstraction whose scope is too broad and weaken the meaning of the
program, instead of stregthen it.

Introducing auxiliary functions could ease unit testing of the
program by introducing a finer test granularity but combining unit
testing for not that low-level procedures and regression testing in
the form of comparisons (with numdiff) of numeric traces of the
procedures does an equally good job.


问:
AngularJS dealing with large data sets (Strategy)
I am working on developing a personal temperature logging viewer based on my rasppi curl'ing data into my web server's api.  Temperatures are taken every 2 seconds and I can have several temperature sensors posting data.  Needless to say I will have a lot of data to handle even within the scope of an hour.  I have implemented a very simple paging api from the server so the server doesn't timeout and is currently only returning data in 1000 units per call, then paging through the data.  I had the idea to intially show say the last 20 minutes of data from a sensor (or all sensors depending on user choices), then allowing the user to select other timeframes from which to show data.  The issue comes in when you want to view all sensors or an extended time period (say 24 hours).

Is there a best practice of handling this large amount of data?

Would it be useful to load those first 20 minutes into the live view and then cache into local storage something like the last 24 hours?

I haven't been able to find a decent idea of this in use yet even though there are a lot of ways to take this problem.  I am just looking for some suggestions as to what might provide a good balance between good performance and not caching the entire data set on the client side (as beyond a week of data this might not be feasible).

答:
Is there a best practice of handling this large amount of data?

Not sure about "best practice", but I think would be a good idea to clearly define what you need to do with the data. What will the user actually need to see at any one time? Instinctively, 24 hours of data points every 2 seconds doesn't seem that possible to handle, cognitively. Maybe you'll have a per-5-minute average, that you'll need to graph? In that case, I would create an API that requests these averages so the browser doesn't need to deal with all the data. You could cache these on the server if needs-be, for other requests. If the user will see one-screen of fine-grained temperatures at any one time, then create an API that requests one-screen's worth of data at a time (similar to your paging API).

Using one-screen's worth of information at a time is also a good strategy if you have lots of Angular's bindings: if you end up with 1000s of them then interface performance will drop.

I am just looking for some suggestions as to what might provide a good balance between good performance and not caching the entire data set on the client side

Would it be useful to load those first 20 minutes into the live view and then cache into local storage something like the last 24 hours?

It's always a bit hard to decide how to optimize before you know exactly where the bottlenecks are. Keeping-it-simple for the first design is often a good idea. Don't build your own caching layer, at least at first: use $http's built-in cache, and maybe also an aggressive caching strategy using http headers, so the browser can cache the Ajax requests as well.


答:
There are two sub-questions to your question:

Can I use unique but mutable identifiers in my URLs?

This can work well if either the IDs change only infrequently or if the URLs containing those IDs are not used outside your site.
As REST APIs usually are built on the premise that any given URL can be re-used to access the same resource at any later time, that second condition goes a bit against the idea of REST.

That leaves the probability of changes to the ID and if you are willing/able to redirect requests made using an old ID. With (encoded) email addresses, this can probably be realized, because an old email address will not be re-used by a different user that often.

Can I use email addresses as my unique ID?

As indicated by the answers of @LucFranken and @9000, using a plain email address in your URL is a bad idea, but you can use an 'encrypted' form of an email address as ID. This 'encryption' can be as simple as base64 encoding.


问:
Slower Ajax Response
Does putting the view logic inside the controller increase page load speed? Because I have a controller action calling a view which I am loading through ajax and I am getting a very slow response. Why is that happening?

Does putting the view logic inside controller like...

```<code>echo "<div>View echoed</div>"
</code>```

a good way to code? does this increase efficiency?

I have writted a controller action like

```<code>class Ajax extends CI_Controller{
  foo ($id){
   $data = $this->model->get_data();//has joins in query
   $this->load->view($data);
 }
}
</code>```

In view,

I have used two foreach loops nested to get the table having about 100 rows

and I load the view through a jquery ajax request to the url ajax/foo/1

My question clearly is whether it is a good practice to put view-logic into the controller for ajax calls? will it increase the speed my page will load.

I am new to coding things very professionally. Is this a good and a professional method or any other alternative available.

答:
Taking a stab at this for what has been asked, rather than trying to change your direction :-)

NO

but then again many people will disagree with me.

If there is ONE thing I've learned over the years, it's this...

"Design patterns, such as MVC and others are NOT a religion, they are there to serve as pointers on how things have worked well in the past, and how you might want to apply them in the future."

There are not, nor should they ever be, a dedicated rule book that states this is how you MUST do this project, or how you MUST do projects of type X.

Using an AJAX based response is designed to allow your page to load, then to allow the other parts to catch up with it as it does so.

If you think about it for a moment.  What would you do, if you saw a blank white page that took ages to load, versus what you would do if you saw a page with SOME content load then wait while it loaded other sub-content, esp if said page had some kind of "Loading data please wait..." message on it.

Looking at your description, I'd be very confident that your slow down is actually in your Database code, esp as if you say your doing a lot of joins and such like.

It's very easy to determine this, just change your model code to something temporary that returns maybe 10 simple rows with no joins or anything, and see what happens.

Ajax calls by their very nature are not really that special, they are no different to regular calls to a web server in terms of making a HTTP request, that is, it's still the same server, it's still the same network connection and it's still the same latency.

Weather or not you put the view logic into your controller or not is entirely up to you, myself personally I don't have a problem with it, but view logic is all I'll put in, other's opinion will vary.

As for speeding up your database access, well there are a lot of things you can do, but since I don't know anything about your project I can't really tell you whats the best idea, all I can do is give you some pointers.

Some things you can try:

Reduce your joins...  joins are a performance killer in most cases, esp if your using something like codeigniter to generate them.  Instead what you might want to do is look at using a stored procedure in the database, or even better use a view to flatten your rows into a single DTO then from PHP all you have to worry about is that flat model, if your crunching a LOT of data, then try to get the database to do as much of the heavy lifting for you as possible, that's what it's designed for.

Use a faster database server, either software or up the spec of the actual machine if you can...

Use caching...  if your not data change critical, and you can afford for your web UI to be a few seconds behind it's writes, then use memcache or some other caching solution, even if you cache only for a few seconds, on a busy server that can make a huge amount of difference.

Try to make your database calls asynchronous, that is fire off the request to the database, then instead of sitting waiting for it to respond to you, go back to doing other things and set up some kind of a call back so that the database tells you when it's ready. environments such as NodeJS and F# excel at this type of model of operation, so that your not waiting for I/O operations all the time.

I can't tell you 100% how to solve this, as there are far too many unknowns, but the advice I've given should hopefully get you thinking about different approaches and angles to explore.

Title: Slower Ajax Response


问:
If mutual exclusion is not implemented, how would we detect a race condition?
Suppose we are in a distributed environment, and mutual exclusion is not implemented yet. So how would we be able to detect race conditions?

When I researched, use of non-blocking algorithms was found as a solution. That is using datastructures like stack, queue, etc. So that we could avoid mutual exclusion.

But how do we detect it?

答:
Anomalous behavior.  Like inconsistent updates.  Like deadlocks.  Like strange things happening.

Unfortunately, debugging anomalous behavior is DIFFICULT.  You have no way of knowing, other than experience, whether you are dealing with a race condition, or something more mundane.

This is why you design race conditions out, at the very beginning. This is why you design mutual exclusion, or something else that accomplishes similar ends, into your system, from the very beginning.

This is also why operating systems used to be a required class.  It was the one that taught you about concurrency issues, including race conditions, deadlock, and the need for mutual exclusion.


问:
Using a “spherical frustum” for 3D projection
I am currently writing a transformation from model space to clip space for use in OpenGL. From what i have seen, programmers typically use a traditional rectangular frustum to define the clipping boundaries in their model space. I personally had in mind a shape like a frustum, except the near and far planes are spheres centered at the apex of the frustum (the camera). So something that looks like this:

The yellow region corresponds to OpenGL's clip space, and the two spheres (depicted as circles in this cross-section image) correspond to OpenGL's z=-1 (inner sphere) and z=1 (outer sphere).

Is this a more realistic way to model the projection, or should i stick with the traditional rectangular frustum when designing my projection matrix?

答:
Recognize that you are not just clipping against a rectangular window into space, the (angular) edges of which correspond to the boundaries of the screen (or window).

You are also projecting onto a plane, the screen surface.

The traditional clipping pyramid gives you both of these attributes.  Your "spherical pyramid" would require correction from the sphere surface to the screen flatness.


答: Assuming you don't want to really detect race conditions (which IMHO hard with or without mutual exclusion available), but just want to avoid them: if your system does not provide you with some kind of Mutex out-of-the-box, you can implement your own. Wikipedia currently list five different algorithms (for a software solution), just pick your favorite one. Of course, Wikipedia also states that these algorithms don't work in an out-of-order execution environment, bat that's a special issue of your hardware and the compiler you are using.

Title: If mutual exclusion is not implemented, how would we detect a race condition?

Body:
Suppose we are in a distributed environment, and mutual exclusion is not implemented yet. So how would we be able to detect race conditions?

When I researched, use of non-blocking algorithms was found as a solution. That is using datastructures like stack, queue, etc. So that we could avoid mutual exclusion.

But how do we detect it?


问:
Is there already a commonly known name for the 'ensure pattern'?
I use a pattern that I call "ensure" extensively in my repository layer. In short, it does the following when I call an Ensure(...) method:

It uses the arguments in the method to attempt to populate an entity of a specified type (ultimately from the database),

If it finds one then it returns it; f it does not, it saves the entity to the database and return it.

So, my Ensure method ensures that there is always a populated entity with specified properties, irrespective of whether one existed before the call was made.

Is there already a more commonly known name for this pattern?

答:
I believe your name is correct, Microsoft has a method called .GetOrCreate(int id, ...) in the LifetimeContext class located at System.Composition.Hosting namespace (.NET 4.5) that does exactly this.
See here

But, my opinion is that you are in fact implementing a different version of a Multiton Pattern (see here) the only difference from the normal implementation is that instead of having a cache of entities, you are going to the database to check for the "instances", so you could consider changing your method to .GetInstance(int id) or even .GetInstance<T> in a generic repository.

But your name is also correct, like i said, it´s a different approach.


答:
There is a race condition whenever there is a possibility of a resource accessed by two or more entities simultaneously.
Access implies,

If a read/write happens simultaneously as follows

```<code>| Thread A  | Thread B | Problem?                                        |
--------------------------------------------------------------------------
|    Read   |  Read    | No                                              |
|    Read   |  Write   |There is a problem if A reads an obsolete value  |
|    Write  |  Read    |There is a problem if B reads an obsolete value  |
|    Write  |  Write   | There IS a problem. The final value will        |
|           |          | depend upon the last value written/over written |
</code>```

Before Execution:

To pinpoint this in a piece of code one needs experience to understand if the resource will be modified in such a manner
You need to think in all possible direction and develop test cases for the same

After (Several) Executions:

You need to keep an eye open for any unexpected/unexplained output. There are chances the problem lies somewhere else but you need to check if there is simultaneous access occurring somewhere in the code

Body:
There is a race condition whenever there is a possibility of a resource accessed by two or more entities simultaneously.
Access implies,

If a read/write happens simultaneously as follows

| Thread A  | Thread B | Problem?                                        |
--------------------------------------------------------------------------
|    Read   |  Read    | No                                              |
|    Read   |  Write   |There is a problem if A reads an obsolete value  |
|    Write  |  Read    |There is a problem if B reads an obsolete value  |
|    Write  |  Write   | There IS a problem. The final value will        |
|           |          | depend upon the last value written/over written |

Before Execution:

To pinpoint this in a piece of code one needs experience to understand if the resource will be modified in such a manner
You need to think in all possible direction and develop test cases for the same

After (Several) Executions:

You need to keep an eye open for any unexpected/unexplained output. There are chances the problem lies somewhere else but you need to check if there is simultaneous access occurring somewhere in the code


问:
Bucketing model by time
I have a model which has timestamped entities. Now I want to do bucketing - "buckets" of entities which can be reasoned about a single entity. Also I want to be able to access related entities from a bucket and get a bucket of those entities.

My main concerns are an implementation of bucketing itself and architecture of code behind this.

Should I create a separate model for bucketed data, or
should I implement tools to work with the existing model?

As I already have a metamodel with all the subclasses and relations
I'd like to be able to easily add bucketing on top.
I have been thinking about subclassing all the
entity classes to create a bucket-entity class which would
extend their common bucket functionality with traits.

答:
Without knowing your metamodel, assuming that you want to respect it, any response is likely to be flawed. Your problem sounds like it could be solved by different kind of approaches. I'll explain some and you can pick one! ;)

Inheritance
You could create a parent to all objects which implements all methods of the sub-class and features the bucket, a list or map of some kind. The implementation would be up to you.

Using an interface
You could create an interface that offers all the methods you require and then create two kind of objects. Your bucket and the item contained in the bucket. Both would, implementing the interface, expose the methods you need.

Wrapping files
You could use any of the two above while wrapping the files of your project with another object. You could then implement the bucket independently of the object it should hold as you will always just throw the wrapper object into it.

Whatever you choose, all of these have their drawbacks and advantages. As I said before, without knowing more, it is hard to really address your issue.

Title: Bucketing model by time


问:
Why are some classes or methods not "parameter compulsory" in java
Question title can be a little confusing but I didn't have a better way to put to put it.

In Java you can have this:

```<code>JLabel HoHoHo = new JLabel();
...
HoHoHo.setText("Ho Ho Ho");
</code>```

And this:

```<code>JLabel HoHoHo = new JLabel("Ho Ho Ho");
</code>```

In both cases, it gives a label with Ho Ho Ho on it.

Question

How is that possible? I mean, are there to JLabel classes, one with a String parameter and one without?

答:
No there are 2 constructors for the same class. The one without parameter just sets the string to a default value (the empty string).

One way to do this would be:

```<code>public class JLabel extends JComponent{

    private text;

    public JLabel(){
        this("");
    }

    public JLabel(String text){
        this.text=text;
    }
}
</code>```

Body:
No there are 2 constructors for the same class. The one without parameter just sets the string to a default value (the empty string).

One way to do this would be:

public class JLabel extends JComponent{

    private text;

    public JLabel(){
        this("");
    }

    public JLabel(String text){
        this.text=text;
    }
}


答:
This JLabel code from openjdk shows that overloaded constructors are used.

```<code>JLabel() : void
JLabel(String) : void
JLabel(Icon) : void
JLabel(Icon, int) : void
JLabel(String, int) : void
JLabel(String, Icon, int) : void
</code>```

Different forms of the constructor are provided so that you don't have to handle the usual validation. Incase only a single constructor with several parameters was provided by the API e.g. JLabel(String, Icon, int) : void you would have to,

Check number of inputs

Check if they are syntactically correct

etc

Title: Why are some classes or methods not "parameter compulsory" in java

Body:
Question title can be a little confusing but I didn't have a better way to put to put it.

In Java you can have this:

```<code>JLabel HoHoHo = new JLabel();
...
HoHoHo.setText("Ho Ho Ho");
</code>```

And this:

```<code>JLabel HoHoHo = new JLabel("Ho Ho Ho");
</code>```

In both cases, it gives a label with Ho Ho Ho on it.

Question

How is that possible? I mean, are there to JLabel classes, one with a String parameter and one without?

Body:
This JLabel code from openjdk shows that overloaded constructors are used.

JLabel() : void
JLabel(String) : void
JLabel(Icon) : void
JLabel(Icon, int) : void
JLabel(String, int) : void
JLabel(String, Icon, int) : void

Different forms of the constructor are provided so that you don't have to handle the usual validation. Incase only a single constructor with several parameters was provided by the API e.g. JLabel(String, Icon, int) : void you would have to,

Check number of inputs

Check if they are syntactically correct

etc


问:
Why did the team at LMAX use Java and design the architecture to avoid GC at all cost?
Why did the team at LMAX design the LMAX Disruptor in Java but all their design points to minimizing GC use? If one does not want to have GC run then why use a garbage collected language?

Their optimizations, the level of hardware knowledge and the thought they put are just awesome but why Java?

I'm not against Java or anything, but why a GC language? Why not use something like D or any other language without GC but allows efficient code? Is it that the team is most familiar with Java or does Java possess some unique advantage that I am not seeing?

Say they develop it using D with manual memory management, what would be the difference? They would have to think low level (which they already are), but they can squeeze the best performance out of the system as it's native.

答:
They would have to think low level

Above makes half of the answer you're looking for. You can find another half to complete the reasoning no farther than in LMAX blog:

While very efficient, it can lead to a number of errors as it is very easy to screw up...

As admitted by LMAX developers, code like that might be quite difficult to develop, understand and debug - even in Java. Going lower level further than where they are now will only exacerbate this problem, as pointed in Wikipedia article on low level programming languages:

A program written in a low-level language can be made to run very quickly, and with a very small memory footprint; an equivalent program in a high-level language will be more heavyweight. Low-level languages are simple, but are considered difficult to use, due to the numerous technical details which must be remembered.

By comparison, a high-level programming language isolates the execution semantics of a computer architecture from the specification of the program, which simplifies development...


问:
Why do HDFS clusters have only a single NameNode?
I'm trying to understand better how Hadoop works, and I'm reading

The NameNode is a Single Point of Failure for the HDFS Cluster. HDFS is not currently a High Availability system. When the NameNode goes down, the file system goes offline. There is an optional SecondaryNameNode that can be hosted on a separate machine. It only creates checkpoints of the namespace by merging the edits file into the fsimage file and does not provide any real redundancy. Hadoop 0.21+ has a BackupNameNode that is part of a plan to have an HA name service, but it needs active contributions from the people who want it (i.e. you) to make it Highly Available.

from http://wiki.apache.org/hadoop/NameNode

So why is the NameNode a single point of failure? What is bad or difficult about having a complete duplicate of the NameNode running as well?

答:
Update:

There is an option of High Availability now.

The HDFS High Availability feature addresses the SPOF problem by
providing the option of running two redundant NameNodes in the same
cluster in an Active/Passive configuration with a hot standby.

This allows a fast failover to a new NameNode in the case that a machine
crashes, or a graceful administrator-initiated failover for the
purpose of planned maintenance.


答:
LMAX is a High Performance Inter-Thread Messaging Library.

To be useful someone else has to write the code to get each thread to do useful work.   Given that the code is most likely to be in Java or C# and then there are very few chooses of language that interface well with them.

Using C or C++ is not a good option unless you wish to limit your users to a single OS, as there is no threading model defined in them.

Java is the standard for a lot of software development these days, so unless you have a good reason otherwise, it tends to be the best choose.   (When in Rome do as the Romans…)

Writing High Performance software in Java (or C#) is often done to prove a point…

Title: Why did the team at LMAX use Java and design the architecture to avoid GC at all cost?

Body:
Why did the team at LMAX design the LMAX Disruptor in Java but all their design points to minimizing GC use? If one does not want to have GC run then why use a garbage collected language?

Their optimizations, the level of hardware knowledge and the thought they put are just awesome but why Java?

I'm not against Java or anything, but why a GC language? Why not use something like D or any other language without GC but allows efficient code? Is it that the team is most familiar with Java or does Java possess some unique advantage that I am not seeing?

Say they develop it using D with manual memory management, what would be the difference? They would have to think low level (which they already are), but they can squeeze the best performance out of the system as it's native.


答:
Because there is a huge difference between optimizing the performance and turning off completely a safety

By reducing the number of GC, their framework is more responsive and can run (presumably) quicker. Now, optimizing for the garbage collector don't mean they don't ever do a garbage collection. It just mean they do it less often, and when they do it, it run really fast. Those kind of optimization include :

Minimizing the number of object that move to a survivor space (i.e that survived at least one garbage collection) by using small throw-away objects. Object that moved to the survivor space are harder to collect and a garbage collection here sometime imply freezing the whole JVM.

Don't allocate too many objects to begin with. This can backfire if you're not careful, as the young generation objects are super cheap to allocate and collect.

Ensure that new object point to old one (and not the other way around) so that the young object are easy to collect, since there is no reference to them that will cause them to be kept

When you tune out the performance, you usually tune some very specific "hot spot" while ignoring code that don't run often. If you do that in Java, you can let the garbage collector still take care of those dark corner (since it won't make a lot of difference) while optimizing very carefully for area that run in a tight loop. So you can choose where you optimize and where you don't, and you can thus focus your effort where it matter.

Now, if you turn off completely garbage collection, then you can't choose. You must manually dispose of every object, ever. That method get called at most once per day? In Java, you can let it be, as its performance impact is negligible (it may be OK to let a full GC occur every month). In C++, you are still leaking resource, so you must take care even of that obscure method. So you must pay the price for resource management in every, single, part of your application, while in Java you can focus.

But it get worse.

What if you have a bug, let say in a dark corner of your application that is only accessed on Monday on a full moon? Java have strong safety guarantee. There is little to no "undefined behavior".  If you use something wrong, an Exception is thrown, your program stop, and no data corruption occur. So you are pretty sure that nothing wrong can happen without you noticing.

But in something like D, you can have a bad pointer access, or a buffer overflow, and you can corrupt your memory, but your program won't know (you turned the safety off, remember?) and will keep running with its incorrect data, and do some pretty nasty things and corrupt your data, and you don't know, and as more corruption happen, your data get more and more wrong, and then suddenly it break, and it was in a life critical application, and some error happened in the computation of a rocket, and so it doesn't work, and the rocket explode, and someone die, and your company is in the front page of every newspaper and your boss point its finger to you saying "You are the engineer that suggested we used D to optimize performance, how come you didn't think of safety? ". And it is your fault. You killed those people with your foolish attempt at performance.

OK, ok, most of the time it is much less dramatic than that. But even a business critical application or just a GPS app or, let say, a government healthcare website can yield some pretty negative consequence if you have bugs. Using a language that either prevent them completely or fail-fast when they happen is usually a very good idea.

There is a cost to turning off a safety. Going native doesn't always make sense. Sometime it is much simpler and safer to just optimize a bit a safe language that to go all in for a language where you can shoot yourself in the foot big-time. Correctness and safety in a lot of case trump the few nano second you would have scrapped by eliminating the GC completely. Disruptor can be used in those situation, so I think LMAX-Exchange made the right call.

But what about D in particular? You do have a GC if you want for the dark corners, and the SafeD subset (that I didn't know of before the edit) remove undefined behavior (if you remember to use it!).

Well in that case its a simple question of maturity. The Java ecosystem is full of well-written tool and mature libraries (better for development). Much more developers know Java than D (better for maintenance). Going for a new and not-so popular language for something as critical as a financial application would not have been a good idea. With less-known language, if you have a problem, few can help you, and the libraries you find tend to have more bugs since they were exposed to less people.

So my last point still hold: if you want to avoid problems with dire consequences, stick with safe choices. At this point in the life of D, its customer are the little start-ups ready to take crazy risks. If a problem can cost millions, you are better staying further in the innovation bell curve.


问:
How to design application with rollback capability
I am currently working on an application (basically its a kind of execution engine capable of running user defined jobs and generate output in real time) that needs to handle rollback functionality, it might sound crazy but is it possible to have such thing at the application level? e.g. imagine some user tries run a job J1 and once it is started to execute he wanted to Edit/Modify it ,

 - that means the current running job has to be killed,

- all the action taken so far must be reverted and

- re-run the job J1 again

few things that comes in my mind is we must anyhow store or maintain application states somehow, somewhere and then call the rollback stuff along with the previous save points. I was reading few articles on DB level rollback but the scenario does not fit in this case as
it need to work on a real time environment.

But I am unable to find a proper approach as to how to proceed and what else should be taken into considerations.
Please let me know if this sounds unclear, I shall try to provide more info if possible.

Any help or advice?

答:
Real time system or not, the memento pattern is an excellent place to start.

The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo via rollback).

  The memento pattern is implemented with three objects: the originator, a caretaker and a memento.

  The originator is some object that has an internal state.

  The caretaker is going to do something to the originator, but wants to be able to undo the change. The caretaker first asks the originator for a memento object. Then it does whatever operation (or sequence of operations) it was going to do.

  To roll back to the state before the operations, it returns the memento object to the originator.

  The memento object itself is an opaque object (one which the caretaker cannot, or should not, change).

  When using this pattern, care should be taken if the originator may change other objects or resources - the memento pattern operates on a single object.

I broke up the Wikipedia article a bit in order to draw focus on some items.

For your scenario, the originator is going to be your primary application code, most likely at the point where jobs are registered and start processing.

The caretaker is what you need to create and could be some kind of logging system or other data store.

The memento is going to be the relevant information that needs to be undone and / or redone.  I suspect this will look like a job description of some sort that can be placed back onto the processing queue.

If you can wrap the existing changes from the job J1 with a database transaction, that will take care of your rollback concerns (all the action taken so far must be reverted).  When a transaction rollback occurs, you would trigger a call to the Caretaker in order to re-queue job J1.

One thing to keep in mind is that last warning in the Wikipedia summary.  You need to make sure that the changes are atomic and that they can be applied or rolled back as a cohesive set.

I'm not sure that being in a real time environment will have much impact upon how you implement the memento pattern.  If there are deadlines for activities, then you may need to profile some of the changes in order to make sure the system responds in an appropriate amount of time.  I think I would implement the functionality first and then verify you are meeting your other application requirements.  I don't foresee you running into anything that would invalidate what you have described so far.


问:
SQL Query syntax - formatting?
I'm looking at a very large (5-6 digit LOC), very complex, code-base, full of interacting bulky, interdependent, views and stored procedures (multiple 4-5 digit count silos).

The source SQL has been touched many times, by many different people, and no formatting constraints have been enforced. This led to wildly differing formatting for SQL, even within single stored procedure/view definitions.

The code continues to be worked on by several groups of, mostly, senior programmers, and sees a steady stream of small changes and improvements.

Under these conditions:

a. what is a sane standard to conform to for formatting (eg, should we use all caps for keywords? seems like the small benefits from having so many programmers not have to press Shift actually add up to significant time/cost savings)

b. is it worthwhile advocating for a major refactor to standardize the formatting (ie, is the cost of training a large body of programmers/changing their behaviour/ill will at enforcing a new constraint worth the benefit in the long-term?)

答: Agree to a sensible coding standard for future work, and fix the problem SQL as needed during refactoring.  Leave intact all of the code that is working that otherwise doesn't need to be touched.</p>

Title: SQL Query syntax - formatting?


问:
Effective way to estimate dead code removal?
I've been working in an application with about 100k LOCs and basically We have been reworking features to comply with a new architecture based on a new technology stack. This work is almost finished but we had to keep the old code because we had to guarantee a stable environment in case of critical bugs in the new .

This has lead to a situation where we have a lot of dead code that mixes with a lot of working code thus making difficult to estimate how much time it would take to remove this dead code.

This codebase in particular is very troublesome as it does not have unit/integration testing other than the one generated in the process of reworking the features we migrated to the new architecture and also I think that a great deal of the new code is interwoven with the dead code (by static calls, using the previously thrown exceptions).

What would be a good start point to estimate how long would it take to safely remove the code?

答:
Each project is going to be different so there is not an effective way to estimate the time to remove dead code.  Needing to keep the old code sounds like you lack a quality source control system that allows you to branch.

In any case: Tools like SonarQube can help identify some dead code, but won't find things like a class that is never used.  I would suggest tackling a portion of the code by hand with the help of SonarQube and develop estimates as you go.  If you work through 20% of the classes and it takes 2 weeks then you can estimate an additional 8 more weeks to do the rest.

Also, having some sort of automated testing will help prevent you find code that is mistakenly deleted faster.


答:
How much is your company worth?

No, seriously.  How much?

Because Knight Capital failed to practice good housekeeping with their systems.  And that led to a glitch that ended with their being acquired at firesale prices.

Either the code is dead, or it isn't.  If it is dead, then get rid of it.  If it isn't, you need to know what's calling the code and make the necessary changes so you can kill off the old code.

If you don't know for sure that it's dead, then either profile your code or make it throw obnoxious, impossible-to-miss errors when those presumed-to-be-dead code paths are hit.

Estimating time / cost for that removal depends upon how well structured the code is to begin with.  If the new code is well isolated from the old code, then it should be a minimal cost to change out.  If you haven't isolated your code, then it's hard to predict how tangled things are.  The more tangled it is, the higher your costs and time.

Title: Effective way to estimate dead code removal?

Body:
I've been working in an application with about 100k LOCs and basically We have been reworking features to comply with a new architecture based on a new technology stack. This work is almost finished but we had to keep the old code because we had to guarantee a stable environment in case of critical bugs in the new .

This has lead to a situation where we have a lot of dead code that mixes with a lot of working code thus making difficult to estimate how much time it would take to remove this dead code.

This codebase in particular is very troublesome as it does not have unit/integration testing other than the one generated in the process of reworking the features we migrated to the new architecture and also I think that a great deal of the new code is interwoven with the dead code (by static calls, using the previously thrown exceptions).

What would be a good start point to estimate how long would it take to safely remove the code?


答:
what is a sane standard to conform to for formatting [SQL] ?

Something that you can express in programmatic form, so that you can send a text file to a program and know if the format is "standard" or not.

Ideally, the rules you care about will be the kind you can automatically impose on a non-standard file or block of text, such as "capitalize all keywords" or "wrap each field on its own line."

is it worthwhile advocating for a major refactor to standardize the formatting?

No.  If the code isn't broken, and you're not making an improvement in the final result, you don't want to touch it and risk breaking it.

As an aside, the benefit of code standards is NOT to increase write-time productivity.  Rather, a good formatting standard will reduce the time it takes for a programmer to look at code they haven't touched in awhile, if ever, and see what's going on.

Title: SQL Query syntax - formatting?

Body:
I'm looking at a very large (5-6 digit LOC), very complex, code-base, full of interacting bulky, interdependent, views and stored procedures (multiple 4-5 digit count silos).

The source SQL has been touched many times, by many different people, and no formatting constraints have been enforced. This led to wildly differing formatting for SQL, even within single stored procedure/view definitions.

The code continues to be worked on by several groups of, mostly, senior programmers, and sees a steady stream of small changes and improvements.

Under these conditions:

a. what is a sane standard to conform to for formatting (eg, should we use all caps for keywords? seems like the small benefits from having so many programmers not have to press Shift actually add up to significant time/cost savings)

b. is it worthwhile advocating for a major refactor to standardize the formatting (ie, is the cost of training a large body of programmers/changing their behaviour/ill will at enforcing a new constraint worth the benefit in the long-term?)


问:
What design pattern matches this problem the closest?
I have two objects, one is a User object and the other is a Content object. The User object has properties like 'reads_articles' or 'reads_books'. The Content object has properties like 'is_article' or 'is_book'. If the two properties match up (i.e. the User reads_articles and the Content is_article), then the User can see the Content. Basically, I am looking for the best solution to approach this without using a switch() statement.

I am also wondering if maybe I'm making this too difficult and/or a design pattern is overkill here. Preliminary research has suggested that the Strategy pattern may be the most appropriate, but I'm having a hard time modeling this problem to that pattern. I don't want to hard code the tests - I would really like to come up with a general solution that examines the properties of both classes, and determines whether the Content can be viewed by that User.

Clarification: My end goal is an algorithm that will examine the properties of the User and the properties of the Content, and see if they match. Basically, I want to see if the two objects have matching properties (without hardcoding the properties themselves into the algorithm) and do some actions.

Not sure if what I want is a pipe dream, so I thought I would ask. Thanks for the help!

答:
You can check to see if an item is a member of a set by using in_array.

So, for example, if your user reads articles and books, the user object's "reads these things" array will contain 'articles' and 'books' (or their coded numerical equivalent), and you can have a method on the user object called ReadsContent() that accepts a content type as a parameter
and returns true or false based on whether that content type is in_array.


答:
Basically, I want to see if the two objects have matching properties (without hardcoding the properties themselves into the algorithm) and do some actions.

Yes, this helps.  The assumption-based answer I started on wouldn't have sufficed.  But KISS - keep it stupid simple - still applies here, IMO.  Keep it short and to the point, no need to force it into a design pattern if it doesn't naturally fit.

Lets use a special language feature to our advantage.  PHP allows you to call dynamic access to attributes, with names stored as strings in variables.  It's often frowned upon in PHP, but is also sometimes the simplest solution.  For example, in this pseudocode:

```<code>$attribs = array(
   array('User' => 'reads_articles', 'Content' => 'is_article'),
   array('User' => 'reads_books', 'Content' => 'is_book'),
);

class User {
   function can_access(Content) {
      foreach ($attribs as $reqs) {
         if (!property_exists(self, $reqs['User'])) {
            throw Exception("User is missing {$reqs['User']}");
         }
         if (!property_exists(Content, $reqs['Content'])) {
            throw Exception("Content is missing {$reqs['Content']}");
         }
         if (self->{$reqs['User']} && Content->{$reqs['Content']}) {
            return true;
         }
      }
      return false;
   }

   reads_articles = true;
   reads_books = true;
}
</code>```

(Warning:  Untested, and I know I have some of the syntax wrong (such as not actually naming the Content argument, and I doubt the scope is right).)

There's 3 possible sources for $attribs that I can think of.  Here's some further thoughts on each:

Hardcoded in the source, as above

Advantages:  It's right there.  For maintenance, very easy to see where it's coming from.  Even in another file, you don't have to mentally switch context to get it.

Disadvantages:  It's static.  All the User and Content classes have to define every single one, unless can_access is modified to accept that "missing" means "false".

Loaded from a database table

Advantages:  Simply put, it's a lot more flexible and easier to extend in the future since the interface to use the database is already there.

Disadvantages:  Reading the code, you now have to also look at the database to figure out which attributes will be used together.  It's also easier to overlook when adding a new one.

Inferred through reflection, examining the class(es)

Advantages:  New attributes are automatically included, and the "rules" for determining which ones go together are pretty straightforward.

Disadvantages:  The rules for pairing attributes could just be skin-deep (is_letter / sends_letters does not fit, for example), and there's a chance they can match something they're not supposed to anyway.  "Meta" programming like this is also less obvious than the other two, since it tends to be used less often, so it should be documented pretty well.

The disadvantages to using a database are so small that that's the way I'd go with it, unless I was very sure this set of attributes was unlikely to change or the project doesn't already have a database - then I might go with the first option, hardcoding somewhere.  At least with it already in a semi-tabulated form like that, it would be simple to convert to a database table if needed.

Inferring it through pattern matching has to be really well-defined, so I'd avoid that as much as possible.  It IMO falls into the "neat trick" category that's rarely more useful than other methods, do to the possibility of false positives and likely needing extra documentation.

Now, there is a halfway option that I think should be used instead of attributes directly on the class:

```<code>class User {
   $permissions = array(
      'reads_articles' => true,
      'reads_books' => true,
   );
}
</code>```

This way, there's no overlap with the normal User attributes, and it's obvious which ones are important.  The caveats about how to pair these with the ones on Content still applies, so one of the former 3 methods would still be necessary.  However, from the question, I'm not sure if this would work for what you have in mind.

(Side note, since it may not be obvious - I'm trying to keep this slightly generic, since I'm not sure if the permissions you speak of are at the class level or instance level.  Almost all of the above can be done either way.)

Title: What design pattern matches this problem the closest?

Body:
I have two objects, one is a User object and the other is a Content object. The User object has properties like 'reads_articles' or 'reads_books'. The Content object has properties like 'is_article' or 'is_book'. If the two properties match up (i.e. the User reads_articles and the Content is_article), then the User can see the Content. Basically, I am looking for the best solution to approach this without using a switch() statement.

I am also wondering if maybe I'm making this too difficult and/or a design pattern is overkill here. Preliminary research has suggested that the Strategy pattern may be the most appropriate, but I'm having a hard time modeling this problem to that pattern. I don't want to hard code the tests - I would really like to come up with a general solution that examines the properties of both classes, and determines whether the Content can be viewed by that User.

Clarification: My end goal is an algorithm that will examine the properties of the User and the properties of the Content, and see if they match. Basically, I want to see if the two objects have matching properties (without hardcoding the properties themselves into the algorithm) and do some actions.

Not sure if what I want is a pipe dream, so I thought I would ask. Thanks for the help!

Body:
Basically, I want to see if the two objects have matching properties (without hardcoding the properties themselves into the algorithm) and do some actions.

Yes, this helps.  The assumption-based answer I started on wouldn't have sufficed.  But KISS - keep it stupid simple - still applies here, IMO.  Keep it short and to the point, no need to force it into a design pattern if it doesn't naturally fit.

Lets use a special language feature to our advantage.  PHP allows you to call dynamic access to attributes, with names stored as strings in variables.  It's often frowned upon in PHP, but is also sometimes the simplest solution.  For example, in this pseudocode:

$attribs = array(
   array('User' => 'reads_articles', 'Content' => 'is_article'),
   array('User' => 'reads_books', 'Content' => 'is_book'),
);

class User {
   function can_access(Content) {
      foreach ($attribs as $reqs) {
         if (!property_exists(self, $reqs['User'])) {
            throw Exception("User is missing {$reqs['User']}");
         }
         if (!property_exists(Content, $reqs['Content'])) {
            throw Exception("Content is missing {$reqs['Content']}");
         }
         if (self->{$reqs['User']} && Content->{$reqs['Content']}) {
            return true;
         }
      }
      return false;
   }

   reads_articles = true;
   reads_books = true;
}

(Warning:  Untested, and I know I have some of the syntax wrong (such as not actually naming the Content argument, and I doubt the scope is right).)

There's 3 possible sources for $attribs that I can think of.  Here's some further thoughts on each:

Hardcoded in the source, as above

Advantages:  It's right there.  For maintenance, very easy to see where it's coming from.  Even in another file, you don't have to mentally switch context to get it.

Disadvantages:  It's static.  All the User and Content classes have to define every single one, unless can_access is modified to accept that "missing" means "false".

Loaded from a database table

Advantages:  Simply put, it's a lot more flexible and easier to extend in the future since the interface to use the database is already there.

Disadvantages:  Reading the code, you now have to also look at the database to figure out which attributes will be used together.  It's also easier to overlook when adding a new one.

Inferred through reflection, examining the class(es)

Advantages:  New attributes are automatically included, and the "rules" for determining which ones go together are pretty straightforward.

Disadvantages:  The rules for pairing attributes could just be skin-deep (is_letter / sends_letters does not fit, for example), and there's a chance they can match something they're not supposed to anyway.  "Meta" programming like this is also less obvious than the other two, since it tends to be used less often, so it should be documented pretty well.

The disadvantages to using a database are so small that that's the way I'd go with it, unless I was very sure this set of attributes was unlikely to change or the project doesn't already have a database - then I might go with the first option, hardcoding somewhere.  At least with it already in a semi-tabulated form like that, it would be simple to convert to a database table if needed.

Inferring it through pattern matching has to be really well-defined, so I'd avoid that as much as possible.  It IMO falls into the "neat trick" category that's rarely more useful than other methods, do to the possibility of false positives and likely needing extra documentation.

Now, there is a halfway option that I think should be used instead of attributes directly on the class:

class User {
   $permissions = array(
      'reads_articles' => true,
      'reads_books' => true,
   );
}

This way, there's no overlap with the normal User attributes, and it's obvious which ones are important.  The caveats about how to pair these with the ones on Content still applies, so one of the former 3 methods would still be necessary.  However, from the question, I'm not sure if this would work for what you have in mind.

(Side note, since it may not be obvious - I'm trying to keep this slightly generic, since I'm not sure if the permissions you speak of are at the class level or instance level.  Almost all of the above can be done either way.)