问:
Mercurial Branching from a branch
We are in a situation where the customer has requested an urgent deployment of the current features we are working on.
These features are being developed in a mercurial branch named 'sprint 1' for arguments sake.

We also need to start working on the next sprint whilst the customer undertakes UAT. If they report any issues, we need to fix them on the 'sprint 1' branch and eventually redeploy them. Meanwhile, the rest of the team is supposed to be working on the 'sprint 2' features.

Would I just start a 'sprint 2' branch from the tip of the 'sprint 1' branch as soon as we go in to UAT?

答:
The flow of the system of old was basically everyone commits to the master / main / trunk / default or whatever, and at some point something is built from a specific revision.  This works well for small projects, but starts to have difficulty (as you noticed) when you start trying to go in different directions at the same time.

So, you branched for the 'sprint 1' for the role of 'bug fixes and stabilization of issues in sprint 1'.  And now you've got sprint 2 that is coming up... and where should that branch be made?

Before going too far, lets delve a bit into philosophy of version control.

Each branch has one or more roles and a policy that is determined when it is branched.

Even if you don't think about it, it is the case. Even if you are working on the 'everyone submits to the master,' it is the case.  I'm going to name these roles:

mainline

development

maintenance

accumulation

packaging

Well, I didn't name them. I <s>stole</s> borrowed them from one of my variate documents on branching: Advanced SCM Branching Strategies

When you are doing the 'everything on master', master has all these roles.  And thats ok.

The idea of a policy comes from Branching Patterns for Parallel Software Development and the policy branch.  This suggests if the policy of the branch needs to change to facilitate work there should be a new branch.  For example, if the policy on /trunk is "it must build successfully at all times" and in order to do some development, some work in progress check-ins are needed, that is a branch based on a change of policy.

Whenever one of those roles changes, or you need a subset of the roles, merge and or branch.

You've branched for 'sprint 1'.  This has the role of development and packaging. Thats ok. But it isn't mainline. And that is where all branches should have as a parent or grand parent (or great grand parent) and where all code should eventually end up.

Branching from 'sprint 1' to 'sprint 2' means that the code for 'sprint 1' didn't make it back into the mainline. It should.

Ideally, you would branch for 'sprint 1' from mainline, work on it, and when work is complete, merge it back to the mainline. You can do that merge back to the mainline multiple times.

With 'sprint 2', it branches from the mainline, and work is done on it. As changes from 'sprint 1' go into the mainline, they get merged from the mainline into 'sprint 2'.

There's a better way of doing this

Back in 2010, there was a blog post about a model for git branching that tried to put some order into the branches.  It was A successful Git branching model and has come to be known as 'git flow'

The 'master' branch is the one that git users tend to have as the mainline in many non-git flow cases.  Its not here.  Master is the tagged releases.

The mainline is the yellow one - develop.  All branches eventually merge to develop.

Your sprint would be one or more feature branches (thats one way of looking at it) and once the features in it get merged to develop, a release branch is made from develop.  That branch has the role of packaging - and the bug fixes are done on it and moved out to the master tagged releases and then back into develop - the mainline.

And wile thats all and good, you're using hg.  So, here's hg flow.

It will impose a bit more structure on how you branch. Thats a good thing.  You should be able to look at a branch and be able to figure out what goes in it, what doesn't go in it, where it is in the release cycle and work from there.

This helps in being able to identify exactly what role each branch has. You know where to go to build the latest release candidate. You know where to go to branch for a spike. You know how to get a hot fix into the product.

You could branch from the mainline for the sprint, branch from the sprint for each feature, merge to the sprint when the feature is done, and merge that back to the mainline.  That works fine too. The sprint has the additional role of the accumulation in that case.

The key thing is to consider the different roles for each branch so that a developer knows what should and what should not go into any given branch. It will save you a lot of grief down the road by being able to reason about the structure of the branches.

Title: Mercurial Branching from a branch


问:
Is a logical error always caused by the line of code for the earliest program state which is wrong?
A logical error, contrary to a fatal runtime error, is a run time error which doesn't fatally terminate a program, but does something not intended.

Is a logical error necessarily caused by the line of code for the earliest state which is wrong?

Or can a logical error be caused by a line of code before the line for the earliest wrong state?

My question mainly comes from

I think debugging can only help to tell if a  state of a  program is right or wrong, and not beyond that.

I guess by debugging we can  locate the line of code that causes a logical error, because I think a logical error is always caused by the line of code for the earliest state which is wrong, not by a line of code that precedes the line of code for the earliest state which is wrong.

I will be wrong if
you provide an example of logical error whose cause can't be found by using a debugger to track the states of the program. In other words, can you provide an example of logical error whose cause is earlier than the earliest states of the program which is wrong?

答:
By your wording, you have defined your answer to be true.

You talk about the first "wrong state."  What defines a wrong state?  What makes it wrong?  Typically the answer is "it wasn't the state that was correct."  By definition, the first wrong state is preceded by only correct states (or something went wrong on the first step, but that starts to be an OS issue).  Thus there is a transition from a right state to a wrong state.

If you assume that the only thing which can change a state is a statement (line of code), then by definition the statement which has just completed and resulted in the first wrong state is "the problem."

These assumptions are not always valid.  For example, its trivial to show that if you use a "memory trainer" which allows one program to push values into another program's memory space, any error caused by this trainer is clearly not caused by any line of code at all!

Also, it is possible to have cases where there is no one line "causing" the problem.  One such example is a multithreading race case.  In such a case it is not always possible to specify which thread "caused" the problem, because the problem actually originated from the interaction between two threads to cause a "wrong state."  Since statements (lines of code) are executed on a thread, and the error is not "on a thread," no line of code is at fault.

A more "constructive" approach might be to change the wording.  Instead of talking about "the line which caused the error," think about "The line which should be changed to fix the error."  That wording changes things up just enough to avoid a blame-game.

This is also very important for dealing with memory bugs.  In the case of those bugs, it is often very difficult to identify the actual first "wrong state," but easy to identify the state which segfaults.  It's easy to accidentally presume the error had to be some line of code near where it segfaulted because you presume the segfault is the first "wrong state" and forget to look for the actual root cause.

ContentLicense: CC BY-SA 3.0


问:
How to deal with long running transactions?
I'm developing a Content Management System (CMS) and I would like to include a "Save Changes" button. I mean: a user performs several changes in the database, but those changes are still not available. Just when the user presses the "Save Changes" button, those changes are "visible" for the website.

I have thinking in "SQL transactions". But I have understood that "SQL transaction" were designed to be used in a short space of time. And in this particular case the user may keep the transaction open for some time (one hour, two hours...).

How can deal with this kind of issues? I'm using PHP and MySQL?

答: One of the approaches is versioning. You'd design your content table with version and active column. Every time you auto-save you bump the version but don't mark row as active. Once you hit Save you will bump version and publish the content. Gives you complete history at the cost of big tables. I think WordPress uses the same approach.


问:
How are comments usually parsed?
How are comments generally treated in programming languages and markup? I am writing a parser for some custom markup language and want to follow the principle of least surprise, so I'm trying to determine the general convention.

For example, should a comment embedded within a token 'interfere' with the token or not? Generally, is something like:

```<code>Sys/* comment */tem.out.println()
</code>```

valid?

Also, if the language is sensitive to new lines, and the comment spans the new line, should the new line be considered or not?

```<code>stuff stuff /* this is comment
this is still comment */more stuff
</code>```

be treated as

```<code>stuff stuff more stuff
</code>```

or

```<code>stuff stuff
more stuff
</code>```

?

I know what a few specific languages do, nor am I looking for opinions, but am looking for whether or not: is there a general consensus what is generally expected by a mark up in regards to tokens and new lines?

My particular context is a wiki-like markup.

答:
In the past I've turned comments into a single token as a part of the lexical analysis.  The same goes for strings.  From there, life is easy.

In the specific case of the last parser I built, an escape rule is passed to the top level parse routine.  The escape rule is used to handle tokens such as comment tokens inline with the core grammar.  In general, these tokens were discarded.

A consequence of doing it this way is that the example you posted with a comment in the middle of a identifier, the identifier would not be a single identifier - this is the expected behaviour in all languages (from memory) that I've worked with.

The case of a comment within a string should be implicitly handled by the lexical analysis.  The rules to handle a string have no interest in comments, and as such the comment is treated as the contents of the string.  The same applies to a string (or quoted literal) within a comment - the string is a part of a comment, which is explicitly a single token; the rules for processing a comment have no interest in strings.

