答:
If you are commonly having difficult merges, there is likely something wrong with the way you are using git.

It sounds like you have branches that don't get deleted within a working day of them being created. That is generally, if not universally, considered to be a bad idea. Most of the time, git branches are more an extra (optional) step in the commit-staging process that gets you a nice clean history. Generally, avoid using them for storing product variants, features, tickets or anything else that has a meaning outside that history.

And of course, if you fix that problem, the manual testing issue goes away, as the testers will just naturally be testing the right version in the first place (i.e. the tag setup by your CI system whenever all automated tests pass).

Title: How do you get complete manual testing by QA in a git/hg flow development process?

Body:
I have a question about working with independent testers doing manual testing (not about automated unit and regression testing.)

In a flow process I do my work on a feature branch until I'm confident that it works and I haven't introduced bugs.  I merge from the develop branch to my feature, late and often, to ensure I haven't broken anything in merges with other recent work.  Sometimes I'll even do it again during the testing phase, so that the tester can work with the most recent snapshot.  Still, there's always a small window of time after testing where new work can -- and in high traffic times does -- come in from other features.

This means that the merge back to the develop/release branch is sometimes not trivial, despite our treating it like it should be.  (Sometimes it's even iterative: by the time I'm done making sure I've correctly integrated one feature that's slipped in, running regression tests, checking the code, and doing some manual testing, yet another one has come in.)

My question is, is there a workflow for developers and testers where you don't lose out on the safety net of testers for that last step (but also hopefully don't need to ask again and again for re-testing tested work)?  What are industry best practices here?  If we could assure that branches won't interfere with one another, we'd be fine, but in practice we get conflicts sometimes.

I'll add that I'm sure we don't want to do our main testing on the develop/release branch.  It's been a huge win and stress-reducer since we switched to flow.  We can easily put off releasing work that's created a problem or raised a question during testing.  In our pre-flow practice, we wound up with emergencies near a release, where a problem was found that we had to deal with urgently before releasing because the work of a non-critical feature was already merged into the main branch for testing.


问:
Algorithm to compute k-permutation without repeating and no duplicates
I have a set of integers, for example 1..20 and I want to get all possible combinations of that set drawing 5 numbers.

So each combination has 5 numbers from that set of integers. But I don't want the numbers in the combination to be duplicates and I want the unordered combination to be unique.

I guess it's not easy to understand, my english is not the best and I don't know all the mathematical terms. So here's an illustration.

My set is 1..20 and obviously has a length of 20.

I want each possible combination to be like [1, 2, 3, 4, 5], [1, 2, 3, 4, 6], ... , [1, 4, 8, 14, 20], always a length of 5.

And this should be prohibited: [1, 2, 3, 4, 5], [3, 2, 1, 5, 4] since those two contain the exact same numbers.

Also this is not allowed: [1, 1, 2, 3, 4] since this combination contains duplicate numbers itself.

So a naive approach would be to iterate via 5 for loops over 20, save all the previous combinations and check for duplicates through the combinations and within the newest combination. But this would result in 3,200,000 loops, which is not very efficient, since the final number of combinations is 1,860,480 (if I didn't calculate wrong, but it should be n! / ((n -k)! * k!) if I'm not totally wrong, where n = 20 and k = 5).

So how can I eliminate the duplicate loops in the first place?
I need a algorithm that is fast and does not take unnecessary steps since I'll calculate stuff with this data that takes a while and so I want to reduce the amount of loops as far as possible.

答:
Unless I'm mistaken:

There are 20^5 = 3,200,000 ways to pick 5 numbers out of 20 (with repeating, with duplicates)

If you don't allow for "duplicates" (picking the same number more than once), you're left with n! / (n - k)!, in this case 20! / (20 - 5)! = 1,860,480. These are k-permutations.

If, then, you don't allow for "repeating" (having collections with the same elements only in a different order), you're left with n! / ((n - k)! * k!), in this case 20! / ((20 - 5)! * 5!) = 15,504. These are called k-combinations. These are what you seem to be looking for.

If you are only looking for combinations of size 5 and want access to the entire set of combinations immediately, then I'd say then 5 nested loop approach is fine, and I don't think you'll be able to do anything faster. You just need to modify your idea a bit so you wont need to check for uniqueness or duplicate numbers and don't do unnecessary iterations. You can produce (only) ordered combinations by doing something like:

public Set<Set<Integer>> all5CombinationsOf20(){
    Set<Set<Integer>> result = new HashSet<Set<Integer>>();
    for(int i = 1; i <= 16; i++){
        for(int j = i+1; j <= 17; j++){
            for(int k = j+1; k <= 18; k++){
                for(int l = k+1; l <= 19; l++){
                    for(int m = l+1; m <= 20; m++){
                        result.add(new HashSet<Integer>(Arrays.asList(i,j,k,l,m)));
                    }
                }
            }
        }
    }
    return result;
}
```

<p>Since this gives you the combinations in a ordered way [1, 2, 3, 4, 5] is produced, but [3, 2, 1, 5, 4] and [1, 1, 2, 3, 4] are not.</p>

<p>However this approach is not extendable to combinations of arbitrary size, then you would need recursion. I once wrote this:</p>

<pre class="lang-java prettyprint-override"><code>public static <T> Set<Set<T>> combinations(Set<T> alphabet, int k) {
    if (alphabet.size() == 0) {
        throw new IllegalArgumentException("alphabet.size must be > 0");
    }
    if (k < 0) {
        throw new IllegalArgumentException("k must be >= 0");
    }
    if (k == 0) {
        Set<Set<T>> result = new HashSet<Set<T>>();
        result.add(new HashSet<T>());
        return result;
    } else {
        Set<Set<T>> result = new HashSet<Set<T>>();
        for (T e : alphabet) {
            Set<T> newAlphabet = new HashSet<T>(alphabet);
            newAlphabet.remove(e);
            Set<Set<T>> smallerCombinations = combinations(newAlphabet, k - 1);
            for (Set<T> smallerCombination : smallerCombinations) {
                Set<T> combination = new HashSet<T>(smallerCombination);
                combination.add(e);
                result.add(combination);
            }
        }

        return result;
    }
}
</code>```

This is not necessarily fast since you are messing around the alphabet a lot, but the idea should be clear: to make a combination of size n over a certain alphabet (in your case 1..20), remove an element e from the alphabet, make a combination of size n-1 over the alphabet minus e and return the combination with e added. Reusing the same alphabet for smaller combinations an letting the HashSet get rid of duplicates would be faster.

Also these sets of combinations get large pretty fast, so you might want to be lazy and not hold them all in memory (depending one how you want to use them), if so, check https://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n

ContentLicense: CC BY-SA 3.0

Body:
Unless I'm mistaken:

There are 20^5 = 3,200,000 ways to pick 5 numbers out of 20 (with repeating, with duplicates)

If you don't allow for "duplicates" (picking the same number more than once), you're left with n! / (n - k)!, in this case 20! / (20 - 5)! = 1,860,480. These are k-permutations.

If, then, you don't allow for "repeating" (having collections with the same elements only in a different order), you're left with n! / ((n - k)! * k!), in this case 20! / ((20 - 5)! * 5!) = 15,504. These are called k-combinations. These are what you seem to be looking for.

If you are only looking for combinations of size 5 and want access to the entire set of combinations immediately, then I'd say then 5 nested loop approach is fine, and I don't think you'll be able to do anything faster. You just need to modify your idea a bit so you wont need to check for uniqueness or duplicate numbers and don't do unnecessary iterations. You can produce (only) ordered combinations by doing something like:

public Set<Set<Integer>> all5CombinationsOf20(){
    Set<Set<Integer>> result = new HashSet<Set<Integer>>();
    for(int i = 1; i <= 16; i++){
        for(int j = i+1; j <= 17; j++){
            for(int k = j+1; k <= 18; k++){
                for(int l = k+1; l <= 19; l++){
                    for(int m = l+1; m <= 20; m++){
                        result.add(new HashSet<Integer>(Arrays.asList(i,j,k,l,m)));
                    }
                }
            }
        }
    }
    return result;
}

Since this gives you the combinations in a ordered way [1, 2, 3, 4, 5] is produced, but [3, 2, 1, 5, 4] and [1, 1, 2, 3, 4] are not.

However this approach is not extendable to combinations of arbitrary size, then you would need recursion. I once wrote this:

public static <T> Set<Set<T>> combinations(Set<T> alphabet, int k) {
    if (alphabet.size() == 0) {
        throw new IllegalArgumentException("alphabet.size must be > 0");
    }
    if (k < 0) {
        throw new IllegalArgumentException("k must be >= 0");
    }
    if (k == 0) {
        Set<Set<T>> result = new HashSet<Set<T>>();
        result.add(new HashSet<T>());
        return result;
    } else {
        Set<Set<T>> result = new HashSet<Set<T>>();
        for (T e : alphabet) {
            Set<T> newAlphabet = new HashSet<T>(alphabet);
            newAlphabet.remove(e);
            Set<Set<T>> smallerCombinations = combinations(newAlphabet, k - 1);
            for (Set<T> smallerCombination : smallerCombinations) {
                Set<T> combination = new HashSet<T>(smallerCombination);
                combination.add(e);
                result.add(combination);
            }
        }

        return result;
    }
}

This is not necessarily fast since you are messing around the alphabet a lot, but the idea should be clear: to make a combination of size n over a certain alphabet (in your case 1..20), remove an element e from the alphabet, make a combination of size n-1 over the alphabet minus e and return the combination with e added. Reusing the same alphabet for smaller combinations an letting the HashSet get rid of duplicates would be faster.

