答:
The interface is a contract - an API that exposes the necessary functionality for the object it represents. Therefore, an interface should support all the methods that are related to the concept it stands for.

So I am confused which methods should go where

Usually, an abstract class, or abstract generic class is used instead of directly implementing the interface. These classes in most cases serve as a faster way of implementing the interface and spare you boilerplate code. Generics usually address type-safety of a potential implementation of the interface. It is normal for them to introduce new methods.

A classical example is an abstract class that implements an interface and performs most of the validations and checks, just leaving a few abstract methods that must contain the user logic. This would reduce most of the boilerplate code for the concrete implementation, and point directly to the functionality that is left unimplemented.

The generic classes usually implement most of the interface with along with the type casts and checks and leave similar, now generic methods for the final implementation, which are being called from the non-generic interface methods.

Besides the above, the base classes may introduce context-specific methods for the implementation, or additional methods that do not seem to belong to the interface concept. For instance, when implementing a network stream using an imaginary Stream interface, the implementation may expose methods or properties for the network location, url or other connection details. These are specific to the NetworkStream and the networking context, and will be out of place on the generic Stream interface, as you may also have a MemoryStream implementation, which has nothing to do with network paths.

Another reason for an abstract class to introduce new methods that must not be present in the interfaces is to avoid code dependencies. The interface should not trigger dependency of libraries that are not directly related to the functionality it covers. In most cases, if you stick to the programming to interfaces paradigm, you will reference the library that has the interface and use any implementation of interface trough it, instead of working directly with the implementation type. This will allow you to avoid direct references to any implementation specific libraries when you work with the interface.

Sometimes I see class A extends Abstractuserclass and sometimes class A extends Abstractuserclass imlements useraInterface. What is the differnece if Abstractclass already impelements Userinterface

There is no difference if you specify the interface, if the base class already implements it. I would assume some people do it either because they are too verbose, or because this makes the code more readable. By reading the following line of code, I will not need to gasp into the Abstractuserclass to see that it implements the UseraInterface:

```<code>class A extends Abstractuserclass implements UseraInterface
</code>```

So, this saves some effort and makes the code a kind of a self-explanatory one.

Title: Which methods should be put in an interface and which in abstract classes?

Body:
I have seen many frameworks and modules and their standard they follow is like this

UserInterface which have some predefined methods

AbstractUserClass which implements userInterface

Then GenericUserClass which extends from AbstractuserClass

Then other classes extending from that generic

Now I have seen that abstract class has additional functions to the interface, and the generic class also has additional functions.

So I am confused which methods should go where

Sometimes I see class A extends Abstractuserclass and sometimes class A extends Abstractuserclass implements UseraInterface. What is the difference if Abstractclass already impelements Userinterface

Body:
The interface is a contract - an API that exposes the necessary functionality for the object it represents. Therefore, an interface should support all the methods that are related to the concept it stands for.

So I am confused which methods should go where

Usually, an abstract class, or abstract generic class is used instead of directly implementing the interface. These classes in most cases serve as a faster way of implementing the interface and spare you boilerplate code. Generics usually address type-safety of a potential implementation of the interface. It is normal for them to introduce new methods.

A classical example is an abstract class that implements an interface and performs most of the validations and checks, just leaving a few abstract methods that must contain the user logic. This would reduce most of the boilerplate code for the concrete implementation, and point directly to the functionality that is left unimplemented.

The generic classes usually implement most of the interface with along with the type casts and checks and leave similar, now generic methods for the final implementation, which are being called from the non-generic interface methods.

Besides the above, the base classes may introduce context-specific methods for the implementation, or additional methods that do not seem to belong to the interface concept. For instance, when implementing a network stream using an imaginary Stream interface, the implementation may expose methods or properties for the network location, url or other connection details. These are specific to the NetworkStream and the networking context, and will be out of place on the generic Stream interface, as you may also have a MemoryStream implementation, which has nothing to do with network paths.

Another reason for an abstract class to introduce new methods that must not be present in the interfaces is to avoid code dependencies. The interface should not trigger dependency of libraries that are not directly related to the functionality it covers. In most cases, if you stick to the programming to interfaces paradigm, you will reference the library that has the interface and use any implementation of interface trough it, instead of working directly with the implementation type. This will allow you to avoid direct references to any implementation specific libraries when you work with the interface.

Sometimes I see class A extends Abstractuserclass and sometimes class A extends Abstractuserclass imlements useraInterface. What is the differnece if Abstractclass already impelements Userinterface

There is no difference if you specify the interface, if the base class already implements it. I would assume some people do it either because they are too verbose, or because this makes the code more readable. By reading the following line of code, I will not need to gasp into the Abstractuserclass to see that it implements the UseraInterface:

class A extends Abstractuserclass implements UseraInterface

So, this saves some effort and makes the code a kind of a self-explanatory one.


问:
What is the relation between clojure reducers and loop fusion
I just stumbled upon Clojure reducers library.

It looks a lot like loop fusion. However the term is not mentioned anywhere on the page. Is there a difference between the two?

答:
Loop fusion is an optimisation where the compiler notices you have two separate loops iterating over the same values, so just fuses the loop bodies.

You get reducers when you split the classic fold/reduce implementation into its separate pieces. In particular, you split out the reducing function itself (the action you take on the accumulator and current value) and the particular traversal scheme.

I imagine the reason you thought of loop fusion is that you can combine reducing functions together, so that when reduction actually takes place (i.e., when you actually iterate over the values of the collection), the reductions happen "together".

The bodies of the loops correspond to the reducing functions, and the loop itself corresponds to the traversal scheme.

One important difference is that the actions that take place inside the loops have no necessary relationship: they could perform completely different actions. With reducers, you're still mapping a collection to a result (in the case of reduce. Obviously for map you're mapping a collection to a collection). It's still a function returning a single result.

ContentLicense: CC BY-SA 3.0


问:
Complexity in nested loops
Foreword:

In this post, I will make the common confusion between O(n) and Theta(n) as complexity notations.

I will write pseudo-code to talk about algorithms, using whatever notation I find to my liking.

I know, yet another question about nested loops and complexity.

I recently wrote a nested algorithm, that would work as a bottleneck of a more complex application. It somehow looked like this:

```<code>while(firstLoopRunning) {
    foreach(element in myArray) {
        doSomeAction(element);
    }
}
</code>```

My keen-eye brought me to the conclusion that, as doSomeAction is in O(1), the algorithm had to be in O(n²).

I know however that nested loops can have a different complexity. For instance the following is in O(n.log(n)):

```<code>for(i in 0..n) // n is constant in this loop
    for(j in 0..i) // j goes up to i and not to a constant
        print(j);
</code>```

Then I thought, hey, I know that myArray has a maximum length. In this particular case, I know by design that there will never be more than 8 elements in myArray, so the algorithm could look like this:

```<code>while(firstLoopRunning) {
    // Let's do this one in Java, myArray would actually be an ArrayList
    try {
        doSomeAction(myArray.get(0));
        doSomeAction(myArray.get(1));
        doSomeAction(myArray.get(2));
        doSomeAction(myArray.get(3));
        doSomeAction(myArray.get(4));
        doSomeAction(myArray.get(5));
        doSomeAction(myArray.get(6));
        doSomeAction(myArray.get(7));
    } catch(ArrayOutOfBoundsException ex) {
       // Just a lazy way for me to avoid checking if the index exists
    }
}
</code>```

And voilà! Here it is in O(n)!

Moreover, I know for a fact that compilers usually transform fake loops such as this one:

```<code>for(i in 0..8) // not really a loop
    someCall(i);
</code>```

into a sequence of calls.

Which brought me to a first conclusion:

A iteration over an array which length will have a known finite upper-bound is in O(1).

I think I'm right about this one (aka: correct me if I'm wrong).

On the other hand, we are working with finite data and the whole point of the complexity theory is to work on theorically infinite data.

So let's use another classical example: we are iterating over the squares in a grid (=~ bidimensional array), so clearly an O(n²) algorithm. What if however we would to put all the squares in a single list and change this:

```<code>// O(n²) algorithm over myGrid[][]
for(i in myGrid)
    for(j in myGrid[i])
        yieldAction(myGrid[i][j])
</code>```

into this

```<code>// O(n) algorithm over myFlatGrid[]
for(i in myFlatGrid)
    yieldAction(myFlatGrid[i mod rowLength][j])
</code>```