I hope that makes sense/helps.

Title: How are comments usually parsed?


问:
Is node.js for algorithmic problems like TSP or graph coloring or exact cover problem a good decision?
I read on node.js's official site that Node.js is a JavaScript run time built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O mode and highly scalable for network applications. And some thread I read that it is not for CPU intensive tasks. Is that mean that its not a good idea to use node.js for solving  problems like TSP, exact cover or graph coloring?

答:
The default event model for Node.JS is single-threaded, cooperative multitasking.  If you are I/O bound, Node.JS can simply accept new requests while yours is waiting for the database call to complete.  But if you are CPU bound, you chew up clock cycles while other requests have to wait.

There are, of course, ways to get around this.  One way is to spin up new threads to handle your long-running computations, just like you would in any other application.  This drops the multitasking load onto the operating system, which has better facilities for multitasking.  Because it's all Javascript, you can run some of it on the server and some of it in the browser.

There are some intricacies, of course.  You can find out in detail what they are and how they work in the article I link below.

Further Reading

Why you should use Node.JS for CPU-Intensive Tasks.


答:
You can use node.js for calculating whatever you want, even TSP problems or graph coloring. For example, I implemented a lot of Project Euler problems in node.js just for the purpose of learning Javascript, and I was astonished about the speed, which is is comparable to other JIT compiled language implementations, much better than the experiences I had with other scripting languages like Python or Perl.

However, if node.js is a "good-enough" choice for your use case, or if there are better alternatives is a completely different question. This depends a lot on non-functional factors like if you want to run your program as part of a web service, the number of concurrent computations you need to process, the need for multithreading, the requirement of reusing existing libraries, and so on.

Title: Is node.js for algorithmic problems like TSP or graph coloring or exact cover problem a good decision?

Body: I read on node.js's official site that Node.js is a JavaScript run time built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O mode and highly scalable for network applications. And some thread I read that it is not for CPU intensive tasks. Is that mean that its not a good idea to use node.js for solving  problems like TSP, exact cover or graph coloring?


答:
Just to confuse things, if you delete an essential line of code from a program, then it will malfunction.

Once you have done this, the logical error in the code will not be down to any line in the program.  It will be caused by the absence of a line.

Title: Is a logical error always caused by the line of code for the earliest program state which is wrong?

Body:
A logical error, contrary to a fatal runtime error, is a run time error which doesn't fatally terminate a program, but does something not intended.

Is a logical error necessarily caused by the line of code for the earliest state which is wrong?

Or can a logical error be caused by a line of code before the line for the earliest wrong state?

My question mainly comes from

I think debugging can only help to tell if a  state of a  program is right or wrong, and not beyond that.

I guess by debugging we can  locate the line of code that causes a logical error, because I think a logical error is always caused by the line of code for the earliest state which is wrong, not by a line of code that precedes the line of code for the earliest state which is wrong.

I will be wrong if
you provide an example of logical error whose cause can't be found by using a debugger to track the states of the program. In other words, can you provide an example of logical error whose cause is earlier than the earliest states of the program which is wrong?


问:
what is the difference between callbacks and listeners?
In blackberry we can override keyChar() method and capture the keypress event or we can register onKeyPressListener. i know, onKeyListener is observer pattern.

In android also there is a KeyEvent.callback and onKeyListener

Both are events why we no need to register for keyChar event.
what is the difference between both pattern?

答:
I suppose that you have an application which use a library:

Listener: Library runs some code on its data, but, the code is implemented on Application.

Callback: Application runs some code on its data, however, the code is implemented on Library.

Because library can't see the application, so there is no way to instead Listener for that case.

Of course Application can see the library, but sometimes library wants to hide it's code, and helps application to make sense with it


答:
Consider this: an algorithm that is either inadequate or premature. That is, when this algorithm is executed, it will go through only a subset of the valid states, leaving some valid states unvisited. In doing so, it will miss the correct answer; therefore, when the algorithm finishes, it will finish in a state (*) that is different from the correct state.

(*) I consider the return value to be considered part of the state.

Example: an algorithm that tries to search for a particular integer value in an integer array.

The algorithm contains a defect, such that it only search for items located on even-numbered index values. Items on odd-numbered index values aren't visited.

The visiting of elements on even indices comprises of valid states. However, the lack of visiting of elements on odd indices is an omission that lead to wrong result.

The logic error lies in incorrect state transitions that cause it to skip over indices.

Because a debugger user is able to step through the program execution, the user is able to see both incorrect states being entered, as well as state transitions that are incorrect. Therefore, the error mentioned above is catchable by using a debugger.

However, for non-trivial algorithmic inadequacies (using an algorithm that is unfit for the task), the logic error can only be seen by a person who (1) knows what algorithm is being implemented in the code, and (2) knows that the implementation will fall short of the requirements of the program. This is the case where "debugging" happens on paper, before any line of code is written.


问:
How common are "bandage" fixes?
Imagine the following scenario:

You've detected that your (or someone else's) program has a bug - a function produces the wrong result when given a particular input. You examine the code and can't find anything wrong: it just seem to bog out when given this input.

You can now do one of two things: you either examine the code further until you've found the actual cause; or you slap on a bandage by adding an if statement checking if the input is this particular input - if it is, return the expected value.

To me, applying the bandage would be completely unacceptable. If the code is behaving unexpectingly on this input, what other input that you've missed will it react strangely to? It just doesn't seem like a fix at all - you're just shoveling the problem under the rug.

As I wouldn't even consider doing this, I'm surprised at how often the professors and books keep reminding us about how applying "bandage" fixes is not a good idea. So this makes me wonder: just how common are these kinds of "fixes"?

答:
We do them exceptionally.

For fixes during development, we are making sure that no fix is done without knowing the root cause. However:

Exceptionally the search for the root cause will start to take too long or stall AND there is a tough deadline,

Exceptionally code changes to fix the root cause are tactically not feasible (change will take too long and deadline approaching)

In those cases we opt of "bandage" fixes. We then open internal defects to address the root cause. Yes, more often than not these internal defects are treated with very low priority.

For fixes in the maintenance stream, we are making sure that no fix is done without knowing the root cause. However:

Very exceptionally the search for the root cause will stall,

Exceptionally it can occur that fixing the root cause is tactically not feasible (change is non trivial and customer needed the fix yesterday).

In those cases we opt for "bandage" temporary fix first and once customer is happy we work on the proper fix and only then the defect is resolved.

ContentLicense: CC BY-SA 2.5

Title: How common are "bandage" fixes?


问:
How to avoid the LoadBy pattern?
In our codebase for a sophisticated system controlling many aspects of businesses, we have a certain unwritten law to not fudge around in code with complicated SQL, instead writing it into a function in the entity's class to centralize the database access, and this great pattern turned into pages and pages of

```<code>class Car:
    List<Car> LoadByManufacturerId(id);
    List<Car> LoadByModelId(id);
    List<Car> LoadByCountryId(id);
    List<Car> LoadByCityId(id);

    Car LoadByChassis(chassis);
    Car LoadById(id);
    Car LoadByCountryIdAndChassis(countryId, chassis);
    Car LoadByPersonIdAndIndex(personId, index);
</code>```

As in, everytime someone needs to make a query by a new parameter, a new method is created, but that's only half the problem: Many times people don't take the time to look at the code before creating one of these (documentation is non-existant) and end up creating multiple versions of the query under the same name, duplicating code all around.

We're in a C# project, but many of the devs don't understand much LINQ beyond basic from s in tablename where blabla select s, so what is the best way to refactor this pattern into something not so prone to these kind of problems with the minimal friction?

答:
Why not to use Specification pattern?

Then you will be able to pass only Specification to a Repository's loadBySpecification() method.

Title: How to avoid the LoadBy pattern?


问:
Fundamental issues of programming
I just let my brain run wild and the results are again chaotic. It is kind of bothering me how in the very basics, programming itself can be pretty redundant.

Let's look at this snippet of code and analyze what it does

```<code>public function __construct($data = array(), $strict = false, $prefix = null) {
    if (!$data) {
        return;
    }

    foreach ($data as $key => $val) {
        if ($prefix) {
            if (($pos = strpos($key, $prefix)) === 0) {
                $key = substr($key, 0, $pos);
            } else {
                continue;
            }
        }

        if ($strict === false || property_exists($this, $key)) {
            $this->$key = $val;
        }
    }
}
</code>```