Also these sets of combinations get large pretty fast, so you might want to be lazy and not hold them all in memory (depending one how you want to use them), if so, check https://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n


问:
How do you go about understanding others' code?
What do you do to understand some code that you didn't write? Or code that you wrote long time ago and don't remember what it does anymore.

Do you have some technique that you go about? Do you analyze the structures first, or the public methods, or do you draw flow charts, etc.? Or do you fire up the debugger and just step through it? Or do you just ad-hoc your way through until you understand it?

答:
Different people have different learning styles, so you have to choose the method that works best for you.

The first thing I do (after building the project) is read the entire code base through at least once. That gives me a general idea of where everything is. Then I choose a section to examine in more detail. Data structures would be a good place to start. Once I have a general idea of what's going on, I do the same with another portion of the code that interacts with the first. After enough iterations, I have a good sense of how the code works.

ContentLicense: CC BY-SA 2.5


问:
How can I reinforce that security questions answers should not be the same and how to encrypt?
When my users are creating an account they need to fill and set several security questions pertaining to their account. I am wondering, how can I make sure that the answer the user enters for each security question is not the same as an answer for a different question? What's the proper attribute for it?

Also, for the security question answers, should I encrypt the answers so that whoever is sniffing the network won't see the answers? How? What should I look into or lookup for this approach?

答:
If you are making a standard web app, then TLS is your only "safe" method of protecting users from MitM attacks and traffic sniffing. Take a look at ipviking's map of real time cyber attacks; a large number come from China because encryption is largely outlawed and browser requests can get hijacked. (Most infosec guys I know agree that X.509 is broken, the IETF is compromised, TLS is likely weakened intentionally by the NSA (kinda like this), and the entire key spaces for RSA and elliptic curves are being precomputed by governments. Nevertheless, it is still better than unencrypted traffic.)

If you must use security questions, I suggest putting everything in lowercase, stripping out whitespace, and hashing with a random salt stored along side it (it could be a single salt stored as part of a user record). I suggest at least 256 bit hash and 100 rounds (fewer if hash algorithm is already slow). Bcrypt hashes are also quite good because they involve encrypting a hash and storing the salt as part of the hash string.

If not using bcrypt, then be sure to not use a simple str1==str2 boolean for checking the answer; you should use something like the following, which will avoid the string comparison side channel attack.

```<code>function compHashes ($h1, $h2) {
    $r = 0;
    if (strlen($h1) !== strlen($h2)) return false;
    for ($i=0; $i<strlen($h1); ++$i)
        $r |= ord($h1[$i])^ord($h2[$i]);
    return $r == 0;
}
</code>```

The considerations for binary apps are a little different in that you can hard code or bundle a public key (or several) and use NaCl to generate client private keys and handle handshakes and encryption between server and client. There are libraries in every compilable language for this, and writing a wrapper for a statically linked library is not too difficult if that is the route you choose. Rolling your own crypto is definitely not recommended if you are not very familiar with cryptography and infosec matters.

Body:
If you are making a standard web app, then TLS is your only "safe" method of protecting users from MitM attacks and traffic sniffing. Take a look at ipviking's map of real time cyber attacks; a large number come from China because encryption is largely outlawed and browser requests can get hijacked. (Most infosec guys I know agree that X.509 is broken, the IETF is compromised, TLS is likely weakened intentionally by the NSA (kinda like this), and the entire key spaces for RSA and elliptic curves are being precomputed by governments. Nevertheless, it is still better than unencrypted traffic.)

If you must use security questions, I suggest putting everything in lowercase, stripping out whitespace, and hashing with a random salt stored along side it (it could be a single salt stored as part of a user record). I suggest at least 256 bit hash and 100 rounds (fewer if hash algorithm is already slow). Bcrypt hashes are also quite good because they involve encrypting a hash and storing the salt as part of the hash string.

If not using bcrypt, then be sure to not use a simple str1==str2 boolean for checking the answer; you should use something like the following, which will avoid the string comparison side channel attack.

function compHashes ($h1, $h2) {
    $r = 0;
    if (strlen($h1) !== strlen($h2)) return false;
    for ($i=0; $i<strlen($h1); ++$i)
        $r |= ord($h1[$i])^ord($h2[$i]);
    return $r == 0;
}

The considerations for binary apps are a little different in that you can hard code or bundle a public key (or several) and use NaCl to generate client private keys and handle handshakes and encryption between server and client. There are libraries in every compilable language for this, and writing a wrapper for a statically linked library is not too difficult if that is the route you choose. Rolling your own crypto is definitely not recommended if you are not very familiar with cryptography and infosec matters.


问:
What is a good alternative to the TestDataBuilder pattern?
The TestDataBuilder pattern is used in unit testing to create collaborators. Its advantages versus using constructors:

Changes to constructors are localized.

Test code becomes clearer, because you don't have to specify all the required parameters to the constructor.

A disadvantage is that the usage is somewhat lengthy which decreases readability:

```<code>var service = serviceBuilder.WithRepo(
    repoBuilder.WithEntities(
      new [] { entityBuilder.WithName("name") }).Build())
  .WithMailSender(mailSenderBuilder.Build())
  .Build();
</code>```

The word "With" is typically repeated many times.

Same for the call to Build().

Same for the word Builder.

Although all of them can be mitigated, I guess the solutions themselves have drawbacks. For instance, we could rename serviceBuilder to service, but this could give the wrong impression about the type of the variable. We could implement an implicit conversion from a builder class to the object it builds, but it is more code in the builder in addition to already abundant With* methods.

Is there an alternative to TestDataBuilder that doesn't have these drawbacks?

答:
My suggestion is to use the Factory pattern with a twist, taking advantage of default parameters. The implementation is more concise than that of a builder, the test code too.

I call it MotherFactory. Here is the code:

```<code>// ==== In a common test library ===

public abstract class MotherFactory
{
}

// ==== In a test project ===

public static class MotherFactoryEntityExtensions
{
    public static Entity Entity(
        this MotherFactory a,
        int? year = 2014,
        string name = "name",
        Dependency dependency = null,
        withoutDependency = false)
    {
        if (withoutDependency && dependency != null)
        {
            throw new ArgumentException(
                "The parameter 'dependency' cannot be used when true is specified for 'withoutDependency'.",
                "dependency");
        }

        if(dependency == null && !withoutDependency)
        {
            dependency = a.Dependency();
        }
        return new Entity(startYear, endYear, name, summary, dependency);
    }
}

public class EntityTest
{
    private static readonly MotherFactory an = null;

    [Fact]
    public void Ctor_GivenNullDependency_Throws()
    {
        Exception e = Record.Exception(() =>
        {
            Entity systemUnderTest = an.Entity(withoutDependency: true);
        });

        Assert.NotNull(e);
    }
}

public class ServiceTest
{
    private static readonly MotherFactory a = null;
    private static readonly MotherFactory an = null;

    [Fact]
    public void Find_GivenCorrectRequest_FindsEntity()
    {
        var service = a.Service(repo: a.Repository(dbEntities: new [] { an.Entity(name: "XXX") });
        var result = service.Find();
        Assert.Equal("XXX", result.Name);
    }
}
</code>```

Notes

Put the MotherFactory class in a library and in test projects create a class with extension methods for each collaborator class.

Parameters that have a prefix without (like withoutDependency) are used only in cases when we want to disable creating the default instance of a dependency and pass null instead.

A MotherFactory*Extensions class can also be an ObjectMother by providing methods like UserWithCompleteProfile().

Body:
My suggestion is to use the Factory pattern with a twist, taking advantage of default parameters. The implementation is more concise than that of a builder, the test code too.

I call it MotherFactory. Here is the code:

// ==== In a common test library ===

public abstract class MotherFactory
{
}

// ==== In a test project ===

public static class MotherFactoryEntityExtensions
{
    public static Entity Entity(
        this MotherFactory a,
        int? year = 2014,
        string name = "name",
        Dependency dependency = null,
        withoutDependency = false)
    {
        if (withoutDependency && dependency != null)
        {
            throw new ArgumentException(
                "The parameter 'dependency' cannot be used when true is specified for 'withoutDependency'.",
                "dependency");
        }

        if(dependency == null && !withoutDependency)
        {
            dependency = a.Dependency();
        }
        return new Entity(startYear, endYear, name, summary, dependency);
    }
}

public class EntityTest
{
    private static readonly MotherFactory an = null;

    [Fact]
    public void Ctor_GivenNullDependency_Throws()
    {
        Exception e = Record.Exception(() =>
        {
            Entity systemUnderTest = an.Entity(withoutDependency: true);
        });

        Assert.NotNull(e);
    }
}

public class ServiceTest
{
    private static readonly MotherFactory a = null;
    private static readonly MotherFactory an = null;

