问:
Why prefer non-static inner classes over static ones?
This question is about whether to make a nested class in Java to be a static nested class or an inner nested class. I searched around here and on Stack Overflow, but couldn't really find any questions regarding the design implications of this decision.

The questions I found are asking about the difference between static and inner nested classes, which is clear to me. However, I have not yet found a convincing reason to ever use a static nested class in Java -- with the exception of anonymous classes, which I do not consider for this question.

Here's my understanding of the effect of using static nested classes:

Less coupling: We generally get less coupling, as the class cannot directly access its outer class's attributes. Less coupling generally means better code quality, easier testing, refactoring, etc.

Single Class: The class loader need not take care of a new class each time, we create an object of the outer class. We just get new objects for the same class over and over.

For an inner class, I generally find that people consider access to the outer class's attributes as a pro. I beg to differ in this regard from a design point of view, as this direct access means we have a high coupling and if we ever want to extract the nested class into its separate top-level class, we can only do so after essentially turning it into a static nested class.

So my question comes down to this: Am I wrong in assuming that the attribute access available to non-static inner classes leads to high coupling, hence to lower code quality, and that I infer from this that (non-anonymous) nested classes should generally be static?

Or in other words: Is there a convincing reason why one would prefer a nested inner class?

答:
Some misconceptions:

Less coupling: We generally get less coupling, as the [static inner] class cannot
  directly access its outer class's attributes.

IIRC - Actually, it can. (Of course if they are object fields, it will not have an outer object to look at. Nonetheless, if it does get such an object from anywhere, then it can directly access those fields).

Single Class: The class loader need not take care of a new class each
  time, we create an object of the outer class. We just get new objects
  for the same class over and over.

I'm not quite sure what you mean here. The class loader is only involved twice in total, once for each class (when the class is loaded).

Rambling follows:

In Javaland we seem to be a bit scared to create classes. I think it has to feel like a significant concept. It generally belongs in its own file. It needs significant boilerplate. It needs attention to its design.

Versus other languages - eg Scala, or maybe C++: There is absolutely no drama creating a tiny holder (class, struct, whatever) anytime that two bits of data belong together. Flexible access rules help you by cutting down the boilerplate, letting you keep the related code physically closer. This reduces your 'mind-distance' between the two classes.

We can wave away design concerns over the direct access, by keeping the inner class private.

(...If you'd asked 'why a non-static public inner class?' that's a very good question - I don't think I've ever yet found a justified case for those).

You can use them anytime it helps with code readability and avoiding DRY violations and boilerplate. I don't have a ready example because it doesn't happen all that often in my experience, but it does happen.

Static inner classes is still a good default approach, btw. Non-static has an extra hidden field generated through which the inner class refers to the outer.

ContentLicense: CC BY-SA 4.0


问:
REST API security Stored token vs JWT vs OAuth
I am still trying to find the best security solution for protecting REST API, because the amount of mobile applications and API is increasing every day.

I have tried different ways of authentication, but still has some misunderstandings, so I need advice of someone more experienced.

Let me tell, how I understand all this stuff. If I understand something incorrectly, please let me know.

As far as REST API is stateless as well as WEB in general, we need to send some auth data in each request(cookies, token....). I know three widely used mechanisms to authenticate user

Token with HTTPS. I have used this approach a lot of times it is good enough with HTTPS. If user provides correct password and login, he will receive token in response, and will use it for the further requests. Token is generated by the server and stored, for instance in the table separate or the same where user info is stored. So for each request server checks if user has token and it is the same as in the database. Everything is pretty straightforward.

JWT Token. This token is self-descriptive, it contains all necessary information about the token itself, user cannot change for example expiration date or any other claim, because this token is generated (signed) by the server with secret keyword. This is also clear. But one big problem, personally for me, how to invalidate token.

OAuth 2. I don't understand why this approach should be used when communication is established directly between server and client. As far as I understand, OAuth server is used to issue token with restricted scope to allow other applications access user information without storing password and login. This is great solution for the social networks, when user wants to sign up on some page, server can request permissions to get user info, for instance from twitter or facebook, and fill registration fields with user data and so on.

Consider mobile client for online store.

First question should I prefer JWT over first type token ? As far as I need login/logout user on mobile client, I need to store somewhere token or in case of JWT, token should be invalidated on logout. Different approaches are used to invalidate token one of the is to create invalid token list (black list). Hmm. Table/file will have much bigger size than if token was stored in table and associated with user, and just removed on logout.

So what are benefits of JWT token ?

Second question about OAuth , should I use it in case of direct communication with my server?  What is the purpose of one more layer between client and server only to issue token, but communication will be not with oauth server but with the main server. As I understand OAuth server is responsible only for giving third-party apps permissions (tokens) to access user private information. But my mobile client application is not third-party.

答:
You can handle the JWT issues you mentioned by storing a salt value along with the user and using the salt as part of the token for the user. Then when you need to invalidate the token, just change the salt.

I know it's been a couple of years but I would actually do this differently now. I think I would ensure that access tokens had a relatively short-lived lifetime, say an hour.  I'd also be sure to use refresh tokens that were stateful on the server and then when I wanted to end someone's session, I would revoke the refresh token by removing it from the server. Then after an hour, the user would be logged out and would have to log in again to regain access.

ContentLicense: CC BY-SA 3.0


问:
Simple Javascript Validation not working
I am trying to do the following:

HTML Code

```<code><body>
    <form name="myform">
    <table>
        <tr>
            <td>First Name:</td>
            <td><input type="text" id="first_name"></td>
            <td><p id="demo"></p></td>
        </tr>
        <tr>
            <td><input type="submit" id="Submit" onclick="validate()"></td>
        </tr>
    </form></body>
</code>```

JavaScript Code

```<code><script>
    function validate(){

        var fname = document.getElementById("first_name").value;
        if(fname.length>0){
            document.getElementById("demo").value="";
        }
        else{
            document.getElementById("demo").value="Name field empty";
        }
    }
    </script>
</code>```

when I click the button with the empty First name field it should assign "name field empty" but it does not do that even though the control of the script goes there but it does not print anything in the
 tag.

答:
While I agree there is a better place to ask this question, that still doesn't mean you shouldn't get an answer.

To explain your problem, your trying to set the value of an HTML tag, but it isn't the value that you need to set.  You need to target the inner HTML of that element instead.

try this

```<code>document.getElementById("demo").innerHTML = "Name field empty";
</code>```

Also here is a reference to some documentation

Body:
While I agree there is a better place to ask this question, that still doesn't mean you shouldn't get an answer.

To explain your problem, your trying to set the value of an HTML tag, but it isn't the value that you need to set.  You need to target the inner HTML of that element instead.

try this

document.getElementById("demo").innerHTML = "Name field empty";

Also here is a reference to some documentation


问:
What are the drawbacks of elastic tabstops?
Look here: a typical holy war on tabs vs spaces.

Now look here: elastic tabstops. All problems solved, and a bunch of very useful new behaviours added.

Are elastic tabstops even mentioned in that tabs vs spaces discussion? Why not? Are there drawbacks to the elastic tabstop idea so serious that nobody has ever implemented them in a popular editor?

EDIT: I apologise for putting too much emphasis on "why aren't they mentioned". That wasn't really what I intended; that question is possibly even off topic. What I really mean is, what are the biggest drawbacks of this that prevent wider adoption of an obviously beneficial idea? (in an ideal world where everything supports it already)

(Turns out there's already a request on the Microsoft Connect for a Visual Studio implementation of elastic tabstops, and a request in Eclipse too. Plus there's a question asking about other editors that implement elastic tabstops)

答:
I just tried out jEdit's implementation of elastic tabstops, which works amazingly well with the programming languages in with which I'm familiar (primarily HTML/XML and C-like languages). With Python code, however, here is how it rendered (spaces used in place of tabs to illustrate how things align):

def foo(x):
             '''<1 tab before the docstring.
No tab       <tab
No tab       <tab
             <tab  <another tab
             <tab  <another tab
             <tab'''
             if 1 or 2:    #<Tab before this comment
                           yield True
```

<p>For a language like Python that relies upon spacing, this is a deal-breaker unless you disable the functionality provided by elastic tabstops. Editors like Vim and Emacs make disabling most kinds of functionality simple if you know the name of the option and how to disable it, but this functionality would be required to be disabled for code like the above.</p>

<p>That being said, it's great for x86 ASM, C, C++, Go, XML, HTML, and others that don't rely on whitespace so much:</p>

<pre class="lang-go prettyprint-override"><code>import (
    "fmt"    // We love formatting functions.
    "io"     // Because I/O is useful.
    "os"     // Can't open a file without os.Open!
)

type Foo struct {
    Field1              int          // This is properly aligned
    ReallyLongField2    string       // with this.
    privateField        io.Reader    // Elastic tabstops are great for Go.
}
</code>```

I will say that Lisp dialects such as Scheme have their own conventions that would also make elastic tabstops render "ugly" code. If I change my tabstop settings to match the convention of 2 columns and insert tabstops at unusual places (between a function and its arguments):

(let loop ((n 1))
  (if  (> n 10)
        '()
        (cons  n
               (loop (+ n 1)))))
```

<p>vs. the more readable:</p>

<pre class="lang-lisp prettyprint-override"><code>(let loop ((n 1))
  (if (> n 10)
      '()
      (cons n
            (loop (+ n 1)))))
</code>```

Granted, this one isn't as bad as the Python example, but it definitely reduces readability of the code. While I very much enjoy the functionality when coding in something like C# or C++, I abhor the functionality when coding in a language like Python or Scheme where whitespace is functional and/or visually helpful. Elastic tabstops were created specifically to be helpful without requiring a separate indentation utility, but clearly it's not meant for all programming languages.