When constructing this object we can provide an array to fill in it's properties, however there is some filtering we can do. If we enable the strict parameter it will only fill in keys it already has, and if we supply a prefix parameter it will only fill in properties that correspond to keys starting with a certain prefix.

See, however, that we have n*2 if-statements evaluated in the given loop at the very least. Meaning if we have 100 elements in the $data array there will be at least 200 if-statements evaluated. Wouldn't it be better if we could reduce that?

```<code>public function __construct($data = array(), $strict = false, $prefix = null) {
    if (!$data) {
        return;
    }

    if ($strict === false) {
        if ($prefix) {
            foreach ($data as $key => $val) {
                if (($pos = strpos($key, $prefix)) === 0) {
                    $this->{substr($key, 0, $pos)} = $val;
                }
            }
        } else {
            foreach ($data as $key => $val) {
                $this->$key = $val;
            }
        }
    } else {
        if ($prefix) {
            foreach ($data as $key => $val) {
                if (property_exists($this, $key) && ($pos = strpos($key, $prefix)) === 0) {
                    $this->{substr($key, 0, $pos)} = $val;
                }
            }
        } else {
            foreach ($data as $key => $val) {
                if (property_exists($this, $key)) {
                    $this->$key = $val;
                }
            }
        }
    }
}
</code>```

As we can clearly see, readability has gone to hell but nevertheless we have reduced the amount of expressions evaluated from 200 to 2 in the best case scenario when $strict === false and prefix === null - that is a 99% increase in efficiency, theoretically.

Mostly everything I said so far is theoretical, so the question is - Is there any actual benefit to example 2 opposed to example 1 regarding program execution?

Given that I have not graduated in computer science I'm not as familiar on programming (and php) internals and how code is evaluated and executed on a deeper level, but I have read this and that on how processors can shortcut redundant if-statements but as I said, am not as familiar to answer the question myself.

答:
There is a great book called Clean Coder. It copes a lot of questions like this and contains some awesome tips for those fundamental issues you are talking about.

For your question, there is a rule called Beware of Optimizations!

The explaination starts with: Focus on writing comprehensible code. Optimized code is often anything but readable... and I personally agree on that.

If you don't need to optimize, don't do it. If you run into performance issues, or if it is probable that you would run into performance issues in the near futur, then you have no choice than to optimize your code for performance (even if that means making your code less readable).

Clean coder: http://clean-code-developer.com/Red-Grade.ashx#Beware_of_Optimizations!_2

Title: Fundamental issues of programming


答:
In answer to this question from the comments:

We say that we sacrifice performance for maintainability and readability but why is this necessary, why is there no way to have the best out of both.

Code is a construct that is used to express a sequence of steps which represents a task to be carried out, or to express a set of expressions to calculate a value. In order for this logic to be of any use it has to be executed at some point, so the reality of this execution has to be taken into account. This is where optimization comes in.

Optimization means adding to or changing the logic of your task to account for details of the mechanism of execution, in order to speed things up. Often times this complicates the code, e.g. by breaking abstractions that are used by your code to get at and change implementation details.

Maintainable code has the properties of (among others) clarity and simplicity; removing these in your code, e.g. by breaking the abstractions that buy them, will cause the loss of some maintainability.

This doesn't necessarily mean that all optimization breaks maintainability. It can be possible to write maintainable code taking into account the particulars of the execution mechanism, or to apply different abstractions to do so. (Or to use abstractions properly in the first place.)

Title: Fundamental issues of programming

Body:
I just let my brain run wild and the results are again chaotic. It is kind of bothering me how in the very basics, programming itself can be pretty redundant.

Let's look at this snippet of code and analyze what it does

```<code>public function __construct($data = array(), $strict = false, $prefix = null) {
    if (!$data) {
        return;
    }

    foreach ($data as $key => $val) {
        if ($prefix) {
            if (($pos = strpos($key, $prefix)) === 0) {
                $key = substr($key, 0, $pos);
            } else {
                continue;
            }
        }

        if ($strict === false || property_exists($this, $key)) {
            $this->$key = $val;
        }
    }
}
</code>```

When constructing this object we can provide an array to fill in it's properties, however there is some filtering we can do. If we enable the strict parameter it will only fill in keys it already has, and if we supply a prefix parameter it will only fill in properties that correspond to keys starting with a certain prefix.

See, however, that we have n*2 if-statements evaluated in the given loop at the very least. Meaning if we have 100 elements in the $data array there will be at least 200 if-statements evaluated. Wouldn't it be better if we could reduce that?

```<code>public function __construct($data = array(), $strict = false, $prefix = null) {
    if (!$data) {
        return;
    }

    if ($strict === false) {
        if ($prefix) {
            foreach ($data as $key => $val) {
                if (($pos = strpos($key, $prefix)) === 0) {
                    $this->{substr($key, 0, $pos)} = $val;
                }
            }
        } else {
            foreach ($data as $key => $val) {
                $this->$key = $val;
            }
        }
    } else {
        if ($prefix) {
            foreach ($data as $key => $val) {
                if (property_exists($this, $key) && ($pos = strpos($key, $prefix)) === 0) {
                    $this->{substr($key, 0, $pos)} = $val;
                }
            }
        } else {
            foreach ($data as $key => $val) {
                if (property_exists($this, $key)) {
                    $this->$key = $val;
                }
            }
        }
    }
}
</code>```

As we can clearly see, readability has gone to hell but nevertheless we have reduced the amount of expressions evaluated from 200 to 2 in the best case scenario when $strict === false and prefix === null - that is a 99% increase in efficiency, theoretically.

Mostly everything I said so far is theoretical, so the question is - Is there any actual benefit to example 2 opposed to example 1 regarding program execution?

Given that I have not graduated in computer science I'm not as familiar on programming (and php) internals and how code is evaluated and executed on a deeper level, but I have read this and that on how processors can shortcut redundant if-statements but as I said, am not as familiar to answer the question myself.


问:
how to split up a delegate class
I have a communication class that incapsulates all the apis of a remote application.
This class happens to be a delegate class because it is interchangeable with another one (the remote application has two different channels).

This class has a number of topics (eg: acknowledge, people, invoices, duedates, payment methods, queues), and each topic has a number of methods (setOne, getOne, getAll, doSomething...). The number of topics is raising rapidly recently, from 1-2 to 6 and possibly more in the future.

Considering that the class itself needs some scaffolding methods (configuration, startup, authentication...) and each topic needs some auxiliary protected method, the total projected number of method is rasing beyond my confort zone.

If this class wasn't itself a delegate class, I would have implemented this solution: a class for each topic, each making use of the common class, and if necessary of the others.
But the client code wants to be given just ONE class to which make requests.

One option is to make a single delegate class with lots of relay methods to composite objects.
But I don't feel this is very far from swallowing the frog and just have a big class full of stuff.

Are there other solutions?

I'm working in php and I colud leverage the ___CALL meta method: class accepts any message and then looks up (via reflection) if it has an auxiliary class to relay the calling. This could be smart, but I would leave this solution for emergencies.

答:
You need to write methods in three dimensions, so to speak: Channel, topic and operation. I once solved a similar problem by combining the the commands from [1] with (abstract) factories [2].

The basic idea is to write one Command-Class for each combination of (channel, topic, operation) which all have a common interface. In your case something like

```<code>Response sendRequest()
</code>```

seems reasonable.

Furthermore every Command-Object needs all resources readily available as member to perform it's task. The details of acquiring those resources and setting up a specific command with it, is encapsulated in the corresponding factories. With clever type hierarchies of the actual commands and factories you can separate common from specialized code.

Let me do a bit of sketching and try to clarify what I mean:

Let's assume you want to list all (operation) people (topic) with last name 'Jackson' (operation) as an XML (channel) request, the client code would look something like this:

```<code>$xmlCommandFactory = CommandFactories.createFactory('XML'); // returns specific factory for channel; Specific factories share same interface
$peopleCommandFactory = xmlCommandFactory->createPeopleFactory(); // returns specialieced factory for topic
$command = peopleCommandFactory->createListByLastName('Jackson'); // creates specific command with specific parameter
$response = command.sendRequest(); // executes command
</code>```

This makes for a lot of abstraction and boiler plate code. However, the beauty of the multiple layers is, that each layer deals with only one dimension. For example if I wanted the same thing as a Json-Request the code would look like this:

```<code>$xmlCommandFactory = CommandFactories.createFactory('JSON'); // returns specific factory for channel; Specific factories share same interface
$peopleCommandFactory = xmlCommandFactory->createPeopleFactory(); // returns specialieced factory for topic
$command = peopleCommandFactory->createListByLastName('Jackson'); // creates specific command with specific parameter
$response = command.sendRequest(); // executes command
</code>```