Basically the same thing but different complexity, yet no loop has in fact been gained. Granted that the grid can grow in both dimensions so the variable really is quadratic, but in a way it can definitely be treated in a linear way (even though that's not worth it).

But I must be missing something. What sense does it make that if a twist the data a litte, I can change the complexity of an algorithm on a theorical point of view although the exact same number of operations is performed?

答:
You seem to think that the complexity of an algorithm is linked to the number of nested loops. It is not the case. The following piece of code is O(1):

```<code>for i in [1.. 10^15]:
    for j in [1.. 10^15]:
        for k in [1.. 10^15]:
            dosomethingO1()
</code>```

Complexity is related to the rate of growth of the number of operations. Unrolling your loop does not change that. So:

```<code>foreach(element in myArray) {
    doSomeAction(element);
}
</code>```

Has 0(1) if the number of elements in myArray is bounded. The complexity will be decided by the number of iterations in the while loop.

About your grid example: if n is the number of cells and your grid is represented as a nested array, looping over those arrays still yields O(n) complexity.

Title: Complexity in nested loops

Body:
You seem to think that the complexity of an algorithm is linked to the number of nested loops. It is not the case. The following piece of code is O(1):

for i in [1.. 10^15]:
    for j in [1.. 10^15]:
        for k in [1.. 10^15]:
            dosomethingO1()

Complexity is related to the rate of growth of the number of operations. Unrolling your loop does not change that. So:

foreach(element in myArray) {
    doSomeAction(element);
}

Has 0(1) if the number of elements in myArray is bounded. The complexity will be decided by the number of iterations in the while loop.

About your grid example: if n is the number of cells and your grid is represented as a nested array, looping over those arrays still yields O(n) complexity.


问:
Is my understanding of abstract datatypes correct?
After reading lots of pages on various sites, I came to the conclusion that abstract datatype helps to separate the use of datastructure from its implementation. We can easily map the data into a datastructure by using an already available abstraction. And this abstraction is called ADT. Please tell me if I have understood this correctly. Also if you can give a small example, it will be very helpful. If you prefer to give any code in your example, C or Python would be helpful for me.

Addition: They are a very special implementation of data abstraction. What separates them from other instances of abstractions is that ADTs are theoretical constructs. Theoretical constructs that help map or represent data in a desired data structure. They have attributes or operations associated with them. These operations may be applied on the data that has been mapped into the ADT. How the data is actually stored inside the ADT or how the operations work are kept hidden.

EDIT: I had previously said, "ADT is like the blueprint of a datastructure". A few of the answers have explained why it's not. I didn't have a clear comprehension of what a 'blueprint' is and that was the reason for using the term. So, I've now removed it from my original text.

答:
An abstract data type is a mathematical abstraction used to describe
algorithms and prove them.  The idea of an algorithm or of an abstract
data type is thus rather independant from any computer language or
even from the availability of a computer. (I am not sure if this is your idea of a blueprint.)

Of course, computers and programming language are a very important
application field of algorithms, and it is quite common to implement
an algorithm in a given computer language.  (Lines are even blurrier
since many programmers will not even make a strong distinction between
an abstract algorithm and its implementation in a given computer
language.)  So, in order to implement these abstract algorithms
described in terms of abstract data types, programmers need to
implement abstract data types.

It is a common case, that am implementation of an abstract data type
has more properties than required, and one may accidentally use one in
a program, which leads to a bug if the implementation is modified.

While formally proving a complex program is typically not worth the
effort, it is important to get a confidence that a program
accomplishes its purpose and functions correctly.  (There is a
parallel with mathematics, since mathematical proofs can be written at
various levels of details, depending of the audience or the purpose.)
The use of appropriate abstract data types is very important for this,
because by introducing the adequate abstractions, one makes not only
the program easier to reason about or to describe but one also
demonstrates its good understanding of the problem and the solution
brought by the program.

The computer language OCaml has the ability to expose abstract data
types, which are types whose definition is kept private to some
module, which helps understanding and using abstract data types.


答:
Yes. But by changing the data, you are also changing the n. In your fist example, the n is actually constant. So it makes sense than the whole algorithms is actually constant.

In your second example, while you can turn the O(n^2) algorithm into O(n) algorithm, the amount of data increases from n to n^2, so it in the end, the total complexity remains same.

As Simon hinted, the O-notation is not about absolute values of n, but how the time of algorithm changes based on how you change n. With O(n) algorithm, the time increases linearly, so if n increases 2x, the time increases 2x. With O(n^2), the time increases quadraticaly, so if n increases 2x the time increases 4x, etc..

The point is by changing the data, the rate of growth of n can also change. Like in your example with grid. If you increase the length of side by 2, then the algorithm is going to take 4x that long no matter what. Because in O(n^2), the n is length of the side and in O(n), the n is number of total items which is equal to square of side.

Title: Complexity in nested loops

Body:
Foreword:

In this post, I will make the common confusion between O(n) and Theta(n) as complexity notations.

I will write pseudo-code to talk about algorithms, using whatever notation I find to my liking.

I know, yet another question about nested loops and complexity.

I recently wrote a nested algorithm, that would work as a bottleneck of a more complex application. It somehow looked like this:

```<code>while(firstLoopRunning) {
    foreach(element in myArray) {
        doSomeAction(element);
    }
}
</code>```

My keen-eye brought me to the conclusion that, as doSomeAction is in O(1), the algorithm had to be in O(n²).

I know however that nested loops can have a different complexity. For instance the following is in O(n.log(n)):

```<code>for(i in 0..n) // n is constant in this loop
    for(j in 0..i) // j goes up to i and not to a constant
        print(j);
</code>```

Then I thought, hey, I know that myArray has a maximum length. In this particular case, I know by design that there will never be more than 8 elements in myArray, so the algorithm could look like this:

```<code>while(firstLoopRunning) {
    // Let's do this one in Java, myArray would actually be an ArrayList
    try {
        doSomeAction(myArray.get(0));
        doSomeAction(myArray.get(1));
        doSomeAction(myArray.get(2));
        doSomeAction(myArray.get(3));
        doSomeAction(myArray.get(4));
        doSomeAction(myArray.get(5));
        doSomeAction(myArray.get(6));
        doSomeAction(myArray.get(7));
    } catch(ArrayOutOfBoundsException ex) {
       // Just a lazy way for me to avoid checking if the index exists
    }
}
</code>```

And voilà! Here it is in O(n)!

Moreover, I know for a fact that compilers usually transform fake loops such as this one:

```<code>for(i in 0..8) // not really a loop
    someCall(i);
</code>```

into a sequence of calls.

Which brought me to a first conclusion:

A iteration over an array which length will have a known finite upper-bound is in O(1).

I think I'm right about this one (aka: correct me if I'm wrong).

On the other hand, we are working with finite data and the whole point of the complexity theory is to work on theorically infinite data.

So let's use another classical example: we are iterating over the squares in a grid (=~ bidimensional array), so clearly an O(n²) algorithm. What if however we would to put all the squares in a single list and change this:

```<code>// O(n²) algorithm over myGrid[][]
for(i in myGrid)
    for(j in myGrid[i])
        yieldAction(myGrid[i][j])
</code>```

into this

```<code>// O(n) algorithm over myFlatGrid[]
for(i in myFlatGrid)
    yieldAction(myFlatGrid[i mod rowLength][j])
</code>```