Body:
I just tried out jEdit's implementation of elastic tabstops, which works amazingly well with the programming languages in with which I'm familiar (primarily HTML/XML and C-like languages). With Python code, however, here is how it rendered (spaces used in place of tabs to illustrate how things align):

def foo(x):
             '''<1 tab before the docstring.
No tab       <tab
No tab       <tab
             <tab  <another tab
             <tab  <another tab
             <tab'''
             if 1 or 2:    #<Tab before this comment
                           yield True

For a language like Python that relies upon spacing, this is a deal-breaker unless you disable the functionality provided by elastic tabstops. Editors like Vim and Emacs make disabling most kinds of functionality simple if you know the name of the option and how to disable it, but this functionality would be required to be disabled for code like the above.

That being said, it's great for x86 ASM, C, C++, Go, XML, HTML, and others that don't rely on whitespace so much:

import (
    "fmt"    // We love formatting functions.
    "io"     // Because I/O is useful.
    "os"     // Can't open a file without os.Open!
)

type Foo struct {
    Field1              int          // This is properly aligned
    ReallyLongField2    string       // with this.
    privateField        io.Reader    // Elastic tabstops are great for Go.
}

I will say that Lisp dialects such as Scheme have their own conventions that would also make elastic tabstops render "ugly" code. If I change my tabstop settings to match the convention of 2 columns and insert tabstops at unusual places (between a function and its arguments):

(let loop ((n 1))
  (if  (> n 10)
        '()
        (cons  n
               (loop (+ n 1)))))

vs. the more readable:

(let loop ((n 1))
  (if (> n 10)
      '()
      (cons n
            (loop (+ n 1)))))

Granted, this one isn't as bad as the Python example, but it definitely reduces readability of the code. While I very much enjoy the functionality when coding in something like C# or C++, I abhor the functionality when coding in a language like Python or Scheme where whitespace is functional and/or visually helpful. Elastic tabstops were created specifically to be helpful without requiring a separate indentation utility, but clearly it's not meant for all programming languages.


问:
Are there areas where TDD provides a high ROI and other areas where the ROI is so low that it is not worth following?
Test driven development. I get it, like it.

But writing tests does require overhead. So should TDD be used universally throughout the code base, or are there areas where TDD provides a high ROI and other areas where the ROI is so low that it is not worth following.

答:
One place where TDD really sucks hard is when testing views in an MVC app.

Since you are testing a function that returns a fat html string, your are stuck doing html parsing just to see if stuff worked out. Moreover, it can become a maintainability nightmare. One day you move a checkbox around and kaboom, your test is broken.

I like TDD for lots of my testing, but it is not the only tool in a programmers belt.

ContentLicense: CC BY-SA 2.5


问:
What is the best data model to represent mathematical range (in database, xml, json...)?
For example,

greater or equal to 50 and smaller than 100 (>=50 && < 100)

smaller than 10 or greater than 40 (<10 || >40)

I have been thinking about how to represent mathematical range in a file and database, the range may be input by non programmer and I need to keep the input simple, but at another side, it also need to keep the input easy to convert to data and easy to check error input e.g.: <10 || >100 seems the most simple but it is harder for me to parse the string to get the data, also need to consider input format error

I have been considering some input methods, using >=50 && < 100 as example, which is in key value form:

Using one string to represent whole range:

```<code><rangeInString>=50 && < 100</rangeInString>
</code>```

Separate two strings, one represent lower bound and another one represent upper bound, then parse each string in program:

```<code><lowerBound> >=50 </lowerBound>
<upperBound> <100 </upperBound>
</code>```

Separate lower and upper bound, also separate the sign from number:

```<code><lowerBound>
  <sign> >= </sign>
  <data>50</data>
</lowerBound>
<upperBound>
  <sign> < </sign>
  <data>100</data>
</upperBound>
</code>```

Separate lower bound and upper bound,also separate sign, and also separate the case that if includes the equal condition:

```<code><lowerBound>
  <sign> > </sign>
  <isIncludeEqual>true</isIncludeEqual>
  <data>50</data>
</lowerBound>
<upperBound>
  <sign> < </sign>
  <isIncludeEqual>false</isIncludeEqual>
  <data>100</data>
</upperBound>
</code>```

auto detect using && or ||, e.g. :>= A with < B,if A < B, must be && e.g. (>= 50 && <100), otherwise it is || e.g. (>= 100 || <50):

```<code><A>
  <sign> > </sign>
  <isIncludeEqual>true</isIncludeEqual>
  <data>50</data>
</A>
<B>
  <sign> < </sign>
  <isIncludeEqual>false</isIncludeEqual>
  <data>100</data>
</B>
</code>```

Use a field "isAnd" to separate >=50 && < 100 (true) and <=50 || > 100 (false) instead of using field sign "<" and ">" :

```<code><lowerBound>
  <isIncludeEqual>true</isIncludeEqual>
  <data>50</data>
</lowerBound>
<upperBound>
  <isIncludeEqual>false</isIncludeEqual>
  <data>100</data>
</upperBound>
<isAnd>true</isAnd>
</code>```

other data model...

I need to consider somethings:

easy for non programmer to input

easy to convert or parse to data into program

easy to check error, for example,parse string increase the complexity of converting data and checking incorrect format, also there may have other incorrect format,e.g.: <=50 && >100 should not be valid, I may allow auto detect using && or || by the sign of input, but it may increase the complexity of the code

答:
If you're working solely with integer ranges, you're probably over-thinking the problem. All you need to store is the lower bound and the upper bound, and use a fixed rule about whether the bounds are inclusive. For example, Python ranges tend to use a half-closed interval, so that:

```<code>range(5,10)
</code>```

Is what mathematicians would write as:

```<code>[5, 10)         # interval notation
5 <= x < 10     # inequality notation
5, 6, 7, 8, 9   # list notation
</code>```

This is easily encoded into XML, JSON, or database values. E.g.:

```<code><range low="5" high="10"/>   # XML
[5, 10]                      # simple list (brackets are data delimiters,
                                            not mathematical interval notation)
{ "low": 5, "high": 10 }     # JSON fragment
</code>```

It's very easy to take a fixed set of rules, which seems very rigid, and get back whatever you want. For example, if you really wanted the 10 high bound included, then don't provide lots of additional flexibility machinery and complexity (which costs extra data encoding bytes, testing requirements, and code complexity). Just encode it as:

```<code><range low="5" high="11"/>  # XML

range(5, 11)                # Python
</code>```

If you don't like the asymmetry of a half-open interval, there's no reason you can't choose a fully closed / inclusive interval, or any other option (i.e., fully open interval, or half-open at the start interval). The trick is choosing a rule that is consistent throughout, and is most consistent / convenient with your programming environment.

This representation nicely handles finite ranges. It's very compact, can be implemented in a very performance-efficient way, and if you'd like extended operations, can be easily implemented as a neat class in Java, Python, and many other languages.

You also seem to want to represent discontinuous, infinite sets such as x < 10 ∪ x > 40. Those are generally not considered "ranges" by most programming languages / systems, and indeed aren't even intervals in the mathematical sense. But they're obviously interesting adjacent concepts to consider--though it will add notable complexity to the implementation.

For example. your disjoint set can be specified as a "multi-range," a combination of individual ranges:

```<code><union>
    <range low="-Infinity" high="10"/>
    <range low="41" high="Infinity"/>
</union>
</code>```

Now you've had to add handling for abstract values (negative and positive infinity) as well as a set combining operation (union) as the multi-range constructor. But, I've read the source of a number of numerical set and multi-range modules, and this is actually how many of them do it.

When you get going down this path of generalizing from individual intervals / ranges to multi-interval, multi-range sets, you may also start to generalize the set operations into other constructive formulations. If you do union, why not intersection, difference, and symmetric-difference as well? Your disjoint range could also be specified alternatively as:

```<code><difference>
    <range low="-Infinity" high="Infinity"/>
    <range low="10" high="41"/>
</difference>
</code>```

But you've got to be careful, because the more operations and the more complexity, the greater chance of errors creeping in.

Body:
If you're working solely with integer ranges, you're probably over-thinking the problem. All you need to store is the lower bound and the upper bound, and use a fixed rule about whether the bounds are inclusive. For example, Python ranges tend to use a half-closed interval, so that:

range(5,10)

Is what mathematicians would write as:

[5, 10)         # interval notation
5 <= x < 10     # inequality notation
5, 6, 7, 8, 9   # list notation

This is easily encoded into XML, JSON, or database values. E.g.:

<range low="5" high="10"/>   # XML
[5, 10]                      # simple list (brackets are data delimiters,
                                            not mathematical interval notation)
{ "low": 5, "high": 10 }     # JSON fragment

It's very easy to take a fixed set of rules, which seems very rigid, and get back whatever you want. For example, if you really wanted the 10 high bound included, then don't provide lots of additional flexibility machinery and complexity (which costs extra data encoding bytes, testing requirements, and code complexity). Just encode it as:

<range low="5" high="11"/>  # XML

range(5, 11)                # Python

If you don't like the asymmetry of a half-open interval, there's no reason you can't choose a fully closed / inclusive interval, or any other option (i.e., fully open interval, or half-open at the start interval). The trick is choosing a rule that is consistent throughout, and is most consistent / convenient with your programming environment.

This representation nicely handles finite ranges. It's very compact, can be implemented in a very performance-efficient way, and if you'd like extended operations, can be easily implemented as a neat class in Java, Python, and many other languages.

You also seem to want to represent discontinuous, infinite sets such as x < 10 ∪ x > 40. Those are generally not considered "ranges" by most programming languages / systems, and indeed aren't even intervals in the mathematical sense. But they're obviously interesting adjacent concepts to consider--though it will add notable complexity to the implementation.