This is also true for the actual implementation. createFactory($type), for example, only deals with the decision of which factory to instantiate for the requested channel.

Another advantage is scalability. You merely add new, small command-classes, instead of maintaining one big monolithic piece of code. This should also help you when writing tests, as smaller chunks of encapsulated code are inherently easier to test.

Last but not least you can decouple the decision making (what to get how and with which parameters) from the actual execution, by passing commands and/or factories around. This might turn out to be beneficial or not.

[1] https://sourcemaking.com/design_patterns/command

[2] https://sourcemaking.com/design_patterns/abstract_factory

Title: how to split up a delegate class

Body:
You need to write methods in three dimensions, so to speak: Channel, topic and operation. I once solved a similar problem by combining the the commands from [1] with (abstract) factories [2].

The basic idea is to write one Command-Class for each combination of (channel, topic, operation) which all have a common interface. In your case something like

Response sendRequest()

seems reasonable.

Furthermore every Command-Object needs all resources readily available as member to perform it's task. The details of acquiring those resources and setting up a specific command with it, is encapsulated in the corresponding factories. With clever type hierarchies of the actual commands and factories you can separate common from specialized code.

Let me do a bit of sketching and try to clarify what I mean:

Let's assume you want to list all (operation) people (topic) with last name 'Jackson' (operation) as an XML (channel) request, the client code would look something like this:

$xmlCommandFactory = CommandFactories.createFactory('XML'); // returns specific factory for channel; Specific factories share same interface
$peopleCommandFactory = xmlCommandFactory->createPeopleFactory(); // returns specialieced factory for topic
$command = peopleCommandFactory->createListByLastName('Jackson'); // creates specific command with specific parameter
$response = command.sendRequest(); // executes command

This makes for a lot of abstraction and boiler plate code. However, the beauty of the multiple layers is, that each layer deals with only one dimension. For example if I wanted the same thing as a Json-Request the code would look like this:

$xmlCommandFactory = CommandFactories.createFactory('JSON'); // returns specific factory for channel; Specific factories share same interface
$peopleCommandFactory = xmlCommandFactory->createPeopleFactory(); // returns specialieced factory for topic
$command = peopleCommandFactory->createListByLastName('Jackson'); // creates specific command with specific parameter
$response = command.sendRequest(); // executes command

This is also true for the actual implementation. createFactory($type), for example, only deals with the decision of which factory to instantiate for the requested channel.

Another advantage is scalability. You merely add new, small command-classes, instead of maintaining one big monolithic piece of code. This should also help you when writing tests, as smaller chunks of encapsulated code are inherently easier to test.

Last but not least you can decouple the decision making (what to get how and with which parameters) from the actual execution, by passing commands and/or factories around. This might turn out to be beneficial or not.

[1] https://sourcemaking.com/design_patterns/command

[2] https://sourcemaking.com/design_patterns/abstract_factory


答:
This is not ideal code because there are two distinct operations being performed in this one function. There is copying a key only if it exists on the target (filter), called "$strict". Then there is matching the key to a prefix value and transforming the key to that value (filter + map). (Note that this latter one especially looks like it has flawed logic, but I used your code verbatim in my answer anyway.)

There should be 2 separate functions which perform their specific operation on ONE item. Then you could simplify the constructor code and even increase maintainability. I haven't used PHP in some time, so I'm not sure if this will run, but here goes.

```<code>private function choosePrefix($prefix, $key) {
    if (($pos = strpos($key, $prefix)) === 0) {
        return substr($key, 0, $pos);
    } else {
        return false;
    }
}

private function strictCopy($target, $key, $value) {
    if (property_exists($target, $key)) {
        $target->$key = $value;
    }
}
</code>```

Note that separating things into functions adds a lot of overhead (well, not in all languages, but in this case). However, it has the advantage of describing the intention of what you are doing! You'll see below.

Secondly, you are treating the object as though it is a collection (dictionary). This feels perfectly natural in PHP, but in most other languages, it is common to represent collection data as a property of the class instead of key/values being intermixed with concrete properties.

```<code>$data = $this->data;
$data[$key] = $value;
</code>```

Thirdly, what solves your specific gripe is choosing your processing functions before running the loop and then running the chosen functions on the data inside the loop. This is pretty common in functional languages, and I believe now available in PHP, if a bit awkwardly. Here is an example... but again, been a while since I've used PHP.

```<code>private function passThru($dummy, $key) { return $key; }
private function choosePrefix($prefix, $key) {
    if (($pos = strpos($key, $prefix)) === 0) {
        return substr($key, 0, $pos);
    } else {
        return false;
    }
}

private function strictFilter($target, $key) {
    if ($key !== false && property_exists($target, $key)) {
        return $key;
    } else {
        return false;
    }
}

public function __construct($data = array(), $strict = false, $prefix = null) {
    if (!$data) {
        return;
    }
    // ternary form of if/then/else
    $chooseFn = ($prefix ? 'choosePrefix' : 'passThru');
    $filterFn = ($strict ? 'strictFilter' : 'passThru');

    foreach ($data as $key => $val) {
        $key = $this->$chooseFn($prefix, $key);
        $key = $this->$filterFn($this, $key);
        if ($key !== false) {
            $this->$key = $value;
        }
    }
}
</code>```

Now if we look at the constructor, without having to actually mentally work through the code, I can see that I might skip some keys, otherwise I will copy the key/value to this object. Giving the operations names by putting them in separate functions helps readability here.

Title: Fundamental issues of programming

Body:
This is not ideal code because there are two distinct operations being performed in this one function. There is copying a key only if it exists on the target (filter), called "$strict". Then there is matching the key to a prefix value and transforming the key to that value (filter + map). (Note that this latter one especially looks like it has flawed logic, but I used your code verbatim in my answer anyway.)

There should be 2 separate functions which perform their specific operation on ONE item. Then you could simplify the constructor code and even increase maintainability. I haven't used PHP in some time, so I'm not sure if this will run, but here goes.

private function choosePrefix($prefix, $key) {
    if (($pos = strpos($key, $prefix)) === 0) {
        return substr($key, 0, $pos);
    } else {
        return false;
    }
}

private function strictCopy($target, $key, $value) {
    if (property_exists($target, $key)) {
        $target->$key = $value;
    }
}

Note that separating things into functions adds a lot of overhead (well, not in all languages, but in this case). However, it has the advantage of describing the intention of what you are doing! You'll see below.

Secondly, you are treating the object as though it is a collection (dictionary). This feels perfectly natural in PHP, but in most other languages, it is common to represent collection data as a property of the class instead of key/values being intermixed with concrete properties.

$data = $this->data;
$data[$key] = $value;

Thirdly, what solves your specific gripe is choosing your processing functions before running the loop and then running the chosen functions on the data inside the loop. This is pretty common in functional languages, and I believe now available in PHP, if a bit awkwardly. Here is an example... but again, been a while since I've used PHP.

private function passThru($dummy, $key) { return $key; }
private function choosePrefix($prefix, $key) {
    if (($pos = strpos($key, $prefix)) === 0) {
        return substr($key, 0, $pos);
    } else {
        return false;
    }
}

private function strictFilter($target, $key) {
    if ($key !== false && property_exists($target, $key)) {
        return $key;
    } else {
        return false;
    }
}

public function __construct($data = array(), $strict = false, $prefix = null) {
    if (!$data) {
        return;
    }
    // ternary form of if/then/else
    $chooseFn = ($prefix ? 'choosePrefix' : 'passThru');
    $filterFn = ($strict ? 'strictFilter' : 'passThru');

    foreach ($data as $key => $val) {
        $key = $this->$chooseFn($prefix, $key);
        $key = $this->$filterFn($this, $key);
        if ($key !== false) {
            $this->$key = $value;
        }
    }
}

Now if we look at the constructor, without having to actually mentally work through the code, I can see that I might skip some keys, otherwise I will copy the key/value to this object. Giving the operations names by putting them in separate functions helps readability here.


问:
MS SQL Server Cell level Encryption options
Recently, i got the task of doing some research into the data encryption at the cell level. I tried using the Symmetric key (by passphrase) & second option i took is Symmetric key (by Certificate). I need the encryption to be performed only on 3 columns inside the customer related data table.

Example:-

```<code>ColumnX1 - Char(9) datatype
ColumnX2 - Char(9) datatype
ColumnX3 - Char(9) datatype
</code>```

