问:
How do you track bugs in your personal projects?
I'm trying to decide if I need to reassess my defect-tracking process for my home-grown projects.  For the last several years, I really just track defects using TODO tags in the code, and keeping track of them in a specific view (I use Eclipse, which has a decent tagging system).

Unfortunately, I'm starting to wonder if this system is unsustainable.  The defects I find are typically associated with a snippet of code I'm working on; bugs which are not immediately understood tend to be forgotten, or ignored.  I wrote an application for my wife which has had a severe defect for almost 9 months, and I keep forgetting to fix it.

What mechanism do you use to track defects in your personal projects?  Do you have a specific system, or a process for prioritizing and managing them?

答:
I use my own TheKBase (since I'm on OSX, I use it on .Net in a virtual machine or Mono, depending on my mood). For one concurrent user only, but: It allow for multiple hierarchies, so it goes from task manager to information manager missing no steps in between. Plus it's open source on Github and free (that's obvious, I guess).

For the curious, instructions are here.


问:
Single responsibility policy problem
I'm a bit stuck using the single responsibility policy.

I have a class named Parser, which can be configured to parse input a certain way. For the sake of convenience I will limit the configuration properties to a single property config in the following example:

```<code>class Parser {

    boolean config;
    State state;

    AST parse(String input) { ... }
}
</code>```

I want to reuse the parse instance for multiple parses. The problem is that the state is redundant for the instance itself, however it is required while parsing. Beside the overhead of the state in memory, it doesn't work in multi-threaded environment.

The same goes for a class named Compiler:

```<code>class Compiler {

    boolean config;
    State state;

    Code compile(String input) { ... }
}
</code>```

I was wondering how this is generally solved.

Note: This is maybe a minimal example, but I'm often stuck thinking of a better design.

答:
It is OK if your parser and compiler have state, but there is no need to reuse the objects. What I tend to do is offer a static public method Compiler.compile() or Parser.parse() that takes care of instantiating a stateful object, feeds the input to it, retrieves the result, and returns the result while discarding the object. Since static methods are problematic, we can split the stateful parser thing from the public API that provides the parse() method:

```<code>public interface Parser {
  public Ast parse(String input);
}

/*internal*/ interface ParserImpl {
  Ast result();
  void doFoo();
  void doBar();
}

class ParserAPI implements Parser {
  @Override
  public Ast parse(String input) {
    ParserImpl p = makeParserImpl(input):
    p.doFoo();
    p.doBar();
    return p.result();
  }

  protected /*virtual*/ ParserImpl makeParserImpl(String input) {
    return new DefaultParserImpl(input, otherDependency);
  }
}

/*internal*/ class DefaultParserImpl implements ParserImpl {
  State state;

  DefaultParserImpl(String input, Dependency otherDependency) {
    ... // initialize state
  }

  @Override
  Ast result() { ... }

  @Override
  void doFoo() { ... }

  @Override
  void doBar() { ... }
}
</code>```

What is the point of this indirection? Testability. The ParserAPI class uses the Template Method Pattern so that subclasses can swap out the dependency on the DefaultParserImpl, e.g. to use a mock object. While a user of the Parser can keep calling parse again and again on the same object, in fact we are re-creating a new state for each parse, and don't keep the parse state around after parsing is completed. This not only makes the parser and code that depends on the parser easy to test; creating a fresh object for each parse also makes it easier to reason about correctness.

The disadvantage is that we now have one more class in our system, so we do lose a bit simplicity. However, this is offset by the simpler API that is exposed to a parser user.

ContentLicense: CC BY-SA 3.0

Title: Single responsibility policy problem

Body:
It is OK if your parser and compiler have state, but there is no need to reuse the objects. What I tend to do is offer a static public method Compiler.compile() or Parser.parse() that takes care of instantiating a stateful object, feeds the input to it, retrieves the result, and returns the result while discarding the object. Since static methods are problematic, we can split the stateful parser thing from the public API that provides the parse() method:

public interface Parser {
  public Ast parse(String input);
}

/*internal*/ interface ParserImpl {
  Ast result();
  void doFoo();
  void doBar();
}

class ParserAPI implements Parser {
  @Override
  public Ast parse(String input) {
    ParserImpl p = makeParserImpl(input):
    p.doFoo();
    p.doBar();
    return p.result();
  }

  protected /*virtual*/ ParserImpl makeParserImpl(String input) {
    return new DefaultParserImpl(input, otherDependency);
  }
}

/*internal*/ class DefaultParserImpl implements ParserImpl {
  State state;

  DefaultParserImpl(String input, Dependency otherDependency) {
    ... // initialize state
  }

  @Override
  Ast result() { ... }

  @Override
  void doFoo() { ... }

  @Override
  void doBar() { ... }
}

What is the point of this indirection? Testability. The ParserAPI class uses the Template Method Pattern so that subclasses can swap out the dependency on the DefaultParserImpl, e.g. to use a mock object. While a user of the Parser can keep calling parse again and again on the same object, in fact we are re-creating a new state for each parse, and don't keep the parse state around after parsing is completed. This not only makes the parser and code that depends on the parser easy to test; creating a fresh object for each parse also makes it easier to reason about correctness.

The disadvantage is that we now have one more class in our system, so we do lose a bit simplicity. However, this is offset by the simpler API that is exposed to a parser user.


问:
Design pattern for wrapping logging around execution

Introduction

I am implementing a abstract Java class of a processing framework*. By implementing the function execute, I am able to add business logical functionality. I would like to add logging at the start and end of every implementation of every of my execute functions. Also in between some logging, if specific things are done. However, I would like to make this in a uniform manner. My thought was to inherit the framework class to an own new class which implements the logging and provides some new executeWithLogging functions, which are wrapping the logging around the specific parts. I am not sure if that is the best idea and whether I am able to use a design pattern that would make the whole endeavor elegant. How would I go on about the whole thing?

Challenges (please consider these!)

One challenge in my case is that the original class has only one execute function, however, I'd need logging around multiple parts.

The second thing is: Using a decorator pattern (was my first idea as well) does not quite work, if I am using also a execute, because the super.execute()-function would have to be called in the first line of my new execute(), isn't it?

There would be at least 4 classes involved: BaseFunction from the framework, LoggingFunction extends BaseFunction from me, MyBusinessFunction extends LoggingFunction from me, MyBusinessClass which instanciates MyBusinessFunction.

Not only do I need logging at the beginning and end of execute, but also in the middle.

The "logging" is not just simple Java logging, but actually logging to a database. This does not change anything about the principles, but demonstrates that the logging might be more than just one line of code.

Maybe an example how I'd do the whole thing would be nice, to get me going.

|* A Storm Trident Function, similar to a Storm bolt, but this is not particularly important.

答:
How about using the Command Pattern?</p>

```<code>abstract class MyLoggingCommandPart {

  MyLoggingCommandPart() {
    log.info("Entering execute part");
    executeWithoutLogging();
    log.info("Exiting execute part");
  }

  abstract void executeWithoutLogging();

}

abstract class MyLoggingCommandWhole {

  MyLoggingCommandWhole() {
    log.info("Entering execute whole");
    executeWithoutLogging();
    log.info("Exiting execute whole");
  }

  abstract void executeWithoutLogging();

}

public final class MyBusinessFunction extends BaseFunction {

    @Override
    public final void execute() {

        new MyLoggingCommandWhole(){

            @Override
            executeWithoutLogging(){

                new MyLoggingCommandPart(){
                    @Override
                    executeWithoutLogging(){
                    // ... what I actually wanne do
                    }
                }

                new MyLoggingCommandPart(){
                    @Override
                    executeWithoutLogging(){
                    // ... some more stuff I actually wanne do
                    }
                }
            }
        }
    }
}
</code>```

Body:
How about using the Command Pattern?

abstract class MyLoggingCommandPart {

  MyLoggingCommandPart() {
    log.info("Entering execute part");
    executeWithoutLogging();
    log.info("Exiting execute part");
  }

  abstract void executeWithoutLogging();

}

abstract class MyLoggingCommandWhole {

  MyLoggingCommandWhole() {
    log.info("Entering execute whole");
    executeWithoutLogging();
    log.info("Exiting execute whole");
  }

  abstract void executeWithoutLogging();

}

public final class MyBusinessFunction extends BaseFunction {

    @Override
    public final void execute() {

        new MyLoggingCommandWhole(){

            @Override
            executeWithoutLogging(){

                new MyLoggingCommandPart(){
                    @Override
                    executeWithoutLogging(){
                    // ... what I actually wanne do
                    }
                }

                new MyLoggingCommandPart(){
                    @Override
                    executeWithoutLogging(){
                    // ... some more stuff I actually wanne do
                    }
                }
            }
        }
    }
}


问:
Java abstract class naming
Example:

You create an abstract class for Ajax actions. Different Ajax actions will all extend this class.

Problem:

Do you name the class AjaxAction or AbstractAjaxAction?

When you create subclasses, do you name them:

Action

AjaxAction

Just name them what they are

I have not been able to find what the "official" convention is. I don't see a need for the "Abstract" prefix or any required naming convention in the subclasses. (It may fit anyway, depending.)

Is there an official convention? Could you link me to it? And what are your opinions on this subject?

答:
When possible, I try to leave implementation details out of names, including a prefix/suffix for an abstract class or interface.

One place to look for guidance/inspiration on naming is the Java API. I can't think of any parts that use the prefix (with a huge exception being the Collections API, which uses the Abstract prefix heavily). The following search will yield some pretty good examples:

"public abstract class" at download.oracle.com/javase/6

You'll find abstract classes are named something abstract and concrete subclasses are named something more concrete. For example, abstract class Reader has concrete subclasses BufferedReader, StringReader, InputStreamReader, etc.

Since your concrete subclasses are just more specific versions of your abstract class, it is intent revealing to choose your names in the same way. In your example, I would name the abstract class AjaxAction and use that in the names for the concrete subclasses (SpecificAjaxAction).

ContentLicense: CC BY-SA 2.5

Title: Java abstract class naming


问:
UX designers working one Sprint ahead
Our UX designers usually have a story in Sprint X that the developers will implement in Sprint X+1 (The UX designers and the devs/testers are on one team). I think this makes sense because if you don't have screen mockups and clear specifications you can't really estimate the work during Sprint Planning.

However in Scrum you are only supposed to have user stories that provide value to the user. In our case the UX design stories don't provide such value (they are more like a backlog grooming activity). Also usually Scrum coaches don't recommend having complete specifications before the start of the Sprint, a recommendation which I find hard to understand.

So do you see any disadvantages in our approach? It seems to work for us, but it goes somewhat against Scrum principles.

答: One of the possible problems I see is that in Scrum the scope for sprint N+1 is normally determined right before it starts. So how can you do UX for sprint N+1 stories in sprint N for before you know which stories will be in scope. If you decide to fix the scope for sprint N+1 at the start of sprint N you lose some flexibility.</p>

Title: UX designers working one Sprint ahead


问:
Sparse set lossy compression algorithm
I am looking for algorithm or idea for the following problem.

Suppose we have a data type, say 64-bit integer. Now we have a relatively small set of such items, say few hundred at most. The simplest way to program that is to have a list of items, that means a sparse set.

Now the problem: I want to compress that list so it is much smaller, possibly losing some information.

Requirements:

There must be a way to check if an item belongs to the set and it must be rather fast.

Generation of the compressed set may be slow.

If an item was present in the uncompressed set, then it must show positive in the compressed set.

If an item was absent from the uncompressed set, then it may be present in the compressed set, however probability of such event must be low.

One idea I had: if we have some pseudorandom number generator, then we look for such seed, so that in the first few thousands of iterations all requested items are present. The seed would be the compressed representation. Another idea: neural networks (description will be the representation).

答:
Since you allow false positives, you do not need a perfect hash. Instead, you can use a bloom filter. A bloom filter consists of a bit vector and a set of different hash functions.

To add an item to the bloom filter, you has the item with each hash function and use each hash as an index to the bit vector. You then set each addressed bit to true.

To test whether an item is in the set, you use the hash functions to retrieve the corresponding bits from the bit vector. If all those bits are true, the item was probably part of the input.

This approach is quite fast, since hash functions can be very simple. You can use a family of hash functions that are parametrized by some constant to generate your set of hash functions. Together with the bit vector, these parameters make up the stored data.

It is important to choose a sensible relation between the size of the input set n, the size of the bit vector m, the number of hash functions k, and the acceptable rate of false positives p. The relevant math is explained in the linked Wikipedia article. Each input item affects k bits in the bit vector regardless of the size of the item, so considerable space savings are possible when you only use few hash functions.

While a bloom filter allows for a test whether the set contains an item, it is not possible to enumerate all items in a set; this information is lost through the hash functions.

Title: Sparse set lossy compression algorithm


问:
SRP and Getters/Encapsulation
I recently watched this presentation of Robert C. Martin about the Single Responsibility Principle:
https://www.youtube.com/watch?v=Gt0M_OHKhQE

He presents an Employee class with multiple responsibilities and suggests splitting the functionality into classes like EmployeeRepository and EmployeeReporter. I can very much relate to these refactorings, but I wonder if this is only possible, if we introduce lots of getters to the Employee class. How else is it possible for the Reporter class, to generate the Report? So for me it seems this breaks OO encapsulation and leads to classes, which pull data out of objects to perform operations with this data instead of the object operating on its data itself.

There are many discussions around the web, about getter being evil and breaking encapsulation, but for me it seems, the Single Responsibility Principle needs getters (at least to some degree), to work out.

Martin Fowler suggests, that Getters might be a sign for procedural code:

Although the defense of encapsulation is the common rallying cry for getter eradicators, I think the real motivation for them is rather more reasonable and pragmatic. There's a hell of a lot of code out there in OO languages that is procedural in design. The OO community may have 'won' in the sense that modern languages are dominated by objects, but they are still yet to win in that OO programming is still not widely used. As a result it's still common to see procedures that pull data out of an object to do something, when that behavior would better fit in the object itself - a violation of the pragmatic programmers principle of "Tell Don't Ask". You can only do this kind of procedural programming if you have getters, so telling people to get rid of getters helps push them to move behavior into the right place.

http://martinfowler.com/bliki/GetterEradicator.html

Any suggestions about this topic? Do you need Getters when following the SRP?

答:
Programmers are mostly divided into two groups:

those who think accessors and mutators are okay

those who think accessors and mutators are evil

Neither of the two groups is correct. Just as anything else in programming, accessors and mutators may be used correctly or incorrectly. But does it mean, they are necessarily evil? Not really. To truly understand when is the right time to use an accessor, you must know what Single responsibility principle is really about.

The problem begins, when people start creating Anemic Domain Models as a part of their procedure to SOLIDify their code.

Many programmers I have worked with misunderstand the concept of Single Responsibility Principle and are afraid to put any logic inside their models, because they are afraid it would break the SRP. This means they end up with models which are really stupid, contain little to no business logic and have to be passed around to thirty different classes to be able to accomplish the simplest data operations.

I believe SRP is the most difficult SOLID principle to get right, what's worse, it's the first of them. Programmers focus so hard on it they usually forget about other important things.

The Single Responsibility principle

Where does it begin and end?

A question, which is so hard to answer, that it is the reason why so many people don't understand the SRP definition.

Let's take a look at a very simple class Human.

```<code>public class Human
{
    public readonly DateTime    DateTimeOfBirth;
    public          DateTime?   DateTimeOfDeath;
    public          string      Name { get; private set; }
    public          float       Height { get; private set; }
    public          float       Weight { get; private set; }

    public Human
        (
        DateTime    dateTimeOfBirth,
        string      name,
        float       height,
        float       weight,
        DateTime?   dateTimeOfDeath = null
        )
    {
        DateTimeOfBirth = dateTimeOfBirth;
        DateTimeOfDeath = dateTimeOfDeath;
        Name            = name;
        Height          = height;
        Weight          = weight;
    }
}
</code>```

As every domain model, the responsibility of this class is to take care of its data and do it well. Does it take care of its data? It does. Does it do it well? Not so much. There are literally no rules for data manipulation of this class, you could set a DateTimeOfDeath before the DateTimeOfBirth, that is an invalid operation, which should never occur.

After tweaking the class you may end up with something like this:

```<code>public class InvalidInputException : Exception
{
    public InvalidInputException(string message) : base(message) { }
}

public class Human
{
    public readonly DateTime    DateTimeOfBirth;
    public          DateTime?   DateTimeOfDeath { get; private set; }
    public          string      Name { get; private set; }
    public          float       Height { get; private set; }
    public          float       Weight { get; private set; }

    public Human
        (
        DateTime    dateTimeOfBirth,
        string      name,
        float       height,
        float       weight,
        DateTime?   dateTimeOfDeath = null
        )
    {
        if (dateTimeOfBirth > DateTime.Now) {
            throw new InvalidInputException("The date and time of birth must not be higher than current date and time.");
        }

        if (dateTimeOfDeath != null && dateTimeOfDeath < dateTimeOfBirth) {
            throw new InvalidInputException("The date and time of death must not be before the date and time of birth.");
        }

        if (name == "") {
            throw new InvalidInputException("The name must not be an empty string.");
        }

        if (height <= 0) {
            throw new InvalidInputException("The height must be a positive number");
        }

        if (weight <= 0) {
            throw new InvalidInputException("The weight must be a positive number");
        }

        DateTimeOfBirth = dateTimeOfBirth;
        DateTimeOfDeath = dateTimeOfDeath;
        Name            = name;
        Height          = height;
        Weight          = weight;
    }

    public void gainWeight(float gainedWeight)
    {
        if (gainedWeight < 0) {
            throw new InvalidInputException("The gained weight must be a positive number.");
        }

        Weight += gainedWeight;
    }

    public void loseWeight(float lostWeight)
    {
        if (lostWeight < 0) {
            throw new InvalidInputException("The lost weight must be a positive number.");
        }

        if (Weight - lostWeight < 0) {
            throw new InvalidInputException("The amount of lost weight must not be greater than the current weight.");
        }

        Weight -= lostWeight;
    }

    public void changeName(string newName)
    {
        if (newName == "") {
            throw new InvalidInputException("The name must not be an empty string.");
        }

        Name = newName;
    }

    public void markAsDead()
    {
        DateTimeOfDeath = DateTime.Now;
    }

    public bool isAlive()
    {
        return DateTimeOfDeath == null ? true : false;
    }
}
</code>```

While remaining simplicity, you now have a class which does something. It encapsulates the logic for the data manipulation. You no longer need to worry about validation of passed data, because the class will tell you what exactly is wrong, should something be.

But the class now has multiple responsibilites! It contains data as well as performs its validation and even creates a DateTime
  object.

Based on Single Responsibility responsibility, a class or module
  should have one, and only one, reason to change, but if I, in the
  future, decide, I want to allow a Human to have an empty name or
  that DateTimeOfDeath can actually occur before the
  DateTimeOfBirth, I will have to perform two changes to my class, but
  I am only allowed to perform one.

No, it does not have multiple responsibilities. This class is responsible for its data, you can pass any data to the class and the class itself will make sure the data is correct. That's all part of its logic.

If you decide to change the rules for integral data validation, even if you changed all of them, you are not violating the one reason to change rule.

The class actually has only one reason to change, that is, if you decided the integral validation should be performed in a different way, and it applies to all the data inside your class.

The connection of SRP and Getters

Following the previous example, even though a class should always contain valid data, you still decide you would like to validate the data so the object can be safely passed to a MySQL database.

You create a Validation interface containing a bool validate method and make your Human class implement it, which will ensure the class' data is MySQL valid.

Doing it that way violates the SRP.

1st reason to change is, if you decided to set different validation rules of integral data.

2nd reason to change is, if you decided, the validate method should perform its operation in a different way, because you decided to switch from MySQL to PostgreSQL and it somehow requires a totally different code to perform the validating operation.

On top of that, all the previous code for MySQL will be either left commented out or completely removed, so if you at any time in the future again decide to validate for MySQL, you will probably have to write all the code again. That's a huge red flag, that something is wrong.

You are forced to create Validators for your class, which somehow have to get access to its data. That's where the accessors come into play.

Accessors (getters) provide a simple public interface to class' internal implementation. If the Validator may not access some attribute, because the accessor for it does not exist, then the Validator should not. It should trust the object its validating, that the internal components will always be valid.

The accessors are there, so you can retrieve the data from the structure and when you retrieve it, unless you change the data, you may treat is as a part of the object.

The class should also perform operations for you, such as finding out whether a Human can vote or not, using a bool canVote() method.

```<code>public bool canVote()
{
    const int allowedVotingAge = 18;

    return (DateTime.Now.Subtract(DateTimeOfBirth).TotalDays/365 >= allowedVotingAge);
}
</code>```

That looks much better than doing the following operation:

```<code>var human = new Human(/* */);

const int allowedVotingAge = 18;
var canVote = DateTime.Now.Subtract(human.DateTimeOfBirth).TotalHours/365 <= allowedVotingAge;
</code>```

Once again, the class itself knows the rules to finding out, whether a Human can vote or not. A user of the Human class should not be forced to come up with the logic.

Even though very simple, canVote method is still a method which encapsulates the internal implementation nobody should know about. Furthermore, it gives you access to a variable, which does not even exist in the class as a member, because the variable is made during the runtime as a return type. So you cannot even access the CanVote variable directly.

A few guidlines on how to become a better developer

Domain Driven Design: Build your app around your business-logic,
that is your domain, not around your data (building around your DL
usually makes your classes include both business and persistence logic).

Pass domain models around your applications, if you do, you will
never be able to pass an object in an invalid state.

Make rich domain models: Your classes have to include some logic. They are responsible for your business, let them take care of handling their data.

SRP is a recommendation: Do not treat it as an idol and do not follow it blindly.

For example, even though it seems as a different responsibility, implementing bool Equals() method on an object is a completely valid operation, the method should however be used to compare only two objects of the same type and return false every time a different type is passed to it.

Because if you compare an Apple and a Banana, no matter how much effort will the Banana put into looking like an Apple, it will never be an Apple.

Recommended reading

Domain-driven Design by Eric Evans: An excelent book on what it says in the title.

Patterns of Enterprise Application Architecture by Martin Fowler: An excelent book to read before diving into agile development. Includes many amazing and modern design patterns, which in my opinion should be enforced, but sadly are ignored in favor of patterns which are easier to implement but don't provide as much space for code reuse.

Design Patterns: Elements of Reusable Object-Oriented Software by The "Gang of Four" (Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides): A no. 2 book about design patterns to read. Great for providing general outlook.

Title: SRP and Getters/Encapsulation

Body:
Programmers are mostly divided into two groups:

those who think accessors and mutators are okay

those who think accessors and mutators are evil

Neither of the two groups is correct. Just as anything else in programming, accessors and mutators may be used correctly or incorrectly. But does it mean, they are necessarily evil? Not really. To truly understand when is the right time to use an accessor, you must know what Single responsibility principle is really about.

The problem begins, when people start creating Anemic Domain Models as a part of their procedure to SOLIDify their code.

Many programmers I have worked with misunderstand the concept of Single Responsibility Principle and are afraid to put any logic inside their models, because they are afraid it would break the SRP. This means they end up with models which are really stupid, contain little to no business logic and have to be passed around to thirty different classes to be able to accomplish the simplest data operations.

I believe SRP is the most difficult SOLID principle to get right, what's worse, it's the first of them. Programmers focus so hard on it they usually forget about other important things.

The Single Responsibility principle

Where does it begin and end?

A question, which is so hard to answer, that it is the reason why so many people don't understand the SRP definition.

Let's take a look at a very simple class Human.

public class Human
{
    public readonly DateTime    DateTimeOfBirth;
    public          DateTime?   DateTimeOfDeath;
    public          string      Name { get; private set; }
    public          float       Height { get; private set; }
    public          float       Weight { get; private set; }

    public Human
        (
        DateTime    dateTimeOfBirth,
        string      name,
        float       height,
        float       weight,
        DateTime?   dateTimeOfDeath = null
        )
    {
        DateTimeOfBirth = dateTimeOfBirth;
        DateTimeOfDeath = dateTimeOfDeath;
        Name            = name;
        Height          = height;
        Weight          = weight;
    }
}

As every domain model, the responsibility of this class is to take care of its data and do it well. Does it take care of its data? It does. Does it do it well? Not so much. There are literally no rules for data manipulation of this class, you could set a DateTimeOfDeath before the DateTimeOfBirth, that is an invalid operation, which should never occur.

After tweaking the class you may end up with something like this:

public class InvalidInputException : Exception
{
    public InvalidInputException(string message) : base(message) { }
}

public class Human
{
    public readonly DateTime    DateTimeOfBirth;
    public          DateTime?   DateTimeOfDeath { get; private set; }
    public          string      Name { get; private set; }
    public          float       Height { get; private set; }
    public          float       Weight { get; private set; }

    public Human
        (
        DateTime    dateTimeOfBirth,
        string      name,
        float       height,
        float       weight,
        DateTime?   dateTimeOfDeath = null
        )
    {
        if (dateTimeOfBirth > DateTime.Now) {
            throw new InvalidInputException("The date and time of birth must not be higher than current date and time.");
        }

        if (dateTimeOfDeath != null && dateTimeOfDeath < dateTimeOfBirth) {
            throw new InvalidInputException("The date and time of death must not be before the date and time of birth.");
        }

        if (name == "") {
            throw new InvalidInputException("The name must not be an empty string.");
        }

        if (height <= 0) {
            throw new InvalidInputException("The height must be a positive number");
        }

        if (weight <= 0) {
            throw new InvalidInputException("The weight must be a positive number");
        }

        DateTimeOfBirth = dateTimeOfBirth;
        DateTimeOfDeath = dateTimeOfDeath;
        Name            = name;
        Height          = height;
        Weight          = weight;
    }

    public void gainWeight(float gainedWeight)
    {
        if (gainedWeight < 0) {
            throw new InvalidInputException("The gained weight must be a positive number.");
        }

        Weight += gainedWeight;
    }

    public void loseWeight(float lostWeight)
    {
        if (lostWeight < 0) {
            throw new InvalidInputException("The lost weight must be a positive number.");
        }

        if (Weight - lostWeight < 0) {
            throw new InvalidInputException("The amount of lost weight must not be greater than the current weight.");
        }

        Weight -= lostWeight;
    }

    public void changeName(string newName)
    {
        if (newName == "") {
            throw new InvalidInputException("The name must not be an empty string.");
        }

        Name = newName;
    }

    public void markAsDead()
    {
        DateTimeOfDeath = DateTime.Now;
    }

    public bool isAlive()
    {
        return DateTimeOfDeath == null ? true : false;
    }
}

While remaining simplicity, you now have a class which does something. It encapsulates the logic for the data manipulation. You no longer need to worry about validation of passed data, because the class will tell you what exactly is wrong, should something be.

But the class now has multiple responsibilites! It contains data as well as performs its validation and even creates a DateTime
  object.

Based on Single Responsibility responsibility, a class or module
  should have one, and only one, reason to change, but if I, in the
  future, decide, I want to allow a Human to have an empty name or
  that DateTimeOfDeath can actually occur before the
  DateTimeOfBirth, I will have to perform two changes to my class, but
  I am only allowed to perform one.

No, it does not have multiple responsibilities. This class is responsible for its data, you can pass any data to the class and the class itself will make sure the data is correct. That's all part of its logic.

If you decide to change the rules for integral data validation, even if you changed all of them, you are not violating the one reason to change rule.

The class actually has only one reason to change, that is, if you decided the integral validation should be performed in a different way, and it applies to all the data inside your class.

The connection of SRP and Getters

Following the previous example, even though a class should always contain valid data, you still decide you would like to validate the data so the object can be safely passed to a MySQL database.

You create a Validation interface containing a bool validate method and make your Human class implement it, which will ensure the class' data is MySQL valid.

Doing it that way violates the SRP.

1st reason to change is, if you decided to set different validation rules of integral data.

2nd reason to change is, if you decided, the validate method should perform its operation in a different way, because you decided to switch from MySQL to PostgreSQL and it somehow requires a totally different code to perform the validating operation.

On top of that, all the previous code for MySQL will be either left commented out or completely removed, so if you at any time in the future again decide to validate for MySQL, you will probably have to write all the code again. That's a huge red flag, that something is wrong.

You are forced to create Validators for your class, which somehow have to get access to its data. That's where the accessors come into play.

Accessors (getters) provide a simple public interface to class' internal implementation. If the Validator may not access some attribute, because the accessor for it does not exist, then the Validator should not. It should trust the object its validating, that the internal components will always be valid.

The accessors are there, so you can retrieve the data from the structure and when you retrieve it, unless you change the data, you may treat is as a part of the object.

The class should also perform operations for you, such as finding out whether a Human can vote or not, using a bool canVote() method.

public bool canVote()
{
    const int allowedVotingAge = 18;

    return (DateTime.Now.Subtract(DateTimeOfBirth).TotalDays/365 >= allowedVotingAge);
}

That looks much better than doing the following operation:

var human = new Human(/* */);

const int allowedVotingAge = 18;
var canVote = DateTime.Now.Subtract(human.DateTimeOfBirth).TotalHours/365 <= allowedVotingAge;

Once again, the class itself knows the rules to finding out, whether a Human can vote or not. A user of the Human class should not be forced to come up with the logic.

Even though very simple, canVote method is still a method which encapsulates the internal implementation nobody should know about. Furthermore, it gives you access to a variable, which does not even exist in the class as a member, because the variable is made during the runtime as a return type. So you cannot even access the CanVote variable directly.

A few guidlines on how to become a better developer

Domain Driven Design: Build your app around your business-logic,
that is your domain, not around your data (building around your DL
usually makes your classes include both business and persistence logic).

Pass domain models around your applications, if you do, you will
never be able to pass an object in an invalid state.

Make rich domain models: Your classes have to include some logic. They are responsible for your business, let them take care of handling their data.

SRP is a recommendation: Do not treat it as an idol and do not follow it blindly.

For example, even though it seems as a different responsibility, implementing bool Equals() method on an object is a completely valid operation, the method should however be used to compare only two objects of the same type and return false every time a different type is passed to it.

Because if you compare an Apple and a Banana, no matter how much effort will the Banana put into looking like an Apple, it will never be an Apple.

Recommended reading

Domain-driven Design by Eric Evans: An excelent book on what it says in the title.

Patterns of Enterprise Application Architecture by Martin Fowler: An excelent book to read before diving into agile development. Includes many amazing and modern design patterns, which in my opinion should be enforced, but sadly are ignored in favor of patterns which are easier to implement but don't provide as much space for code reuse.

Design Patterns: Elements of Reusable Object-Oriented Software by The "Gang of Four" (Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides): A no. 2 book about design patterns to read. Great for providing general outlook.


问:
Reusing an interface or method chaining
I am learning about coding to an interface in OOP programming. I understand you should code to an interface so you can 'swap out' functionality.

However, I have a situation where I feel I can reuse an interface again rather than simply swap it out.

```<code>interface GetFile
{
    public function getFile();
}

class GetFileFromUrl implements GetFile
{
    public function __construct($url, $destination_path) {...}

    public function getFile()
    {
        // download file from url and return path of file

        return 'file_path';
    }
}

class GetFileFromZip implements GetFile
{
    public function __construct($path, $extraction_path) {...}

    public function getFile()
    {
        // extract file from zip and return path of file

        return 'file_path';
    }
}

class DoStuff
{
    // coding to an interface
    public function doStuff(File $file) {
        $do_stuff = $file->getFile();
        //do stuff with file
    }
}
</code>```

I thought this would allow the greatest amount of flexibility in code reuse in future as I can extend the interface further

```<code>class GetFileFromDirectory implements GetFile(...)
class GetFileFromTar implements GetFile(...)
</code>```

I feel this a fairly good approach as I can pass whatever implementation of GetFile to DoStuff and it will execute readFile within the doStuff() method.

My question I am trying to ask, is how can I 'chain' these classes which implement GetFile together?

i.e. GetFileFromUrl then GetFileFromZip to get a zip file from a URL and unzip it?

So using just one would be

```<code>$file_from_url = new GetFileFromUrl($url_path, $destination_path);
$do_stuff      = (new DoStuff)->doStuff($file_from_url);
</code>```

But 'chaining' two I am currently doing;

```<code>$zip_file_path = (new GetFileFromUrl($url_path, $destination_path))->getFile();
$file_from_zip = new GetFileFromZip($zip_file_path, $destination_path);
$do_stuff      = (new DoStuff)->doStuff($zip_from_tar);
</code>```

Is there a better / cleaner way of doing this?

Thanks to thepacker, my revised thought is to separate the functionality into one interface which gets a file from somewhere and another interface which does something to the file;

```<code>interface GetFile()
interface ConvertFile()
</code>```

Then I could do

```<code>class GetFileFromUrl implements GetFile {...}

class ConvertFileFromZip implements ConvertFile {
    // coding to an interface
    public function __construct(GetFile $from) {...}
}

$zip_from_url = new GetFileFromUrl($url, $destination);
$file_path    = new ConvertFileFromZip($zip_from_url);
</code>```

I just want to confirm this is the correct course of action in this case.

答:
Well maybe I can enlighten you slightly. You are not swapping the interface out, but the implementation.

```<code>GetFile fileGetter=new GetFileFromUrl(...);
// but you can use every other filegetter instead...
fileGetter->getFile();
</code>```

Think about this class:

```<code>class ConfigParser
{
    public function readConfig(GetFile fileGetter)
    {
        ...
        currentFile = fileGetter->getFile()
        ...
    }
}
</code>```

Whenever you feel that you need something to get files from anywhere, you can implement a method and transfer the Strategy on how to get files either from Zip or tar, or URL or whatever strategy you like to the one instance which requires that. Consider this:

```<code>ConfigParser configParser...;
configParser->readConfig(fileGetter)
</code>```

Since ConfigParser doesn't care about how to access files (it uses the interface instead), it can be used to read and parse configfiles from everywhere.

You can also implemet a Class using another instance of GetFile. Like a FileGetter which uses urls, but can cache files.

```<code>class CachingFileGetter implements GetFile {
  GetFile wrappedGetFileStrategy;
  ....

  public function __construct(GetFile nonCached) {
      wrappedGetFileStrategy=nonCached;
      ....
    }

  public function getFile() {
    if(isCached())
    {
       [do your caching magic here]
    }
    else
    {
       wrappedGetFileStrategy->getFile();
       ...
    }
  }
}
</code>```

This is what interfaces could be for. You are separating your concerns like implementing a cached FileGetter, bou you do not care where that file comes from - Instead you are using the abstract GetFile-thing. Read about Liskov-Substitition-Principle the L in SOLID.

[Update]

In response to your update. Do not use Method chaining (allo over your code) since you have a way to hide that behavior. You can replace the idea of a cache simply by the idea of a virtual file system (VFS), so you do not need to copy everywhere:

```<code>$zip_file_path = (new GetFileFromUrl($url_path, $destination_path))->getFile();
$file_from_zip = new GetFileFromZip($zip_file_path, $destination_path);
</code>```

The Idea behind that is, that your code doesn't need to know that the file is a zip in an url, it is just a file resource. There is only one place to leave that information, that you are using Zip files over URLs, in the configuration. Do not copy and paste such "solutions" (knowledge about your configuration) all over your code - If you change your mind to use newest FOO istead of zip, or BAR instead of URLs you are constantly fixing your code everywhere. Implement a class VFS which is hiding that method chaining behavior and uses URL-FileGet and Zip-FileGet inside.  And then use

```<code>(new DoStuff)->doStuff($VFS) instead .
</code>```

Title: Reusing an interface or method chaining

Body:
Well maybe I can enlighten you slightly. You are not swapping the interface out, but the implementation.

GetFile fileGetter=new GetFileFromUrl(...);
// but you can use every other filegetter instead...
fileGetter->getFile();

Think about this class:

class ConfigParser
{
    public function readConfig(GetFile fileGetter)
    {
        ...
        currentFile = fileGetter->getFile()
        ...
    }
}

Whenever you feel that you need something to get files from anywhere, you can implement a method and transfer the Strategy on how to get files either from Zip or tar, or URL or whatever strategy you like to the one instance which requires that. Consider this:

ConfigParser configParser...;
configParser->readConfig(fileGetter)

Since ConfigParser doesn't care about how to access files (it uses the interface instead), it can be used to read and parse configfiles from everywhere.

You can also implemet a Class using another instance of GetFile. Like a FileGetter which uses urls, but can cache files.

class CachingFileGetter implements GetFile {
  GetFile wrappedGetFileStrategy;
  ....

  public function __construct(GetFile nonCached) {
      wrappedGetFileStrategy=nonCached;
      ....
    }

  public function getFile() {
    if(isCached())
    {
       [do your caching magic here]
    }
    else
    {
       wrappedGetFileStrategy->getFile();
       ...
    }
  }
}

This is what interfaces could be for. You are separating your concerns like implementing a cached FileGetter, bou you do not care where that file comes from - Instead you are using the abstract GetFile-thing. Read about Liskov-Substitition-Principle the L in SOLID.

[Update]

In response to your update. Do not use Method chaining (allo over your code) since you have a way to hide that behavior. You can replace the idea of a cache simply by the idea of a virtual file system (VFS), so you do not need to copy everywhere:

$zip_file_path = (new GetFileFromUrl($url_path, $destination_path))->getFile();
$file_from_zip = new GetFileFromZip($zip_file_path, $destination_path);

The Idea behind that is, that your code doesn't need to know that the file is a zip in an url, it is just a file resource. There is only one place to leave that information, that you are using Zip files over URLs, in the configuration. Do not copy and paste such "solutions" (knowledge about your configuration) all over your code - If you change your mind to use newest FOO istead of zip, or BAR instead of URLs you are constantly fixing your code everywhere. Implement a class VFS which is hiding that method chaining behavior and uses URL-FileGet and Zip-FileGet inside.  And then use

(new DoStuff)->doStuff($VFS) instead .


问:
Why is (position < size) such a prevalent pattern in conditionals?
In a condition statement (IF) everyone uses (position < size), but why?

Only convention or there is a good reason for that?

Found in the wild:

if (pos < array.length) {
   // do some with array[pos];
}
```

<p>Rarely found:</p>

<pre class="lang-c prettyprint-override"><code>if (array.length > pos) {
   // do some with array[pos];
}
</code>```

答:
It's a combination of two things, both coming from the underlying assembler that early languages got compiled to (and a lot of current ones too).

Arrays are zero-based offsets in memory (i.e. the first chunk of data is at the start of the allocated memory block...the 0-index). Hence the use of 0..n-1 for the varying piece.

Branching if a value is less than another value (or register, etc) is typically a single instruction. Hence the use of the simple less-than (<) operator.

So, the pattern moved from old-timey assembler into ANSI-C (which is more like a macro assembler in some ways) and from there to Java and the other C-like languages.


问:
Subclassing vs Using properties to discriminate types
Often when writing code I wonder what the best way is to discriminate between types (by which I don't necessarily mean types used in typesystems). That brings up 3 questions:

What is better?

When is it better?

What are the (dis)advantages?

Using properties to discriminate

```<code>class BinaryExpression {

    String operator; // e.g. "+"
    Number lhs, rhs;
}
</code>```

Subclassing to discrimination

```<code>class BinaryExpression {
    Number lhs, rhs;
}

class Addition extends BinaryExpression {}

// Etc.
</code>```

Note: I'm not sure if I have the terms right. Please correct me if I'm wrong.

答:
If there's a functional or operational difference between the types, then creating explicit types allows cleaner object-oriented implementations of the different functional behaviors.

If the difference is just an appearance thing, then full object-orientation might be overkill (though there will be many purists who object to this pragmatic approach).

For your example of operators. If you were actually using the operator class to perform calculations, then subclassing is probably the way to go (because of the differing implementations of a "compute" method for example).

If you are simply holding the content for output serialization, then a property containing the operator character might be all you need for your purposes.


问:
How can I architect P2P discovery?
I've never really done network programming so this is all new to me. What I'm attempting to make is a Peer to Peer "chat" client. The idea is that anyone can connect to someone whose IP they know. All chat messages are to be distributed to everyone.

What I'm getting stuck on is the peer discovery. What I've done so far is:

App has an IP of a known person (user provided)

Connects to known IP

Known IP provides it's list of known Peers; we store it in peer list

Discovery loop:

Make a local copy of peer list

For each Peer in local peer list

Request Peer list (i.e. step 2 + 3)

If error, remove this peer from original peer list

Otherwise, add new peers to original peer list

Queue another Discovery Loop in 1min

The listening for connections in step 3 and the discovery loop are asynchronous.

The reason a copy is made in the first place is due to some other design decisions for down the road.

The problem is that if I introduce a client with a bad peer on it's peer list, i.e. you can't connect to it, what happens is that this Peer is passed via step 3 when serving the known peer list and then other clients have it in theirs. They propagate this bad peer and later on, during the Discover Loop, remove that peer. But then, they will do another Discover Loop and will receive that Peer from someone else again.

The end result is that bad peer never leaves the network.

One option I can think of is a vague idea of having Peer "health" that each client keeps track of separately so that they can ignore peers provided on someone elses list. However, this would, I think, need to be somewhat "timed" so that when someone disconnects they aren't shut out of the network forever.

The other idea I had was for a broadcast message to all known peers when a bad peer is encountered. However, I didn't like this idea because it leaves it open for someone to make a different client that's job is to poison the network by insisting peers are bad. This would then require me to have peers check that a remove request is genuine by also attempting to connect to his peer immediately.

I'm looking for opinions on the two options above.

答:
Your solution only has a problem if there is a period when an invalid up can enter an ip list. If a bad ip can't enter a list it will die out quickly.

So the only change you need to make is to separate out the concepts of the verified list and the pending list.

If a client requests your list you only ever provide the verified list (this may contain bad ips but new bad ips can't enter it).

On each refresh cycle you ask each of your existing ips for their lists, if you can't contact them they are removed from your list. If they provide new ips they enter the pending list, missing ips are ignored.

Once the list of known ips has been polled you poll the pending list, if and only if they reply do they enter the verified list

Title: How can I architect P2P discovery?


问:
Update XML file versus overwriting XML file
I have a console application that will make modifications to 1200 systems remotely using SCCM. One of the items to be modified is a GUI menu app that is XML driven to display buttons that launch other applications. I need to change the XML.

Changing the XML wouldn't be terribly hard, but overwriting the file would be a snap. I'd just have to include the XML with my console app. The permissions should be the same either way. Is there a preferred or recommended way or is it just dealer's choice?

Edit: The target file is an app.config file that is 10KB in size. The app.config should be consistent across all target workstations. I have access to the original app.config file. I can pre-update the file and send a copy along with my updater app.

答: What are the expected sizes of the files you are going to be dealing with? In place updates are more complex, and without a significant reason to do otherwise replacement is the way to go.  It is easier to understand and code and as an added benefit, if you have to worry about an interrupted write, it is easier to make it fail safe (in that the worst that happens is you loose the new file).</p>


答:
How would you reliably update an XML file, or any other document, without overwriting at least a portion of it? Maybe I misunderstand the question, but suppose you have the following file:

```<code><xml>
  <menuItems>
    <item>Foo</item>
  </menuItems>
</xml>
</code>```

And you want to overwrite the value Foo with Foo2. How are you going to do that? You'd have to compute the new size of the file, reallocate the file size, move everything after "Foo" up by one character, and then write the new character 2 in the hole. Now imagine doing that with several different updates in the file, some that are smaller than the original content, and some that are larger. It becomes a non-trivial task. For this reason, I believe almost every app that writes files to disk works by replacing the original file with the edited copy from memory. The app lets the OS/file system worry about reallocating the space.

And performance-wise, most workloads won't be improved by trying to overwrite pieces of the original file because at the disk level, I/O happens in blocks.

Title: Update XML file versus overwriting XML file

Body:
I have a console application that will make modifications to 1200 systems remotely using SCCM. One of the items to be modified is a GUI menu app that is XML driven to display buttons that launch other applications. I need to change the XML.

Changing the XML wouldn't be terribly hard, but overwriting the file would be a snap. I'd just have to include the XML with my console app. The permissions should be the same either way. Is there a preferred or recommended way or is it just dealer's choice?

Edit: The target file is an app.config file that is 10KB in size. The app.config should be consistent across all target workstations. I have access to the original app.config file. I can pre-update the file and send a copy along with my updater app.

Body:
How would you reliably update an XML file, or any other document, without overwriting at least a portion of it? Maybe I misunderstand the question, but suppose you have the following file:

<xml>
  <menuItems>
    <item>Foo</item>
  </menuItems>
</xml>

And you want to overwrite the value Foo with Foo2. How are you going to do that? You'd have to compute the new size of the file, reallocate the file size, move everything after "Foo" up by one character, and then write the new character 2 in the hole. Now imagine doing that with several different updates in the file, some that are smaller than the original content, and some that are larger. It becomes a non-trivial task. For this reason, I believe almost every app that writes files to disk works by replacing the original file with the edited copy from memory. The app lets the OS/file system worry about reallocating the space.

And performance-wise, most workloads won't be improved by trying to overwrite pieces of the original file because at the disk level, I/O happens in blocks.


问:
Why does(/did) Bertrand Meyer think subclassing is the only way to extend a "closed" module?
In Meyer's Object-Oriented Software Construction (1988) he defines the open/closed principle as follows:

A module will be said to be open if it is still available for extension. For example, it should be possible to add fields to the data structures it contains, or new elements to the set of functions it performs.

A module will be said to be closed if it is available for use by other modules. This assumes that the module has been given a well-defined, stable description (the interface in the sense of information hiding).

He goes on to say:

If you reopen a module, you must also reopen all its clients to update them, since they rely on the old version. … [This problem] arises every time a module must be extended by a new function or data element, triggering changes in direct and indirect clients. ... With classical approaches to design and programming, there is no way to write modules that are both open and closed.

Meyer's solution to this dilemma is: never extend a library module by modifying existing classes; instead, write a new module that subclasses the existing classes, and have new clients depend on that new module.

Now, in 1988, I was was writing toy (procedural) programs in Turbo Pascal and Blankenship Basic, and my 21st-century professional experience is on the JVM, the CLR, and in dynamic languages, so I don't know what Meyer meant by "classical approaches to design and programming".

Meyer's one concrete example of why client modules must be reopened (a switch statement on an enumeration which now has more members, requiring more cases) seems reasonable enough, but he doesn't nearly justify the assertion that every time you add functionality to a library module, you need to update all its clients.

Is there a historical reason that this assertion seemed self-evident in 1988? Did, say, adding functions or data structures to a C static library change the layout such that even with backwards-compatible APIs, clients had to be recompiled? Or is Meyer really just talking around a mechanism for enforcing API backwards compatibility?

答:
As far as I can tell, this question has been answered by Bertrand Meyer himself, and the answer is, this statement is not accurate. With classical approaches to design and programming, there indeed can be a way to write modules that are both open and closed.

To find this out, you need to study second edition of this book (published nine years later, in 1997). According to Foreword to the second edition, it is

not an update but the result of a thorough reworking. Not a paragraph of the original version has been left untouched. (Hardly a single line, actually.)

In particular, the statement that confuses you has gone. There still is Open-Closed principle chapter in "§3.3 Five Principles", and there is further thorough discussion of this topic in "§14.7 Introduction To Inheritance" but the statement from first edition isn't there anymore.

What is there instead focuses on how it is more convenient and idiomatic in OO approach as opposed to prior ways,

Thanks to inheritance, O-O developers can adopt a much more incremental approach to software development than used to be possible with earlier methods...(§3.3)

This double requirement (open and closed) looks like a dilemma, and classical module structures offer no clue. But inheritance solves it. A class is closed, since it may be compiled, stored in a library, baselined, and used by client classes. But it is also open, since any new class may use it as a parent, adding new features and redeclaring inherited features; in this process there is no need to change the original or to disturb its clients... (§14.7)

Since you also seem to wonder about what "classical approaches" Meyer meant here, you can find explanation of these in §4.7 Traditional Modular Structures. This section explains that these mean "libraries of routines" and "packages" (for the latter, author says the term is taken from Ada and mentions other languages having this feature - clusters in CLU and modules in Modula).

If you think of it, none of these approaches was originally intended to aid in writing code that adheres to open-closed principle. This could lead author to their somewhat premature assessment that was later corrected in second edition.

As for what specifically made author change their mind on that statement in between first and second edition, I think one can find an answer, again, in the book itself, namely in Part F: Applying the method in various languages and environments". In this chapter, author discusses how object oriented methods can be used in older languages:

Classical languages such as Fortran are not O-O at all, but people who must still use them... may want to apply as many O-O ideas as feasible within the limitations of these older approaches.

In particular, in this part Meyer explains in details how it would be possible to implement inheritance (with some caveats and limitations, but still) in C and even in Fortran.

You see, this really calls for revising that statement from first edition. It seems practically impossible to explain how to reconcile "with classical approaches... there is no way" with realistic examples on how exactly it can be done.


答:
You're getting stuck in the religion of the process and along the way I see scrum/agile getting misused and users mislabeled.  Scrum is not a universal tool, it is a means to an end.

I think that your group has mislabeled who your users are and are planning for the wrong audience.

The UX group is using scrum in the classical way, user value and agile adaptation to inputs from some magical end users.  They are the one with users.  Your group is misusing scrum because you're merely filling in mechanics to make an existing design work, there is nothing agile required and scrum is filling the role of management tracking.

That is why this feels wrong to you, you don't actually need or benefit from scrum in any way because you are in a service group and your work flows forward from the UX people who have already done the agile/scrum parts.

Nothing really bad there, just a different process is in place than what you were told.

Title: UX designers working one Sprint ahead

Body:
Our UX designers usually have a story in Sprint X that the developers will implement in Sprint X+1 (The UX designers and the devs/testers are on one team). I think this makes sense because if you don't have screen mockups and clear specifications you can't really estimate the work during Sprint Planning.

However in Scrum you are only supposed to have user stories that provide value to the user. In our case the UX design stories don't provide such value (they are more like a backlog grooming activity). Also usually Scrum coaches don't recommend having complete specifications before the start of the Sprint, a recommendation which I find hard to understand.

So do you see any disadvantages in our approach? It seems to work for us, but it goes somewhat against Scrum principles.


问:
Web Service or pure TCP
We are trying to establish a 6LoWPAN network.

Our Devices have only the 6LoWPAN connection so we need a bridge to connect them to CMS server. A small computer (something like BeagleBone) which runs Linux acts as a bridge and communicates with multiple devices via 6LoWPAN and provides TCP connection to server.

In this bridge we have some applications which provide APIs for controlling and getting data from our devices. For now it's a bit of a dummy network. Bridge gets requests from TCP and transfers them to devices.

By the way, devices not only respond to requests but also send notifications whenever an alarm situation happens.

Now we want to make the bridge smarter. We're thinking to develop a web service on the bridge and provide some functionality (like Configuration, Scheduled Control, Group Management etc.).

It won't be a problem to provide a SOAP based web service on the bridge. But we are not sure if we should develop a web service for our network.

Is opening a TCP connection from the server to all bridges a better approach or communicating to bridges via web service a better approach?

答:
For your particular use case, I would think HTTP communication would be a better fit than TCP.

In general, the main reason I would choose TCP over HTTP would be when performance was paramount and you could maintain an active connection. You can also send data both ways. With TCP, you are in more or less full control of what gets sent over the wire. (But if you use anything fancy, you have to be sure that you can put your custom code on the other end to read it.)

However, it could be too much to expect the bridge to maintain a TCP connection. (Are we talking wifi links to the bridge?) Whereas HTTP is request/response, so it just needs to be stable long enough to send and receive. (Idempotent messages are a good idea regardless.) HTTP will scale better than active TCP connections if there are many controllers. HTTP has ubiquity -- there are many HTTP servers available, and just about any language and platform can submit an HTTP request with little effort. HTTP is potentially easier to debug since you can examine the wire format (text) with human eyes.

Many of the same advantages and disadvantages of TCP can be had with WebSocket, so long as your devices can use it. One advantage of WebSocket over TCP is that most firewalls don't block the HTTP port used by WebSockets whereas your chosen custom TCP port might be blocked.

Title: Web Service or pure TCP


答:
I'd be worried about the overhead in transmitting the whole list of peers each time.  If you have N users, and during each 'discovery loop' each peer connects to the rest of the N peers and downloads a list of N peers, then the bandwidth dedicated to synchronizing the peers list grows like O(N^3)!  By using some tricks to only transmit the peers that differ between the two you can get it down to O(N^2 log N) or O(N^2), but that's still pretty steep.

I heard some time ago of a synchronization model designed to avoid this problem.  I don't remember the name so I'll call it "rumor mill synchronization."

Your client maintains three lists of peers:

Known good peers.

Recently changed peers.  Each peer in this list is associated with a boolean 'added/removed' flag and a (local) time.

Possibly changed peers.  Each peer is this list also has the 'added/removed' flag, and also has an associated counter.

You also choose a length of time for changes to be considered 'new,' and a required number of 'votes' before you commit a change (K).  I would suggest that the former is fixed (based on your testing) and the latter is user-configurable (so they can set how trusting they are of the network).  Here is the procedure:

You start off with the addresses of a few peers that you think are good; these might be your servers' addresses preloaded into the app, or a set of peers that the user chooses.  Query a number of them, asking to download their entire list of known good peers.  Check them against each other so that an attacker will have a more difficult time adding malicious addresses.  (This takes O(KN) bandwidth.)

Assuming that you trust most of the peers you just talked to, you can add peers that are in a majority of their lists to your list of known good peers.  Now we start the discovery loop.

Each cycle, you connect to a new peer from your known good list, and ask for their recently changed list.  (If the network is relatively static, this list should be less than O(N).)  If the network is large you can choose a random peer for this step, otherwise you should loop through the (randomly ordered) list.  The goal is to talk to as many different peers as possible without biasing towards a certain subset.

If they don't respond, remove them from your known good list and add them to your recently changed list as 'removed' (overwriting an 'added' entry for that peer if it exists; don't forget to update the time too).

Otherwise, go through the received peers one by one.

If they're in your known good list, there's nothing to do.

If they're in your possible changes list, increment their counter; otherwise, add them to the list with their counter at one.

Check the list of possible changes to see if any have surpassed K votes; if so, add them to your list of recently changed, and add or remove them from your known good list as appropriate.

Check the list of recent changes to see if any changes on this list are 'stale,' i.e. older than your time threshold.  If so, remove them.

Wait for a little, then go back to step 2.  You should also repeat step 1 occasionally with random peers from your 'known good' list; treat this like step 2 but download their list of known good peers, not recently changed peers.

If you receive a connection from an unknown peer, treat this as in step 3, adding them to your recently changed and known good peers.

Note that this approach only works if the network is relatively static, otherwise the list of recent changes will encompass almost all the clients.

The implementation details might be a bit off (it was a long time ago that I read about this) but the idea is there; basically you ring up as many peers as you can and ask, 'hear about any new people?'

Title: How can I architect P2P discovery?

Body:
I've never really done network programming so this is all new to me. What I'm attempting to make is a Peer to Peer "chat" client. The idea is that anyone can connect to someone whose IP they know. All chat messages are to be distributed to everyone.

What I'm getting stuck on is the peer discovery. What I've done so far is:

App has an IP of a known person (user provided)

Connects to known IP

Known IP provides it's list of known Peers; we store it in peer list

Discovery loop:

Make a local copy of peer list

For each Peer in local peer list

Request Peer list (i.e. step 2 + 3)

If error, remove this peer from original peer list

Otherwise, add new peers to original peer list

Queue another Discovery Loop in 1min

The listening for connections in step 3 and the discovery loop are asynchronous.

The reason a copy is made in the first place is due to some other design decisions for down the road.

The problem is that if I introduce a client with a bad peer on it's peer list, i.e. you can't connect to it, what happens is that this Peer is passed via step 3 when serving the known peer list and then other clients have it in theirs. They propagate this bad peer and later on, during the Discover Loop, remove that peer. But then, they will do another Discover Loop and will receive that Peer from someone else again.

The end result is that bad peer never leaves the network.

One option I can think of is a vague idea of having Peer "health" that each client keeps track of separately so that they can ignore peers provided on someone elses list. However, this would, I think, need to be somewhat "timed" so that when someone disconnects they aren't shut out of the network forever.

The other idea I had was for a broadcast message to all known peers when a bad peer is encountered. However, I didn't like this idea because it leaves it open for someone to make a different client that's job is to poison the network by insisting peers are bad. This would then require me to have peers check that a remove request is genuine by also attempting to connect to his peer immediately.

I'm looking for opinions on the two options above.


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

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

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

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

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

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

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答: Generators. As in Python, with yield.</p>

Body: Generators. As in Python, with yield.


问:
Best way to separate public API from internal implementation
I'm developing a little framework (in Scala) where I want to define clean and simple interface for the users of the framework. Some of theses interfaces have to be implemented by the framework itself, but I want to hide theses implementations from the user to keep the "surface" of the framework small and simple.

My idea is to have a package "internal" inside the root package of the framework where all these internal things go in.

```<code>com/
  example/
    framework/
      internal/
        SomeImplementation.scala
        SomeInternalThing.scala
      SomethingPublic.scala
      SomeInterface.scala
</code>```

Another common option is to create an "api" package for the public things, but I feel that the package path should be as short as possible for the normal user.

```<code>com/
  example/
    framework/
      api/
        SomethingPublic.scala
        SomeInterface.scala
      SomeImplementation.scala
      SomeInternalThing.scala
</code>```

Another, more radical, way would be to create two separate projects: one for the public API and one for the implementation. That is essentially what is done in the Java EE world. But this could be a bit overkill in may scenario since I'm not creating an official standard.

What would you prefer and why? Do you have any other suggestions?

答:
I would definately go with the "overkill" solution:  have a public project for the api, and a separate project for implementation.

```<code>com/
  example/
    framework/
      api/
      implementation/
</code>```

implementation of course will have a dependency on api.
I see 2 advantages:

It will be easy for you to keep your public api interface clean. No classes creeping into the api because ide added 'public' keywords.

I found that following best practices always pays dividends in the long run.  So even if you are not creating an official standard, following this practice will ensure that you have no problems when and if your framework grows in code and user base.

Body:
I would definately go with the "overkill" solution:  have a public project for the api, and a separate project for implementation.

com/
  example/
    framework/
      api/
      implementation/

implementation of course will have a dependency on api.
I see 2 advantages:

It will be easy for you to keep your public api interface clean. No classes creeping into the api because ide added 'public' keywords.

I found that following best practices always pays dividends in the long run.  So even if you are not creating an official standard, following this practice will ensure that you have no problems when and if your framework grows in code and user base.


答: Ability to throw exceptions in __destructor or __toString. And, really, is there any explanation why it is not possible?</p>

Title: What features would you like to have in PHP?

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

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

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

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

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

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

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.


问:
Would Rebol (or Red) benefit from Lisp-style Macros?
As a 'seasoned' Rebol developer with some knowledge of the world outside, I'd be curious as to the utility/pitfalls of implementing Lisp-style macros in Rebol (and/or Red).

My understanding (always happy to revise) is that Lisp is able to preprocess code prior to evaluation/compilation, modifying that code according to the rules of the applicable macros. This can allow for more complex/expressive statements than otherwise, with efficiencies as those statements are expanded only once as a body of code is loaded. The macro rules themselves are relatively straightforward as the homoiconicity of Lisp allows the code to be manipulated by the same terms one would modify data.

As Rebol is also a homoiconic language, it stands that it too could accommodate macros between loading and evaluation with similarly expressive transformation grammar (though I'd posit that Rebol's more freeform evaluation model—statements not generally bound by parentheses—makes it harder to identify the portions of code to be transformed).

My own inclination is that in the main, macros aren't really necessary in Rebol—you can already create complex code structures that are fairly efficient, and where more efficiency is desired, Rebol has the capabilities to accommodate without significant loss of expressivity. On the other had, 'fairly' and 'no significant loss' could be considered weasel words and macros do offer an efficiency/expressivity bump, but at what implementation cost?

Also, as in Rebol you can load code prior to evaluation, it would be possible to implement a mechanism for load-expand-evaluate at the user-level permitting third-party macro implementations.

This post is partly a response to this question and everything (pretty much) I know about macros comes from this exchange.

Update

Entering the World of Macros

Red introduced a rudimentary macro system in version 0.6.2. I have used them effectively to create cross-compatible scripts that target both the Ren-C branch of Rebol 3 and Red.

答:
Rebol probably would not, since there is no explicit compilation step. An extra 'macro expansion' pass would have to be added to implement Lisp macros properly, which is not all that different from the expand-* suggestion by @rgchris.

Lisp macros "work" because everything which enters a Lisp image is technically required to go through a compilation step by the Common Lisp specification. That pass is  what determines the result of (eval-when) calls, figures out how to handle control flow bits and pieces, do JIT-ting, and general purpose code magery. Lisp code goes through the reader, yet there is always an existing image there to call back to. In a sense, the Lisp runtime and compiler are working in tandem. As opposed to C, where the compiler is working by itself. Rebol is similar to C in that aspect; the interpreter is running by itself. You need both for Lisp macros to make sense.

Since Red has a planned JIT and carries along Red/System which is both JIT or compiled ahead of time, the ability to immitate Lisp macros would be advantageous. Most of the work done to support macros is already done by necessity by both JIT and AOT compilers, as they already must scan functions and parameter signatures to determine what kind of assembly code will be produced. All that remains at that point is to decide whether a statement is part of a statement to compile, or  a statement to run in the compiler's Red context and treat the return value as a statement to compile. Since running eval is a frowned-upon practice in general, this means the only time a macro could potentially change the state of your Red environment is during the bootstrapping or development phases of your program--you already modify the environment in those, so you expect it.

Lisp also has the (macroexpand-1) and (macroexpand-all) facilities, which allow you to see what the Lisp environment is going to use as the expansion of a given macro. This is surprisingly more useful for debuggability than normal template systems--you can ask for an exact copy of the template expansion, which is not something you can ask of any C++ compiler. I mention this because someone ultimately always brings up how macro systems can make debugging slightly more difficult; yet, a system which is even more difficult to debug is being used on a much more popular language on a daily basis.

An example of this usefulness is that PARSE from Red could be used to create a dialect which accepts the definition of a binary file format, which then outputs a block of Red/System code, which would then ultimately be compiled. Since execution is only necessary at compile time the entire code which does the parsing, as well as the specification text itself, are not needed in the binaries. The entire preprocessor could also be removed, since everything from #if to #define and #import would be achievable using a Lisp-like macro system.


答:
You've had several interesting answers, but for what you're discussing - the distribution of a critical configuration file to over a thousand machines - you should be following an atomic replacement protocol instead.  The point is to make it impossible for the application to ever see a partially-complete configuration file, or for the update process to deliver a partial file.

Create new a temporary file on the same drive where the existing file is.

Open the new file, write the new configuration into it, and close it.

Atomically replace the old file with the new file.

How you do #3 depends on the environment you're using.  For example, In .NET, that would be the System.IO.File.Replace() method.


问:
What are the advantages of dynamically binding a method to class instance?
I came across Instagram's API client written in Python.

In their class InstagramAPI, they bind the methods to a function in bind.py. When called, the function returns an instance of the class InstagramAPIMethod and execute the request call.

What are the advantages of doing it this way? (over directly creating instances of InstagramAPIMethod in InstagramAPI)?

What will happen if the methods in InstagramAPI are called numerous times? Will it create new a instance every call?

Note, the only advantages I thought of are (probably I'm off track):

The class doesn't/shouldn't care what the implementing class is.

If a particular method is not called, we will never create an instance.

答: Benefit of Dynamic binding is that we can tell the compiler that here is the possibility to exist more subclasses of this class and the method can be over ridden there so please leave it for future refrence, otherwise compiler bind it to the present call and our next over riding for this method will not produce the desired result.</p>


问:
grouping variables into a system in C?
Within C, say I have a number of variables, floats, integers etc, is there a way that I can group them all into one object, lets call it a system, and then create N copies of such an object.

Further, is there a way to assign to each copy of the system a particular value of a variable T such that each system has a different but predetermined T?

I am very new to C programming so don't quite know where to start, your help is much appreciated.

答:
Quick and dirty way to do it:

```<code>typedef unsigned int t_t;

struct your_thing {
    int a;
    float b;
    char z[20];

    t_t t;
};

struct your_thing copy_thing(struct your_thing thing) {
    static t_t counter = 0;
    thing.t = counter++;
    return thing;
}
</code>```

Example:

```<code>struct your_thing a = { ... };
a = copy_thing(a); // needed to initialize a.t
struct your_thing b = copy_thing(a);
</code>```

b.t is now different than a.t, and as long as all copies of the struct are made with copy_thing() they will never collide.

This is not a very good way of doing this, though, since the static variable is global and not thread safe. I can't see why you would want to do this. What you probably have here is the XY problem.

Title: grouping variables into a system in C?

Body:
Quick and dirty way to do it:

typedef unsigned int t_t;

struct your_thing {
    int a;
    float b;
    char z[20];

    t_t t;
};

struct your_thing copy_thing(struct your_thing thing) {
    static t_t counter = 0;
    thing.t = counter++;
    return thing;
}

Example:

struct your_thing a = { ... };
a = copy_thing(a); // needed to initialize a.t
struct your_thing b = copy_thing(a);

b.t is now different than a.t, and as long as all copies of the struct are made with copy_thing() they will never collide.

This is not a very good way of doing this, though, since the static variable is global and not thread safe. I can't see why you would want to do this. What you probably have here is the XY problem.


问:
How to avoid LazyInitializationException using Hibernate and Jersey
I am working with Spring Boot + Jersey + JPA/Hibernate to build a RESTful API. The issue I am encountering right now is when I have a relationship in my JPA Entity that is lazy loaded I get a lazy load exception when Jersey goes to serialize the object. My question is what is the best way to avoid this / best practices.

I realize I could just do FetchType.EAGER but that seems like a really really bad idea building a huge object graph that may not be necessary.

I've thought about using the DTO pattern, but that seems like a lot of code duplication, so not sure I want to go down this route unless its the best option.

I could switch to EclipseLink because as I understand it does not suffer from the Lazy load no session issues Hibernate like Hibernate does.

The other option I thought about was to put @JsonIgnore on all lazy loaded properties and make another API endpoint to fetch that property. As an example let's say a Person has many addresses, if the end users wants the addresses they would have to request /person/addresses

What is the best way to handle this issue, and why? At the end of the day this API will interface with an AngularJS application. The application will be a pretty decent size. The database that backs in has 80-90 tables.

答: I highly recommend you to go for DTO pattern since you have a large model. The reason for that is only by using DTO pattern you can have clear separation between your domain model and service objects. In other case you will not have a layer/room to manage possible future changes in your domain entities or service requirements and those changes most likely will break your existing services.  </p>


问:
Should I stop using the term C/C++?
I understand C and C++ are different languages but when I was learning C++ I was always told that C is a subset of C++ or C++ is C with classes. And that was quite true until the appearance of C++x0, C++11 (or the modern C++ 11/14/17 in general). In fact (especially when working on embedded systems) it's very likely to find code written in C++ but with a lot of parts written entirely in pure C language. Here I have several questions:

Should I stop using the term C/C++?

If the answer to #1 is yes, how would I call a program that use a mix of C and C++?

Given that both of them are 'different' languages is it likely that at some point C++ compilers stop supporting code written in the C language (since modern c++ is diverging from the C mentality for basic stuff like pointers, dynamic memory handling, etc)

Is there right now any collaboration between the people who makes the standards of C/C++ to keep the compatibility

If #4 is yes, such collaboration could end up in the near future with the appearance of the modern c++ (11/14/17)

I know that there already similar questions, but I'm sure that a lot of people share these questions so I'm very interested to get good answers especially for the points that have to do with the C++ tendency in the near future.

答:
This is a response of sorts to the position that "this is a code for programmers who work close to the metal and is OK in a management context" seen in some of the other answer and comments.

I'd argue that even that interpretation should be taken with care.

Starting by at least the mid '90s if you wanted a C++ programmer and someone who described themselves as a C programmer applied you'd have had to ask how much they know about object oriented design, how much experience they have with debugging in an object oriented context, and about their ability to use template libraries. You'd want to probe exactly those issues during the interview and hiring process.

On the flip side, it has now been more than a decade since C++ gurus started pushing "modern C++" meaning a emphasis on moving away from bare pointers to safer pointer objects and iterator-based idioms. With the emergence of C++11 there is now explicit support for multi-paradigm programming and the push toward code that exhibits no bare pointers is very strong. What that means is that if I interviewed a C++ programmer for a C position today I'd be very concerned about checking how familiar this person was with actual, foot-shooting-enabled pointers.

I'm not in the business these days (even to the degree that I was when Stack Overflow was in its infancy), so I won't venture a guess at how often either imaginary interviewee would not have the cross-over skills, but I think that as most often applied the languages are now very different indeed.

In short "C/C++" should be dropped not only in technical contexts but in most business contexts as well.

OwnerDisplayName: redobot

Title: Should I stop using the term C/C++?


问:
Generating combinations algorithmically
Suppose I have an n-high pyramid of numbers like:

```<code>    1
   5 8
  2 5 4
 8 9 3 1
2 8 3 7 2
</code>```

How can I algorithmically walk through every possible path from the top of the pyramid to the bottom?

To better explain, let me represent the pyramid this way:

```<code>1 2 3 4 5
-----------
1         | a
5 8       | b
2 5 4     | c
8 9 3 1   | d
2 8 3 7 2 | e
</code>```

For example:

```<code>        On the path | a b c d e (Path)
       -------------|------------------
Path 1:  1 5 2 8 2  | 1 1 1 1 1
Path 2:  1 5 2 8 8  | 1 1 1 1 2
Path 3:  1 5 2 9 8  | 1 1 1 2 2
Path 4:  1 5 2 9 3  | 1 1 1 2 3
...
Path m:  1 8 4 1 2  | 1 2 3 4 5
</code>```

Where m is the total number of paths.

I understand that the problem can be reduced to simply generate all the possible paths denoted in the second column of the table, and I could come up fairly easily with an algorithm to generate those for a 5-high (or any other fixed high) pyramid, but I can't seem to come up with a general solution.

The algorithm cannot be recursive, for the simple reason that I've already solved the problem recursively and I'm interested in a non-recursive solution to get a complete view of the problem.

答:
Maybe this:

Make a list t of left or right markers (0: left, 1: right) for all levels-1:
So in your example t has 4 entries initially all set to zero (marking the first path) through your pyramid (tree).

so now you need to count through all left or right possibilities
at each level (except level 0, which is the first node) we either go right or left :

Python:

```<code>pyr = [
        [1] ,
        [5 ,8]     ,
        [2,5, 4]   ,
        [8, 9, 3, 1]   ,
        [2, 8,3, 7, 2] ]

pyrD = len(pyr)-1

t = [0]*pyrD

def getNodes(t):
      print("---------------")
      print("leftRightIndices: " , t)
      nodesIdx = [0]
      nodes = [ pyr[0][nodesIdx[0]] ]
      for idx,LorR in enumerate(t):
          nodesIdx.append( nodesIdx[idx]+LorR )
          nodes.append(pyr[idx+1][nodesIdx[idx+1]])

      print("nodes: " , nodes)
      print(nodes)

done = False
while not done:

    getNodes(t)

    for i in range(0,pyrD):
        carryOver = (t[i] + 1) > 1
        if not carryOver:
            t[i]+=1
            break;
        else:
            if i == pyrD-1:
                done = True
            t[i] = 0;
</code>```

Which gives:

```<code>    ---------------
leftRightIndices:  [0, 0, 0, 0]
nodes:  [1, 5, 2, 8, 2]
---------------
leftRightIndices:  [1, 0, 0, 0]
nodes:  [1, 8, 5, 9, 8]
---------------
leftRightIndices:  [0, 1, 0, 0]
nodes:  [1, 5, 5, 9, 8]
---------------
leftRightIndices:  [1, 1, 0, 0]
nodes:  [1, 8, 4, 3, 3]
---------------
leftRightIndices:  [0, 0, 1, 0]
nodes:  [1, 5, 2, 9, 8]
---------------
leftRightIndices:  [1, 0, 1, 0]
nodes:  [1, 8, 5, 3, 3]
---------------
leftRightIndices:  [0, 1, 1, 0]
nodes:  [1, 5, 5, 3, 3]
---------------
leftRightIndices:  [1, 1, 1, 0]
nodes:  [1, 8, 4, 1, 7]
---------------
leftRightIndices:  [0, 0, 0, 1]
nodes:  [1, 5, 2, 8, 8]
---------------
leftRightIndices:  [1, 0, 0, 1]
nodes:  [1, 8, 5, 9, 3]
---------------
leftRightIndices:  [0, 1, 0, 1]
nodes:  [1, 5, 5, 9, 3]
---------------
leftRightIndices:  [1, 1, 0, 1]
nodes:  [1, 8, 4, 3, 7]
---------------
leftRightIndices:  [0, 0, 1, 1]
nodes:  [1, 5, 2, 9, 3]
---------------
leftRightIndices:  [1, 0, 1, 1]
nodes:  [1, 8, 5, 3, 7]
---------------
leftRightIndices:  [0, 1, 1, 1]
nodes:  [1, 5, 5, 3, 7]
---------------
leftRightIndices:  [1, 1, 1, 1]
nodes:  [1, 8, 4, 1, 2]
</code>```

Title: Generating combinations algorithmically

Body:
Maybe this:

Make a list t of left or right markers (0: left, 1: right) for all levels-1:
So in your example t has 4 entries initially all set to zero (marking the first path) through your pyramid (tree).

so now you need to count through all left or right possibilities
at each level (except level 0, which is the first node) we either go right or left :

Python:

pyr = [
        [1] ,
        [5 ,8]     ,
        [2,5, 4]   ,
        [8, 9, 3, 1]   ,
        [2, 8,3, 7, 2] ]

pyrD = len(pyr)-1

t = [0]*pyrD

def getNodes(t):
      print("---------------")
      print("leftRightIndices: " , t)
      nodesIdx = [0]
      nodes = [ pyr[0][nodesIdx[0]] ]
      for idx,LorR in enumerate(t):
          nodesIdx.append( nodesIdx[idx]+LorR )
          nodes.append(pyr[idx+1][nodesIdx[idx+1]])

      print("nodes: " , nodes)
      print(nodes)

done = False
while not done:

    getNodes(t)

    for i in range(0,pyrD):
        carryOver = (t[i] + 1) > 1
        if not carryOver:
            t[i]+=1
            break;
        else:
            if i == pyrD-1:
                done = True
            t[i] = 0;

Which gives:

    ---------------
leftRightIndices:  [0, 0, 0, 0]
nodes:  [1, 5, 2, 8, 2]
---------------
leftRightIndices:  [1, 0, 0, 0]
nodes:  [1, 8, 5, 9, 8]
---------------
leftRightIndices:  [0, 1, 0, 0]
nodes:  [1, 5, 5, 9, 8]
---------------
leftRightIndices:  [1, 1, 0, 0]
nodes:  [1, 8, 4, 3, 3]
---------------
leftRightIndices:  [0, 0, 1, 0]
nodes:  [1, 5, 2, 9, 8]
---------------
leftRightIndices:  [1, 0, 1, 0]
nodes:  [1, 8, 5, 3, 3]
---------------
leftRightIndices:  [0, 1, 1, 0]
nodes:  [1, 5, 5, 3, 3]
---------------
leftRightIndices:  [1, 1, 1, 0]
nodes:  [1, 8, 4, 1, 7]
---------------
leftRightIndices:  [0, 0, 0, 1]
nodes:  [1, 5, 2, 8, 8]
---------------
leftRightIndices:  [1, 0, 0, 1]
nodes:  [1, 8, 5, 9, 3]
---------------
leftRightIndices:  [0, 1, 0, 1]
nodes:  [1, 5, 5, 9, 3]
---------------
leftRightIndices:  [1, 1, 0, 1]
nodes:  [1, 8, 4, 3, 7]
---------------
leftRightIndices:  [0, 0, 1, 1]
nodes:  [1, 5, 2, 9, 3]
---------------
leftRightIndices:  [1, 0, 1, 1]
nodes:  [1, 8, 5, 3, 7]
---------------
leftRightIndices:  [0, 1, 1, 1]
nodes:  [1, 5, 5, 3, 7]
---------------
leftRightIndices:  [1, 1, 1, 1]
nodes:  [1, 8, 4, 1, 2]