For example. your disjoint set can be specified as a "multi-range," a combination of individual ranges:

<union>
    <range low="-Infinity" high="10"/>
    <range low="41" high="Infinity"/>
</union>

Now you've had to add handling for abstract values (negative and positive infinity) as well as a set combining operation (union) as the multi-range constructor. But, I've read the source of a number of numerical set and multi-range modules, and this is actually how many of them do it.

When you get going down this path of generalizing from individual intervals / ranges to multi-interval, multi-range sets, you may also start to generalize the set operations into other constructive formulations. If you do union, why not intersection, difference, and symmetric-difference as well? Your disjoint range could also be specified alternatively as:

<difference>
    <range low="-Infinity" high="Infinity"/>
    <range low="10" high="41"/>
</difference>

But you've got to be careful, because the more operations and the more complexity, the greater chance of errors creeping in.


答:
You need lower and higher bounds, and which of these two are inclusive.

```<code><lower inclusive="true">-50</lower>
<higher inclusive="false">100</higher
</code>```

would be the range [-50,100).

Title: What is the best data model to represent mathematical range (in database, xml, json...)?

Body:
For example,

greater or equal to 50 and smaller than 100 (>=50 && < 100)

smaller than 10 or greater than 40 (<10 || >40)

I have been thinking about how to represent mathematical range in a file and database, the range may be input by non programmer and I need to keep the input simple, but at another side, it also need to keep the input easy to convert to data and easy to check error input e.g.: <10 || >100 seems the most simple but it is harder for me to parse the string to get the data, also need to consider input format error

I have been considering some input methods, using >=50 && < 100 as example, which is in key value form:

Using one string to represent whole range:

```<code><rangeInString>=50 && < 100</rangeInString>
</code>```

Separate two strings, one represent lower bound and another one represent upper bound, then parse each string in program:

```<code><lowerBound> >=50 </lowerBound>
<upperBound> <100 </upperBound>
</code>```

Separate lower and upper bound, also separate the sign from number:

```<code><lowerBound>
  <sign> >= </sign>
  <data>50</data>
</lowerBound>
<upperBound>
  <sign> < </sign>
  <data>100</data>
</upperBound>
</code>```

Separate lower bound and upper bound,also separate sign, and also separate the case that if includes the equal condition:

```<code><lowerBound>
  <sign> > </sign>
  <isIncludeEqual>true</isIncludeEqual>
  <data>50</data>
</lowerBound>
<upperBound>
  <sign> < </sign>
  <isIncludeEqual>false</isIncludeEqual>
  <data>100</data>
</upperBound>
</code>```

auto detect using && or ||, e.g. :>= A with < B,if A < B, must be && e.g. (>= 50 && <100), otherwise it is || e.g. (>= 100 || <50):

```<code><A>
  <sign> > </sign>
  <isIncludeEqual>true</isIncludeEqual>
  <data>50</data>
</A>
<B>
  <sign> < </sign>
  <isIncludeEqual>false</isIncludeEqual>
  <data>100</data>
</B>
</code>```

Use a field "isAnd" to separate >=50 && < 100 (true) and <=50 || > 100 (false) instead of using field sign "<" and ">" :

```<code><lowerBound>
  <isIncludeEqual>true</isIncludeEqual>
  <data>50</data>
</lowerBound>
<upperBound>
  <isIncludeEqual>false</isIncludeEqual>
  <data>100</data>
</upperBound>
<isAnd>true</isAnd>
</code>```

other data model...

I need to consider somethings:

easy for non programmer to input

easy to convert or parse to data into program

easy to check error, for example,parse string increase the complexity of converting data and checking incorrect format, also there may have other incorrect format,e.g.: <=50 && >100 should not be valid, I may allow auto detect using && or || by the sign of input, but it may increase the complexity of the code

Body:
You need lower and higher bounds, and which of these two are inclusive.

<lower inclusive="true">-50</lower>
<higher inclusive="false">100</higher

would be the range [-50,100).


答:
In XSD, ranges are represented using the four element minInclusive, maxInclusive, minExclusive, maxExclusive, for example

```<code><xs:restriction>
  <minExclusive="10"/>
  <maxInclusive="20"/>
</xs:restriction>
</code>```

In my experimental FtanML design I took that approach and simplified it to four attributes le, lt, ge, gt:

```<code><integer gt=10 le=20>
</code>```

If we take a pure data modelling approach, the range has two properties, a min and a max, each of which may be absent, and each of which, if present, comprises an integer (the limit), and a boolean (indicating whether a value equal to the limit is permitted). That might suggest a cleaner design is:

```<code><range>
  <min limit="10" inclusive="true"/>
  <max limit="20" inclusive="false"/>
</range>
</code>```

But at this point it becomes clear that the best design depends on what you are trying to optimise.

Body:
In XSD, ranges are represented using the four element minInclusive, maxInclusive, minExclusive, maxExclusive, for example

<xs:restriction>
  <minExclusive="10"/>
  <maxInclusive="20"/>
</xs:restriction>

In my experimental FtanML design I took that approach and simplified it to four attributes le, lt, ge, gt:

<integer gt=10 le=20>

If we take a pure data modelling approach, the range has two properties, a min and a max, each of which may be absent, and each of which, if present, comprises an integer (the limit), and a boolean (indicating whether a value equal to the limit is permitted). That might suggest a cleaner design is:

<range>
  <min limit="10" inclusive="true"/>
  <max limit="20" inclusive="false"/>
</range>

But at this point it becomes clear that the best design depends on what you are trying to optimise.


问:
How to integrate static analysis tools in a running project
I've started in a company that has been developing an app for 4 years. They haven't used any static analysis tool until now so if we include them we will have tons of warnings.

Do you know how can we integrate these tools in a way that we get warnings somehow only in new code and we extend their usage to the rest of the code bit by bit?

Edit: the tools to use are FxCop and StyleCop, both for C# in case it matters but anyway I think the solutions proposed can be adopted as well.

答:
Although you don't say which tools you use (Fortify is different from cppcheck for example) most tools allow you to specify which code files to operate on. Specifying only new files will allow you to check new code without looking at the old, but obviously only if you put all new code in new files. This is not going to help in bugfixing but you could migrate any changed code to one of the new files as changes are made. This will introduce old functions into the analysis but might not be such a bad thing - if you bugfix a function, you also have to fix up all the other warnings too.

But I think that's a lot of effort that belongs in a DailyWTF article. Analyse the entire codebase, take a day to fix the low-hanging fruit of warnings you get and then allocate the more difficult fixups as bugs to be fixed when you can.

Remember those warnings the analysis tools report are still potential code errors, its best to fix them regardless.


答:
Start with the maths involved. Do you want the set to be closed under the operations you use? Most definitely yes, otherwise it won't be useful. Then you'd have to implement: + and - infinities, open vs. closed endpoints, an empty set, and multi-interval ranges.