Three new columns:-

```<code>ColumnX1Crypt - varbinary(200) datatype
ColumnX2Crypt - varbinary(200) datatype
ColumnX3Crypt - varbinary(200) datatype
</code>```

So far, it worked fine when i used the option of using the Certificates. But i have some open doubts and questions on using the certificates.

My queries:-

a) How do i perform the creation of a master key, certificate & the symmetric in various testing regions such as DEV, UAT, QA and finally to production ? If i prepare the sql script & ask the DBA's to run it in various regions, will it fine or i need to convey some additional information along with it. ? Please suggest.

b) Do i need to keep the backups of the master key, certificate & the symmetric key for every region such as DEV, UAT, QA etc. ? If i create a master key with the same password in all the regions. Will it be fine ?  Will the backup files of the various objects taken in the Prod db work in lower regions db's ?

c) Are there any drawbacks of using the Certificate option with the Symmetric key?

d) Which encyption algo is best to choose.? In my case, the maximum data length is 9 characters for encryption.

Some Misc statements used in the MS SQL Server:-

```<code>CREATE MASTER KEY ENCRYPTION BY
PASSWORD = '23987hxJKL#1946kcj$n44ncjhdlj'

CREATE CERTIFICATE Partner_Cert
   WITH SUBJECT = 'Certificate For Encryption',
   Expiry_Date = '20180101';

CREATE SYMMETRIC KEY PARTNER_ENCR_KEY
    WITH ALGORITHM = TRIPLE_DES
    ENCRYPTION BY CERTIFICATE [Partner_Cert]
</code>```

Please suggest your views for the soln approach.

答:
a) Your script looks good to me. You want to just add authentication in this script, so only that user can access the key & certificate. Also some minor changes. Please change your key, do not post your actual key on forum or any type of websites.

```<code>CREATE MASTER KEY ENCRYPTION BY
PASSWORD = '23987hxJKL#1946kcj$n44ncjhdlj'

CREATE CERTIFICATE Partner_Cert
   WITH SUBJECT = 'Certificate For Encryption',
   START_DATE = '1/1/2011',
   EXPIRY_DATE = '1/1/2100'

CREATE SYMMETRIC KEY PARTNER_ENCR_KEY
    WITH ALGORITHM = TRIPLE_DES
    ENCRYPTION BY CERTIFICATE [Partner_Cert]

GRANT CONTROL ON SYMMETRIC KEY :: Encryptmy TO myUser;
GRANT CONTROL ON CERTIFICATE::Partner_Cert  TO myUser;
</code>```

b) Yes you need backup of each key & certificate. You never know when you lose it. Itb better idea to keep backup. You can keep same key for Dev and QA, I prefer separate key for production

c) I don't know.

d) You can also use the "TRIPLE_DES_3KEY". I think "TRIPLE_DES" is also good enough.

Body:
a) Your script looks good to me. You want to just add authentication in this script, so only that user can access the key & certificate. Also some minor changes. Please change your key, do not post your actual key on forum or any type of websites.

CREATE MASTER KEY ENCRYPTION BY
PASSWORD = '23987hxJKL#1946kcj$n44ncjhdlj'

CREATE CERTIFICATE Partner_Cert
   WITH SUBJECT = 'Certificate For Encryption',
   START_DATE = '1/1/2011',
   EXPIRY_DATE = '1/1/2100'

CREATE SYMMETRIC KEY PARTNER_ENCR_KEY
    WITH ALGORITHM = TRIPLE_DES
    ENCRYPTION BY CERTIFICATE [Partner_Cert]

GRANT CONTROL ON SYMMETRIC KEY :: Encryptmy TO myUser;
GRANT CONTROL ON CERTIFICATE::Partner_Cert  TO myUser;

b) Yes you need backup of each key & certificate. You never know when you lose it. Itb better idea to keep backup. You can keep same key for Dev and QA, I prefer separate key for production

c) I don't know.

d) You can also use the "TRIPLE_DES_3KEY". I think "TRIPLE_DES" is also good enough.


问:
How can we only include ready-to-be-released features in our production releases every other week?
I'm a software developer on a fairly large agile team (we have eight developers actively making changes to a single code repository).  Every two weeks, we push a new version of our software to production.  Here's our current workflow:

When starting a new task, developers create a "feature branch" off of the main development branch (we use git) and work off this new branch

Once a developer has finished work on their task, they merge their feature branch back into the development branch

The developer merges the development branch into the QA branch.

A build is triggered off the QA branch.  The output of this build is deployed into our QA environment to allow the testers to begin their testing.

It's quite common for our testers to find issues with these new features that have been merged into the QA branch.  This means that at any given time, the QA environment likely contains several new features - some tested and bug-free, and some broken.  This makes releasing difficult because it's rare that the QA build is in a production-ready state.

To mitigate this, we've been trying to initiate a "QA freeze" which means developers don't merge our development branch into the QA branch a couple days before the release.  Bug fixes to the QA environment are made directly on the QA branch and merged down to the development branch.  Theoretically, this keeps new, broken features out of QA while still allowing us to fix issues already in QA.

While this "QA freeze" concept has been partially successful, it's hard to coordinate and people are often confused about whether they are allowed to merge to QA.  It's also been hard to set a "QA freeze" deadline - everyone likes the idea of some breathing room in between the freeze and the release, but in practice, they'd rather have their feature in the next release than respect the deadline.

Is there a better way to ensure that we have a clean build for our releases every other week?

答:
You are somewhat mapped to the Development-MAIN-Production branching model seen below. The area above MAIN is said to be the development area. The area below MAIN is the production area.

Highlights of this model which I consider relevant for you:

Your devs needs to Forward Integrate (FI) (FI = merge away from MAIN) frequently (2-3 times a week) into their DEV branches to ensure their latest changes always consider the latest overall developments.

Your devs need to Reverse Integrate (RI) (RI = merge towards MAIN) in the TEST branch only when they've reached a feature-completion milestone which they want to expose to QA and for which they're ready to provide prompt fixes in response to QA feedback. The fixes will be performed on TEST branch and immediately FI in their DEV branch.

Never RI from any DEV branch into MAIN

Always RI from TEST branch into MAIN, exclusively when your QA considers the quality of TEST being OK. Keep a high quality threshold for merging into MAIN. At the very least, your Product Manager must be able to always demo a working version of your Product from the latest commit in MAIN.

Create branches in the production area only as needed. Your build server should always tag all branches, including those from development area, and the source of any build/release should be identifiable at all times regardless of the branch it came from.