Basically the same thing but different complexity, yet no loop has in fact been gained. Granted that the grid can grow in both dimensions so the variable really is quadratic, but in a way it can definitely be treated in a linear way (even though that's not worth it).

But I must be missing something. What sense does it make that if a twist the data a litte, I can change the complexity of an algorithm on a theorical point of view although the exact same number of operations is performed?


答:
It seems, you have no clear understanding about what the n is in O(n), which is why you are puzzled.

My keen-eye brought me to the conclusion that, as doSomeAction is in O(1), the algorithm had to be in O(n²).

This is only true if both loops are in O(n) but if the loops have complexities O(p) and O(q) then the overall program has complexity O(pq) and so on.  In your example, you have an outer loop taking place n times and triggering a loop of length p not greater than 8, so that the overall loop has complexity bounded by O(8n) = O(n).

If the complexity of the inner loop is not constant, you have to do some finer approximation.

I know however that nested loops can have a different complexity. For instance the following is in O(n.log(n))

It is not. Recall that

```<code>1 + 2 + ... + n = n(n+1)/2 = O(n²)
</code>```

so that the complexity of your loop is O(n²) and not O(n.log(n)).

Title: Complexity in nested loops

Body:
It seems, you have no clear understanding about what the n is in O(n), which is why you are puzzled.

My keen-eye brought me to the conclusion that, as doSomeAction is in O(1), the algorithm had to be in O(n²).

This is only true if both loops are in O(n) but if the loops have complexities O(p) and O(q) then the overall program has complexity O(pq) and so on.  In your example, you have an outer loop taking place n times and triggering a loop of length p not greater than 8, so that the overall loop has complexity bounded by O(8n) = O(n).

If the complexity of the inner loop is not constant, you have to do some finer approximation.

I know however that nested loops can have a different complexity. For instance the following is in O(n.log(n))

It is not. Recall that

1 + 2 + ... + n = n(n+1)/2 = O(n²)

so that the complexity of your loop is O(n²) and not O(n.log(n)).


答:
When taking N and your grid to get your O(n^2) you should instead talk about a grid with for instance N columns and N rows.

Now you will see that with a doubling N, that amounth of tiles quadruples.

And no matter if you put it in  list or change the notation, the problem will always have O(n^2) complexity.

Title: Complexity in nested loops


问:
Is path coverage stronger than condition coverage?
I have encountered (even in literature) two contradicting opinions related to path vs condition coverage (not branch or edge!). Some say Path coverage is stronger than the condition coverage, some say the opposite.

Having code like this:

```<code>If(X<0 OR X>100)
   DoStuff();
</code>```

Path coverage - 1 test case is needed to cover the path. With X=-1, the second expression will not be tested and possible bug will be missed.

Condition coverage - test cases X=-1 and X=100 are needed to test both conditions.

Am I missing something or condition coverage is really stronger than path coverage?

Condition coverage (ISTQB):

Our next level of coverage is called condition coverage. The basic concept is that, when a decision is made by a complex expression that eventually evaluates to TRUE or FALSE, we want to make sure that each atomic condition is tested both ways.

Practical Insight Into CMMI

Condition coverage measures the true and false outcome of each Boolean
  subexpression.

References:

Software Testing: Principles and Practices from Srinivasan Desikan,Gopalaswamy Ramesh: page 61

Condition coverage is a much stronger criteria than path coverage,
  which in turns is a much stronger criteria than statement coverage.

答:
As already mentioned, neither

Path Coverage implies Condition Coverage NOR

Condition Coverage implies Path Coverage

There are very simple examples which proof that:

(1): Path Coverage doesn't imply Condition Coverage:

```<code>if (A and B) then
    some elementary statement(s)
end if
</code>```

Path Coverage is provided by:

A = false

A = true and B = true

But: For Condition Coverage we require A = true and B = false as well.

(2): Condition Coverage doesn't imply Path Coverage:

```<code>if (A)
    some elementary statement(s)
end if
if (B)
    some (other) elementary statement(s)
end
</code>```

Condition Coverage is provided by:

A = false and B = false

A = true and B = true

But: For Path Coverage we require A = false and B = true as well as A = true and B = false.

Body:
As already mentioned, neither

Path Coverage implies Condition Coverage NOR

Condition Coverage implies Path Coverage

There are very simple examples which proof that:

(1): Path Coverage doesn't imply Condition Coverage:

if (A and B) then
    some elementary statement(s)
end if

Path Coverage is provided by:

A = false

A = true and B = true

But: For Condition Coverage we require A = true and B = false as well.

(2): Condition Coverage doesn't imply Path Coverage:

if (A)
    some elementary statement(s)
end if
if (B)
    some (other) elementary statement(s)
end

Condition Coverage is provided by:

A = false and B = false

A = true and B = true

But: For Path Coverage we require A = false and B = true as well as A = true and B = false.


问:
Where to store the private key?
Say I want some parts of my software to be encrypted. For example, the credentials for a database, etc. I need to store those values somewhere, but doing so in cleartext would make it easy for an attacker to gain unauthorised access.

However, if I encrypt some cleartext, then where do I store the key? Anything that software has access to, a determined attacker would have access to, no matter what level of obfuscation:

Say the key is protected by the filesystem's security model; but what about (malicious) superusers, or platforms that don't provide such fidelity?

Or the key is hardcoded into software binaries, but it could always be decompiled and what about open source software or interpreted code?

If the key is generated, such an algorithm would need to be deterministic (presumably) and then the same problem applies to the seed.

etc.

Cryptography is only as strong as the weakest link in its chain and this seems like a pretty loose one! Presuming it's the right tool for the job (humour me), then how can one secure such information robustly?

Regarding the right tool for the job: Probably, in -- for example -- the case of service access (DBs, authentication servers, etc.), you would restrict access at this tier with a service account, maybe with some service-level auditing, etc. and so having the credentials in cleartext isn't such a worry.

To me, however, that still seems inadequate: I don't want anyone poking around where they shouldn't be!

答:
What you want can't be done.

Say the key is protected by the filesystem's security model; but what
  about (malicious) superusers, or platforms that don't provide such
  fidelity?

You basically want protection from people turning malicious. In your model, at some point someone will have access to the key. What if that person is malicious? What if YOU are malicious? See, the problem as you state is unsolvable except by not having a key at all.

So don't work with Database credentials but other authentication mechanisms. But no matter what, someone at some point needs access to the data and that someone can be malicious.

Title: Where to store the private key?


答:
One of systems I currently use works this way.

I start with a login form of the authentication service. It uses two-factor authentication to make sure I am who I claim I am.

I receive a temporary SSL certificate that I can use to access the protected service. The service keeps track of the certificates it accepts.

My exchanges are encrypted by this certificate from eavesdropping. Trying to crack it is not very useful since it will expires.

The certificate expires quickly (in several hours), but not too quickly so that I don't need to provide a password for every interaction.

The certificate can be instantly revoked on the other side.

Of course the protected service runs somewhere out of my reach. It could run on my machine under a different account (and possibly in a container), but I have superuser privileges and could then try to circumvent the restrictions.

Basically if you have a malicious superuser, all bets are off. And you should assume the presence of a malicious superuser in your threat model.

So you need to isolate your protected service from the client-accessible machine. Move the protected service to a machine only accessible via network. Put your clients to virtual machines that prevent them from reaching out to the rest of the physical machine where your protected service runs.

If your protected service is not so precious as to be able to command such measures, go with whatever encrypted key store the OS gives you: both Windows, Linux, and OSX have keyring implementations.

Title: Where to store the private key?

Body:
Say I want some parts of my software to be encrypted. For example, the credentials for a database, etc. I need to store those values somewhere, but doing so in cleartext would make it easy for an attacker to gain unauthorised access.

However, if I encrypt some cleartext, then where do I store the key? Anything that software has access to, a determined attacker would have access to, no matter what level of obfuscation:

Say the key is protected by the filesystem's security model; but what about (malicious) superusers, or platforms that don't provide such fidelity?

Or the key is hardcoded into software binaries, but it could always be decompiled and what about open source software or interpreted code?

If the key is generated, such an algorithm would need to be deterministic (presumably) and then the same problem applies to the seed.

etc.

Cryptography is only as strong as the weakest link in its chain and this seems like a pretty loose one! Presuming it's the right tool for the job (humour me), then how can one secure such information robustly?

Regarding the right tool for the job: Probably, in -- for example -- the case of service access (DBs, authentication servers, etc.), you would restrict access at this tier with a service account, maybe with some service-level auditing, etc. and so having the credentials in cleartext isn't such a worry.

To me, however, that still seems inadequate: I don't want anyone poking around where they shouldn't be!


问:
TDD and complete test coverage where exponential test cases are needed
I am working on a list comparator to assist sorting an unordered list of search results per very specific requirements from our client.  The requirements call for a ranked relevance algorithm with the following rules in order of importance:

Exact match on name

All words of search query in name or a synonym of the result

Some words of search query in name or synonym of the result (% descending)

All words of the search query in the description

Some words of the search query in the description (% descending)

Last modified date descending

The natural design choice for this comparator seemed to be a scored ranking based on powers of 2.  The sum of lesser important rules can never be more than a positive match on a higher importance rule.  This is achieved by the following score:

32

16

8 (Secondary tie-breaker score based on % descending)

4

2 (Secondary tie-breaker score based on % descending)

1

In the TDD spirit I decided to start with my unit tests first.  To have a test case for each unique scenario would be at a minimum 63 unique test cases not considering additional test cases for secondary tie breaker logic on rules 3 and 5.  This seems overbearing.

The actual tests will actually be less though.  Based on the actual rules themselves certain rules ensure that lower rules will always be true (Eg. When 'All Search Query words appear in description' then rule 'Some Search Query words appear in description' will always be true).  Still is the level of effort in writing out each of these test cases worth it?  Is this the level of testing that is typically called for when talking about 100% test coverage in TDD?  If not then what would be an acceptable alternative testing strategy?

答:
Still is the level of effort in writing out each of these test cases worth it?

You'll need to define "worth it". The problem with this sort of scenario is that the tests will have a diminishing return on usefulness. Certainly the first test you write will be totally worth it. It can find obvious errors in the priority and even things like parsing errors when trying to break up the words.

The second test will be worth it because it covers a different path through the code, probably checking another priority relation.

The 63rd test will probably not be worth it because it's something you're 99.99% confident is covered by the logic of your code or another test.

Is this the level of testing that is typically called for when talking about 100% test coverage in TDD?

My understanding is 100% coverage means that all of the code paths are exercised. This does not mean you do all combinations of your rules, but all the different paths your code could go down (as you point out, some combinations can't exist in code). But since you're doing TDD, there is no "code" yet to check paths for. The letter of the process would say make all 63+.

Personally, I find 100% coverage to be a pipe dream. Beyond that, it's unpragmatic. Unit tests exists to serve you, not vice versa. As you make more tests, you get diminishing returns on the benefit (the likelihood that the test prevents a bug + the confidence that the code is correct). Depending on what your code does defines where on that sliding scale you stop making tests. If your code is running a nuclear reactor, then maybe all 63+ tests are worth it. If your code is organizing your music archive, then you could probably get away with a lot less.


答:
I'd argue that this is a perfect case for TDD.

You have a known set of criteria to test, with a logical breakdown of those cases.  Assuming you are going to unit test them either now or later, it seems to make sense to take the known result and build around it, insuring you are, in fact, covering each of the rules independently.

Plus, you get to find out as you go if adding a new search rule breaks an existing rule.  If you do these all at the end of coding, you presumably run a bigger risk of having to change one to fix one, which breaks another, which breaks another...  And, you learn as you implement the rules whether your design is valid or needs tweaking.

Title: TDD and complete test coverage where exponential test cases are needed

Body:
I am working on a list comparator to assist sorting an unordered list of search results per very specific requirements from our client.  The requirements call for a ranked relevance algorithm with the following rules in order of importance:

Exact match on name

All words of search query in name or a synonym of the result

Some words of search query in name or synonym of the result (% descending)

All words of the search query in the description

Some words of the search query in the description (% descending)

Last modified date descending

The natural design choice for this comparator seemed to be a scored ranking based on powers of 2.  The sum of lesser important rules can never be more than a positive match on a higher importance rule.  This is achieved by the following score:

32

16

8 (Secondary tie-breaker score based on % descending)

4

2 (Secondary tie-breaker score based on % descending)

1

In the TDD spirit I decided to start with my unit tests first.  To have a test case for each unique scenario would be at a minimum 63 unique test cases not considering additional test cases for secondary tie breaker logic on rules 3 and 5.  This seems overbearing.

The actual tests will actually be less though.  Based on the actual rules themselves certain rules ensure that lower rules will always be true (Eg. When 'All Search Query words appear in description' then rule 'Some Search Query words appear in description' will always be true).  Still is the level of effort in writing out each of these test cases worth it?  Is this the level of testing that is typically called for when talking about 100% test coverage in TDD?  If not then what would be an acceptable alternative testing strategy?


问:
How bad can it be to lack teamwork when you are a programmer?
I'm still at school, and I know I have problems dealing with other people.

I'm not an angry or shy or different, I just like to work my way and with my opinions while respecting other's, I have a big curiosity and hunger for knowledge, but I lack practice and I guess people don't want to work with me because they might fear I would talk some kind of morale. (For example I started to learn programming using linux instead of windows, even if I use windows a lot. And I have a mac).

What happens to programmers who lack teamwork? Where does the problems begin? Does being a good programmer compensate at least a little? Is it normal for a programmer to have a vision about his work instead of just doing what he is told?

答:
Professional software development today is primarily a team effort. The best software is produced through sharing of new ideas and high collaboration and not tinkering by your lonely self. The cowboy coder ideal is a known impediment to teams. In fact, it is by definition the complete opposite of teamwork.

So yes, having poor team skills in a team setting is very bad. But if you are honestly willing to work with it, there is no reason you won't eventually be a great team contributor (with great coding skills to boot)!

ContentLicense: CC BY-SA 2.5


答:
Consider writing a class that goes through a predefined list of conditions and multiplies a current score by 2 for every successful check.

This can be tested very easily, using just a couple of mocked tests.

Then you can write a class for each condition and there are only 2 tests for each case.

I'm not really understanding your use case, but hopefully this example will help.

```<code>public class ScoreBuilder
{
    private ISingleScorableCondition[] _conditions;
    public ScoreBuilder (ISingleScorableCondition[] conditions)
    {
        _conditions = conditions;
    }

    public int GetScore(string toBeScored)
    {
        foreach (var condition in _conditions)
        {
            if (_conditions.Test(toBeScored))
            {
                // score this somehow
            }
        }
    }
}

public class ExactMatchOnNameCondition : ISingleScorableCondition
{
    private IDataSource _dataSource;
    public ExactMatchOnNameCondition(IDataSource dataSource)
    {
        _dataSource = dataSource;
    }

    public bool Test(string toBeTested)
    {
        return _dataSource.Contains(toBeTested);
    }
}

// etc
</code>```

You'll notice that your 2^conditions tests quickly comes down to 4+(2*conditions). 20 is much less overbearing than 64. And if you add another one later, you don't have to change ANY of the existing classes (open-closed principle), so you don't have to write 64 new tests, you just have to add another class with 2 new tests and inject that into your ScoreBuilder class.

Body:
Consider writing a class that goes through a predefined list of conditions and multiplies a current score by 2 for every successful check.

This can be tested very easily, using just a couple of mocked tests.

Then you can write a class for each condition and there are only 2 tests for each case.

I'm not really understanding your use case, but hopefully this example will help.

public class ScoreBuilder
{
    private ISingleScorableCondition[] _conditions;
    public ScoreBuilder (ISingleScorableCondition[] conditions)
    {
        _conditions = conditions;
    }

    public int GetScore(string toBeScored)
    {
        foreach (var condition in _conditions)
        {
            if (_conditions.Test(toBeScored))
            {
                // score this somehow
            }
        }
    }
}

public class ExactMatchOnNameCondition : ISingleScorableCondition
{
    private IDataSource _dataSource;
    public ExactMatchOnNameCondition(IDataSource dataSource)
    {
        _dataSource = dataSource;
    }

    public bool Test(string toBeTested)
    {
        return _dataSource.Contains(toBeTested);
    }
}

// etc

You'll notice that your 2^conditions tests quickly comes down to 4+(2*conditions). 20 is much less overbearing than 64. And if you add another one later, you don't have to change ANY of the existing classes (open-closed principle), so you don't have to write 64 new tests, you just have to add another class with 2 new tests and inject that into your ScoreBuilder class.


问:
Can some LGPL library published upgrades use a commercial library?
I am using a LGPL v3 library and have made upgrades to it. Before using these upgrades, I understand I have to publish them. That's al-right.

Is it legal if I perform upgrades that use a commercial library of
my own (upgrades will be published, but not my commercial library)? Note: usually, questions are the other side: commercial applications that want to use GPL libraries.

If yes to (1), is there some restrictions on the build of the upgraded LGPL library ? Shall the commercial library be dynamically or statically linked, or whatever ?

答:
First, the necessary IANAL disclaimer. IMHO the LGPL cannot force you to publish working code. Lets assume you would publish a new version of that lib and introduce a new bug. There is no obligation for you to fix that bug (at least, not from the LGPL itself, maybe you have a contract with your customers, but that's a different question).

Now let's assume further that this "bug" is of a nature that the lib (or the features you have added) only works when your commercial library is available on the target system. This does not make a big difference to the first situation, there is still no obligation to publish your commercial part. There is a risk of making your fork unpopular, but I don't think it will become illegal this way.

However, AFAIK one core point of the LGPL is that end-users should be enabled to update the LGPL-covered parts of the application system you are publishing, without any restrictions. This probably won't be possible if your deployed version of the LGPL library is statically linked against anything you don't publish to the world. So if you want to avoid a license breach, you should make sure that after your modifications, others can still compile the LGPL lib in a form which is "enabled" for working together with your commercial lib, even when they don't have a license for your commercial lib.


答:
I do not find the LGPL conclusively denying or allowing the scenario you describe.
It does sounds somewhat against the spirit of the LGPL.

Wouldn't it be a better solution if you refactor the LGPL code such that you add interfaces that allow you to plug in your proprietary functionality? This may benefit others with similar requirements.

This would be also to your own benefit if your patch is accepted by the library's maintainers: you don't need to merge your fork of the library with later revisions of the library.

Title: Can some LGPL library published upgrades use a commercial library?

Body:
I am using a LGPL v3 library and have made upgrades to it. Before using these upgrades, I understand I have to publish them. That's al-right.

Is it legal if I perform upgrades that use a commercial library of
my own (upgrades will be published, but not my commercial library)? Note: usually, questions are the other side: commercial applications that want to use GPL libraries.

If yes to (1), is there some restrictions on the build of the upgraded LGPL library ? Shall the commercial library be dynamically or statically linked, or whatever ?


问:
Why is 80 characters the 'standard' limit for code width?
Why is 80 characters the "standard" limit for code width? Why 80 and not 79, 81 or 100? What is the origin of this particular value? </p>

答: One of the reasons for the 80 column cards may be associated with the 'hand punch' which was probably in use before the electronic card punch machines. It is one which I used in the early 70s on an ICL System 4-50 main frame computer site. One had to punch a section of three? punch knives in the carriage at the same time.</p>


问:
Java web application folder structure
As a beginner to J2EE, I have recently started developing my own project from scratch using the Core of J2EE : Servlets & Jsps.

I could not evaluate whether my project folder structure is right or not.
Here is my project folder structure.

Before asking question, I admit that I could not answer or neither justify if somebody asks me, why this type of folder structure.
The question: Is it a good sign to put my jsps outside of web-inf. If not, why is it so? If yes why?

Is there any standard folder structure convention for a J2EE web application, I know maven has brought up some standards but still, we can customize as per the requirement I believe.

I have done a bit of googling and found the two references
1
2

where in the answers are not on the same page, from which I couldn't draw any conclusion.

What are the points to be considered while laying out the folder structure for a J2EE web application, importantly where should the Jsps, static content should go into & why?

答:
I agree with Brice. I'm beginner too in J2EE, but I think that it´s better working easy and clearly in the beginning.

The root folder is WEBAPP, and you should make your web structure thinking that the most of the pages will locate there. If not, when the pages communicate between them probably you can't manage file relationships without errors.

Title: Java web application folder structure


答:
I am not a fan of strictly interpreting 100% test coverage as writing specs against every single method or testing every permutation of the code.  Doing this fanatically tends to lead to a test-driven design of your classes that doesn't properly encapsulate business logic and yields tests/specs that are generally meaningless in terms of describing the business logic supported.  Instead, I focus on structuring the tests much like the business rules themselves and strive to exercise every conditional branch of the code with tests with the explicit expectation that that tests are easily understood by the tester as generally use-cases would be and actually describes the business rules that were implemented.

With this idea in mind, I would exhaustively unit test the 6 ranking factors you listed in isolation to each other followed up with 2 or 3 integration style tests that ensure you're rolling up your results to expected overall ranking values.  For example, case #1, Exact Match on Name, I would have at least two unit tests to test when its exact and when its not and that the two scenarios return expected score.  If its case sensitive, then also a case to test "Exact Match" vs. "exact match" and possibly other input variations such as punctuation, extra spaces, etc. also returns expected scores.

Once I've worked through all the individual factors contributing to the ranking scores, I essentially assume these to be functioning correctly at the integration level and focus on ensuring their combined factors correctly contribute to the final expected ranking score.

Assuming cases #2/#3 and #4/#5 are generalized to same underlying methods, but passing different fields in, you only have to write one set of unit tests for the underlying methods and write simple additional unit tests to test the specific fields (title, name, description, etc.) and scoring at designated factoring, so this further reduces redundancy of your overall testing effort.

With this approach, the above described approach would probably yield 3 or 4 unit tests on case #1, perhaps 10 specs on some/all w/synonyms accounted for -- plus 4 specs on correct scoring of cases #2 - #5 and 2 to 3 specs on the final date ordered ranking, then 3 to 4 integration level tests that measure all 6 cases combined in likely ways (forget about obscure edge cases for now unless you clearly see a problem in your code that needs to be exercised to ensure that condition is handled) or ensure does not get violated/broken by later revisions.  That yields about 25 or so specs to exercise 100% of the code written (even though you didn't directly call 100% of the methods written).


问:
How to maintain view logic separation with a server
I am writing a client server application. I wanted to fully separate the server logic, from the view. The first thing I wanted to to, is to make a sort of a message log.

The server itself should not know if the messages will be shown at a GUI, or on the console.

What I was thinking, would be to have a handler method, that would be called every time a new message was posted. So a GUI app would have it's own method to maybe add to a listView, while the console would have a simple printf.

Is there a better way to do this?

答:
You're on the right track and more or less describing the Adapter Design Pattern, which is defined by wikipedia as:

Adapter design pattern is used when you want two different classes
  with incompatible interfaces to work together. Interfaces may be
  incompatible but the inner functionality should suit the need. The
  Adapter pattern allows otherwise incompatible classes to work together
  by converting the interface of one class into an interface expected by
  the clients.

In your case, you would probably have a GUI adapter and a Console adapter, both which would consume handle the server messages as appropriate for their user interface and you would instantiate at run-time whichever adapter is most appropriate.


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答:
Programmers who became managers saying:

"Three weeks?! I've coded in the past, how hard can it be?"


答:
Your question implies that TDD has something to do with "writing all test cases first". IMHO that's not "in the spirit of TDD", actually it's against it. Remember that TDD stands for "test driven development", so you need only those test cases which really "drive" your implementation, not more. And as long as your implementation is not designed in a way where the number of code blocks grows exponentially with each new requirement, you won't need an exponential number of test cases either. In your example, the TDD cycle probably will look like this:

start with the first requirement from your list : words with "Exact match on name" must get a higher score than everything else

now you write a first test case for this (for example: a word matching a given query) and implement the minimal amount of working code which makes that test pass

add a second test case for the first requirement (for example: a word not matching the query), and before adding a new test case, change your existing code until the 2nd test passes

depending on details of your implementation, feel free to add more test cases, for example, an empty query, an empty word etc (remember: TDD is a white box approach, you can make use of the fact that you know your implementation when you design your test cases).

Then, start with the 2nd requirement:

"All words of search query in name or a synonym of the result" must get a lower score than "Exact match on name", but a higher score than everything else.

now build test cases for this new requirement, just like above, one after another, and  implement the next part of your code after each new test. Don't forget to refactor in between, your code as well as your test cases.

Here comes the catch: when you add test cases for requirement/category number "n", you will only have to add tests for making sure that the score of the category "n-1" is higher than the score for category "n". You will not have to add any test cases for every other combination of the categories 1,...,n-1, since the tests you have written before will make sure that the scores of that categories will still be in the correct order.

So this will give you a number of test cases which grows approximately linear with the number of requirements, not exponentially.


答:
I've never been a fan of 100% test coverage.  In my experience, if something is simple enough to test with only one or two test cases, then it's simple enough to rarely fail.  When it does fail it's usually due to architectural changes that would require test changes anyway.

That being said, for requirements like yours I always unit test thoroughly, even on personal projects where no one is making me, because those are the cases when unit testing saves you time and aggravation.  The more unit tests required to test something, the more time unit tests will save.

That's because you can only hold so many things in your head at once.  If you're trying to write code that works for 63 different combinations, it's often difficult to fix one combination without breaking another.  You end up manually testing other combinations over and over.  Manual testing is much slower, which makes you not want to rerun every possible combination every time you make a change.  That makes you more likely to miss something, and more likely to waste time pursuing paths that don't work for all cases.

Aside from the time saved compared to manual testing, there is much less mental strain, which makes it easier to focus on the problem at hand without worrying about accidentally introducing regressions.  That lets you work faster and longer without burnout.  In my opinion, the mental health benefits alone are worth the cost of unit testing complex code, even if it didn't save you any time.


问:
Refactoring this code that produces a reverse-lookup hash from another hash
This code is based on the idea of a Form Object
http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/
(see #3 if unfamiliar with the concept).

My actual code in question may be found here: https://gist.github.com/frankjmattia/82a9945f30bde29eba88

The code takes a hash of objects/attributes and creates a reverse lookup hash to keep track of their delegations to do this.

```<code>delegate :first_name, :email, to: :user, prefix: true
</code>```

But I am manually creating the delegations from a hash like this:

```<code>DELEGATIONS = {
    user: [ :first_name, :email ]
}
</code>```

At runtime when I want to look up the translated attribute names for the objects, all I have to go on are the delegated/prefixed (have to use a prefix to avoid naming collisions) attribute names like :user_first_name which aren't in sync with the rails i18n way of doing it:

```<code>en:
  activerecord:
    attributes:
      user:
        email: 'Email Address'
</code>```

The code I have take the above delegations hash and turns it into a lookup table so when I override human_attribute_name I can get back the original attribute name and its class. Then I send #human_attribute_name to the original class with the original attribute name as its argument.

The code I've come up with works but it is ugly to say the least. I've never really used #inject so this was a crash course for me and am quite unsure if this code effective way of solving my problem. Could someone recommend a simpler solution that does not require a reverse lookup table or does that seem like the right way to go?

Thanks,
- FJM

答:
I think I would keep the actual class constants intact so you're not jumping through ActiveSupport's library so much and also immediately build the delegations table instead of also having the REVERSE_DELEGATIONS constant.  Finally, refactor the humanize_attribute_name into two lines for clarity's sake.

```<code>class RegistrationForm
  DELEGATIONS = {
    User => [
      :first_name, :first_name=,
      :last_name, :last_name=,
      :email, :email=,
      :password, :password=,
      :password_confirmation, :password_confirmation=
    ],

    Organization => [
      :name, :name=
    ]

  }.map{|klass, attrs| attrs.map{|attr| {:"#{klass.to_s.downcase}_#{attr}" => [klass, attr]}}}.flatten.reduce({}, :merge)

  def self.human_attribute_name(method)
    klass, attribute = DELEGATIONS[method]
    klass ? klass.send(:human_attribute_name, attribute) : method
  end
end
</code>```

You could also further refine the reverse_mapping to create both :user_first_name, and :user_first_name= from just :first_name and do away with the always paired declarations.

Body:
I think I would keep the actual class constants intact so you're not jumping through ActiveSupport's library so much and also immediately build the delegations table instead of also having the REVERSE_DELEGATIONS constant.  Finally, refactor the humanize_attribute_name into two lines for clarity's sake.

class RegistrationForm
  DELEGATIONS = {
    User => [
      :first_name, :first_name=,
      :last_name, :last_name=,
      :email, :email=,
      :password, :password=,
      :password_confirmation, :password_confirmation=
    ],

    Organization => [
      :name, :name=
    ]

  }.map{|klass, attrs| attrs.map{|attr| {:"#{klass.to_s.downcase}_#{attr}" => [klass, attr]}}}.flatten.reduce({}, :merge)

  def self.human_attribute_name(method)
    klass, attribute = DELEGATIONS[method]
    klass ? klass.send(:human_attribute_name, attribute) : method
  end
end

You could also further refine the reverse_mapping to create both :user_first_name, and :user_first_name= from just :first_name and do away with the always paired declarations.


问:
Game server code design
I'm designing a multiplayer game server where the players are in rooms. Right now I have classes to take care of the client, networking, etc. I'm struggling however to find a design for this Room class. For example, when I want to change a client's room, should I call client.changeRoom(newRoom) or newRoom.addClient(client)? What about when leaving a room, should a client detach itself from the room or the room detach the client? I'm very confuse here, I just don't want to end up with a design I will regret in the future.

答:
With flashbacks to my LPmud days, the answer is the client (player, object, ...) is moved from one room to another and notifies the previous room (and everything else in the room) of this fact.

Upon entering a new room, the client again notifies all things in the room of its entry.

Not all rooms (or things in rooms) care about this fact and can quietly ignore this message.

The way the LPmud design works is that the room is "just" a special type of object with connivence functions for linking it to other rooms.

The design of the room doing the moving of a player from one location to another means quite a few more lookups.

Note: I'm using getRoom() here as an example function.  The method might have been getEnvironment() which returns the container an object is in... and all objects had a container (an coin in a bag in a player inventory coin-> getEnvironment() would get the bag and coin-> getEnvironment()-> getEnvironment() would get the player, and coin-> getEnvironment()-> getEnvironment()-> getEnvironment() would fetch the room...)

The player would need to do a me->getRoom()->moveMeTo(newRoom); to move around.  This gets a bit cumbersome and sometimes, when things go wrong, you don't have room that you are in which would make it impossible to move to another room.

The thing with the 'intelligence', the thing doing the acting is the player, and thus that should be the thing doing the acting in the room.

```<code>me->getRoom()->notify_all(me,leaving);
me->moveRoom(newRoom);
me->getRoom()->notify_all(me,arriving);
</code>```

Before you point out that I said me->getRoom()->moveMeTo(newRoom); was bad above and yet use me->getRoom()->notify_all(...) above, the difference is that in the case that the client is not anywhere, the getRoom() would return a null object that ignores all messages and so nothing goes wrong there.  However, in the moveMeTo approach, the null object would ignore all messages, and you wouldn't get anywhere.

As an aside, you might want to download an LP mudlib to look at it and consider how the various components are architected.  A lot of design thoughts have been put into it over the years that probably represent many programmer-decades of refinement.

The locations of hooks, connivence functions, and structure, when looked at can make some of your own decisions easier to come by, understand, and reconsider.

Title: Game server code design

Body:
With flashbacks to my LPmud days, the answer is the client (player, object, ...) is moved from one room to another and notifies the previous room (and everything else in the room) of this fact.

Upon entering a new room, the client again notifies all things in the room of its entry.

Not all rooms (or things in rooms) care about this fact and can quietly ignore this message.

The way the LPmud design works is that the room is "just" a special type of object with connivence functions for linking it to other rooms.

The design of the room doing the moving of a player from one location to another means quite a few more lookups.

Note: I'm using getRoom() here as an example function.  The method might have been getEnvironment() which returns the container an object is in... and all objects had a container (an coin in a bag in a player inventory coin-> getEnvironment() would get the bag and coin-> getEnvironment()-> getEnvironment() would get the player, and coin-> getEnvironment()-> getEnvironment()-> getEnvironment() would fetch the room...)

The player would need to do a me->getRoom()->moveMeTo(newRoom); to move around.  This gets a bit cumbersome and sometimes, when things go wrong, you don't have room that you are in which would make it impossible to move to another room.

The thing with the 'intelligence', the thing doing the acting is the player, and thus that should be the thing doing the acting in the room.

me->getRoom()->notify_all(me,leaving);
me->moveRoom(newRoom);
me->getRoom()->notify_all(me,arriving);

Before you point out that I said me->getRoom()->moveMeTo(newRoom); was bad above and yet use me->getRoom()->notify_all(...) above, the difference is that in the case that the client is not anywhere, the getRoom() would return a null object that ignores all messages and so nothing goes wrong there.  However, in the moveMeTo approach, the null object would ignore all messages, and you wouldn't get anywhere.

As an aside, you might want to download an LP mudlib to look at it and consider how the various components are architected.  A lot of design thoughts have been put into it over the years that probably represent many programmer-decades of refinement.

The locations of hooks, connivence functions, and structure, when looked at can make some of your own decisions easier to come by, understand, and reconsider.


答:
The usual answer to "what is the right way?" or "is this the right way?" is..... it depends.

All I can do is tell you the pros and cons to specific ideas.  What follows is 100% my opinion.  I don't know of any specific requirements or rules.  I'm sure somebody will disagree with me.

JSP's

Let's work on whether to put JSP's in WEB-INF or not.

Pros of putting JSP's in WEB-INF:

You control how the JSP's are executed.  If you want a JSP to be parameterized and re-usable (which is really hard with a JSP anyway), you can put them into WEB-INF and use a servlet or a Struts action controller or some other front controller to do pre-processing and then pass control to the JSP, passing in the right environment context (like request attributes, any security checks, parameter sanitation, etc.)

You can programmatically or even at a firewall or IDS level block HTTP requests to *.jsp to reduce the likelihood of somebody uploading a JSP to the web root and then being able to execute code as the web server.  They'd have to over-write an existing JSP.  Not a huge security gain, but it does make compromise slightly harder.

Enforces good habits, like MVC, front controller, servlet filters, dependency injection, etc. as opposed to a big monstrous JSP that does all the work itself and is difficult to read/maintain.

Cons of putting JSP's in WEB-INF:

You cannot access the page directly, even if it is a simple standalone page which needs no upfront processing.  This is because files under /WEB-INF are not servable by a servlet container.

Static files

In terms of purely static files like HTML, image, stylesheet, javascript, etc. put those under the web root (my_app in your case), but NOT /WEB-INF (because it is not accessible).

Overall layout

As for the overall directory layout, it depends somewhat on your build process.  I like storing everything under "src" or "source" because it makes it clear what files are generated by building and which are pure source files.  main lets you separate test code like junit classes from your main source code, which is good too.  But if you don't have any unit tests (oh no!), then it's a meaningless distinction.

On the other hand, if you don't manipulate the web root at all during build (like if it's all JSP and static files), then perhaps you keep it at the top level, like /webroot or /deploy and copy files in as needed, such as .class or .jar files.  It is a habit of human beings (especially developers) to over-organize.  A good sign of over-organizing is having lots of folders with only a single sub-folder.

What You've Shown

You've indicated that you are following a convention set by maven, so if you are already using maven, just stick with that layout.  There is absolutely nothing wrong with the layout you described.

Title: Java web application folder structure

Body:
As a beginner to J2EE, I have recently started developing my own project from scratch using the Core of J2EE : Servlets & Jsps.

I could not evaluate whether my project folder structure is right or not.
Here is my project folder structure.

Before asking question, I admit that I could not answer or neither justify if somebody asks me, why this type of folder structure.
The question: Is it a good sign to put my jsps outside of web-inf. If not, why is it so? If yes why?

Is there any standard folder structure convention for a J2EE web application, I know maven has brought up some standards but still, we can customize as per the requirement I believe.

I have done a bit of googling and found the two references
1
2

where in the answers are not on the same page, from which I couldn't draw any conclusion.

What are the points to be considered while laying out the folder structure for a J2EE web application, importantly where should the Jsps, static content should go into & why?


答:
I can think of a number of excellent programmers who are considered (by many) to be "quite difficult to work with":

Ulrich Drepper - Maintainer of the GNU C Library (Link is one of many)

Theo De Raddt - OpenBSD Lead

In this industry, I think that a fair amount of us expect and assume that competency and the ability to articulate our competency is critical. After all, we go to work to accomplish some tasks in order to earn money, making friends is secondary.

At some point in your life, you will realize one of two things:

You are in a position to be as snide, withdrawn, antisocial, cynical or rude as you like because despite your behavior, your skills (and ability to articulate your knowledge) ends all arguments.

You are just like everyone else and need to be able to work in a team setting, while putting up with (and brain picking) snide, withdrawn, antisocial, cynical and rude behavior from others whose skills and proficiency at articulating knowledge ends most arguments.

If you are questioning this, I think you see some value in participating agreeably in a team setting, and perhaps 'doing it for the sake of doing it' is a good enough excuse to explore the possibility.

I'm also a lot like you. I hate disruptions, It took me the better part of five years just to learn how not to interrupt and dismiss people. I've also worked on teams where I learned more in a month than I could have in a year on my own. Isn't it odd that you only want people around you when you have something interesting to show or discuss?

If you have not yet seen it, take in a viewing of the movie "Real Genius". Pay special attention to Lazlo Hollyfeld. Jump into a team with an open mind, and feel free to borrow my pyjamas.

Title: How bad can it be to lack teamwork when you are a programmer?

Body:
I'm still at school, and I know I have problems dealing with other people.

I'm not an angry or shy or different, I just like to work my way and with my opinions while respecting other's, I have a big curiosity and hunger for knowledge, but I lack practice and I guess people don't want to work with me because they might fear I would talk some kind of morale. (For example I started to learn programming using linux instead of windows, even if I use windows a lot. And I have a mac).

What happens to programmers who lack teamwork? Where does the problems begin? Does being a good programmer compensate at least a little? Is it normal for a programmer to have a vision about his work instead of just doing what he is told?


答:
This is one of those problems that can't really be solved at the same level that it was created. We'll have to take a step back to a few fundamental philosophies, and follow the cascade in hope of a resolution.

The first philosophy is "never trust the client", and the closely related "if you really want to keep a secret, don't tell anyone!"

A simple example is database credentials, as you mentioned. Obviously you want your client to have access to it, but not any random Internet Stranger, so you need some kind of identity/verification/login system. But the core premise of hiding this is a problem: if the user itself must possess a secret, but you don't want them to know what that secret is, all you can do is hide it or make it hard for them to open "the secret package". But they can still find out, so you'd better have a backup plan!

The easiest solution is, "don't do that." Use the user's own account credentials to permit client-level access to the database for the software, and that's it. If the client becomes malicious, the worst-case scenario should be that the client can screw up their own data. That's it. Your database and system should, at most, now contain junk entries from that client, solely for that client, with no one else (including you) suffering from the mayhem.

There are specific use cases where you just only want deployed software to do something but not have everyone in the world able to connect and do that same stuff, but for that you are just hiding secrets and the only good reason to do that is just to reduce headaches or system activity. If your hidden info becomes common knowledge it had better not be game-breaking, just at worst annoying.

If you are in one of those narrow use cases, it's just about obfuscation, which is all about getting creative. It's a lot like Code Golf, really - except you are the one creating the puzzle. That's all it really is - a puzzle. And people like solving puzzles, so again, it better be ok when someone figures it out.

But for the majority of things in the world, it is just best to operate without worrying about having to keep a secret from the user. Instead, best practice is to just let the user in on the secret, make it their responsibility to help protect it (their username and password, for instance), and limit the downside risk of what happens if the secret gets out or gets abused.

In true "key management" cryptographic/security contexts, the answer of "where to store the private key" is "somewhere else!" Encryption is point-to-point protection, and public-private key encryption is designed to protect info in transit through time and space. The private key is inherently vulnerable, and protecting it is not really a question of overlapping encryption - it is securing it against access entirely. And if the System must access it, then the System itself must be secured - and you can't do that on a client's machine. They can always run a VM, dump the RAM, sniff their network traffic, install a proxy or virtual NIC, decompile the executables...don't voluntarily get involved in that loosing battle.

Now if you need to do something like DRM, where your need to store a secret is actually based on controlling use of the software itself, that's another situation entirely.

TLDR: Don't keep secrets FROM the user, keep secrets WITH the user.

Title: Where to store the private key?


答:
When you look at it at the top level, it could go either way, with neither solution theoretically better than the other.  You already know that, or you wouldn't ask the question.  This dilemma is fairly common in object-oriented programming.  The trick is to look one level of abstraction deeper.  The implementation is almost always much cleaner one way compared to the other.  When in doubt, try implementing it both ways and see which one works out better.

For example, say you choose client.changeRoom(newRoom).  If that's the wrong choice, the method will end up consisting mainly of calls on the newRoom object, like:

```<code>newRoom.populateFurniture()
newRoom.populateNPCs()
newRoom.attachChat()
newRoom.notifyPlayers()
...
</code>```

This often results in wanting to make too many Room methods public, which increases coupling.  Not being familiar with your architecture, and never having created something similar, I don't know which way it will go for you, although adds generally end up working better on the container object.  However, in my experience, the choice has always been blindingly obvious after trying it both ways.

Also, don't discount the possibility that the best method may be a combination of both, like:

```<code>Client::changeRoom(Room newRoom) {
    room.removeClient(this)
    newRoom.addClient(this)
    room = newRoom
}
</code>```

Title: Game server code design

Body: I'm designing a multiplayer game server where the players are in rooms. Right now I have classes to take care of the client, networking, etc. I'm struggling however to find a design for this Room class. For example, when I want to change a client's room, should I call client.changeRoom(newRoom) or newRoom.addClient(client)? What about when leaving a room, should a client detach itself from the room or the room detach the client? I'm very confuse here, I just don't want to end up with a design I will regret in the future.

Body:
When you look at it at the top level, it could go either way, with neither solution theoretically better than the other.  You already know that, or you wouldn't ask the question.  This dilemma is fairly common in object-oriented programming.  The trick is to look one level of abstraction deeper.  The implementation is almost always much cleaner one way compared to the other.  When in doubt, try implementing it both ways and see which one works out better.

For example, say you choose client.changeRoom(newRoom).  If that's the wrong choice, the method will end up consisting mainly of calls on the newRoom object, like:

newRoom.populateFurniture()
newRoom.populateNPCs()
newRoom.attachChat()
newRoom.notifyPlayers()
...

This often results in wanting to make too many Room methods public, which increases coupling.  Not being familiar with your architecture, and never having created something similar, I don't know which way it will go for you, although adds generally end up working better on the container object.  However, in my experience, the choice has always been blindingly obvious after trying it both ways.

Also, don't discount the possibility that the best method may be a combination of both, like:

Client::changeRoom(Room newRoom) {
    room.removeClient(this)
    newRoom.addClient(this)
    room = newRoom
}


答:
The standard structure for a WAR file is:

```<code>/META-INF
   Standard jar stuff like manifest.xml
/WEB-INF
  web.xml
  /classes
    /com...etc.
  /lib
</code>```

Maven generates this for you using your src/main/java, resources, webapp and your dependencies (placing them in /lib) in the maven-webapp-plugin, but that's implementation. The important thing to realize is that anything you put in WEB-INF is not externally accessible, whereas everything in the root directory of the WAR is public.

Generally you don't want to put much in the root, since you want your application to handle all access using the servlets and filters you define in web.xml. It's common to see an index.html (or .jsp) in the root that redirects to a servlet, for instance a Struts action.

Typical MVC implementations such as Stripes or Struts recommend against user's accessing JSPs directly, preferring that JSPs be view-only. They recommend creating controllers that forward to JSPs after processing the request, and the JSPs merely render the result. For instance, submitting a form to /login will run an action that processes the login request, creates the user's session, and forwards the user to the logged-in view of the home page JSP.

Title: Java web application folder structure

Body:
The standard structure for a WAR file is:

/META-INF
   Standard jar stuff like manifest.xml
/WEB-INF
  web.xml
  /classes
    /com...etc.
  /lib

Maven generates this for you using your src/main/java, resources, webapp and your dependencies (placing them in /lib) in the maven-webapp-plugin, but that's implementation. The important thing to realize is that anything you put in WEB-INF is not externally accessible, whereas everything in the root directory of the WAR is public.

Generally you don't want to put much in the root, since you want your application to handle all access using the servlets and filters you define in web.xml. It's common to see an index.html (or .jsp) in the root that redirects to a servlet, for instance a Struts action.

Typical MVC implementations such as Stripes or Struts recommend against user's accessing JSPs directly, preferring that JSPs be view-only. They recommend creating controllers that forward to JSPs after processing the request, and the JSPs merely render the result. For instance, submitting a form to /login will run an action that processes the login request, creates the user's session, and forwards the user to the logged-in view of the home page JSP.


答:
Others have already covered most of what I was gonna say, so I'll just add this: just because you have an opinion or a vision doesn't mean you're right or that your approach is the best one. There's a lot you can learn from others if you open your mind to the possibility that they have an opinion and/or vision, too.

Teamwork is about making all those opinions come together into something that builds on the collective experience of the people involved and addresses flaws that a single person might not have considered.

That was one of the first lessons I learned on the job, and I became a better programmer after that.


问:
What is the accepted practice for string resource management in java?
In Android, final strings are stored in a strings.xml file, which makes it easy to update text, reuse strings and to translate an app to a different locale -- because everything is in one place.

However, in all the examples that I have seen of desktop applications all the strings have been hardcoded into each class.

Is hardcoding strings into files standard practice for desktop applications? Or is there a better way to do this?

答:
What you're referring to is called internationalization (often abbreviated as i18n), which in desktop Java is accomplished by creating properties files for each locale, then using resource bundles to get strings from those files as needed (see this tutorial).  It's not universally used, because there is some setup involved, and it's shorter to type "greetings" compared to messages.getString("greetings").  Usually you only see it when people actually need to have their program translated into different languages.

You can hard code strings in Android too, if you want, but they emphasized using the xml from the start in all their documentation and tutorials, and set up the tools to make it easier.


问:
Win loss code that does not make 1-0 record better than someone like 20-3
ok, am just looking for a win loss code example. This can be for any language, just wanting the outline. Fairly new to programming, so dummy it up for me :)

I can do (win-loss/total of win loss). Guessing that is a good standard win loss ratio, but I don't want a new person that has 1-0 to be ranked higher than someone that has 20-3.

Any help is appreciated and thank you.

EDIT:

The chess styles are a little more than needed. Just want a ranking system with win/loss. so lest say 20-3 is top in league right now. he is, say 23 weeks in so far. if one guy comes in and wins first match against anyone, I don't want him to take #1 spot over people thats been there longer and have a great winning record. To respond to ampt... maybe he will be best in league, but I don't want him instantly there cause he had one good match. Not sure if that clarify any more. Didn't really follow Doc all the way. Looks as if he is hindered in list up to his 11th game. Not sure if thats what you ment there. Thanks again for all reasponses.

答:
Here is a very simple solution, not so sophisticated as the chess rating systems suggested in the comments, but easier to implement: divide your current score value (win-loss)/(# of games played) by a "factor of uncertainty f", where f is a high value if the total number of games played is small, and f converges to 1 the more games a player has played. For example, you can choose

```<code>f(k)=10-k
</code>```

after k games as long as k<10, and

```<code>f(k)=1 if k>=10
</code>```

Or, if you want to double the confidence with each game played, choose

```<code>f(k) = 2^(5/k)
</code>```

(the ^ means here "to the power of", translate this to your favorite programming language).

The values 5 or 10 are just arbitrary choosen, reflecting the confidence you want to assign to the a player after one game, and the point where you want to reach (almost) full confidence. Choose your own values accordingly.

Body:
Here is a very simple solution, not so sophisticated as the chess rating systems suggested in the comments, but easier to implement: divide your current score value (win-loss)/(# of games played) by a "factor of uncertainty f", where f is a high value if the total number of games played is small, and f converges to 1 the more games a player has played. For example, you can choose

f(k)=10-k

after k games as long as k<10, and

f(k)=1 if k>=10

Or, if you want to double the confidence with each game played, choose

f(k) = 2^(5/k)

(the ^ means here "to the power of", translate this to your favorite programming language).

The values 5 or 10 are just arbitrary choosen, reflecting the confidence you want to assign to the a player after one game, and the point where you want to reach (almost) full confidence. Choose your own values accordingly.


问:
“/*@null@*//*@out@*/” in C function declaration
In alloc.h of djbdns-1.05 there's the following code:

extern /*@null@*//*@out@*/char *alloc();

My question is about the goofy-looking /*@null@*//*@out* “decorator.” I assume this is “just a comment” with some significance to djbdns's build system. But I can't find anything referencing it in other files.

Anybody know what this is?

答:
They're almost certainly annotations used by a static code analysis tool. I don't know for sure which tool those annotations are for, but it might be Splint, which uses that @foo@ syntax. The Splint manual, Appendix C: Annotations lists various annotations which can be used.

Static analysis tools are used to automatically check for some classes of programming error. This is similar to how compilers can emit warnings about common mistakes or potential problems in the code, except that static analysis tools typically perform much more extensive (and computationally expensive) analysis of the code. Annotations in the code are used to give the tool more information about how the code is intended to behave.


问:
Proper way to "compile" a javascript project?
I'm developing a small open-source javascript library, and I was wondering about the proper method for compiling the source into one javascript file.

It's easier to develop if the code is split into multiple files, but libraries are included as one large file when used in another application.  My current "compilation" method involves using a makefile to copy each submoudle into the main file and then minify it. What is the proper way to do this?

答:
I would look at tools like Browserify in order to combine your code.  When you use Browserify, your code is your build tool. Browserify gives you all the benefits of writing code in node (no anon functions to avoid globals, npm, simple requires, imports instead of namespaced globals) and it allows you to package that code to run on the client with one command and only load one file.

You can checkout my open source js framework Luc JS for an example.  It runs on node and IE6.  I'm able keep the code modular and build the single browser file with a one line command.


问:
Which methods should be put in an interface and which in abstract classes?
I have seen many frameworks and modules and their standard they follow is like this

UserInterface which have some predefined methods

AbstractUserClass which implements userInterface

Then GenericUserClass which extends from AbstractuserClass

Then other classes extending from that generic

Now I have seen that abstract class has additional functions to the interface, and the generic class also has additional functions.

So I am confused which methods should go where

Sometimes I see class A extends Abstractuserclass and sometimes class A extends Abstractuserclass implements UseraInterface. What is the difference if Abstractclass already impelements Userinterface

答: Use interfaces to reuse contracts. Use abstract classes to reuse implementation. My guess is that AbstractUserClass provides some common code that all foreseeable implementations of UserInterface will need.


答:
Some answers here are very generic stating that an interface is a contract. It's difficult to say they are a contract when there is no scope for interfaces and classes in PHP. So it's impossible to enforce the contract. There is nothing stopping a developer from instantiating a class and ignoring the interface. So the contract description isn't that clear to developers who haven't used Java or C++ before.

So what's it all about?

Your example is not a very good one. UserInterface to AbstractUserClass to GenericUserClass doesn't really show the benefits of what is going on. So let me expand on that a bit.

Why do we have interfaces, because an object can implement multiple interfaces. Think of an interface not as methods but as a defined behavior for a class. The interface is saying "I can behave like a user". It doesn't matter how the code achieves this. Just that it supports this interface.

The key to good interface design is not to create multi-purpose interfaces. Let each interface define a single behavior. This makes it much easier to create single purpose classes that work upon those kinds of objects. Instead of having one UserInterface you might expand that to include AdminInterface, AuthenticatedUserInterface and UserPermissionsInterface. So later in your code you can ask an object if it supports the AdminInterface and if so, then that user is an administrator.

Why do we have abstract classes?

Interfaces, interfaces, everywhere interfaces... One of the drawbacks to using interfaces is that an interface implements absolutely no code. For every interface a programmer must implement at least one class. A good framework that uses interfaces will provide you with a wide range of already implemented abstract classes that give you a starting point to using those interfaces. A bad framework is one that requires many interfaces and gives you nothing to start from.

Avoid the super abstract class that implements many interfaces and provides most of the functionality for those interfaces. It's also heavily inherited by many other classes.

What you want are small abstract class that implement an interface from different perspectives. You might want to create a couple of classes that implement UserInterface like this AbstractInvalidUser, AbstractAnonymousUser or AbstractAuthenticatedUser. Later you might need to use Facebook for logging in a user. You can then create a FaceBookUser that extends AbstractAuthenticatedUser. It's clear now what each abstract class does but they all implement the UserInterface.

So now the big question "Where do all the methods go?"

The key to creating maintainable source code is to always reduce dependencies down to their smallest part. That means you do not want source code using FaceBookUser when all it's doing is displaying the current user's name. If everything in your source code is using FaceBookUser then it's difficult to move that class to another folder or rename that class. It's easier for you to just use UserInterface to display a user's name and now all that source code doesn't care if it's Facebook, Google+ or your own sign in. The dependency is kept small because the interface is simple and single purpose.

Because interfaces separate code from the implementation of the interface. Your other code doesn't care if the current object is a wrapper class, delegate class, super heavy class or just a simple class. As far as the code cares it's just a UserInterface reference.

Interfaces are tools that help you create management code. Place methods in interfaces so you don't create dependencies between classes. You create break up your dependency by creating more then one interface.

That is what people mean when they call it a contract thingy.

Body:
I have seen many frameworks and modules and their standard they follow is like this

UserInterface which have some predefined methods

AbstractUserClass which implements userInterface

Then GenericUserClass which extends from AbstractuserClass

Then other classes extending from that generic

Now I have seen that abstract class has additional functions to the interface, and the generic class also has additional functions.

So I am confused which methods should go where

Sometimes I see class A extends Abstractuserclass and sometimes class A extends Abstractuserclass implements UseraInterface. What is the difference if Abstractclass already impelements Userinterface


问:
Drawback of mixing C++ code with C for performance purposes
Often you can see answers like “Avoid using C libraries in your C++ code“ or “This can be rewritten using STD/Boost in pure C++“.

I understand C++ produces more maintainable code and has many advantages, but is it actually bad using C libraries when performance is a priority? I mean writing in what is sometimes  called C-with-classes.

I‘ve been developing a text file parser with both C and C++ versions and the C one was considerably faster.

What i would like to know is if using C libraries in C++ has hidden drawbacks apart from the obvious ones like making the code less maintainable.

答:
is it actually bad using C libraries when performance is a priority?

It is if you don't actually need the performance boost that the C library would provide, or the C library only produces a minimal performance increase, because you're trading off too many of the benefits you get by using STD/Boost.

If:

You profile your code using STD/Boost, and

You profile your code using C libraries, and

There is a significant performance improvement with the C libraries, and

You actually need the performance improvement; i.e. using the C libraries fixes an actual performance problem

Then I would say that the C library is a better choice.  But about 99 percent of the time, it won't be the best choice, because the performance increase (if there is one) will be so small that it won't be worth it.

Further Reading

Using/Mixing C in C++ code? on StackOverflow


问:
A Web Service to collect data from local servers every hour
I'm trying to find a way to collect data from different servers around the world.

Here are the details:

There is only one single PowerShell script on servers that encrypts data (simple csv file) and sends with preferred method (HTTP/HTTPS Post could be)

There is no more control on that servers. Can't install any service, process etc. Just I can configure script to execute every hour.

This script also will have encrypted username/password/license key for every server. Script will compress data and send to me with these information.

So I need a service (I'm not sure if Web Service is the rigth solution) on the cloud that will help me to:

Will get data that is sent from servers using a method.
Will authenticate request to recognize sender using license key/username/password
and most importantly, Will redirect/send this filecab to my SQL Server on the cloud (Azure). Also it should seperate data according to customer information in license key. So every data for every customer will be stored in dedicated DB/Tables on my SQL
All the processes above should be completed automatically. No way for manual steps.

Question:

A Web Service (SOAP or Restful) is the rigth solution for that?

答:
A web service is an excellent choice for this type of situation. Using HTTPS plus compression, you should have no issues.  It doesn't matter whether this is SOAP or RESTful, although I'd recommend REST because it's easy to work with, especially if you have PowerShell 4.0 (which includes the Invoke-RestMethod cmdlet). Failing that, I'd install curl and work with it that way.

I will note that you should consider doing something a little more sophisticated than a plain POST; you'll probably want error checking, so consider a two-stage service where you request a token, providing a checksum, and then POST the data along with the token you received. Then the service can use the checksum to validate the data that it received.


答:
C++ programmers seem to have a fear of not using enough of the language's features all the time. 'C with classes' can be a perfectly acceptable solution if it solves your problem, and writing libraries in C gives you the advantage of being able to use them with other languages too.

You will have to ensure any resources allocated by you library have explicit ownership or you'll get leaks.

Having said this I'm surprised your C code outperformed your C++ code, this indicates an issue with your C++ code (you're probably using std::string all over the place)

Title: Drawback of mixing C++ code with C for performance purposes

Body:
Often you can see answers like “Avoid using C libraries in your C++ code“ or “This can be rewritten using STD/Boost in pure C++“.

I understand C++ produces more maintainable code and has many advantages, but is it actually bad using C libraries when performance is a priority? I mean writing in what is sometimes  called C-with-classes.

I‘ve been developing a text file parser with both C and C++ versions and the C one was considerably faster.

What i would like to know is if using C libraries in C++ has hidden drawbacks apart from the obvious ones like making the code less maintainable.


问:
Invoking a web service in a Web API Project…in which layer to invoke?
I am using Microsoft ASP.NET Web API 2 and one of my end points has to internally invoke a legacy non-Microsoft web service (not asmx or svc) .

Which layer should I invoke this in?

I currently have :
Repository layer: where all the CRUD calls to DB are done now.

Domain Manager: where respective manager classes invoke the Repository Layer methods.

And my Web API Controller methods invoke the respective Domain Manager methods.

Should I just have another method in my Repository Layer which invokes the web service? And follow the usual pattern above?

答: The repository layer is the logical place to put it; the data that you're pulling back from the web service will need to be wrapped in domain-specific abstractions, so (in concept) it is essentially another data store alongside your own databases.</p>