Database storage can proceed via a custom datatype (you'd have to port your business logic to the DB for sane retrieval, comparison, sorting, and indexing), or by a separate table where each atomic range is stored in 5 attributes (ID, left bound type, left bound value, right bound type, right bound value).

In-program storage has to have records using the same items, but this time the burden of indexing is on you - you have to make retrieval/lookup efficient (O(1) is the best thing to have) to be able to process large disjoint ranges and algebraic/set operations on them.

Source: own experience implementing a set ops library for in-house use.


问:
How do you look for programmers when your project's not in a particularly popular language?
So, we've got a product, written in Perl. Mind you, it's good Perl, pretty well object-oriented, with a strong functional-programming influence, extensive test suites, and it's an agile environment doing Extreme Programming with elements of Scrum.

We also have about 4 open headcount that we're trying to fill sooner rather than later, and we've historically had trouble filling even just one or two. I've been taking a look at the sort of candidates that our existing postings seem to be attracting, and they're not particularly impressive. Most of them have a background in QA automation or something similar.

We know that we can take good OO software engineers who know Python or Ruby or even just C++/Java and bring them up to speed quickly enough. We're pretty good at being able to pitch the actual job itself to qualified candidates if we have their ear. What we're not good at, it seems, is attracting these people to our postings in the first place.

What sort of things can we do to market ourselves to these engineers?

What sort of things should we be careful to avoid in job postings and the like?

(The posting is omitted since I don't want to get in any trouble by doing an end-run around the job-board. Also, our current in-house recruiter isn't helping much.... rumors are his days are numbered and I'm not at all surprised...)

答:
hmmm...I can only tell you how I've gotten Perl jobs.

First time, I monitored the perljobs mailing list (jobs.perl.org) until a job in my area came up. I applied and got it.

Second time, I went to indeed.com and did a search on "perl". I found an opening in my area, applied, and got it.

OwnerDisplayName: Steven


问:
How to store one-to-many graph? Passing root or passing root and children seperately?
Suppose in the application, there is a type Teacher and a type Students. A Teacher may have a list of Students. So in design, class Teacher has a field of type Collection of Students (aka List).

Suppose I want to register (insert) a new Teacher with his all new Students.

I either could make a Teacher object and set its StudentList field. In other words, an object graph is to be formed then the root is passed to Data Access Layer to store.

OR

I could make a Teacher object, then make a list of Students and then pass both of them to Data Access Layer to store.

I almost always face this dilemma. I'm aware that it depends on whether the DAL is able to detect changes in a graph or not. But lets assume we are in perfect world of Persistence Ignorant DALs.

Which one is better?

答:
Neither is better.  It depends on the intended atomicity of the change, and how that matches with the client interaction.

If you're manipulating things through a UI and a user first creates a teacher, and then creates or links to 1 or more students, doing them separately and sequentially is correct.

If you're processing a service request which batches in classes, you want to do them in a single atomic action, and that's more naturally expressed by passing the whole graph.

Ideally, your DAL should handle both use cases, as the functional events here are different and have different constraints.


问:
non-optional pointers vs. non-const references in C++
In Other C++ Features, Reference Arguments of the Google C++ Style Guide, I read that non-const references must not be used.

All parameters passed by reference must be labeled const.

It is clear that looking at function calls that use references as arguments is absolutely confusing for C programmers, but C and C++ are different languages now. If an output parameter is required, using a pointer for a required output parameter, may cause the whole function body to be skipped, which makes the implementation of a function more complicated (formally increases the cyclomatic complexity and depth of a function).

I'd like to make C++ code as easy to understand/maintain as possible, so I'm generally interested to read coding style guides. But as to adapt best practices in a team, I think that understanding the rationale behind style guide elements is an important factor.

Are non-const references really that bad? Is banning them only Google specific or is it a commonly accepted rule? What justifies the extra effort for implementing output parameters as pointers?

答:
There are 2 options for dealing with an invalid pointer passed in, first check and early return or let it be undefined behavior (if you care more about speed than robustness).

Checking is as simple as:

```<code>void foo(void* buffer){
    if(buffer == nullptr)
        return;

    //actually foo

    // note no increase in indentation required

}
</code>```

This type of check is generally accepted as a parameter check. If you see the code it's quite clear that you expect a non-null pointer to be passed in and return early if not. This lets you not worry so much about invalid pointers.

Body:
There are 2 options for dealing with an invalid pointer passed in, first check and early return or let it be undefined behavior (if you care more about speed than robustness).

Checking is as simple as:

void foo(void* buffer){
    if(buffer == nullptr)
        return;

    //actually foo

    // note no increase in indentation required

}

This type of check is generally accepted as a parameter check. If you see the code it's quite clear that you expect a non-null pointer to be passed in and return early if not. This lets you not worry so much about invalid pointers.


答:
It comes down to your observation If an output parameter is required.

The only place where a function signature is required to have an output parameter is when it is specified by an external API, and in such a case you just wrap the external API in something that ensures there is always a valid pointee.

Internally you avoid output parameters by extending the return type to be a composite of all of the "outs"

Title: non-optional pointers vs. non-const references in C++

Body:
In Other C++ Features, Reference Arguments of the Google C++ Style Guide, I read that non-const references must not be used.

All parameters passed by reference must be labeled const.

It is clear that looking at function calls that use references as arguments is absolutely confusing for C programmers, but C and C++ are different languages now. If an output parameter is required, using a pointer for a required output parameter, may cause the whole function body to be skipped, which makes the implementation of a function more complicated (formally increases the cyclomatic complexity and depth of a function).

I'd like to make C++ code as easy to understand/maintain as possible, so I'm generally interested to read coding style guides. But as to adapt best practices in a team, I think that understanding the rationale behind style guide elements is an important factor.

Are non-const references really that bad? Is banning them only Google specific or is it a commonly accepted rule? What justifies the extra effort for implementing output parameters as pointers?


答:
What I did with Cppcheck was to format the output with the same format as used in a suppression file, then I just copied the lines. With this tool, it is also possible to use patterns (single checks, whole files) for suppressions. (My personal advice: Don't suppress checking "old code" if you are not able to ensure that it will never get touched.)

Cppcheck also provides parameters that let you concentrate on the errors and warnings first. In all projects of our company, that Cppcheck was used on for the first time, it found errors. So don't skip the stage of understanding the checking results for old code.

If interested in details, the command line help is more straightforward than the online manual.

Title: How to integrate static analysis tools in a running project

Body:
I've started in a company that has been developing an app for 4 years. They haven't used any static analysis tool until now so if we include them we will have tons of warnings.

Do you know how can we integrate these tools in a way that we get warnings somehow only in new code and we extend their usage to the rest of the code bit by bit?

Edit: the tools to use are FxCop and StyleCop, both for C# in case it matters but anyway I think the solutions proposed can be adopted as well.


答:
If I were to choose among the two, I would certainly opt for the first solution.  I see absolutely no merit in passing a Teacher object with an empty list of Students along with a separately populated free-standing list of Students, as opposed to passing a Teacher object with its own list of students already populated.

However, if it was up to me, I would not choose either of these two approaches.

Keep in mind that the fact that the teacher has a list of students is an elaborately constructed and maintained illusion that your persistence layer provides you with. From a relationally normalized point of view, the teacher does not actually have a list of student; instead, either each student has a teacher, or, if a student may need to have many teachers, then this is realized by means of a many-to-many relationship.

The many-to-many relationship is implemented as an extra table containing rows with pairs of just teacher ids and student ids. In this case, the illusion of a collection applies to students, too: a student may have a list of teachers just as easily as a teacher may have a list of students.  So, when you create a student, why not create them with their list of teachers already filled in? Clearly, this is absurd, so I think that the whole idea of creating entities with pre-filled-in relationships is absurd.

So, what I would do is that I would instantiate and pass around separate teacher entities and student entities, (without any pre-filled-in relationships among them,) and then in separate steps I would specify the relationships among them on an individual basis.

Title: How to store one-to-many graph? Passing root or passing root and children seperately?

Body:
Suppose in the application, there is a type Teacher and a type Students. A Teacher may have a list of Students. So in design, class Teacher has a field of type Collection of Students (aka List).

Suppose I want to register (insert) a new Teacher with his all new Students.

I either could make a Teacher object and set its StudentList field. In other words, an object graph is to be formed then the root is passed to Data Access Layer to store.

OR

I could make a Teacher object, then make a list of Students and then pass both of them to Data Access Layer to store.

I almost always face this dilemma. I'm aware that it depends on whether the DAL is able to detect changes in a graph or not. But lets assume we are in perfect world of Persistence Ignorant DALs.

Which one is better?


问:
Coding to an interface vs more generic interfaces
I have a number of classes (and interfaces) which 'code to an interface'

```<code>interface File
{
    ...
}

interface FileConverter {
    public function convert(File $file); //coding to an interface
    public function success($message);
    public function failure($message);
}
</code>```

I feel I can make the FileConverter interface even more generic by removing the File class type-hint in this interface to allow conversion between strings, arrays etc rather than just classes that implement File;

```<code>interface Converter {
    public function convert($input);
    public function success($message);
    public function failure($message);
}
</code>```

However, if I do this, I feel I loose the 'coding to an interface' aspect - even though none of my classes directly use the FileConverter interface. Is this a wise choice or should I create a different interface? ie;

```<code>interface StringConverter {
    public function convert(string $string); //PHP 7
    public function success($message);
    public function failure($message);
}
</code>```

答:
All objects implementing a particular interface must not only define methods with matching signatures, but also with matching semantics.

Meaning: you should be able to replace object A which implements I with object B which imolements I and still have things work.

If in your case both A and B define convert(), but A will only work with a string and otherwise crash or return something weird, and B can only work with files, thab they are not substituable, and do not actually implement the same interface.

(
It just seems they do, because a dynamically typed language such as PHP doesn't force you to define the types in the method signature. The equivalent Java methods, for example, would be Something convert(String s) and Something convert(File f). Now it's clear that they're not the same interface.

I'm not saying you should always use type hinting in PHP. I'm saying that implementing an interface means matching particular semantics, and not just a signature.


问:
Create parts of DSL as Quickfix from xtext grammar
I currently experimenting with DSLs with xtext. I want to implement a quick fix for the dsl I'm writing and I'm wondering, if there is a possibility in xtext or xtend hook (or something else) to generate a dsl fragment code from the DSL grammar and a given Ecore node.

For example

```<code>Model:
  entities+=Entity*;

Entity:
  'entity' name = ID  ('extends' superType=[Entity])? '{'
        attributes += Attribute*
  '}';
</code>```

I validate that the Supertype may not exist, and I want to suggest a Quickfix (Ctrl+1) to create a new Entity. I know how to do the validation part and know where to implement the quickfix. But since the DSL is in development i do not want to write two code generators (one for creating DSL code, and the second for the code derived from the model) since the DSL is subject to change. I guess, that there could be a more general solution, since the grammar is known, because of the xtext grammar definition and the Ecore node I want to create, whose name I know from the validator. I also guess I am not the only one providing such a "feature" and thus I assume there is already a solution which i did not found yet.

My Question, is there a generic way in xtext/xtend building an ecore node or AST and serialize that AST back into xtext based DSL using the xtext grammar?

答:
Yes, there is exactly that. You can provide your quickfix as a semantic modification to the EMF resource. Xtext's serialization mechanism will figure out how to convert your changes to the AST back to text.

Something along these lines should do the trick:

```<code>@Fix(MISSING_SUPERTYPE_ID)
public void fixupSupertype(final Issue issue, IssueResolutionAcceptor acceptor) {
    acceptor.accept(issue, "label", "description", null, new ISemanticModification() {
        @Override
        public void apply(EObject element, IModificationContext context) {
            Model model = (Model)element.eResource().getContents().get(0);
            Entity newEntity = MyDslFactory.eInstance().createEntity()
            model.getEntities().add(newEntity);
            ((Entity)element).setSuperType(newEntity);
        }
    });
}
</code>```

Body:
Yes, there is exactly that. You can provide your quickfix as a semantic modification to the EMF resource. Xtext's serialization mechanism will figure out how to convert your changes to the AST back to text.

Something along these lines should do the trick:

@Fix(MISSING_SUPERTYPE_ID)
public void fixupSupertype(final Issue issue, IssueResolutionAcceptor acceptor) {
    acceptor.accept(issue, "label", "description", null, new ISemanticModification() {
        @Override
        public void apply(EObject element, IModificationContext context) {
            Model model = (Model)element.eResource().getContents().get(0);
            Entity newEntity = MyDslFactory.eInstance().createEntity()
            model.getEntities().add(newEntity);
            ((Entity)element).setSuperType(newEntity);
        }
    });
}


答:
The rationale behind Google's style guide is simply to make it clear from a function's call site whether a parameter is an input parameter or an output parameter.  (See here for further discussion.)  Other languages make out parameters explicit by design; C#, for example, has an out keyword that must be used at the call site.  Since C++ doesn't make it explicit, Google chose to use const ref. versus pointer to make it clear.

Is this only a Google rule?  No, but I doubt it's very widespread.  I don't think I've seen it outside of Google's style guide and groups that explicitly adhere to parts of the Google style guide.  (For example, I liked the idea when I first read the Google style guide years ago and have used it for some of my own code.)

In particular, the newly announced C++ Core Guidelines prefer return values to output parameters for (almost) everything and uses non-const refs for the rest.  Google's use of pointers versus references might make output parameters clearer, but return values are clearer still.  Now that C++11 has standardized moves (rvalue references, &&, to make returns of many types cheap) and tuples (allowing an easy way to return multiple values), many of the use cases for out parameters no longer apply.

The C++ Core Guidelines have some big names (Bjarne Stroustrup, Herb Sutter) behind them, are supported by Microsoft, and embrace the latest C++ features (unlike Google's style guide), so I expect its recommendations to be more popular than Google's.


问:
Domain Model vs Presentation Model vs General Function
I have been building an app for my company i join for the past > 1 year, we're using

Java

Spring

Hibernate

Javascript

jQuery

Kendo UI

And for the structure i can say something like this from Backend to Frontend :

Backend (pojo > dao > bo > service > web service) > UI ( model, view
  model, html/view)

Well i think i know how to code them all, but then earlier today my senior asked me this and i can't say a word jeez i need to know more of the concept. He asked me this

What Presentation Model is, how it differs from Domain Model and its general function ? i'm looking for hours combining article to article but it got me more confused. Can anyone explain with "easy explanation about this"? and also are pojo = domain model in java, then view model = presentation model in MVVM ?

答:
Domain Model

The domain model is a collection of classes without any presentation specific code. Just think of a pure list of customers. Also, one may add the buissnes logic into the domain model: code to modificate/change the model.

Presentation model by Martin Fowler

As Fowler describes:

The essence of a Presentation Model is of a fully self-contained class that represents all the data and behavior of the UI window, but without any of the controls used to render that UI on the screen. A view then simply projects the state of the presentation model onto the glass.

As you read, the domain model and the presentation model are completely different. If the domain is out list of customers we need a nice GUI to display this list. Here comes the presentation model and defines classes which contains the state of all elements in the GUI.

POJO (Plain-old-Java-Object)

A POJO is a class in Java which only extends Object. nothing more.

```<code>class Foo { // this is a POJO
}

class Foo implements Bar { // this is also a POJO
}

class Foo extends Baz { // this is *not* a POJO
}
</code>```

MVVM (Model-View-ViewModel)

The presentation model is slightly different from MVVM. The term model is the domain model. The view contains all GUI elements. The ViewModel only contains the correct representation of the data and includes a data binding. This pattern requires the use of any kind of binding whereas the presentation model does not. (Fowler said to have data binding but does not say in which class)

As we can read in this article MVVM comes after the presentation model and I think we should use MVPVM. in MVVM the ViewModel contains logic to present and logic to create the representation of the data which violates the Single-Responsibility-Principle. If we create a presenter and put the presentation logic into that class the violation is gone. So I think MVPVM is compatible with the SOLID-Design.

Body:
Domain Model

The domain model is a collection of classes without any presentation specific code. Just think of a pure list of customers. Also, one may add the buissnes logic into the domain model: code to modificate/change the model.

Presentation model by Martin Fowler

As Fowler describes:

The essence of a Presentation Model is of a fully self-contained class that represents all the data and behavior of the UI window, but without any of the controls used to render that UI on the screen. A view then simply projects the state of the presentation model onto the glass.

As you read, the domain model and the presentation model are completely different. If the domain is out list of customers we need a nice GUI to display this list. Here comes the presentation model and defines classes which contains the state of all elements in the GUI.

POJO (Plain-old-Java-Object)

A POJO is a class in Java which only extends Object. nothing more.

class Foo { // this is a POJO
}

class Foo implements Bar { // this is also a POJO
}

class Foo extends Baz { // this is *not* a POJO
}

MVVM (Model-View-ViewModel)

The presentation model is slightly different from MVVM. The term model is the domain model. The view contains all GUI elements. The ViewModel only contains the correct representation of the data and includes a data binding. This pattern requires the use of any kind of binding whereas the presentation model does not. (Fowler said to have data binding but does not say in which class)

As we can read in this article MVVM comes after the presentation model and I think we should use MVPVM. in MVVM the ViewModel contains logic to present and logic to create the representation of the data which violates the Single-Responsibility-Principle. If we create a presenter and put the presentation logic into that class the violation is gone. So I think MVPVM is compatible with the SOLID-Design.


答:
Ask yourself why you need to invalidate the original token.

A user logs in, a token is generated and off the app goes.

The user presses logout, a new token is generated and replaces the original token.  Once again, all is well.

You seem to be worrying about the case where both tokens hang around.  What if the user logs out and then somehow makes a request using the logged in token. How realistic is this scenario?  Is it just a problem during logout or are there many possible scenarios where multiple tokens can be a problem?

I myself don't think it's worth worrying about.  If someone is intercepting and decoding your encrypted https data then you have much bigger problems.

You can give yourself some additional protection by putting an expiration time on the original token.  So if does end up being stolen or something then it would only be good for a short period of time.

Otherwise, I think you would need to have state information on the server.  Don't blacklist tokens but instead whitelist the current token's signature.

Title: REST API security Stored token vs JWT vs OAuth

Body:
I am still trying to find the best security solution for protecting REST API, because the amount of mobile applications and API is increasing every day.

I have tried different ways of authentication, but still has some misunderstandings, so I need advice of someone more experienced.

Let me tell, how I understand all this stuff. If I understand something incorrectly, please let me know.

As far as REST API is stateless as well as WEB in general, we need to send some auth data in each request(cookies, token....). I know three widely used mechanisms to authenticate user

Token with HTTPS. I have used this approach a lot of times it is good enough with HTTPS. If user provides correct password and login, he will receive token in response, and will use it for the further requests. Token is generated by the server and stored, for instance in the table separate or the same where user info is stored. So for each request server checks if user has token and it is the same as in the database. Everything is pretty straightforward.

JWT Token. This token is self-descriptive, it contains all necessary information about the token itself, user cannot change for example expiration date or any other claim, because this token is generated (signed) by the server with secret keyword. This is also clear. But one big problem, personally for me, how to invalidate token.

OAuth 2. I don't understand why this approach should be used when communication is established directly between server and client. As far as I understand, OAuth server is used to issue token with restricted scope to allow other applications access user information without storing password and login. This is great solution for the social networks, when user wants to sign up on some page, server can request permissions to get user info, for instance from twitter or facebook, and fill registration fields with user data and so on.

Consider mobile client for online store.

First question should I prefer JWT over first type token ? As far as I need login/logout user on mobile client, I need to store somewhere token or in case of JWT, token should be invalidated on logout. Different approaches are used to invalidate token one of the is to create invalid token list (black list). Hmm. Table/file will have much bigger size than if token was stored in table and associated with user, and just removed on logout.

So what are benefits of JWT token ?

Second question about OAuth , should I use it in case of direct communication with my server?  What is the purpose of one more layer between client and server only to issue token, but communication will be not with oauth server but with the main server. As I understand OAuth server is responsible only for giving third-party apps permissions (tokens) to access user private information. But my mobile client application is not third-party.


问:
How to best futureproof frontend code as server response evolves?
I find that in the early stages of a project the structure of the data returned by the server can change quite frequently as the data model changes.

For example, if I'm building an application that plots the locations of local points of interest I might start by returning json that looks like this :

```<code>[{"name" : "Odeon", "poiType" : "cinema", "lat" : 34.4, "lon" : 10.3},
 {"name" : "McDonalds", "poiType" : "restaurant", "lat" : 34.5", "lon" : "10.5"}, ...]
</code>```

On the client I might have several components that need the lat/lon information, and they would typically access the data as follows:

```<code>function showPointsOfInterest(pois) {
    pois.forEach(function (poi) {
         var icon = getIcon(poi.poiType);
         addToMap(poi.lon, poi.lat, icon);
     })
}

function listPointsOfInterest(pois) {
     pois.forEach(function (poi) {
         var icon = getIcon(poi.poiType);
         addToList(poi.lon, poi.lat, icon);
     })
}
</code>```

I then decide that I would like to change the data structure so that it now looks like

```<code>[
{
    "name": "Odeon",
    "type": "cinema",
    "location": {
        "coordinates": {
            "lat": 34.4,
            "lon": 10.3
        },
        "address": "Main St, 54"
    }
},
{
    "name": "McDonalds",
    "type": "restaurant",
    "location": {
        "coordinates": {
            "lat": 34.5,
            "lon": 10.5
        },
        "address": "Main St, 154"
    }
}, ... ]
</code>```

The changes being that poiType is now type, and lat and lon are now children of location.coordinates.

I now need to change my client side code to

```<code>function showPointsOfInterest(pois) {
    pois.forEach(function (poi) {
     var icon = getIcon(poi.type);
      var coords = poi.location.coordinates;
      addToMap(coords.lon, coords.lat, icon);
   })
}

function listPointsOfInterest(pois) {
    pois.forEach(function (poi) {
        var icon = getIcon(poi.type);
        var coords = poi.location.coordinates;
        addToList(coords.lon, coords.lat, icon);
    })
}
</code>```

Having to go through the code and find where I'm accesssing poiType , lat and lon can be a pain.

So I'm wondering if it's good practice to create some utility functions like

```<code>function getLon(poi) {
    return poi.location.coordinates.lon;
}

function getLat(poi) {
    return poi.location.coordinates.lat;
}

function getType(poi) {
    return poi.type;
}
</code>```

and then having

```<code>function showPointsOfInterest(pois) {
    pois.forEach(function (poi) {
     var icon = getIcon(getType(poi));
     addToMap(getLon(poi), getLat(poi), icon);
   })
}

function listPointsOfInterest(pois) {
    pois.forEach(function (poi) {
        var icon = getIcon(getType(poi));
        addToList(getLon(poi), getLat(poi), icon);
    })
}
</code>```

The advantage of this approach is that if my data model changes I only need to make changes in my utility functions.

Is this the best approach? Are there any downsides to doing this?

答:
The usual way is to version the API. Your API still responds with the old data structure at the old URI. Then you add another URI to your API with the new data structure. Then the client code still continues to function on the old data until you get around to changing it over. This is how you have to do it when you have external customers depending on your API.

If you're just being a perfectionist, and then keeping the client code in sync with the changes, then you can use whatever strategy works for you. Bear in mind that the data you return from the API doesn't have to be the canonical version of the data. It could be a representation of the data that best suits the use case. In this instance, a flat object seems just as good if not better than the more organized version.


问:
Designing around shallow constness with inheritance

Background

I'm writing an image handling class. For this question two requirements of the class are of interest:

Must have "deep" const correctness.

Must allow sub-image aliases, a.k.a. sections or slicing without performing deep copies of image data.

By deep constness I mean the following. Consider this example class:

```<code>class Image{
public:
    ...
    Image(const Image&);

    Image alias(int x0, int y0, int x1, int y1) const;
private:
    Buffer image_data;
};
</code>```

And assume you have a function that is passed a const reference to a image, like so:

```<code>void foo(const Image& im){
    Image alias = im.alias(0,0, 10, 10);
    // Hold on, the mutable alias can modify the data in the const argument!
}
</code>```

The above alias function call defeats the constness of the argument because the contents of the argument image can be modified through the non-const alias. I can't return a const Image from alias because well that makes no sense really and the copy constructor of Image will happily construct a mutable instance anyway.

My solution (and I've seen it used often so I don't claim originality here) is to introduce two classes (interfaces really, but for the simplicity they are classes in this example and return by value is okay, in reality alias(...) returns a shared_ptr to interface):

```<code>class ConstImage{
public:
    ConstImage alias(...) const;
};

class Image{
public:
    Image alias(...);
};
</code>```

Now the following code:

```<code>void foo(const Image& im){
    // compile error, cannot convert ConstImage to Image, perfect!
    Image alias = im.alias(...);
}
</code>```

And of course you would change the signature to void foo(const ConstImage& im) so that you can accept invocations like foo(const_im.alias(...)) or other ConstImage objects.

Now of course we want foo(const ConstImage& im) to be callable (1) with a mutable Image too and here is where the question comes in.

Question

Using inheritance: class Image : public ConstImage will make all Image types usable through ConstImage references and pointers. It will also facilitate code-reuse between the const and non-const implementations which by necessity are very similar.

This solves the above mentioned problem (1). However if you look at the inheritance relation as an "is a" statement then "a mutable image IS AN immutable image" makes no sense. Which speaks against using inheritance here.

My question is, is this kind of (ab)use of inheritance widely acceptable? Is there some other better solution that I have overlooked? Note that the Image class is more of an interface so naive value conversion from Image to ConstImage isn't possible. Although one could probably come up with something crazy to allow it.

答:
The fundamental problem is you are trying to use an unsound model of types. Despite wording in the ISO C++ Standard and wrong ideas expressed by Bjarne in the ARM originally, there is no such thing as a const type. Contrarily, constness is a property of pointers only (and references but lets leave them out for simplicity). Therefore a class representing a const and non-const type is a wrong concept.

Const in C++ itself is an unsound concept, it should have been removed. This is evident in the Standard Library when trying to model the concept generically. It only works one level deep as you have observed. It applies to the access path to an object, but does not propagate to a data structure (linked collection of objects). The simplest example is a singly linked list: a const pointer to a list node immediately yields a non-const next pointer.

In a theoretical model, const and non-const abstractions are distinguished by the absence or presence of mutator methods and are therefore distinct types without any "isA" relation, whatever that is.

My best advice: stop trying to model abstractions with OO techniques because OO is proven to be so highly restricted in applicability it is not suitable for modelling any but the simplest concepts. Learn some functional programming methods instead.


答:
I think you'd be better to come at the problem from a slightly different perspective.

C++ in many ways works best with types that act like value types. That is, they behave like built-in types or most STL types. You could make an Image class that acts like an std::vector and is a value type with 'deep' const correctness by simply copying data whenever you copy an image or take an image slice but that would be somewhat inefficient due to all the copying. Those are the semantics you'd ideally like from your Image class however.

You should think of the sharing of image data for efficiency as purely an implementation detail of your class. It's not something the end user should need to know about from an interface point of view. One way to achieve this is by using copy-on-write to give the appearance of a value type while under the hood you are sharing data wherever possible. This used to be a common implementation tactic for std::string although it is not any more, primarily because of thread safety concerns (which you'll have to address too if you want to use your Image class in multi-threaded scenarios).

One implication of this alternative approach is that alias() is a bad name for your image slice function. It exposes an implementation detail in the name of a public API. That function should instead be called slice(). With a copy-on-write implementation you could call slice() on a const Image and get an Image. Behind the scenes the image data would be shared until you tried to write to it, at which point you would make a copy. A more sophisticated implementation might tile the image and only copy tiles that were touched by the write so changing a few pixels wouldn't take a copy of the entire image slice.

Title: Designing around shallow constness with inheritance

Body:
Background

I'm writing an image handling class. For this question two requirements of the class are of interest:

Must have "deep" const correctness.

Must allow sub-image aliases, a.k.a. sections or slicing without performing deep copies of image data.

By deep constness I mean the following. Consider this example class:

```<code>class Image{
public:
    ...
    Image(const Image&);

    Image alias(int x0, int y0, int x1, int y1) const;
private:
    Buffer image_data;
};
</code>```

And assume you have a function that is passed a const reference to a image, like so:

```<code>void foo(const Image& im){
    Image alias = im.alias(0,0, 10, 10);
    // Hold on, the mutable alias can modify the data in the const argument!
}
</code>```

The above alias function call defeats the constness of the argument because the contents of the argument image can be modified through the non-const alias. I can't return a const Image from alias because well that makes no sense really and the copy constructor of Image will happily construct a mutable instance anyway.

My solution (and I've seen it used often so I don't claim originality here) is to introduce two classes (interfaces really, but for the simplicity they are classes in this example and return by value is okay, in reality alias(...) returns a shared_ptr to interface):

```<code>class ConstImage{
public:
    ConstImage alias(...) const;
};

class Image{
public:
    Image alias(...);
};
</code>```

Now the following code:

```<code>void foo(const Image& im){
    // compile error, cannot convert ConstImage to Image, perfect!
    Image alias = im.alias(...);
}
</code>```

And of course you would change the signature to void foo(const ConstImage& im) so that you can accept invocations like foo(const_im.alias(...)) or other ConstImage objects.

Now of course we want foo(const ConstImage& im) to be callable (1) with a mutable Image too and here is where the question comes in.

Question

Using inheritance: class Image : public ConstImage will make all Image types usable through ConstImage references and pointers. It will also facilitate code-reuse between the const and non-const implementations which by necessity are very similar.

This solves the above mentioned problem (1). However if you look at the inheritance relation as an "is a" statement then "a mutable image IS AN immutable image" makes no sense. Which speaks against using inheritance here.

My question is, is this kind of (ab)use of inheritance widely acceptable? Is there some other better solution that I have overlooked? Note that the Image class is more of an interface so naive value conversion from Image to ConstImage isn't possible. Although one could probably come up with something crazy to allow it.


问:
How to store (and find) updated values in a Distributed Hash Table?
Distributed Hash Tables are a great way to store immutable data in a resilient way.

However, I am wondering about how it would be possible to store new versions of old data in this system.

Because it is impossible in a distributed network to unconditionally trust the other party, a way is needed to ensure that another party does not manipulate stored data. The easiest way to do this is to store data values under keys that are generated from these values using a one-way hash function. This means that when someone wants to change data, they invalidate the key->value relation of that data, which is easy to check against.

Say, someone stores a document in the DHT, but later made some changes and wants to store that new version. How can other people connected to the DHT find out that there is a new version of this document?
The only information that I found about this said that an idea would be to store versioned data like this:

```<code>v1: hash(random_number) -> document1
v2: hash(key(v1)) -> document2
v3: hash(key(v2)) -> document3
...etc.
</code>```

Then, to check if there is a new version, all a client would need to do is to apply the hashing algorithm one more time to the hash of the current value.

Drawback: This approach does not have the relation between key and value, meaning that a value might be changed (by a malicious server or a man-in-the-middle) without invalidating the key.

How can these two approaches be combined? Or is there a different, better way to manage this?

答:
There are ways in which this can be solved, and you can make this as complex as you like.  The simplest way is to authenticate the other servers, and allow the servers to trust each other if they are authenticated.  Client and Server authenticated SSL for the network connection would achieve this.

You could also do a federated authentication system, where you are asking trusted third parties to vouch for other servers.  This can also be achieved using SSL certificates on both the client and server, and authenticated that the certificates are signed by a trusted certificate.

If you are truly after an internet scale cache, the final option is to have the cache vote, based on the majority answer, and trust that there are more honest servers than there are dishonest servers in the network.  However, when you have a situation where you don't trust the servers, you still need to solve the problem from the client's perspective...  how does the client trust the servers to send their data?  How does the client know that their data is distributed to enough trusted servers that their data is accepted.  Now having read all this, have a read up on the CAP hypothesis and realise that if you go down this route, you must have partition tolerance as you don't know the servers who are part of the system.  You Must have Availability, which means the thing you must sacrifice is consistency.


问:
Finite Element Shader
I am working on a geometric wrapper for a space jet exhaust impingement solver.  A key part of the solution is determining what the jet can "see" and therefore hit.  My model is grouped with nodes or grids arranged in 3 or 4 sided elements which are further grouped into bodies.  Shading for bodies is handled via outward facing normals and runs very fast, ie backside detection.  Shading body to body is currently done by projecting all visible points to the plane of an element and shading the points contained inside the outline of that element provided the z value is greater than the distance to the element.  This operation is slow.

My current benchmark is processing only about 3000 elements per second.  I know there must be terrible inefficiencies in my code but I feel like this is because of poor approach.  I basically check each point until it either is shaded or I run out of elements so it's visible.  Loop within loop and another looping check for self-shadowing.

I have looked into 3D Convex Hull and Direct Visibility of Point Sets.  Also I looked into Hidden Point Removal.  As expected most of the discussion is about 3D rendered applications.  I do not have this.  All the information is being processed by the CPU and never rendered.

I need suggestions for ways to effectively build/approach such a shader.  What things work well, what things to avoid.  I do not have access to graphics hardware on the machines that will run the final solution.  If it matters I am currently working in C/C++ on Linux systems.

答:
I'm sure you will get other good answers, but in my experience (with ray-tracing) it always helps to see exactly what takes time, and this it the technique I and others use.

Over and above obvious fixes like eliminating needless memory management,
what I have found is the sequence of decisions and computations from one ray to the next has strong similarity.
That similarity can be exploited to massively speed things up.
Chances are something similar can be done in your case.

Title: Finite Element Shader


问:
Measures of Javascript engine performances over time?
Since the beginning of the Javascript race -- which I would situate around Google Chrome launch in 2008 -- the improvement in the Javascript engine performances have been impressive.

The web is crowded with comparisons such as "Firefox V3.42.7 vs. Safari 3.0-prealpha2", and the winner of those comparisons changes every few months and differs on each benchmark.

But the big picture, independently of who got their new version out last, is that the average speed of current up-to-date browsers has improved a lot over the last years. Yet this long-term improvement is difficult to quantify:

people usually compare the last version of each browser, and not different versions of one browser

announced performance improvements do not generally pile up: when someone announce V3 twice as fast as V2, and later V4 twice as fast as V3, this does not mean that V3 is fourth times as fast as V1, because they usually mean "in a favorable case", and the favorable case in the V3-4 transition are not necessarily the same as in the V2-3 transition

benchmarks themselves evolve over time; what is referred as "the Sunspider test" today is not the same as in 2008, so we cannot compare raw scores over time.

Does anyone know of a valuable measurement of javascript engines performance improvement over the last few years?

答: I did some investigation into this using the benchmark game data mentioned by igouy in the other answer.  You can find a full writeup at https://cube3x.com/javascript-performance-since-2008/ but long story short the Benchmark game benchmarks show a roughly 2.6X improvement since V8 was introduced, and V8 was a roughly 10X improvement over IE7, the most prevalent browser at the time.</p>


问:
Optimal fixed-size sequential sorting algorithms
I have been working on sorting algorithms for a few weeks now, but one of my question still hasn't an answer: are there optimal sequential comparison sorts for fixed-size – and random-access – collections? Most sorting algorithms adapt to the size of the collection, but knowing the size of the collection to sort allows to pick a specific sorting algorithm for this size. For example, the following algorithm should sort three values with both an optimal number of comparisons and an optimal number of swaps or assignments (it's C++, but it should be fairly easy to translate to any language):

```<code>void sort3(int& x, int& y, int& z)
{
    if (x < y) {
        if (z < y) {
            if (z < x) {
                int tmp = z;
                z = y;
                y = x;
                x = tmp;
            } else {
                std::swap(y, z);
            }
        }
    } else if (z < y) {
        std::swap(x, z);
    } else if (z < x) {
        int tmp = x;
        x = y;
        y = z;
        z = tmp;
    } else {
        std::swap(x, y);
    }
}
</code>```

Whatever the input, this algorithm will sort three values with at most 3 comparisons and 4 assignments. I may be wrong, but I don't think that sorting three values can be done with less comparisons and less assignments than this algorithm. If it is indeed the case, then this would be an optimal comparison sorting algorithm to sort three values.

It seems that optimal sorting algorithms of this kind for any size could be generated thanks to some permutation algorithm, but I was unable to find such a generation algorithm and writing one does not seem to be trivial. I tried to find near-optimal sorting algorithms for some fixed sizes, but couldn't find any simple way to generate such algorithms:

Sorting networks seemed like a good idea but they always perform a fixed number of comparisons and swaps, which means that they do not adapt to the data. Even optimal sorting networks of size greater than 5 qickly lose the battle against a simple insertion sort for some inputs.

Parallel sorting algorithms and non-comparison sorts (spreadsort, radix sort...) are interesting but I am interested in sequentially sorting small collections. And these categories of algorithms tend to hide a big constant complexity, which means that they are more suitable for big collections.

My current method to find the most optimal sorting algorithm to sort a small fixed-size collection is to count the number of comparisons needed to sort all the possible permutations of a collection of size N:

```<code>// Fill an array of size N
std::array<int, N> collection;
std::iota(std::begin(collection), std::end(collection), 0);

// Count comparisons made by an insertion sort
cppsort::counting_adapter<
    cppsort::insertion_sorter
> sorter;

// Total number of comparisons
std::size_t count = 0;

// For each possible permutation of collection
do
{
    auto to_sort = collection;
    // Sort collection, get the number of comparisons made
    count += sorter(to_sort);
} while (std::next_permutation(std::begin(collection), std::end(collection)));
</code>```

This code uses my cpp-sort library. I used it because it makes it easy to count comparisons made by a sorting algorithm, but it could be implemented without it or in another language. This method has a problem though: it only takes into account the number of comparisons and can only help to find the most optimal algorithm amongst known algorithms, it doesn't allow to write a sorting algorithms generators.

That was quite the introduction, but my question is basically as follows: are there known methods to generate sequential comparison sorting algorithms for fixed-size collections that are optimal with regards to the number of assignments and/or the number of comparisons performed?

答:
The problem with finding the optimal algorithm is the word "optimal": A sorting algorithm may be optimal in one case, but it will be suboptimal in at least one other case. The question is, what optimum you are designing it for. Take for instance your algorithm. It is optimal for the sequences:

```<code>x < y <= z
x >= y > z
</code>```

(Aside: This means that you failed to optimize the cases x == y <= z and x >= y == z properly, because they could have been handled by the same code paths. But that's not my point here.)

Yet your algorithm is suboptimal for the other four possible orderings. Now, you can write algorithms like yours, that are optimal for any two of the six possible orderings (taking two comparisons), but they will all require a third comparison in the other four cases.

It is simply not possible to write an algorithm that is optimal for any input order. This is true for any count of objects larger than two. That is, you have to decide, what input orderings to optimize for, and whether you have input orderings which you don't want to optimize for.

To take my point a bit further: Consider the two algorithms quick-sort and insertion-sort. Can you say that either one is absolutely better than the other? No, you can't. Quick-sort will be much faster for random input, but it will simply be pawned by insertion-sort on almost sorted input. Only when you know what kind of input data to expect, you can choose one over the other.

It is a bit like trying to measure location and momentum of a quantum particle. If you know one, you have no idea about the other, and vice versa. You can measure both at the same time, but then both will be inexact. Nature simply does not allow you to know both precisely at the same time. Likewise, when you compare x and y first in your algorithm, you are already breaking the symetry of the problem at hand, making optimal sorting of two thirds of the possible input sequences impossible.

Body:
The problem with finding the optimal algorithm is the word "optimal": A sorting algorithm may be optimal in one case, but it will be suboptimal in at least one other case. The question is, what optimum you are designing it for. Take for instance your algorithm. It is optimal for the sequences:

x < y <= z
x >= y > z

(Aside: This means that you failed to optimize the cases x == y <= z and x >= y == z properly, because they could have been handled by the same code paths. But that's not my point here.)

Yet your algorithm is suboptimal for the other four possible orderings. Now, you can write algorithms like yours, that are optimal for any two of the six possible orderings (taking two comparisons), but they will all require a third comparison in the other four cases.

It is simply not possible to write an algorithm that is optimal for any input order. This is true for any count of objects larger than two. That is, you have to decide, what input orderings to optimize for, and whether you have input orderings which you don't want to optimize for.

To take my point a bit further: Consider the two algorithms quick-sort and insertion-sort. Can you say that either one is absolutely better than the other? No, you can't. Quick-sort will be much faster for random input, but it will simply be pawned by insertion-sort on almost sorted input. Only when you know what kind of input data to expect, you can choose one over the other.

It is a bit like trying to measure location and momentum of a quantum particle. If you know one, you have no idea about the other, and vice versa. You can measure both at the same time, but then both will be inexact. Nature simply does not allow you to know both precisely at the same time. Likewise, when you compare x and y first in your algorithm, you are already breaking the symetry of the problem at hand, making optimal sorting of two thirds of the possible input sequences impossible.


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答: support for type hinting for all types, and _toXXX magic methods for every type possible. (php common usage drifts IMHO rather to limit type juggling /with some exceptions, such like convertion float<->int/)</p>


问:
Testing front-end app that hits a REST service
A lot of questions about testing here... And I have another one. Forgive me, but I want to make sure I do this right.

Let's say I have a front-end application, be it a mobile app, or a single-page website, or anything else. This app hits a REST service, that I also develop. The service fetches data from 3rd party REST APIs, processes this data, and returns the results to the application.

My service is well tested and developed in a hexagonal manner, with comprehensive black-box unit tests (canned data) and few integration tests (hitting 3rd party services) to see that adapters are working ok with ports (see here).

My front end is also well tested with unit tests and mock data (it doesn't really hit the service in tests). I feel though that it would be nice if it was tested together with the service I develop. The few things I am unsure of:

Should I be using canned data when testing my service, or should I be hitting 3rd party APIs in the tests?

Should these be comprehensive automated tests (provided that all functionality is already tested with canned data on front end, and the service is really well tested too, so a lot of these tests would be testing what's already tested), or should it be just few manual tests, like hitting some buttons and seeing if the data comes through? Here I am mainly thinking about the cost/benefit ratio.

Are there any frameworks to write comprehensive automated tests like that?

I am sure many of you were in similar situation. So it would be great to get some advice. If you can link a white paper or a conference about the subject, it would be even better. Thanks in advance for any suggestions.

答:
In my opinion, there are two distinct scenarios that you are testing.

1) Test that your application is invoking the external APIs properly.

The goal of these tests is to isolate your application code and ensure it is properly invoking and responding to the external APIs.  Accordingly, these should be done with mock services and data to eliminate irrelevant noise from the test.

2) Ensure the external APIs are available and responding as expected.

The goal is to ensure that your application has all necessary resources available in order to operate properly.  It is not a unit test, since you are not exercising any piece of code.  This is a system health monitor.  It is generally of very low value to run a single test against an external dependency at compile time, you want these checks to run continuously at periodic intervals and raise proper alerts when they fail.  The ideal solution is a separate application that will run along side your application that will monitor all of the external resources your application depends on.  Establishing proper monitoring and alerting on these external dependencies through a system health monitor is essential in high availability scenarios in order to respond as rapidly and efficiently as possible to mitigate any service outage.


问:
ASP.NET how to handle external application settings
I'm converting an application from C# WebForms to MVC.

The application gets settings from a centralized location using Web Services. These are settings you would typically find in a Web.Config, but the desire of the company is to store these values in a centralized location for all apps.

Currently, any time you request an application setting, it checks HttpContext.Cache to see if you've already retrieved the settings. If you haven't, it makes the web service call, and stores the settings (100+ objects that are essentially key/values) in the HttpContext.Cache. So the call to get application settings only occurs once.

Should I be looking at another way to do this? I was thinking the settings should just be a REST service call where you pass the key and get a value (the current service is an *.ashx which is really not ideal for exception handling amoung other reasons). But obviously this would result in more web requests. What is considered a best practice here? Is the current method fine and I should just leave the code working the same in the MVC app?

答:
The current approach seems reasonable. It's basically lazy loading the settings on first call and is "chunky" -- sending back all settings at once. Your proposed approach is more precise but is "chatty" -- multiple calls may be needed to get what you require. The two questions I would ask are:

Does the "chunky" version take up too much memory?

Assuming you only need a small percentage of all the configuration objects. Could you save a significant amount of memory (which depends on your platform) by not loading everything? Is that amount of memory going to affect performance or app/host stability?

Does the "chatty" version cause too much latency?

Is it possible that you may have to make 15 calls to the configuration service to handle the first request? What kind of wait time will that cause the user?

From experience, I would likely choose the chunky communication, especially since you already have it written.

If you do get a chance to change it, consider a precise but chunky request where you request all settings used by your application at once. That would give you the best of both worlds. However, it better be worth it, because you will still have to maintain a list of required setting keys in your application. There's nothing quite so infuriating as spending a while debugging your code only to realize you forgot to add the setting key to the request list. If code tries to access a missing key, make sure you provide a clear error message!


问:
Making a security on webapi for browser usage
I have a webapi project working in production for few months now.

The entire webapi is server to server.

There is a need now to have the same functionality in a browser, meaning the customers can invoke via ajax functions directly on the webapi server.

Since the webapi is stateless and session usage is not really recommended, what are my options here?

Today (server to server), every request reaching the server has user and pass, and on every request there is a login check (not that efficient, I know).

What happens when the same rest webapi needs to go to the browser and have security?

答:
The most common way to provide security in a Web API application is through the usage of the built-in [Authorize] attribute. You can read more about authentication in Web API here.  The Authorize attribute depends upon the ASP.NET membership or identity framework.  Either the membership system or the identity system can be used.  I would recommend the identity framework since it is newer and the model that will be supported going forward.  You can read more about the ASP.NET identity framework here.  A sample application that implements authorization and authentication using the ASP.NET identity framework can be found here.  I will provide a few common examples.

To restrict access to all controllers/routes globally:

```<code>public static void Register(HttpConfiguration config)
{
    config.Filters.Add(new AuthorizeAttribute());
}
</code>```

To restrict access on individual controllers:

```<code>// Require authorization for all actions on the controller.
[Authorize]
public class ValuesController : ApiController
{
    //Allow anonymous access on Get, but restrict all other actions
    [AllowAnonymous]
    public HttpResponseMessage Get(int id) { ... }
    public HttpResponseMessage Post() { ... }
}
</code>```

To restrict access on specific actions:

```<code>public class ValuesController : ApiController
{
    // Anonymous access is allowed on Get
    public HttpResponseMessage Get() { ... }

    // Require authorization for Post.
    [Authorize]
    public HttpResponseMessage Post() { ... }
}
</code>```

To restrict access to a specific role/user:

```<code>public class ValuesController : ApiController
{
    // Anonymous access is allowed on Get
    public HttpResponseMessage Get() { ... }

    // Require specific user access on Post
    [Authorize(Users="Bob,Joe")]
    public HttpResponseMessage Post() { ... }

    // Require specific role access on Delete
    [Authorize(Roles="Administrators")]
    public HttpResponseMessage Delete() { ... }
}
</code>```

Body:
The most common way to provide security in a Web API application is through the usage of the built-in [Authorize] attribute. You can read more about authentication in Web API here.  The Authorize attribute depends upon the ASP.NET membership or identity framework.  Either the membership system or the identity system can be used.  I would recommend the identity framework since it is newer and the model that will be supported going forward.  You can read more about the ASP.NET identity framework here.  A sample application that implements authorization and authentication using the ASP.NET identity framework can be found here.  I will provide a few common examples.

To restrict access to all controllers/routes globally:

public static void Register(HttpConfiguration config)
{
    config.Filters.Add(new AuthorizeAttribute());
}

To restrict access on individual controllers:

// Require authorization for all actions on the controller.
[Authorize]
public class ValuesController : ApiController
{
    //Allow anonymous access on Get, but restrict all other actions
    [AllowAnonymous]
    public HttpResponseMessage Get(int id) { ... }
    public HttpResponseMessage Post() { ... }
}

To restrict access on specific actions:

public class ValuesController : ApiController
{
    // Anonymous access is allowed on Get
    public HttpResponseMessage Get() { ... }

    // Require authorization for Post.
    [Authorize]
    public HttpResponseMessage Post() { ... }
}

To restrict access to a specific role/user:

public class ValuesController : ApiController
{
    // Anonymous access is allowed on Get
    public HttpResponseMessage Get() { ... }

    // Require specific user access on Post
    [Authorize(Users="Bob,Joe")]
    public HttpResponseMessage Post() { ... }

    // Require specific role access on Delete
    [Authorize(Roles="Administrators")]
    public HttpResponseMessage Delete() { ... }
}


问:
Flat files for events and alarms
So I'm working on a project that I was introduced to a year ago. One of the features of project involves alarming the users when certain events are triggered. There is also a log of these events. First you need to understand this:

Not all alarms generate event logs

Events can be logged without generating alarms.

The design of this involves flat files that hold a bunch of information about the events and the alarms. This includes everything from where the alarms are sent, priority levels, etc.

What happens in the code is when an event is trigger, it sends a message with a bunch of data attached to it to a process that reads in the flat files, replaces the data appropriately, and then routes it.

My question is this:

Is it normal design to save all this information outside of the code. We're running into problems when we deploy because we have to ensure that the flat files and the code are in sync. It's created some troubleshooting nightmares, and it honestly just feels like more hassle then just having a class dedicated to this stuff, and shipping it with the code.

答:
So, as I understand your question you save the configuration of the alarms/events in a file.

Its pretty normal to have configuration files. but I suspect from the tone of the  question that you have taken it a step further in this case and have 'generic' system which you can use to make 'any' alarm/event and that the configuration has both configuration and elements of logic to it.

I think its a constant temptation to write systems this way. Obviously you want a flexible system that 'users' can configure without rewriting code.

However, in my view it can be a bad practice. As a system evolves and features are added, you have the choice to add them to config or to hard code them. The more features you add as configurable options, the more like a programming language your configuration becomes! You can end up with a very sketchy programming language/config, with lots of undocumented tricks and unversioned files.

Its not so much that its wrong to write a new programming language, but that you still have to apply the normal rigour of documentation, version control, deployments, testing etc which you would normally do with a new version of the code.

Also I would add that if you do create a generic alarm/event system, which is not specific to your business. Then you could probably have bought it off the shelf for a lot less than it took to write it.

Title: Flat files for events and alarms