    [Fact]
    public void Find_GivenCorrectRequest_FindsEntity()
    {
        var service = a.Service(repo: a.Repository(dbEntities: new [] { an.Entity(name: "XXX") });
        var result = service.Find();
        Assert.Equal("XXX", result.Name);
    }
}

Notes

Put the MotherFactory class in a library and in test projects create a class with extension methods for each collaborator class.

Parameters that have a prefix without (like withoutDependency) are used only in cases when we want to disable creating the default instance of a dependency and pass null instead.

A MotherFactory*Extensions class can also be an ObjectMother by providing methods like UserWithCompleteProfile().


问:
Use of "this" in Golang
On the closest thing Golang has to a style guide found here, under Receiver Names this is written:

The name of a method's receiver should be a reflection of its identity; often a one or two letter abbreviation of its type suffices (such as "c" or "cl" for "Client"). Don't use generic names such as "me", "this" or "self", identifiers typical of object-oriented languages that place more emphasis on methods as opposed to functions. The name need not be as descriptive as a that of a method argument, as its role is obvious and serves no documentary purpose.

I personally have always just used "this" as the identifier because "this" is the focus of what I am working on when I write and edit the function. It sounds right, and (to me at least) it makes sense.

If the name need not be descriptive, it's role is obvious, and it serves no documentary purpose, why would the use of "this" be frowned upon?

答:
This is from a perspective of JavaScript where this has actual keyword meaning to the compiler, but from my understanding, if they're okay with two-letter abbreviations for the object type, it should be easy enough to use that instead. The reason for the difference is that in a decently-large block of progressively deeper asynchronous code, it could be very easy to misinterpret what "this", or the receiver, is in a deeper context; and it's possible it won't be the same object.

In JavaScript for instance, a control module might start up a dialog and declare an onLoad function inline for it. But at that point, it could be very easy for another coder to misinterpret this inside onLoad to refer to the control module, not the dialog; or vice versa. This could be avoided if the control were referred to as ctrl and the dialog as dg.

ContentLicense: CC BY-SA 4.0

Title: Use of "this" in Golang


答:
We'd have to ask the author of that style guide to know for sure, but I think the main reason I kind of agree with him is that the connection between struct and method is much looser in Go than other languages.

In essence, when you write a method like this:

```<code>func (m *MultiShape) area() float64 {
  ...
}
</code>```

That's almost exactly the same thing as writing a function like this:

```<code>func area(m *MultiShape) float64 {
  ...
}
</code>```

The only difference is a slight syntax change in how we call the function/method.

In other languages the this/self/whatever variable typically has some special properties such as being magically provided by the language, or having special access to private methods (remember Go doesn't have private fields/methods). Though the "receiver" is still being "magically provided" to some extent, it's so similar to a regular function argument it arguably doesn't count.

Plus, in "traditional" OOP languages a struct/class' methods all come with the struct/class definition, such that no more can be added from outside. In Go, as far as I know anyone can add more methods to anything (within the scope of their own code, of course).

I haven't written enough Go to make my own style guide, but personally I'd probably use this in methods defined in the same file as the struct they receive, and some more descriptive receiver name on methods that I attach to structs from other files.

Title: Use of "this" in Golang

Body:
On the closest thing Golang has to a style guide found here, under Receiver Names this is written:

The name of a method's receiver should be a reflection of its identity; often a one or two letter abbreviation of its type suffices (such as "c" or "cl" for "Client"). Don't use generic names such as "me", "this" or "self", identifiers typical of object-oriented languages that place more emphasis on methods as opposed to functions. The name need not be as descriptive as a that of a method argument, as its role is obvious and serves no documentary purpose.

I personally have always just used "this" as the identifier because "this" is the focus of what I am working on when I write and edit the function. It sounds right, and (to me at least) it makes sense.

If the name need not be descriptive, it's role is obvious, and it serves no documentary purpose, why would the use of "this" be frowned upon?

Body:
We'd have to ask the author of that style guide to know for sure, but I think the main reason I kind of agree with him is that the connection between struct and method is much looser in Go than other languages.

In essence, when you write a method like this:

func (m *MultiShape) area() float64 {
  ...
}

That's almost exactly the same thing as writing a function like this:

func area(m *MultiShape) float64 {
  ...
}

The only difference is a slight syntax change in how we call the function/method.

In other languages the this/self/whatever variable typically has some special properties such as being magically provided by the language, or having special access to private methods (remember Go doesn't have private fields/methods). Though the "receiver" is still being "magically provided" to some extent, it's so similar to a regular function argument it arguably doesn't count.

Plus, in "traditional" OOP languages a struct/class' methods all come with the struct/class definition, such that no more can be added from outside. In Go, as far as I know anyone can add more methods to anything (within the scope of their own code, of course).

I haven't written enough Go to make my own style guide, but personally I'd probably use this in methods defined in the same file as the struct they receive, and some more descriptive receiver name on methods that I attach to structs from other files.


答: Use a white board to write out and diagram interactions between classes or methods. This can help you to see the flow of the program. Once you have the 100ft view, then start digging, tracing and debugging to find the nuances of the system.</p>

Title: How do you go about understanding others' code?

Body:
What do you do to understand some code that you didn't write? Or code that you wrote long time ago and don't remember what it does anymore.

Do you have some technique that you go about? Do you analyze the structures first, or the public methods, or do you draw flow charts, etc.? Or do you fire up the debugger and just step through it? Or do you just ad-hoc your way through until you understand it?


问:
What is the best way to go about storing application options: file system or db?
We are looking to find the best way to store user options (skills, degrees, industries, languages, etc.) for drop downs. The options are between a JSON file we can store on the server file system or in the db (MongoDB).

What are the pros and cons of each method and how will they affect server performance under heavy usage?

答:
There are very good arguments for and against each option.  If you were speaking with regards to configuration data I would think a longer and more in-depth discussion would be warranted.

Since you're talking about application data, I would be inclined to believe that unless you know for certain that these data would never need to be queryable for reports and/or that it was static data that would never change, this data should belong in the database.


问:
If I #include a file, do I need to have a valid path to any headers #included in the included file
For example, if I have created a library, libcommon, which uses some other custom, but widely used library in a specific field (some_other), like this:

```<code>libcommon.h

#ifndef LIBCOMMON_H
#define LIBCOMMON_H

#include "some_other.h"

void do_something1();
void do_something2();

#endif  /* LIBCOMMON_H */
</code>```

Then if I want to use the library, and I have something like this in my main.c

```<code>#include "libcommon.h"

int main() {
    do_something1();
    do_something2();
}
</code>```

Then in my project I get

```<code>fatal error C1083: Cannot open include file: 'some_other.h': No such file or directory.
</code>```

Now I can fix this by providing the include path to some_other.h in my project, but I would prefer to make life easier for users of libcommon.  How do I do that?

I assume I need to make sure I do not use any types or functions defined in some_other.h for this to work?  Is that a common approach?  Or is it quite often the case that for say a helper library that uses a standard other library, same some_other library, then making the user of your lib set up include paths for some_other headers is ok?

I am trying to get an idea of how other people solve this issue and good approaches.

答:
Yes, the compiler has to be able to reach all files referenced int he project, including headers for other modules you may use.

There are 2 techniques to achieve this:

specify an Include path to the complier, passing in INCLUDE= style statements on the command line/makefile for each directory that contains relevant headers.

copy all headers into a single 'include' directory and reference that.

Which you prefer to use depends on your build system and preferences. I use a mix of these, typically copying all my own header files into a single directory as part of the compile steps (just as I copy binaries or libs into a common directory once they are built) but reference 3rd party module explicitly.


答:
If libcommon.h cannot be compiled without some_other.h, then anyone who wants to compile a call to doSomething1() is going to have to #include some_other.h as well as libcommon.h, otherwise the compiler simply doesn't have enough information to do its job. There's no magical way around that. As others have pointed out, when this dependency is correct you usually do something like set your build tools to look at all the .h files in a special "include" directory so you don't have to list each one individually on the command line.

The real question you should be asking is whether libcommon.h needs to depend on some_other.h, or if it's only libcommon.c that cares about what's in some_other.h. A function signature like void do_something1() doesn't require any special information to compile, so in your toy example you should be able to simply move the #include "some_other.h" statement into the .c file. If your real function signatures rely on type definitions in some_other.h, you might be out of luck, or this might be a reason to consider changing those function signatures.

Note that all users of libcommon still have to link against some_other's object code at link time no matter what, but because of how static linking works, it's likely that your libcommon.o includes the some_other object code, so there may not be any equivalent nuisance there. If you need more help with the linking stuff, that should be a separate question.

Title: If I #include a file, do I need to have a valid path to any headers #included in the included file

Body:
For example, if I have created a library, libcommon, which uses some other custom, but widely used library in a specific field (some_other), like this:

```<code>libcommon.h

#ifndef LIBCOMMON_H
#define LIBCOMMON_H

#include "some_other.h"

void do_something1();
void do_something2();

#endif  /* LIBCOMMON_H */
</code>```

Then if I want to use the library, and I have something like this in my main.c

```<code>#include "libcommon.h"

int main() {
    do_something1();
    do_something2();
}
</code>```

Then in my project I get

```<code>fatal error C1083: Cannot open include file: 'some_other.h': No such file or directory.
</code>```

Now I can fix this by providing the include path to some_other.h in my project, but I would prefer to make life easier for users of libcommon.  How do I do that?

I assume I need to make sure I do not use any types or functions defined in some_other.h for this to work?  Is that a common approach?  Or is it quite often the case that for say a helper library that uses a standard other library, same some_other library, then making the user of your lib set up include paths for some_other headers is ok?

I am trying to get an idea of how other people solve this issue and good approaches.


问:
In git, how to do versioning for a dozen libraries all worked at in parallel
We are doing projects, but we reuse a lot of code between the projects and have lots of libraries that contain our common code. As we implement new projects we find more ways to factor out common code and put it into libraries. The libraries depend on each other, and the projects depend on the libraries. Each project, and all libraries used in that project, need to use the same version of all the libraries they are referring to. If we release a piece of software we will have to fix bugs and maybe add new features for many years, sometimes for decades. We have about a dozen libraries, changes often cut across more than two, and several teams work on several projects in parallel, making concurrent changes to all these libraries.

We have recently switched to git and set up repositories for each library and each project. We use stash as a common repository, do new stuff on feature branches, then make pull requests and merge them only after review.

Many of the issues we have to deal with in projects requires us to do changes across several libraries and the project's specific code. These often include changes of library interfaces, some of which are incompatible. (If you think this sounds fishy: We interface with hardware, and hide specific hardware behind generic interfaces. Almost each time we integrate some other vendor's hardware we run into cases our current interfaces did not anticipate, and so have to refine them.) For example, imagine a project P1 using the libraries L1, L2, and L3. L1 also uses L2 and L3, and L2 uses L3 as well. The dependency graph looks like this:

```<code>   <-------L1<--+
P1 <----+  ^    |
   <-+  |  |    |
     |  +--L2   |
     |     ^    |
     |     |    |
     +-----L3---+
</code>```

Now imagine a feature for this project requires changes in P1 and L3 which change the interface of L3. Now add projects P2 and P3 into the mix, which also refer to these libraries. We cannot afford to switch them all to the new interface, run all the tests, and deploy the new software. So what's the alternative?

implement the new interface in L3

make a pull request for L3 and wait for the review

merge the change

create a new release of L3

start working on the feature in P1 by making it refer to L3's new release, then implement the feature on P1's feature branch

make a pull request, have this reviewed, and merged

(I just noticed that I forgot to switch L1 and L2 to the new release. And I don't even know where to stick this in, because it would need to be done in parallel with P1...)

This is a tedious, error-prone, and very long process to implement this feature, it requires to independent reviews (which makes it much harder to review), does not scale at all, and is likely to put us out of business because we get so bogged down in process we never get anything done.

But how do we employ branching and tagging in order to create a process that allows us to implement new features in new projects without too much overhead?

答:
The solution you are looking for is a dependency management tool in coordination with git submodules

Tools such as:

Maven

Ant

Composer

You can use those tools to define dependencies of a project.

You can require a submodule to be at least version  > 2.x.x  or denote a range of versions that are compatible  = 2.2.*  or less than a particular version  < 2.2.3

Whenever you release a new version of one of the packages you can tag it with the version number, that way you can pull in that specific version of the code into all other projects


问:
Are (basic) SQL queries semantically equivalent to Higher Order Functions?
Is SQL basically a domain specific instance of map + fold + filter?

It seems to me that the following SQL:

```<code>SELECT name
FROM fruits
WHERE calories < 100
</code>```

is just syntactic sugar for the following map + filter + fold operation:

```<code>var fruits = [{id : 1, name: 'orange', calories : 100},
    {id : 2, name : 'banana',  calories : 150},
    {id : 3, name: 'apple', calories : '50'}];

fruits.map(function(fruit) { return { name : fruit.name, calories : fruit.calories })
    .filter(function(obj) { return obj.calories < 100 })
    .reduce(function (accumulator, obj) { accumulator + "\n" + val.name; });
</code>```

Is this coincidence, or is there a sound semantic equivalence that can be proven? How, roughly?

I know in practice SQL has a lot of bells and whistles but at its core is it simply a map-fold-filter operation?

The following article is relevant:
Link

答:
Have a look at LINQ, which takes the basic concepts behind SQL and generalizes it to object-oriented programming.  The Where operator is a bog-standard Filter, the Select operator is a projection/Map, and so on.  All of the basic SQL query operations are represented in LINQ, implemented using higher-order functions, so yes, you're correct in your intuitive understanding of SQL.

The big difference between the example you've got and the way a relational database works is that SQL is designed with a very limited set of commands in mind.  It's not Turing-complete and the database designers know what it can and can't do, which makes it a lot easier for them to design the system to optimize queries to a far greater degree than would be possible with a simple Map enumerating a data set element-by-element.


答:
SQL is based on Relational Algebra and Tuple Relational Calculus, not higher-order functions or functional programming.  While SELECT, FROM and WHERE have analogous functions in other languages, SQL itself doesn't support generalized higher order functions, but only those "higher-order" functions that the language itself defines.

Since SQL doesn't allow you to write your own custom higher-order functions, it can't be said with any authority that the language supports higher-order functions.

Title: Are (basic) SQL queries semantically equivalent to Higher Order Functions?

Body:
Is SQL basically a domain specific instance of map + fold + filter?

It seems to me that the following SQL:

```<code>SELECT name
FROM fruits
WHERE calories < 100
</code>```

is just syntactic sugar for the following map + filter + fold operation:

```<code>var fruits = [{id : 1, name: 'orange', calories : 100},
    {id : 2, name : 'banana',  calories : 150},
    {id : 3, name: 'apple', calories : '50'}];

fruits.map(function(fruit) { return { name : fruit.name, calories : fruit.calories })
    .filter(function(obj) { return obj.calories < 100 })
    .reduce(function (accumulator, obj) { accumulator + "\n" + val.name; });
</code>```

Is this coincidence, or is there a sound semantic equivalence that can be proven? How, roughly?

I know in practice SQL has a lot of bells and whistles but at its core is it simply a map-fold-filter operation?

The following article is relevant:
Link


问:
Basing all .NET applications on a central CORE library?
The company I work for was recently acquired by a much larger company.
In conversation with their IT systems group there was some discussion about modifying the existing programs so that they use a 'CORE' library.  This 'CORE' library is a replacement for standalone class libraries that we created.

My basic understanding is that the UI (windows client program/console/website) all talk to a central core that is web-service based.

Are there any pitfalls to this setup?

My main concern would be in read-write intensive applications that the CORE would not be as fast as a program running all the libraries directly (in the same install path).

Note:  We primarily run Windows servers with .NET applications.

答:
The pitfalls range from Nothing to Everything, with your real-world results lying somewhere in between.

Standard libraries are used everywhere. For example, we have the C++ standard library that almost all C++ programs are based off of to some degree. Even this standard library changes depending on your compiler, in that the standard library that ships with GCC is not the same as what ships with Visual Studio. Additionally, programs targeting the .NET platform use mscorlib in the same fashion.

We trust these core libraries implicitly because they are written by large teams of very brilliant people, and hope that they run as well as we'd like. However that doesn't prevent someone from writing their own implementation of mscorelib (I'm looking at you, Mono) which they then base their own applications on. Quite simply, there are things that Mono does extremely poorly compared to the Microsoft library that most .NET applications are compiled against. Does that mean that it will break your application? It depends.

Now it doesn't sound like this is the same kind of core library that you're concerned about, but the same concerns apply. If the library is written very well, it's certainly possible to get new functionality and performance boosts. However if it is written very poorly, your application could perform extremely poorly or straight-up break.

Broadly speaking, it depends on where this CORE service is running. For example, a single server running the core functionality is probably a poor replacement to each individual computer running that same functionality. However that may be a trade-off that gains you various benefits, and so it's not black and white.


答:
Sure, this sort of Software as a Service stuff has existed for quite some time now.

Are there any pitfalls to this setup?

Yeah, non-functional internet makes it hard for web services to work without some sort of local caching layer. The latency you talk about can be a concern. It can be harder to test your application depending on how it is designed. And depending on how the library is designed, it can cause issues since any change there impacts all clients, either breaking them or slowing changes to the core libraries.

But none of that matters.

For a large company, they likely have handfuls to hundreds of commercial software applications, it is enormously costly to keep developing and maintaining the same bits of code (authentication, authorization, billing, logging, technical support, internationalization frameworks, etc) and hardware to support that code over and over again. Oh, and it helps speed development since pretty much every large company has to support multiple platforms (web, mobile, desktop).

So while it might inconvenience your customers with shoddy internet connections, it will not make up for the literally millions of dollars the company saved by consolidating the common code.

Title: Basing all .NET applications on a central CORE library?

Body:
The company I work for was recently acquired by a much larger company.
In conversation with their IT systems group there was some discussion about modifying the existing programs so that they use a 'CORE' library.  This 'CORE' library is a replacement for standalone class libraries that we created.

My basic understanding is that the UI (windows client program/console/website) all talk to a central core that is web-service based.

Are there any pitfalls to this setup?

My main concern would be in read-write intensive applications that the CORE would not be as fast as a program running all the libraries directly (in the same install path).

Note:  We primarily run Windows servers with .NET applications.


问:
Why are regular expressions so morbidly attractive?
Exhibit 1, Exhibit 2, I guess you won't find it hard to recall other examples.

Thing is: if there is more than one way to solve a problem, the PHP programmer (I usually browse the PHP tag on StackOverflow) will ask for help on the solution involving regular expressions.

Even when it will be less economic, even when the php manual suggests (link) to use str_replace instead of any preg_* or ereg_* function when no fancy substitution rules are required.

Does somebody have a clue about why this happens?

Don't get me wrong, some of my best friends are regular expressions and I don't despise Perl. What I don't get is why there is no looking for alternatives whatsoever, even when the overkill is obvious (regex to switch strings) or the code complexity rises exponentially (regex for getting data from html in PHP)

答:
Why are regular expressions so morbidly attractive?

Because on the subconscious level they feel like an entire smart program who can accomplish a lot on its own accord while being encompassing and self-adjusting (think patterns).

This is why people immediately believe regular expressions will solve any of their text-based task, somehow not thinking it might be overkill and not realizing it might me underkill (parsing languages with it).

A tiny thing containing magic power. You can't say no, can you?


问:
Appropriate use case for "accepted"?
We have a task enqueued by a REST endpoint that will create a resource and then enqueue a task either immediately or delayed based on some business logic.

I was thinking of using HTTP/1.1 200 OK for the immediate case, and HTTP/1.1 202 Accepted for the case where that task has been delayed, however, the resource POSTed  is created immediately, it's just the resulting task that affects the user which is delayed, so it seems like a bit of misuse to do a 202. Am I overthinking this? Is there a better way I can tell the client about this delayed task?

答:
202 Accepted

The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place.

Seems like a good fit to me.  That the resource gets created immediately does not actually complete the processing in your case.

Title: Appropriate use case for "accepted"?


答:
There are two similar responses that should be considered depending on what the expected response should be.

The 202 Accepted response is a "yep, got that" response. The resource is created and the server will get around to doing something with that.

The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. There is no facility for re-sending a status code from an asynchronous operation such as this.

The 202 response is intentionally non-committal. Its purpose is to allow a server to accept a request for some other process (perhaps a batch-oriented process that is only run once per day) without requiring that the user agent's connection to the server persist until the process is completed. The entity returned with this response SHOULD include an indication of the request's current status and either a pointer to a status monitor or some estimate of when the user can expect the request to be fulfilled.

( http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html )

The other response to look at is the 201 Created response:

The request has been fulfilled and resulted in a new resource being created. The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field. The response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. The origin server MUST create the resource before returning the 201 status code. If the action cannot be carried out immediately, the server SHOULD respond with 202 (Accepted) response instead.

( http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html )

In particular, the 201 response responds back with the resource location that has been created.  This part matches the description of your requirement:

... the resource POSTed is created immediately, it's just the resulting task that affects the user which is delayed ...

Related blog post:

http status 201 created vs 202 accepted

Title: Appropriate use case for "accepted"?

Body:
We have a task enqueued by a REST endpoint that will create a resource and then enqueue a task either immediately or delayed based on some business logic.

I was thinking of using HTTP/1.1 200 OK for the immediate case, and HTTP/1.1 202 Accepted for the case where that task has been delayed, however, the resource POSTed  is created immediately, it's just the resulting task that affects the user which is delayed, so it seems like a bit of misuse to do a 202. Am I overthinking this? Is there a better way I can tell the client about this delayed task?


问:
Recursion, iteration, and ...?
Here are three common code structures that apply a function multiple times:

```<code>foo(x) {
    if basecase(x) return k else return foo(g(x))
}
</code>```

uses recursion.

```<code>for i in 0..10 {
    n *= bar(i)
}
</code>```

uses iteration.

```<code>baz(baz(baz(baz(quux))))
</code>```

uses...?

In mathematics it'd be considered iteration, but mathematics doesn't generally concern itself with for and while loops, which are what people associate with the term in programming. How do programmers tersely and unambiguously refer to the third construct?

答: The term you're looking is for is function composition, although I'm not sure if there's a more specific term for the special case of a function composed with itself.

Title: Recursion, iteration, and ...?


问:
The best shard key for user authentication
For access to my API user should send login and password and get generated token for access.

```<code>Account
 login
 password
</code>```

Suppose the size of account's table is very large. So large - so needs sharding.
Usually I prefer sharding by ranges (which excludes re-sharding) when I do it for tables with primary key ID (and the same shard key). But in this case sharding key should be a string (login).

What is the last best practices you use for this task?
Consistent hashing (from Guava, for example) and resharding only (K / n) keys in the case of changing structure of nodes? May be there are some practices without re-sharding? Something else?

答: If you do have to go with re-sharding, one way to do this is to use another database table to store the actual account and host/table mapping. Mapping table contains only key fields to lookup on which are optimized for performance (id, name, email) and rest of the account data is in the table that the mapping table points to. This gives the most flexible re-sharding technique.</p>


问:
Java Serialization - Variables Visible in Text Editor
When I serialize my class and save it as a custom file extension, some of the variables and imports are visible when you open the file in a text editor. Is there a way to avoid this or is there an alternate method to save class instances as a file? My file saving code:

```<code>//Make file
FileOutputStream fileOut = new FileOutputStream("fileName.ext");
ObjectOutputStream out;
out = new ObjectOutputStream(fileOut);
out.writeObject(instanceToSave);
out.close();
fileOut.close();
</code>```

The instanceToSave is a class instance in which the class implements java.io.Serializable.

Note: I do not mean transient variables.

答:
First of all, I highly recommend you read up a little on Java serialization. This article is a bit dated but covers the essentials.

Specifically, this bit is important:

2. Serialization is not secure

It often comes as an unpleasant surprise to Java developers that the
  Serialization binary format is fully documented and entirely
  reversible. In fact, just dumping the contents of the binary
  serialized stream to the console is sufficient to figure out what the
  class looks like and contains.

This means that the default serialization cannot be relied upon to obfuscate or secure the contents of objects.

However there is a way that may be able to achieve what you need. You can write custom serialization methods on the class being serialized where you can transform data however you want. Keep in mind that at best you can hope to obfuscate or slow down someone from reading the data.

```<code>public class MyClass implements Serializable {
  private String secret;
  ...
  private void writeObject(ObjectOutputStream out) throws IOException {
    out.writeObject(encrypt(secret));
  }

  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    ename = decrypt(in.readUTF());
  }

  private String encrypt(String plaintext) {
    return ...;
  }

  private String decrypt(String ciphertext) {
    return ...;
  }
}
</code>```

Body:
First of all, I highly recommend you read up a little on Java serialization. This article is a bit dated but covers the essentials.

Specifically, this bit is important:

2. Serialization is not secure

It often comes as an unpleasant surprise to Java developers that the
  Serialization binary format is fully documented and entirely
  reversible. In fact, just dumping the contents of the binary
  serialized stream to the console is sufficient to figure out what the
  class looks like and contains.

This means that the default serialization cannot be relied upon to obfuscate or secure the contents of objects.

However there is a way that may be able to achieve what you need. You can write custom serialization methods on the class being serialized where you can transform data however you want. Keep in mind that at best you can hope to obfuscate or slow down someone from reading the data.

public class MyClass implements Serializable {
  private String secret;
  ...
  private void writeObject(ObjectOutputStream out) throws IOException {
    out.writeObject(encrypt(secret));
  }

  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    ename = decrypt(in.readUTF());
  }

  private String encrypt(String plaintext) {
    return ...;
  }

  private String decrypt(String ciphertext) {
    return ...;
  }
}


问:
Ways to have a history of changes of database entries
What are ways to allow the versioning of database entries (data)?

Think of the content-managment-systems abilities to revert back changes of articles.

What are their pros/cons?

答: also, if you want to store ALL changes to the DB over time, you might want to check out logging (https://stackoverflow.com/questions/3394132/where-can-i-find-the-mysql-transaction-log)</p>


答:
There is the question whether 202 is the right result for what you are doing, and the other question is how the client processes it.

If a client receives a 202, chances are that it doesn't handle it properly (many clients will only recognise 200 as success, everything else is bad).

But what if the client recognises it: 202 means the server promised to do it, but the operation might actually fail. That means the client can't rely on the server having stored the data. The client must make some other request at some later point to check whether the request actually has been performed. That's a pain.

So unless you have a lengthy queue of operations that you need to do, where you suspect a client could timeout (60 seconds usually), I'd think very hard if it isn't better to return 200 when the request has actually been processed.

Title: Appropriate use case for "accepted"?


问:
Why would we need to rollback twice before closing in a finally block?
I'm trying to implement the change in database connection closing suggested in this question's answers.  More than once, I've come across this block of code at the end of my try blocks:

```<code>try {
    -Code-
} catch(DatabaseException de) {
    if(conn != null)
    try{
        conn.rollback();
    } catch(SQLException e) { }
    throw de;
} catch(SQLException se) {
    if(conn != null)
    try {
        conn.rollback();
    } catch(SQLException e) { }
    throw new DatabaseException("SQLException caught: "+se.getMessage());
} finally{
    if(conn != null)
    try{
        conn.rollback();
        conn.rollback();
        conn.close();
    } catch(SQLException e) { }
}
</code>```

This absolutely baffles me - why would we need to rollback our connection twice before closing it in a Finally block, when we're already catching the rollback separately?

答:
I have seen this code before in another language (Delphi).  It was implemented that way because of an issue where the database (in this case Oracle 7 or 8) wouldn't reliably rollback the first time the rollback method was called.  The bug was seemingly random and could not be reliably reproduced - even in production.

Rather than spending days tracking down the Heisenbug the developer decided to put a second rollback in which "fixed" the problem.  We made sure that this was properly commented to document the hack.

IIRC moving to directly use the Oracle Call Interface rather than the Borland Database Engine resolved the issue which points to the problem being something weird in the database abstraction layer.


问:
Should I use generics whenever possible or is object ok in some cases?
I'm having an interface ProgressReporter which basically takes a list of input items (the working queue) through a method SetWorkPackages(IEnumerable<T> workPackages) and then has another method FinishedWorkPackage(T workPackage) to indicate that one package has been finished.

It will then handle this the correct way, i.e. display a new percentage number, update a progress bar on the UI, whatever is implemented.

Using generics, I have to call it like this:

```<code>var cpr = new ConsoleProgressReporter<WorkPackage>();
cpr.SetWorkPackages(...);
cpr.FinishedWorkPackage(...);
</code>```

Actually, I have the feeling that the user does not really care about the type T, because he never gets results back through the API. Even internally in the current implementations, it does not matter what type T is.

Is it ok in such cases, to just allow object instead of using generics? Are there general guidelines when to use generics and when to use object?

答:
If it makes no difference whatsoever what the element type is, then sure, you could ignore the fact that they're T objects. But if you're never going to perform any T-specific operations on them, why store the objects at all? You might be better off with just a counter recording how many they are.

The only situation where I can imaging holding things as Objects makes sense is if you want to call Object-defined methods but not T-defined methods in them, e.g. toString(). But frankly, there aren't all that many useful Object methods to begin with.


问:
How safe & trustworthy are hosting sites such as sourceforge, github or bitbucket for closed-source projects?
I am considering using sourceforge, bitbucket or github for managing source control for my business.  I have open projects and I participate in open projects such as gcc.  But I also have a business where I develop closed-source software for my living.

How trustworthy are sourceforge, github or bitbucket in terms of keeping software secure from prying eyes?  How stable is the hosting in terms of data loss prevention?  Has anyone out there based their business logic with such an outfit?  Has anyone out there surveyed several of the hosting solutions?

答:
SourceForge is not considered trustworthy anymore. It has been hijacking accounts and replacing Windows packages with adware installers (GIMP, nmap, and others). SourceForge has also been active in filtering out users from specific countries. Nothing really prevents other hosting services from interfering with software installers since we have yet to see SF prosecuted legally. Caveat emptor.

EDIT: https://helb.github.io/goodbye-sourceforge/ is a good resource for hosting comparison (I'm not affiliated with them).


问:
What is an "assertion framework"?
I was reading about the js-test-driver unit-testing framework, when I found out that the guys behind the framework intend it to be integrated with an assertion framework. What is an assertion framework? Is it a kind of unit-testing framework? If it is the case what is specific to such frameworks?</p>

答:
An example of an Assertion Framework would be Hamcrest which was integrated into JUnit 4.  Hamcrest does not run tests, it merely provides an expressive way to write assertions.

Old JUnit style equality assertion:

```<code>assertEquals(constant, underTest);
// or for doubles
assertEquals(3.5, underTest, .001); // within 1/1000th
</code>```

Hamcrest style equality assertions:

```<code>assertThat(underTest, Is.EqualTo(constant));
// or for doubles
assertThat(underTest, Is.EqualTo(3.5).Within(.001));
</code>```

Essentially, an assertion framework allows you to perform your assertions in an easily extensible manner.  Because the assertion framework focuses on assertions alone, it can do the job much better than a tool that has to collect and run tests as well.  NUnit has also adopted the Hamcrest approach to assertions.  You would not use Hamcrest to run your tests, merely to write the assertions.

Title: What is an "assertion framework"?

Body:
An example of an Assertion Framework would be Hamcrest which was integrated into JUnit 4.  Hamcrest does not run tests, it merely provides an expressive way to write assertions.

Old JUnit style equality assertion:

assertEquals(constant, underTest);
// or for doubles
assertEquals(3.5, underTest, .001); // within 1/1000th

Hamcrest style equality assertions:

assertThat(underTest, Is.EqualTo(constant));
// or for doubles
assertThat(underTest, Is.EqualTo(3.5).Within(.001));

Essentially, an assertion framework allows you to perform your assertions in an easily extensible manner.  Because the assertion framework focuses on assertions alone, it can do the job much better than a tool that has to collect and run tests as well.  NUnit has also adopted the Hamcrest approach to assertions.  You would not use Hamcrest to run your tests, merely to write the assertions.


问:
Early subtasking at the beginning of each sprint
I have joined a new team which is using Agile/Scrum, and their development process is as follows:

1) developers review each story before each sprint to make sure it doesn't miss anything critical. There's a formal state for that in the workflow.

2) during the Sprint kickoff, the entire team does an estimation (poker planning) on how many story points each story would cost.

3) finally, immediately after each sprint starts, each developer is required to eagerly break down all of assigned stories into subtasks with time estimates (as opposed to subtasking before starting each story).

The main argument for the last step is that it helps to discover if implementing a story would take longer than anticipated and warn scrum master about potential risks of missing sprint deadlines.

Yet I find this counter-productive, mainly because of the following reasons:

if the aim is to provide rough estimate, story points (step #2) is what does the job. Otherwise why bother with story points at all? - just do subtasking early on.

if the aim is to provide accurate estimates, then this is a clear example of what is described in Human Task Switches Considered Harmful. This, I think, is especially the case for fresh developers who join existing teams in big projects where understanding what needs to be done can take up to 50% of the time. You are required to get into details of story #1, then story #2, #3, etc. etc. which yields a lot of information churn.

I am also being told that such practice is "by the book" and I'm not even meant to discuss this. Can anyone provide a reference to such practice - whether this is clearly defined in Scrum bibles, and/or perhaps provide any extra insight?

答:
I would assume that your Sprint Kickoff means the Sprint Planning meeting. I think your Scrum Master misinterpreted how this meeting should go. You do not only decide on what stories to develop, you also test them to your team its definition of ready to make sure they don't miss anything (usually using INVEST), and you also subdivide those stories into tasks. To quote Mike Cohn (one of the founders of the Scrum Alliance);

The sprint backlog is the other output of sprint planning. A sprint backlog is a list of the product backlog items the team commits to delivering plus the list of tasks necessary to delivering those product backlog items. Each task on the sprint backlog is also usually estimated.

So the breaking down of stories and estimating them is all part of the Sprint Planning session; not after the planning session has finished and not individually.

To provide some more insight, our workflow during the Sprint Planning meeting is as follows:

we take a story from the top of the product backlog, and split it up into tasks. As a rule of thumb,
one task should generally be smaller than a day.

We estimate the story given the tasks we've deducted. If the story
turns out large, we try and split up the story into smaller stories.

Rinse and repeat until we reach the total of estimated points

Contrary to what Cohn says, I found that there is no real need to estimate each of the tasks separately, as the tasks are specified to be smaller than a day. Given that tasks are smaller than one day of work, you can easily notice during Daily Standup when a task is taking longer than expected, as the person working on the specific task will say that he is still working on it.

During sprint the team works its way through the stories, and at the end the team should reflect on how much actually got done. This is what the scrum retrospective meeting is for. If theres still stories on the table, you may deduct that your estimation was too optimistic and act on it for the next sprint. Alternatively there could have been certain incidents that occurred that affect how much you got done, etc. You will find that the estimations get better over time when you reflect on them.


答:
Just how many users are you expecting to have?

I've worked with systems that have hundreds of thousands of users and have never felt the need for sharding (just proper indexing).

And, of course, you're not actually storing the password, are you ...

Title: The best shard key for user authentication

Body:
For access to my API user should send login and password and get generated token for access.

```<code>Account
 login
 password
</code>```

Suppose the size of account's table is very large. So large - so needs sharding.
Usually I prefer sharding by ranges (which excludes re-sharding) when I do it for tables with primary key ID (and the same shard key). But in this case sharding key should be a string (login).

What is the last best practices you use for this task?
Consistent hashing (from Guava, for example) and resharding only (K / n) keys in the case of changing structure of nodes? May be there are some practices without re-sharding? Something else?


问:
Best practice to handle POST with array of objects if at least one object raise an Exception
I want to POST an array of objects and make an insertion in database concerning each of them.

What is the best practice if one object does not conform and raise an Exception? (cancel all transactions or just one and specify it when I return this list of objects?)

答:
If it's a batch operation, I'd rather process all the operations one by one, and return the array of objects with their own status.

You can return the HTTP status code 200 OK if all the operations succeeded, or a 207 Multi-Status if you have operations that failed amongst your batch.


问:
How to pick a random move/action/element non-probabilistically?
I am trying to create a simple AI that can play Go using Monte Carlo Tree Search.

This question, however, is valid for all games where players take turns doing some action that, on average, reduce the amount of possible actions to take in the future. (Other examples might be Tic Tac Toe, Connect 4 and a whole bunch of others.), or any situation in which we need to  "Pick a random possibility until it is within expected parameters".

In Go, Players take turns placing a stone of their color on the board. As the board fills up, some moves are no longer valid (For instance, because there might be a stone at that location already.*)

The algorithm should pick a move at random. However, how do we ensure that the move we picked is valid? I see the following options, each with their own drawbacks:

When the move is not valid, pick a new random one. Drawback: The program is now probabilistic; it is very possible that it picks only invalid moves repeatedly, and therefore never finishes executing.

When the move is not valid, move to the next square (wrapping around at the edges of the board). Drawback: When there is a large region of the board that is already occupied, the distribution of moves picked is no longer random: It is far more likely that the position right next to the filled area is picked, as when the random number falls in this range, this is the chosen square.

First obtain a list of all possibilities, and choose a random element from this list. This ensures an equal distribution of probabilities. Drawback: Because we need to iterate over the whole board and obtain a list of all possible moves, this is inefficient. As the algorithm should run as fast as possible (As we want to simulate as many games as possible), iterating over the whole board should best be avoided.

Now, I am wondering if there exist another method of picking a move at random that:

Does not significantly favour certain outcomes over others.

Will terminate.

Does not need to find out all possible moves from a certain position beforehand.

*(The rules of Go have more conditions for a move to be valid, but these do not change this question)

答:
Let's try to analyse the costs

When the move is not valid, pick a new random one.

  Drawback: The program is now probabilistic; it is very possible that it picks only
  invalid moves repeatedly, and therefore never finishes executing.

is it? Even if you play in a 19x19 board and have only one move left, this gives you a 1/361 chance to pick it and you'll have to try 1660 times to have a 99% chance to terminate. This drops rapidly; for the previous move it's 828 and for the vast majority is around 20 so the average is around 27

the cost would be (pickMove + isValid)*27

Yes the worst case is inf but we want the average case.

First obtain a list of all possibilities, and choose a random element from this list. This ensures an equal distribution of
  probabilities.

  Drawback: Because we need to iterate over the whole
  board and obtain a list of all possible moves, this is inefficient. As
  the algorithm should run as fast as possible (As we want to simulate
  as many games as possible), iterating over the whole board should best
  be avoided.

so this would be: 361 * isValid + pickMove

Maintain and update the list of possible moves to pick from.

finally, this would be pickMove + updateList

So now we have an approximation of the costs, which one is better?

(pickMove + isValid)*27 vs 361 * isValid + pickMove vs pickMove + updateList

I agree with ratchet freak that the solution with the list seems the best. But I don't know for sure; maybe updateList becomes super slow after adding all the rules for liberties and ko. Is the second one better than the first? Maybe not if pickMove is way faster than isValid.

But maybe we can avoid all these; I have a hunch that the following algorithm will generate a uniform distribution:

pick a move, n

if it's invalid, check square n+1

skip one square and check square n+3

if it's invalid, go to 4

the idea is to skip one more square for every invalid square you encounter. It might not work and it definitely involves more than one steps.

So my answer would: profile them. This is not a trivial case of using quicksort over bubblesort. And, in fact, sometimes it might actually not matter if you use bubblesort. Which brings us to my real answer: do you know that this is where you should focus your optimisation efforts?

Maybe most of the time is wasted in a datastructure or in RNG. Or maybe one approach enables parallelisation or you can write it a low-level language easier thus making number crunching faster. Yes it's probably your innermost loop but you should still implement, test and then optimise the performance.


问:
How to acquire data and render page in context of REST/API application?
In typical REST/API application, build on MVC architectural pattern, what is the best available technique for acquiring data for rendering views?

Should it be:

as in any non-API application: data is acquired directly from DB (through models), as in classical MVC, and controllers are rendering views basing on standard model data, and forms sends data through typical POST,

since this is an API application, even its very own website should be a client, that acquires data through API requests only and controllers are rendering views basing on JSON-like data, and forms must encode data to a typical JSON and push it API-way, just like an average JSON PUT request,

something else.

This question may sound silly or even naive. Unfortunately, I'm a very beginner to API/REST topic. Sorry.

答:
If the data will be consumed by something else, either a frontend UI or another application somewhere else on the Internet, then you need a REST API.

Otherwise, you don't.


问:
Should private functions be held to the same standards as public functions?
If I'm building private utility functions, should they be held to the same rigorous standards in terms of handling invalid data as public functions?

Example:If I'm writing code to calculate the length of a linked list, and the list being passed is one created by my own code, should it be checked for loops if my code does not create linked lists with loops in the 1st place?

答:
I will disagree with the other answers and say no. Verifying input is much more important in public than in private methods.

Especially if you write a component for reuse, you cannot make any assumptions about what values are passed to the public methods, except what is guaranteed by the type system.

For private methods it is a different matter, since you can easily see everywhere the method is called and with what arguments, at least if your class have a sensible size. If you never assign null to an object reference for example, you don't need to check for null in a private method. In a public method you cannot make such assumptions. Your example where you know you never create cycles in a linked list is the same.

Of course there is always the risk that somebody modifies another method in the same class to break the assumptions, but then again if you have mad monkeys changing the code at random, you also risk they delete the verification checks anyway. Unit tests are the right approach to verify the integrity of a class and protect against changes that introduces bugs.

In theory it would be nice if all methods verified all input. but introducing verification also have cost. For example a simple extract-method refactoring will require you to copy paste input verification from the host method, introducing code weight for no clear benefit.


问:
What is a proper way to chain instructions if previous one is ok
I'm currently working on a big file I have to parse and process and each step needs to be done in an order as I do SQL queries and need inserted IDs to make other insertions ...
The problem is I often find my code to look like this :

```<code>if( function1() ) {
    // process things to continue
    if( function2() ) {
        // process things to continue

        // ... and so on

    } else {
        // fail2
    }
} else {
    // fail1
}
</code>```

And same goes for form validations, etc... and it gets really hard to follow the steps, and it's just not pleasant to see in the code.

As I said, I need function1 to be done before function2, so I can't do otherwise than be sure previous functions are done correctly.

Is there as proper way, or a design pattern, to code this kind of chained conditional functions ?

(FYI : I use OO PHP5, and I'm pretty much a novice in terms of standards in programming, so please don't behead me if this is casual !)

(concerning possible duplicate of When, if ever, should I daisy chain functions? ) : the functions can be used seperately and thus can't be used with daisy-chaining (see "B" in the given link).

The //Fails are here to "raise a flag" to say there has been a problem and further in the code (after the if/elses) it rollbacks all changes (with PDO's transaction rollback). But I would like to warn user there has been a problem, write a message (database error ? empty values ? ...) and maybe pass more informations like variables to be displayed/debugged.

答:
the easiest way to refactor that is to use a success variable,
eg

```<code>res = do_stuff();
if (res)
    res = do_more_stuff();
if (res)
    ....
</code>```

If you use a counter instead of a boolean success variable, then you can also tell if all of the steps succeeded at the end (ie. the counter will equal the number of steps that successfully ran)

The one thing you cannot do with this pattern is to have different 'else' clauses for error, but you can instead throw an exception to handle the flow (not so recommended if you expect the steps to fail). You could track the last method that was executed and have a switch handler at the end of the method that called the appropriate fail routine for each, but that can get messy - depends on your circumstances of course.

There are more complex ways to handle this - eg instead of calling each method, call a helper that takes 2 functions as parameters, the method to call and the method to call on failure, then the helper can return true/false as before, or construct a collection of functions to call and iterate through it, calling each one in turn.. but these are best left for special circumstances when you need them. As you say you're a bit of a novice, I'd go for the pattern I first suggested, its simple.

Body:
the easiest way to refactor that is to use a success variable,
eg

res = do_stuff();
if (res)
    res = do_more_stuff();
if (res)
    ....

If you use a counter instead of a boolean success variable, then you can also tell if all of the steps succeeded at the end (ie. the counter will equal the number of steps that successfully ran)

The one thing you cannot do with this pattern is to have different 'else' clauses for error, but you can instead throw an exception to handle the flow (not so recommended if you expect the steps to fail). You could track the last method that was executed and have a switch handler at the end of the method that called the appropriate fail routine for each, but that can get messy - depends on your circumstances of course.

There are more complex ways to handle this - eg instead of calling each method, call a helper that takes 2 functions as parameters, the method to call and the method to call on failure, then the helper can return true/false as before, or construct a collection of functions to call and iterate through it, calling each one in turn.. but these are best left for special circumstances when you need them. As you say you're a bit of a novice, I'd go for the pattern I first suggested, its simple.


问:
How many threads is too many to maintain a chat server?
I'm writing a chat server and client. For the chat server I have 3 "services" all running on their own threads:

ConnectionListener that loops over accept, and adds any new clients to a ConcurrentLinkedQueue

MessageListener that waits for incoming messages from clients; also adding them to another ConcurrentLinkedQueue

MessageBroadcaster that sits on the other end of MessageListener's queue, and sends out any received messages to the clients in ConnectionListener's queue.

I think that's all the background tasks that I'll need, but say in the future, I have another task that I think should operate concurrently in the background. At that point, the server will be using 4 threads for 4 separate background tasks.

Is there a point where I should reconsider my design? What is a better way of arranging this?

My question stems from 2 concerns:

I hear threads are expensive. While that isn't an issue yet, I don't want to get into the habit of spawning a new thread for everything if there's a better way.

I'm not sure if I should sacrifice "separation of concerns" to save using threads. In theory, the message receive/broadcast jobs could be combined; although they're separate duties.

答:
I hear threads are expensive. While that isn't an issue yet, I don't want to get into the habit of spawning a new thread for everything if there's a better way.

Threads have overhead. The longer a thread lives, the less of a concern the overhead is. For example, let us assume a thread has a ton of overhead and requires 100ms to spin up. However, the thread lives for an hour. That is a tiny fraction of its life, so who cares? If you can bury the thread initialization in application startup when users expect delays anyway, all the better. If the thread lived for less than a second, then the overhead is a bit much and maybe you should consider alternatives.

That being said, do not spawn threads to do nothing. Each thread should have a purpose.

I'm not sure if I should sacrifice "separation of concerns" to save using threads. In theory, the message receive/broadcast jobs could be combined; although they're separate duties.

In my experience, multithreaded applications need multiple threads. Combining concerns with e.g. a listener and a broadcaster in this case will increase complexity to the point of it being unmanageable. It will create bugs. The key here is where do the threads block? If you have a listener that blocks on accepting a socket, it makes no sense for it also to handle requests. One of its concerns will suffer: requests will be delayed, or new connections might fail. Just create more threads.

Note 1: you should be using thread primitives, not raw threads. Since you tagged this question java I will point to the specific class: ExecutorService. The Executors class provides several factory methods to make it easy to create them for various tasks. The basic idea is you submit tasks (Future or Runnable) and let the framework manage the threads.

This has two primary advantages:

Managing threads can be hard. While it appears easy, there is a lot of boilerplate logic that is easy to screw up, resulting in weird, difficult to replicate (and fix) bugs. Push this responsibility into a robust framework that is well-tested and used in millions of other programs. If there were bugs then Oracle (or Microsoft for .NET, or whatever other vendor) would have found them by now.

Your program's purpose is not "to manage threads" it is "to run a chat server." Let the framework handle the threading concerns, and focus on the chat server aspect. By focusing on the tasks and not the threads, your code is more concise, expressive, and clear.

I wrote up an answer to this old Stack Overflow question that shows a use case for this. I do not want to derail the focus on this answer too much, so you can read more here as well as search both Programmers and SO: Creating an unknown amount of threads in Java?

Note 2: given that this appears to be a desktop/server application as opposed to embedded, there is not much need to be concerned with spawning threads. Modern CPUs (amd64, Intel Core) have multiple cores on-die, typically between two and six. Some models are hyperthreaded or superscalar, adding more logical cores that can execute code concurrently. Add in time slicing with today's high clock speeds, and there is no need to concern oneself with spawning too many threads as long as the threads are reasonable. In the case of your question, the threads appear to be performing small bits of work and possibly blocking on I/O. You are not spawning a million threads for digital video encoding, for example.

Even on embedded architectures, speed and concurrency are not as strong as desktop and server CPUs but should have no problem handling a few threads. My smart phone and tablet both have many applications running in the background and have zero performance problems even with many applications and threads running.

Note 3: if you are interested in learning more about the tradeoffs of a single-threaded algorithm vs. splitting it into pieces and using concurrency, there are a few topics worth exploring. Given the problem described in your question this is not an immediate need, but could make for some interesting and educational reading.

MapReduce is an algorithm for splitting a task into pieces that do not rely on each other, performing those tasks, and joining the results together.

Parallelism in databases involves multiple threads querying data and joining the results. There has been a lot of research into the tradeoffs of using multiple threads for a single database query and a lot of information is out there. Outside of schema/query optimization this is very useful information from a more theoretical perspective.


问:
Why don't Windows/Linux use relational Databases (RDBMS)?
Why don't Windows/Linux use relational databases (RDBMS)?

I know they use file systems to store all data but don't you think it is more efficient to use databases like we use in web sites/web apps?

Please elaborate on the use of a file system over a database for storage.

This is not a duplicate of When should use of database be preferred over parsing data from a text file? I am talking in terms of only operating system contexts, and that question is generalized.

答:
The main function of any OS is to facilitate interactions between applications, hardware and the users.

So.. why don't Windows/Linux OS use relational Databases (RDBMS)?  This is a question of biblical proportions, but the short answer is: There is not any real benefit to be gained from using a complex structure such as an rdbms as a file system.

"Relational" is the operative word in "Relational Database" and most data stored in a file system is unrelated to other data. File systems generally are implemented as limited databases, just not relational ones.


问:
What is the difference between function() and function(void)?
I have heard that it is a good practice to write functions that do not receive anything as a parameter like this:

```<code>int func(void);
</code>```

But I hear that the right way to express that is like this:

```<code>int func();
</code>```

What is the difference between these two function declarations in both C and C++?

答:
In C, a function with an empty parameter list () can take anything for its arguments. Literally anything. This is usually used to implement a function which can take a variable number of arguments, though these days it's considered preferable to use the more explicit ellipsis syntax (...) for these functions.

In C, a function with the parameter list (void) explicitly takes nothing for its arguments. That means the compiler can actually tell you you've made a mistake if you try to pass something.

In C++, these function declarations are equivalent. A blank parameter list means "no parameters" the same as void does.


答:
There are two methods for running a standard site (non-RESTful) in parallel with a RESTful service.

The website consumes the RESTful service.  This would often mean you are creating a one page app (Angular, etc).  This is simplest from the backend standpoint in that you should have minimal additional coding on the backend, but you need to create an entire web app in Angular (or other single page app framework)

The website functions as a normal app and you abstract the common code out of the controllers so that all business logic for both services resides in one place.  For instance, you have a create user action, the generation of the form HTML and redirecting after form submission is handled in the non-RESTful controller and the formatting of the JSON data is handled in the RESTful controller.  The actual logic of saving the user would reside either in a repository or in an abstract controller that both of the other two controllers extend off of.

Title: How to acquire data and render page in context of REST/API application?

Body:
In typical REST/API application, build on MVC architectural pattern, what is the best available technique for acquiring data for rendering views?

Should it be:

as in any non-API application: data is acquired directly from DB (through models), as in classical MVC, and controllers are rendering views basing on standard model data, and forms sends data through typical POST,

since this is an API application, even its very own website should be a client, that acquires data through API requests only and controllers are rendering views basing on JSON-like data, and forms must encode data to a typical JSON and push it API-way, just like an average JSON PUT request,

something else.

This question may sound silly or even naive. Unfortunately, I'm a very beginner to API/REST topic. Sorry.


答:
4 threads are nothing, especially since these background tasks that you described are mostly doing nothing but waiting for something to happen.

A modern server can easily have hundreds of such threads simultaneously running, precisely because the word "running" here is mostly a figure of speech: they are not really running, they are just waiting.

I open up Sysinternals Process Explorer on my desktop computer right now, select "System Information", and it says that I have about 957 threads running.  Does that answer your question?

The problems start when your threads actually have processing to do, but this is actually quite rare. You might be writing lots of code and you might be thinking that this thread of yours is going to have lots of stuff to do, but in most cases this is just an illusion.

The vast majority of threads written by the vast majority of programmers spend the vast majority of their time waiting for something external to the thread to happen.  When we say that a thread is waiting, we mean that it is sitting in an efficient wait state, and consuming zero CPU.

Examples:

When a thread opens a file to read or write data from/into it, it is mostly waiting for the data to be transferred from/to the disk.  While the data are being transferred, the thread is sitting around doing nothing.

When a thread issues a SELECT statement to a database, it is mostly waiting for the database to execute the command, and then for data to arrive via the network.  During that time, the thread is sitting around doing nothing.

When a thread performs a network operation like reading from a socket, --you guessed it, it is just sitting around doing nothing.

So, unless you do something silly, like spin-looping, (also known as busy-waiting,) all of the code that you have written which constitutes your thread represents but a minuscule percentage of the total running time of that thread. Over the course of an hour it will usually wait for almost entirely an hour, and it will do actual work for a grand total of a few milliseconds.

In other words, the thread sleeps for aeons of computer time, and once every few centuries it wakes up to eat a quick breakfast and immediately go back to sleep.

So, I would not worry about these 4 threads of yours at all.

Title: How many threads is too many to maintain a chat server?

Body:
I'm writing a chat server and client. For the chat server I have 3 "services" all running on their own threads:

ConnectionListener that loops over accept, and adds any new clients to a ConcurrentLinkedQueue

MessageListener that waits for incoming messages from clients; also adding them to another ConcurrentLinkedQueue

MessageBroadcaster that sits on the other end of MessageListener's queue, and sends out any received messages to the clients in ConnectionListener's queue.

I think that's all the background tasks that I'll need, but say in the future, I have another task that I think should operate concurrently in the background. At that point, the server will be using 4 threads for 4 separate background tasks.

Is there a point where I should reconsider my design? What is a better way of arranging this?

My question stems from 2 concerns:

I hear threads are expensive. While that isn't an issue yet, I don't want to get into the habit of spawning a new thread for everything if there's a better way.

I'm not sure if I should sacrifice "separation of concerns" to save using threads. In theory, the message receive/broadcast jobs could be combined; although they're separate duties.


答:
You can factor out the error handling, so that your function can simply return on error. In C/C++ this would look something like this:

```<code>int handleError(int errorCode, char* message) {
    if(errorCode) {
        //Notify user, whatever
    }
    return errorCode;
}

int functionThatCanFail(...) {
    int result;

    if(result = handleError(do_stuff(), "do_stuff() failed")) return result;
    if(result = handleError(do_more_stuff(), "do_more_stuff() failed")) return result;
}
</code>```

Of course, you can have a small set of such error handling functions to distinguish, for example, between fatal errors, errors and warnings or that handle different error returning conventions (error code vs. NULL pointer, for instance). In C++, the later differentiation can be handled by a template, but that's not a language agnostic consideration anymore.

Title: What is a proper way to chain instructions if previous one is ok

Body:
I'm currently working on a big file I have to parse and process and each step needs to be done in an order as I do SQL queries and need inserted IDs to make other insertions ...
The problem is I often find my code to look like this :

```<code>if( function1() ) {
    // process things to continue
    if( function2() ) {
        // process things to continue

        // ... and so on

    } else {
        // fail2
    }
} else {
    // fail1
}
</code>```

And same goes for form validations, etc... and it gets really hard to follow the steps, and it's just not pleasant to see in the code.

As I said, I need function1 to be done before function2, so I can't do otherwise than be sure previous functions are done correctly.

Is there as proper way, or a design pattern, to code this kind of chained conditional functions ?

(FYI : I use OO PHP5, and I'm pretty much a novice in terms of standards in programming, so please don't behead me if this is casual !)

(concerning possible duplicate of When, if ever, should I daisy chain functions? ) : the functions can be used seperately and thus can't be used with daisy-chaining (see "B" in the given link).

The //Fails are here to "raise a flag" to say there has been a problem and further in the code (after the if/elses) it rollbacks all changes (with PDO's transaction rollback). But I would like to warn user there has been a problem, write a message (database error ? empty values ? ...) and maybe pass more informations like variables to be displayed/debugged.

Body:
You can factor out the error handling, so that your function can simply return on error. In C/C++ this would look something like this:

int handleError(int errorCode, char* message) {
    if(errorCode) {
        //Notify user, whatever
    }
    return errorCode;
}

int functionThatCanFail(...) {
    int result;

    if(result = handleError(do_stuff(), "do_stuff() failed")) return result;
    if(result = handleError(do_more_stuff(), "do_more_stuff() failed")) return result;
}

Of course, you can have a small set of such error handling functions to distinguish, for example, between fatal errors, errors and warnings or that handle different error returning conventions (error code vs. NULL pointer, for instance). In C++, the later differentiation can be handled by a template, but that's not a language agnostic consideration anymore.