Take releases for production only from MAIN or the production area. If later you need to provide a fix for an exact released version (i.e. you can't just give the latest version from MAIN), create a branch in the production area from the MAIN tag of the faulty release, when the fix is needed. Always fix the problem on the HotFix branch and then immediately RI into MAIN and FI into TEST.

I suspect you have problems because:

Your devs RI into TEST code that is not feature-milestone complete

Your devs RI into TEST without getting the green light from QA (i.e. QA is not in control of what gets injected into TEST)

When QA reports a bug on TEST, your devs fix it on their DEV branch and then RI into TEST. This is a major bad practice because the merge will always bring in other incomplete dev crap. They should always fix it on TEST and then FI into their DEV branch. If it's not fixable on TEST, they delivered total crap in the first place and you have bigger problems.

Your devs don't FI often enough from TEST and so they destabilize TEST whenever they deliver there. It's a fine art balancing how often to FI into DEV. Postpone it too much and it will be extremely costly & risky right before delivery, which you never want. Do it too often and you don't get any actual dev work done if you overlap too much with work delivered by other people in TEST in the mean time.


问:
Advantages of extending the default Exception class
I've seen that it's possible to extend the default Exception class in PHP, enabling one to throw an IncorrectParameterTypeException exception, or a ValueOutOfRangeException exception (maybe these are bad examples of custom exceptions... I'm still learning).

But I'm just wondering, why would I want to do this? I would include "Parameter must be a string" (or whatever the error was) as the Exception's message anyway, so it's not like it's offering any new information.

Is it just a code readability thing, or am I missing something? I am just starting to learn about custom Exception classes, so I'm assuming the latter.

答:
It allows you to wrap exceptions in a more generic exception.

Let's say that you are developing a library to manage products. In order to support as many different environments as possible, you make your data access system flexible and allow the users of your library to store data in a MySQL database, an XML file and a JSON file and 'plug in' the right storage.

The code that works with the library might need to trap the exceptions that occur in your library to provide meaningful feedback. For example, it might want to 'fall back' to some local storage when the actual storage is not available. In order to do this it would need to trap every kind of exception that has to do with the storage, but might not want to trap something like a NullPointerException or ObjectIsInAnInvalidStateToBePersistedException.

Hence, you create a generic DataStorageException. Each implementation catches their own exceptions at appropriate places and wraps that exception in the generic DataStorageException. The MySQL implementation might trap a CannotConnectToServerException or InvalidUserException while the XML implementation might want to catch the DataFileNotFoundException.

The consumer of your library simply needs to catch the DataStorageExceptions and does not need to know about the implementation.

It allows you to require additional information.

You can define exceptions that require information to be passed. For example, an ArgumentOutOfRangeException could be forced by the constructor to provide the actual range that is valid. The class could then construct the message for the exception dynamically based on these values.


答:
There needn't be any trade-off. I unfortunately don't know php well enough to write in it, so I'll use pseudo-code instead. Your algorithm can look like:

```<code>if($prefix) {
    $data = $data filtered to only include items prefixed with $prefix;
    $data = $data mapped to remove $prefix;
}

if($strict) {
    $data = $data filtered to only include items where $item.$key already exists;
}

foreach($item in $data) {
    add $item to $this;
}
</code>```

This allows you to not repeat your logic or your checks, and in a language that provides you with declarative collection manipulation (like C#'s LINQ or Java 8's Stream API), would be very clean and clear.

Note that, realistically because checking booleans is so cheap, this would probably still be less performant than your version, but that's just because you chose an operation that's so cheap as to be pointless to optimize. Hopefully this addresses a more general point of performance vs cleanliness: often, it's illusive.

Title: Fundamental issues of programming

Body:
There needn't be any trade-off. I unfortunately don't know php well enough to write in it, so I'll use pseudo-code instead. Your algorithm can look like:

if($prefix) {
    $data = $data filtered to only include items prefixed with $prefix;
    $data = $data mapped to remove $prefix;
}

if($strict) {
    $data = $data filtered to only include items where $item.$key already exists;
}

foreach($item in $data) {
    add $item to $this;
}

This allows you to not repeat your logic or your checks, and in a language that provides you with declarative collection manipulation (like C#'s LINQ or Java 8's Stream API), would be very clean and clear.

Note that, realistically because checking booleans is so cheap, this would probably still be less performant than your version, but that's just because you chose an operation that's so cheap as to be pointless to optimize. Hopefully this addresses a more general point of performance vs cleanliness: often, it's illusive.


答:
Its useful in that you can then add extra information that the base exception class does not hold.

So you can create a NetworkException class and that would contain information about the socket error code and/or the destination connection address or whatever you liked. Callers can catch this and present better information for diagnosis of the error.

However you now start to get into an analysis issue - why bother writing all that info and a new exception class when chances are, the caller who catches your exception will just write all that custom info into a string and dump it into log file or display it as 'detailed information' to the user - you might as well write it to the base classes string member and have done with it, save everyone a load of hassle.

But, if you did have a custom exception class, the client can catch only those that they care about and let others continue up the call stack for someone else to handle - eg the caller might catch a NetworkException when the user clicks connect, but let an OutOfMemoryException continue and .. well, usually crash the client.

So its a bit of one of those areas where you have to think hard about the design, and often no answer you come up with is the "right" one, any are just as good. (for example, I have a tool written in C#, and there are lots and lots of Microsoft exception classes that I might catch... although I do catch a few special exception classes for certain circumstances, I still tend to catch all of them and print out the base class message anyway (or worse - the innerexception message, don't go there). This is a admin tool so writing out every exception message is what I need, and every Microsoft exception contains a message with the details I want to log so I really don't care about the exception class!

so its up to you, though I would advise against creating a huge inheritance hierarchy of every possible error, that way lies a lot of maintenance and documentation trouble.

Title: Advantages of extending the default Exception class

Body:
I've seen that it's possible to extend the default Exception class in PHP, enabling one to throw an IncorrectParameterTypeException exception, or a ValueOutOfRangeException exception (maybe these are bad examples of custom exceptions... I'm still learning).

But I'm just wondering, why would I want to do this? I would include "Parameter must be a string" (or whatever the error was) as the Exception's message anyway, so it's not like it's offering any new information.

Is it just a code readability thing, or am I missing something? I am just starting to learn about custom Exception classes, so I'm assuming the latter.


答:
The reason you're getting these problems is because your code released to QA is not good enough quality (and is anyones?!), so you need to start getting a better release to QA so they do not need to receive bigfixes so often. the simplest way to do this is to introduce an intermediary branch you release to (lets call it test). This is still under the development remit, but it allows developers to push to it to continue working, while also having an integrated branch that should be good enough quality to be sent to QA.

Integration testing can take place on this branch in order to find the bugs QA are currently finding, bugs can be fixed on the original branch and then merged in again, and again until right or bugs can be fixed on this branch directly (I recommend the former). Once its passed a load of basic tests, it can then be sent to QA for the 'user sticky fingers and the they-did-what?' testing.

So this approach is designed to protect the QA branch from broken development features - whether that's because the feature wasn't coded well enough or whether there were unexpected integration issues doesn't matter. Only dev branches that pass the integration testing get to be promoted to QA.

Title: How can we only include ready-to-be-released features in our production releases every other week?

Body:
I'm a software developer on a fairly large agile team (we have eight developers actively making changes to a single code repository).  Every two weeks, we push a new version of our software to production.  Here's our current workflow:

When starting a new task, developers create a "feature branch" off of the main development branch (we use git) and work off this new branch

Once a developer has finished work on their task, they merge their feature branch back into the development branch

The developer merges the development branch into the QA branch.

A build is triggered off the QA branch.  The output of this build is deployed into our QA environment to allow the testers to begin their testing.

It's quite common for our testers to find issues with these new features that have been merged into the QA branch.  This means that at any given time, the QA environment likely contains several new features - some tested and bug-free, and some broken.  This makes releasing difficult because it's rare that the QA build is in a production-ready state.

To mitigate this, we've been trying to initiate a "QA freeze" which means developers don't merge our development branch into the QA branch a couple days before the release.  Bug fixes to the QA environment are made directly on the QA branch and merged down to the development branch.  Theoretically, this keeps new, broken features out of QA while still allowing us to fix issues already in QA.

While this "QA freeze" concept has been partially successful, it's hard to coordinate and people are often confused about whether they are allowed to merge to QA.  It's also been hard to set a "QA freeze" deadline - everyone likes the idea of some breathing room in between the freeze and the release, but in practice, they'd rather have their feature in the next release than respect the deadline.

Is there a better way to ensure that we have a clean build for our releases every other week?


问:
Algorithm to determine best combination of keeping students together in their camp rooms
I have a problem I'd like to solve and am not sure whether there is a known algorithm or how the best way to approach it would be.

Say for example there is a class of 30 students who are going on a school camp. They will each share a room with other students. Each student can provide a list of 3 friends that they ideally want to share a room with.

I'd like to know if there is a programmatic way to determine the best outcome for keeping students together with who they requested to go with?

There is also another complication here, being that there are x amount of rooms, each room allowing a varying amount of students per room (up to 7).

答:
Wow, not easy task, since basically the number of possible results grows with the formula

Total = M! / (n! * (M - n)!) (Combination without repetition)

For 6 kids in two rooms of three, is already 120 possibilities. Just do the math for your numbers  and you will clearly see you need another approach.

This type of problem is what is call an NP-Hard. If you find a solution, you will never be sure that is the best till you try all the possibilities.

You can read a bit about genetic algorithms, that basically what it does is randomize the selection using ideas similar to the, yep!, genetics.

You will also need a goodness function, to understand when one solution is better than other.

Another approach is to analyze your population and find if you can find rules to distribute them. E.g Males vs females, with this you already divide your problem in half.

Different courses, ages, likeness, etc...

Im trying to make an algorithm, if I found an acceptable solution, I will let you know!


答:
As I understand the question you have two problems. (a) broken features are being merged in with the good features you want to release; (b) you want to be able to release the good features while holding back the broken ones. As a constraint on possible solutions, I assume you want your final/official QA testing to happen on an integrated branch that contains all the features slated for the next release.

Regardless of your SCM branching model, I suggest you try one or both of the following:

Assign a QA resource to each feature team. Have them do some feature
testing   on builds from the feature branch, and give them authority
to decide when a   feature is good enough to merge. Ideally, have
them work collaboratively with (the rest of) the feature team, so
stuff is tested shortly after being written. (Note this does not
mean they have to do all the testing themselves.)

Use feature toggles, either instead of feature branches or in
addition to them. Done right, feature toggles allow you to turn off
a broken feature without trying to un-merge it from the code, so you
can test and release the other features. The kind of toggle I'm
talking about is not accessible by customers; you don't want an
exponentially rising number of combinations to test. You set the
toggles on the QA branch to match the features you're planning to
release, and if the plan changes because a feature isn't ready, you
change that toggle.


问:
Model-View-Controller design question (One vs. multiple models for multiple view+controller)
I have an issue with shared code in a MVC application. Application controllers/views ABC are different classes but use a common framework. It is a single class reused multiple times.

Let me introduce exhibit A, which shows a mock-up of the application's A's main window.

There are two main points of interest. To the left there is a table view, which shows a number of available rubber ducks. Each rubber duck has a number of attributes, which are not editable and mainly used to sort the table. To the right is a screen where you can, in this case, edit the appearance of the selected rubber duck. The table is used to select which entry should be shown here.

The real table view is a lot more complicated than just a standard QTableView,  It has an own controller class, a view class, and right now an own model class.

Also the application has a controller, view and model. The table view model is initialized from the main application model when the application inits. Removal/Insertion of items is not a use case.

Let me introduce exhibit B, which is a new application sharing the table view.

Application B contains the same listview, but here the right view is used to compose an image of a rubber duck race. That means you can add one or more
rubber ducks from the table. Also, after application A, there have been a number of calculations resulting in more columns in the table (such as a cuteness value which can be used to sort the table).

Now since application B has entered the scene, the model needs to be adjusted to contain more values. That means we can:

share the code with application A, whose model will then be cluttered with useless (uninitialized) entries which are only used in other Applications.

clone the code with different models, which leaves us with seperate classes and code redundancy.

modify the table view to use the application's model at the cost of needing to check in the table's view which roles exist in the current model and should be displayed.

Also, there are plans for Application C which builds pairs of rubber ducks, does matchmaking (assigns a similarity score of both ducks) which should be shown in the table instead of "singular" rubber ducks. This application's model will vary greatly from the previous ones. This makes option 1 (and probably 3) rather difficult to implement.

So I prefer option 3 while my colleague disagrees, preferring separated models.

How can I accomplish what I am wanting to do?

Image attribution disclaimer:

Cyber duck image: commons.wikimedia.org/wiki/File:Cyberduck_icon.png

Duck race image: commons.wikimedia.org/wiki/File:Leichlingen_-_Entenrennen_2010_-_Rennen_13_ies.jpg

答:
How about secret option 4?

Extract the common code into helpers / base classes, and extend or include as necessary?

This removes the duplication, and avoids putting anything more than what is actually used in each model.

You end up with one model per controller, and some helpers and base classes that (provided you organized and named them carefully) will be obvious in their function.


问:
Patterns for migration to multi-tenant application
I have a complex web application that  manages stores and their customers.

The application follows a basic MVC architecture and I should migrate it to a multi-tenant application:
- I should go from one store to more stores belonging the same company

I will have a db for each store (one db with tenant_id is not an option)

I would like to keep the existing interfaces, for example customer.getOrders(). But now "customer" must search on several stores/db. This would allow me keep most of the logic and presentation

It's not clear to me how what is the best pattern from an OOP point of view.

Should I have for example an interface Customer and then 2 implementations, CustomerSingle (the existing one) and CustomerMulti that contains a collection of CustomerSingle? Is there a known software pattern for this situation?

In other words, all the original classes will be still valid in the multi tenant situation but I must "aggregate" their result.

答:
Just looking for suggestions, experiences ...

Design for the new functionality. Without the big picture how can you - much less I - assess a microscopic issue like a Customer interface.

Once you see what you need you can better assess how the existing code base might change. Once you see what needs to change you can contemplate how.

Design is everything. If you start by ripping apart your code as random thoughts cross your mind, well, you're in for a world of hurt.


问:
How often should I use try/catch statements?
Everything I've read says that they should be used when something that simply "shouldn't happen" does happen. But the thing is, there's a lot of things that could go wrong.

For example, if I'm accessing an object's property via the magic __get($property) method, it's possible that there would be no property called $property. So does this mean that I should wrap every $foo->bar in a try/catch?

And what about database queries? Do I really need to wrap every $stmt->execute() in a try/catch statement?

I feel like if I wrapped everything that could go wrong in a try/catch statement, I'd end up with several dozen try/catches per file!

答:
Everything I've read says that they should be used when something that
  simply "shouldn't happen" does happen. But the thing is, there's a lot
  of things that could go wrong.

That's about when you should throw, not when you should catch.

The point of a catch is to do something sensible when an error occurs. If you can't do anything sensible, don't catch the error. My SQL statement may fail, but I can't really do anything sensible if it does. The property I expected to be on an object may be missing, but I can't do anything sensible if it does.

On the other hand, if my connection to an external server times out, I could try again. If my client stops responding, I could disconnect it. If some unknown error occours while rendering my page, I can show an error message.

In general, the vast majority of cases are ones where there is no sensible recovery when something goes wrong. Things go wrong because of bugs in your code or configuration, and you should fix those bugs. There are a few cases where you can actually take meaningful action in the face of a bug, and those are the cases where you should catch the exceptions.


问:
Should a REST API be able to convert datetime to appropriate clients timezone?
Whilst implementing our API, the issue of datetime and timezones came up.

All dates are normalized to UTC in the database. Currently, in the non-API application, all datetimes are converted based on users preferences first before presented.

Now the same question came up for the API: should the the API be able to return the datetime appropriate for a timezone based on request semantics?

E.g. GET /posts?timezone=America/Sao_Paulo ?

Or should it still be done on whatever client is accessing the API?

Update: since it came up a few times: currently timestamps with timezone are returned (although it's always TZ offset +00:00). The format is the popular 8601: 2015-10-29T23:00:49+00:00

答:
If you already have the logic to convert datetime values to the local timezone of the user, you could offer both possibilities in your API.

If a client makes a request like GET /posts, then they get all times in the default timezone (UTC).

If a client makes a request like GET /posts?timezone=America/Sao_Paul, then all times in the reply would be adjusted to the specified timezone.

It is then up to the client implementation what they want to do with timezones.


问:
Adding centralized logging mechanism to Project (Best Practice)
I want to add a logging mechanism to my project but I am afraid to have logging code spread all over the place.

I thus had the idea of having only one class Logger responsible for writing relevant information into the log, and all the other classes A, B, ... having a Logger object and just calling the corresponding logging function in that one Logger class instead of implementing logging function in classes A, B, directly.

```<code>class A {
  public:
    Logger logger;
    ...
    void foo {
       ...
       logger.log(this);
    }
};

...

class Logger {
  public:
    void log(A a);
    void log(B b);
...

};
</code>```

Is that considered good practice or what is a clean way of doing logging without cluttering the production code?

答:
I would heavily recommend against this design. You are creating a cyclic dependency between your project's individual classes A, B, C, ... and your Logger class, which makes your Logger unusable in other projects or in components of your project which shall not depend on A, B and C. Moreover, whenever you are going to add a new class which needs logging, you will not only have to chance that class, but also the Logger. And if you ever want to put the Logger into a separated, reusable library, you get a cyclic dependency between that lib and the library where A, B, C live (luckily, in languages like C# the latter is forbidden).

That is exactly the way to the well-known "big-ball-of-mud architecture".


答:
You should return an absolute point in time, then anyone can localize that timestamp as needed. By "absolute timestamp" I mean either a UNIX timestamp or a human readable timestamp which includes the timezone in one of the standardized ISO formats, e.g. "2007-04-05T14:30Z". This can trivially be converted to a local timezone by the client as necessary.

If you want to accept a timezone parameter and localize the timestamp to that timezone that's fine, but you should still use the absolute timestamp incl. timezone in your response, e.g. "2007-04-05T16:30-02:00". Given that this value is identical to the previous non-localized one, it's pretty questionable why you'd go through the trouble of offering this parameter. The exact display format of the timestamp is ultimately up to the frontend of the client, so it'll likely post-process the value anyway.

Title: Should a REST API be able to convert datetime to appropriate clients timezone?

Body:
Whilst implementing our API, the issue of datetime and timezones came up.

All dates are normalized to UTC in the database. Currently, in the non-API application, all datetimes are converted based on users preferences first before presented.

Now the same question came up for the API: should the the API be able to return the datetime appropriate for a timezone based on request semantics?

E.g. GET /posts?timezone=America/Sao_Paulo ?

Or should it still be done on whatever client is accessing the API?

Update: since it came up a few times: currently timestamps with timezone are returned (although it's always TZ offset +00:00). The format is the popular 8601: 2015-10-29T23:00:49+00:00


问:
What was the first language to support convenient user-land recursion?
What was the first programming language to support convenient user-land recursion?

I know that early languages did not support it, but can find no specifics on when it was introduced.

答: ALGOL-60 by Dijkstra and Zonneveld.  Recursion was not part of the original specification, but Dijkstra insisted.</p>


答:
Usualy you would expect UTC from an API.

However, if your 'REST API' is just the server side part of a webpage using a javascript framework. I would argue that in fact you are returning a ViewModel and so it should contain localized strings, numbers and times.


答:
One of the design goals of Lisp was to support recursion. John McCarthy, the designer of Lisp, writes in his History of Lisp:

I spent the summer of 1958 at the IBM Information Research Department at the invitation of Nathaniel Rochester and chose differentiating algebraic expressions as a sample problem. […] In fact, the differentiation program was not implemented that summer, because FLPL [ed: a Fortran dialect] allows neither conditional expressions nor recursive use of subroutines. At this point a new language was necessary, since […] neither conditional expressions nor recursion could be implemented with machine language Fortran functions - not even with “functions” that modify the code that calls them.

– LISP prehistory - Summer 1956 through Summer 1958

The implementation of LISP began in Fall 1958. […]

[…] Anyway, I decided to write a paper describing LISP both as a programming language and as a formalism for doing recursive function theory. The paper was Recursive functions of symbolic expressions and their computation by machine, part I (McCarthy 1960).

– The implementation of LISP

Lisp and Algol were designed in parallel and were aware of each other. For example, if-then-else was proposed by McCarthy for Algol-58 and included in Algol-60. Later Lisps borrowed heavily from Algol. So it's a bit difficult to tell which came first – while the idea behind Lisp including recursion seems to be older than that idea in Algol 60, actual Algol 60 compilers were already available in 1960, well before the first complete Lisp compiler of 1962. However, it seems that Steve Russell implemented Lisp via the eval interpreter function in 1958, although good references are hard to come by.
It seems fair to say that Lisp and in Algol-60 were published at approximately the same time, even though the Lisp language is generally dated to 1958, not to 1960. In general, Lisp is considered to be the second high-level language after Fortran, predating Cobol and Algol.

In any case, Lisp took many ideas including explicit support for recursion from the 1956 Information Processing Language, an assembly-style list processing language.

Title: What was the first language to support convenient user-land recursion?

Body:
What was the first programming language to support convenient user-land recursion?

I know that early languages did not support it, but can find no specifics on when it was introduced.


问:
Does syntax really matter in a programming language?
One of my professors says "the syntax is the UI of a programming language", languages like Ruby have great readability and it's growing, but we see a lot of programmers productive with C\C++, so as programmers does it really matter that the syntax should be acceptable?

I would love to know your opinion on that.

Disclaimer: I'm not trying to start an argument. I thought this is a good topic of discussion.

Update: This turns out to be a good topic. I'm glad you are all participating in it.

答: I don't think it matters beyond personal preference.  All things (performance, capabilities, etc) being equal then I can see why one would put greater weight on a language syntax but choosing to pass over the performance of languages like c/c++ or any other language better suited for the job simply because of syntax would seem like a bad idea all around.</p>


问:
Rest api with a hello resource / main entry point
I'm designing a Rest API for our web application.

There's one idea that came to my mind today and I haven't found in recent searches: a "hello" resource, where clients are supposed to connect as the first step; it should be like the "entrance" to the whole service.

The main reason is to have a defined point where I can attach server-side logging logic; it could tell the whole application state, so that clients do not try to access several other resources that would fail; theoretically it could return a reader token that allows requests toward resources to be successful for anonymous clients.

That's almost it, quite an initial shape of idea instead of a complete one, but the idea appeals to me.

What do you think about it?

答:
One of the characteristics of a RESTful API is HATEOAS (Hypertext as the engine of application state). HATEOAS implies that "a REST client enters a REST application through a simple fixed URL" (quoted from Wikipedia). So yes, it is common to REST APIs to have a resource that clients use as the first step.

HATEOAS aims at decoupling client and server. If there were multiple entry points, then the clients would not only have to know the URI of one entry point, but the URI of all entry points. It would not be possible to change these URIs without impacting the clients. If the user should be able to choose what to do first, then the API should offer a resource containing one link for every thing the user could do first. These URIs can then change without impacting the clients.

Furthermore, a single entry point allows us to enable/disable certain functionality server-side. The clients will not access resources when they don't have the corresponding links. You are probably referring to this benefit in your question ("clients do not try to access several other resources that would fail").

You could use the entry point also to initialize a session, at least that's what I understand from your question ("attach server-side logging logic" and "return a reader token"), but be careful that keeping server-side session information might be harmful for scaleability.

ContentLicense: CC BY-SA 4.0


问:
How are abstract database interfaces written to support multiple database types?
How does one begin to design an abstract class for the larger application that can interface with several types of databases, such as MySQL, SQLLite, MSSQL etc?

What is the design pattern called and where exactly does it start?

Let's say you need to write a class that has the following methods:

```<code>public class Database {
   public DatabaseType databaseType;
   public Database (DatabaseType databaseType){
      this.databaseType = databaseType;
   }

   public void SaveToDatabase(){
       // Save some data to the db
   }
   public void ReadFromDatabase(){
      // Read some data from db
   }
}

//Application
public class Foo {
    public Database db = new Database (DatabaseType.MySQL);
    public void SaveData(){
        db.SaveToDatabase();
    }
}
</code>```

The only thing I can think of is an if statement in every single Database method:

```<code>public void SaveToDatabase(){
   if(databaseType == DatabaseType.MySQL){

   }
   else if(databaseType == DatabaseType.SQLLite){

   }
}
</code>```

答:
What you want is multiple implementations for the interface that your application uses.

like so:

```<code>public interface IDatabase
{
    void SaveToDatabase();
    void ReadFromDatabase();
}

public class MySQLDatabase : IDatabase
{
   public MySQLDatabase ()
   {
      //init stuff
   }

   public void SaveToDatabase(){
       //MySql implementation
   }
   public void ReadFromDatabase(){
      //MySql implementation
   }
}

public class SQLLiteDatabase : IDatabase
{
   public SQLLiteDatabase ()
   {
      //init stuff
   }

   public void SaveToDatabase(){
       //SQLLite implementation
   }
   public void ReadFromDatabase(){
      //SQLLite implementation
   }
}

//Application
public class Foo {
    public IDatabase db = GetDatabase();

    public void SaveData(){
        db.SaveToDatabase();
    }

    private IDatabase GetDatabase()
    {
        if(/*some way to tell if should use MySql*/)
            return new MySQLDatabase();
        else if(/*some way to tell if should use MySql*/)
            return new SQLLiteDatabase();

        throw new Exception("You forgot to configure the database!");
    }
}
</code>```

As far as a better way of setting up the correct IDatabase implementation at run time in your application, you should look into things like "Factory Method", and "Dependancy Injection".

Body:
What you want is multiple implementations for the interface that your application uses.

like so:

public interface IDatabase
{
    void SaveToDatabase();
    void ReadFromDatabase();
}

public class MySQLDatabase : IDatabase
{
   public MySQLDatabase ()
   {
      //init stuff
   }

   public void SaveToDatabase(){
       //MySql implementation
   }
   public void ReadFromDatabase(){
      //MySql implementation
   }
}

public class SQLLiteDatabase : IDatabase
{
   public SQLLiteDatabase ()
   {
      //init stuff
   }

   public void SaveToDatabase(){
       //SQLLite implementation
   }
   public void ReadFromDatabase(){
      //SQLLite implementation
   }
}

//Application
public class Foo {
    public IDatabase db = GetDatabase();

    public void SaveData(){
        db.SaveToDatabase();
    }

    private IDatabase GetDatabase()
    {
        if(/*some way to tell if should use MySql*/)
            return new MySQLDatabase();
        else if(/*some way to tell if should use MySql*/)
            return new SQLLiteDatabase();

        throw new Exception("You forgot to configure the database!");
    }
}

As far as a better way of setting up the correct IDatabase implementation at run time in your application, you should look into things like "Factory Method", and "Dependancy Injection".