答:
An O(N) algorithm would be to construct a new dictionary where the key is formed from the values that you're trying to search for.

```<code>Dictionary<string, Dictionary<string, object>> records;
Dictionary<Tuple<string,string,string>, Dictionary<string,object>> lookup;

foreach (var record in records.Values)
{
    var key = new Tuple<string,string,string>(record["Client"], record["Location"],record["Transaction"]);
    lookup[key] = record; // this assumes that the composite key is unique
}

foreach(var kvp in lookup)
{
    var key = kvp.Key;
    var altKey = new Tuple<string,string,string>(key.Item1,key.Item2,FlipTransaction(key.Item3));
    if (lookup.ContainsKey(altKey))
    {
        // lookup[altKey] contains the paired transaction.
    }
}
</code>```

FlipTransaction is a function that returns "Buy" if its argument is "Sell" or vice-versa.

You have an O(N) loop to build the new lookup dictionary and an O(N) loop to iterate through its contents.

Also, like the algorithm in the question this will find each pair twice.

Body:
An O(N) algorithm would be to construct a new dictionary where the key is formed from the values that you're trying to search for.

Dictionary<string, Dictionary<string, object>> records;
Dictionary<Tuple<string,string,string>, Dictionary<string,object>> lookup;

foreach (var record in records.Values)
{
    var key = new Tuple<string,string,string>(record["Client"], record["Location"],record["Transaction"]);
    lookup[key] = record; // this assumes that the composite key is unique
}

foreach(var kvp in lookup)
{
    var key = kvp.Key;
    var altKey = new Tuple<string,string,string>(key.Item1,key.Item2,FlipTransaction(key.Item3));
    if (lookup.ContainsKey(altKey))
    {
        // lookup[altKey] contains the paired transaction.
    }
}

FlipTransaction is a function that returns "Buy" if its argument is "Sell" or vice-versa.

You have an O(N) loop to build the new lookup dictionary and an O(N) loop to iterate through its contents.

Also, like the algorithm in the question this will find each pair twice.


问:
Two structs with the same members but different naming, is it a good idea?
I am writing a program that involves working with both polar and Cartesian coordinates.

Does it make sense to create two different structs for each kind of points, one with X and Y members and one is with R and Theta members.

Or is it too much and it is better to have just one struct with first and second as members.

What I am writing is simple and it won't change much. But I am curious what is better from a design point of view.

I am thinking the first option is better. It seems more readable and I will get the benefit of type checking.

答:
In the end, the goal of programming is to toggle transistor bits to do useful work.  But thinking at such a low level would lead to unmanageable craziness, which is why there are higher-level programming languages to help you hide the complexity.

If you just make one struct with members named first and second, then the names don't mean anything; you would essentially treat them as memory addresses.  That defeats the purpose of the high-level programming language.

Furthermore, just because they all happen to be representable as a double doesn't mean that you can use them interchangeably.  For example, θ is a dimensionless angle, whereas y has length units.  Since the types are not logically substitutable, they should be two incompatible structs.

If you really need to play memory-reuse tricks — and you almost certainly shouldn't — you can use a union type in C to make your intention clear.

ContentLicense: CC BY-SA 3.0


问:
Do licenses matter if there's nobody around to enforce them?
Suppose that the original creators can't (or won't) enforce a license on their software/code, but that work is still popular.

I guess if you want to visualize it, I'll throw out a convoluted hypothetical:

Imagine a very small group of developers that released a code project under an open-source license. The repository was hosted on their servers. However, everybody on the immediate development team passed away in a tragic accident or something. Their servers shut down after this happened. The project had a fairly large user base, and so others began to host the last revision on their own servers for others to download.

(Yes, I have an active imagination)

Does abiding by the license simply become a matter of morality by its users, or can there still exist a legal penalty when there is no one user or group to enforce it? Could anything be done if an unscrupulous user decided to branch off the project and use it under a different license?

I am not looking for legal advice -- I am simply curious about how software licenses work. I tend to think of strange situations and wonder what would happen in those scenarios.

答: Software Licenses work on basis of FEAR. Suppose you alter the code which was not supposed to be changed and distribute it, no one is going to find that out easily and you are presumably safe BUT once you are found out it is going to cost you a few million dollars to settle the matter. </p>

ContentLicense: CC BY-SA 2.5


问:
Are there any significant disadvantages to depending upon abstractions?
I was reading this wiki on the Stable Abstractions Principle (SAP).

The SAP states that the more stable a package the more abstract it should be. This implies that if a package is less stable (more likely to change) then it should be more concrete. What I don't really understand is why this should be the case. Surely in all cases regardless of stability we should be depending upon abstractions and hiding the concrete implementation?

答:
Because of YAGNI.

If you currently have only one implementation of one thing, why bothering with an extra and useless layer ? It will only lead to unnecessary complexity. Even worse, sometimes you provide an abstraction thinking to the day a second implementation will come... and this day never happens. What a waste of work !

I also think the real question to ask itself is not "Do I need to depend on abstractions ?" but rather "Do I need modularity ?". And modularity is not always needed, see below.

In the company I am working, some of the softwares I develop are strongly tied to some hardware device with which it must communicate. These devices are developed to fulfill very specific goals and are everything but modular. :-)
Once the first produced device goes out of the factory and is installed somewhere, both its firmware and hardware can never change, ever.

So, I can be sure that some parts of the software will never evolve. These parts don't need to depend on abstractions since it exists only one implementation and this one will never change. Declaring abstractions on these parts of code will only confuse everyone and take more time (without producing any value).


问:
Using compound statements ("{" ... "}" blocks) to enforce variable locality

Introduction

Many "C-like" programming languages use compound statements (code blocks specified with "{" and "}") to define a variables scope.

Here is a simple example.

```<code>for (int i = 0; i < 100; ++i) {
    int value = function(i); // Here 'value' is local to this block
    printf("function(%d) == %d\n", i, value);
}
</code>```

This is good because it limits the scope of the value to where it is used. It is hard for programmers to use value in ways that they are not meant to because they can only access it from within its scope.

I am almost all of you are aware of this and agree that it is good practice to declare variables in the block they are used to limit their scope.

But even though it is an established convention to declare variables in their smallest possible scope it is not very common to use an naked compound statement (that is an compound statement that is not connected to an if, for, while statement).

Swapping the values of two variables

Programmers often write the code like this:

```<code>int x = ???
int y = ???

// Swap `x` and `y`
int tmp = x;
x = y;
y = tmp;
</code>```

Would it not be better to write the code like this:

```<code>int x = ???
int y = ???

// Swap `x` and `y`
{
    int tmp = x;
    x = y;
    y = tmp;
}
</code>```

It looks quite ugly but I think that this is a good way to enforce variable locality and make the code safer to use.

This does not only apply to temporaries

I often see similar patterns where a variable is used once in a function

```<code>Object function(ParameterType arg) {
    Object obj = new Object(obj);
    File file = File.open("output.txt", "w+");
    file.write(obj.toString());

    // `obj` is used more here but `file` is never used again.
    ...
}
</code>```

Why don't we write it like this?

```<code>RET_TYPE function(PARAM_TYPE arg) {
    Object obj = new Object(obj);
    {
       File file = File.open("output.txt", "w+");
       file.write(obj.toString());
    }

    // `obj` is used more here but `file` is never used again.
    ...
}
</code>```

Summary of question

It is hard to come up with good examples. I am sure that there are betters ways to write the code in my examples but that is not what this question is about.

My question is why we do not use "naked" compound statements more to limit the scope of variables.

What do you think about using a compound statement like this

```<code>{
    int tmp = x;
    x = y;
    y = z;
}
</code>```

to limit the scope of tmp?

Is it good practice? Is it bad practice? Explain your thoughts.

答:
Yes, naked blocks may limit variable scopes further than you would normally limit them. However:

The only gain is an earlier end of the variables lifetime; you can easily, and entirely unobstrusively limit the beginning of its lifetime by moving the declaration down to the appropriate place. This is common practice, so we are already halfway of where you can get with naked blocks, and this half way comes for free.

Typically, each variable has its own place where it ceases to be useful; just like each variable has its own place where it should be declared. So, if you wanted to limit all variables scopes as much as possible, you would end up with a block for every single variable in many cases.

A naked block introduces additional structure to the function, making its operation harder to grasp. Together with point 2, this can render a function with fully restricted scopes pretty near unreadable.

So, I guess, the bottom line is that naked blocks simply don't pay off in the vast majority of cases. There are cases, where a naked block may make sense because you need to control where a destructor gets called, or because you have several variables with nearly identical end of use. Yet, especially in the later case you should definitely think about factoring the block out into its own function. The situations that are best solved by a naked block are extremely rare.


问:
Should a parent CSS class be added to the markup or @extended?
Reading SASS basic features on their website, I stumbled upon the @extend feature.

The example they give is the following:

```<code>.message {
    border: 1px solid #ccc;
    padding: 10px;
    color: #333;
}

.success {
    @extend .message;
    border-color: green;
}

.error {
    @extend .message;
    border-color: red;
}

.warning {
    @extend .message;
    border-color: yellow;
}
</code>```

That compiles to

```<code>.message, .success, .error, .warning {
    border: 1px solid #cccccc;
    padding: 10px;
    color: #333;
}

.success {
    border-color: green;
}

.error {
    border-color: red;
}

.warning {
    border-color: yellow;
}
</code>```

Thus with this snippet of HTML

```<code><div class="success">hello world</div>
</code>```

you style your element with properties of .message and .success. However I feel this way of writing HTML (and CSS) very poor, in terms of semantic (you don't explicitly see from the markup above that the element has also the styling of .message).

Shouldn't the snippet above be

```<code><div class="message success">hello world</div>
</code>```

?

I feel it to be more descriptive, and more easily reusable. For example I could assign the .success class (as written in the above CSS but without the @extend) to other elements which are not messages, and so using the class as a modifier, in a BEM-fashion.

So my question is, is the SASS example approach more desiderable than mine?

答:
Coming back a year later, I now support the exactly opposite view: @extend is usually better than filling your markup with classes.

Let's take for example this code

```<code>.component1 {
   font-family: 'custom font', sans-serif;
   text-transform: capitalize;
   border: 2px dashed red;
}
.component2 {
   font-family: 'custom font', sans-serif;
   text-transform: capitalize;
   text-align: center;
   padding: 10px;
}

<div class="component1"></div>
<div class="component2"></div>
</code>```

I notice component1 and component2 share a common style, that could potentially be used in other components as well: it's a good candidate for a separate class (by the DRY principle),

```<code>.utility1 {
   font-family: 'custom font', sans-serif;
   text-transform: capitalize;
}
.component1 {
   border: 2px dashed red;
}
.component2 {
   padding: 10px;
}

<div class="component1 utility1"></div>
<div class="component2 utility1"></div>
</code>```

But this code brings at least 2 new problems in town:

If I'm coding sensically, component1 and component2 styles will live in different stylesheets. This means that by looking at component1.css, I can see all the styles that are going to be applied to the component, except this is not the case anymore: utility1, which will probably reside is a separate stylesheet, changes the styles of the component without any explicit reference to it in the component own stylesheet.

Another way to see this is that you are not tying the utility1 styles to component1, but you leave them as separate entities that could as well live separately, yet this is a false assumption because component1 needs always those styles, and can't live without (it's not a state like a modifier class, it's part of its very own visual nature).

Even worse, this reference is moved into the markup.

In the question, I talk about semantics, but while in the case of a modifier class (i.e. --active, --hidden, --warning/--error/--success), an extra class in the markup will actually provide additional semantic information on the component, it isn't the case here. utility1 is a purely styling hook, and styling has no place in the page markup except for stylesheets declarations in the  section. Putting utility1 in the component markup is no different from styling things from the style attribute. You're relying on markup code to change the visual styles of your components, and that's no good.

I understand these views are not absolutely shared or right (there is not such a thing as an absolute truth in coding, yet we can agree on some general principles), because there are school of thought that sees styling from markup as completely legit.

Body:
Coming back a year later, I now support the exactly opposite view: @extend is usually better than filling your markup with classes.

Let's take for example this code

.component1 {
   font-family: 'custom font', sans-serif;
   text-transform: capitalize;
   border: 2px dashed red;
}
.component2 {
   font-family: 'custom font', sans-serif;
   text-transform: capitalize;
   text-align: center;
   padding: 10px;
}

<div class="component1"></div>
<div class="component2"></div>

I notice component1 and component2 share a common style, that could potentially be used in other components as well: it's a good candidate for a separate class (by the DRY principle),

.utility1 {
   font-family: 'custom font', sans-serif;
   text-transform: capitalize;
}
.component1 {
   border: 2px dashed red;
}
.component2 {
   padding: 10px;
}

<div class="component1 utility1"></div>
<div class="component2 utility1"></div>

But this code brings at least 2 new problems in town:

If I'm coding sensically, component1 and component2 styles will live in different stylesheets. This means that by looking at component1.css, I can see all the styles that are going to be applied to the component, except this is not the case anymore: utility1, which will probably reside is a separate stylesheet, changes the styles of the component without any explicit reference to it in the component own stylesheet.

Another way to see this is that you are not tying the utility1 styles to component1, but you leave them as separate entities that could as well live separately, yet this is a false assumption because component1 needs always those styles, and can't live without (it's not a state like a modifier class, it's part of its very own visual nature).

Even worse, this reference is moved into the markup.

In the question, I talk about semantics, but while in the case of a modifier class (i.e. --active, --hidden, --warning/--error/--success), an extra class in the markup will actually provide additional semantic information on the component, it isn't the case here. utility1 is a purely styling hook, and styling has no place in the page markup except for stylesheets declarations in the <head> section. Putting utility1 in the component markup is no different from styling things from the style attribute. You're relying on markup code to change the visual styles of your components, and that's no good.

I understand these views are not absolutely shared or right (there is not such a thing as an absolute truth in coding, yet we can agree on some general principles), because there are school of thought that sees styling from markup as completely legit.


问:
Any benefits of splitting web project stylesheets?
Regarding the fact that C in CSS stands for Cascade, so generally speaking rules described in one file can modify/subsitute rules in other files, can we claim that all project css files should be concatenated to a single file in most cases.

Because browser still won't get all style computed till all rules will be taken into consideration.

In other words, is there any sense in parallelizing download of styles for web project. What will be the rule of thumb to decide whether css  file should be splitted into multiple or vice versa?

May be, say, we can claim that there are "crucial" css properties - like dimensions, paddings and margins - and less crucial - like colors, transitions etc.? And that less crucial styles could be downloaded as a separate resource?

答:
One reason to keep multiple CSS files in the development environment is that one part of the style is common for all (or many) web pages and other parts differ per web page. For example, an application may support multiple brands. One css file contains the styles common for all brands and there are brand-specific styles.

You could also have separate style sheets per logical unit, e.g. a style sheet for styling customer data, one for styling an image gallery etc. When multiple developers need to adapt the styles simultaneously, the chance that they need the same file (and thus need to merge often) decreases.

However, in most cases, style sheets are concatenated and minified in the production environment.

One reason why it may be good to keep the files separate in the production environment is that the css file that is reused on multiple pages can be cached. When loading a page, only the page-specific style sheet needs to be downloaded. You have one more file to download, but less data to download in total. In many cases, the size of a style sheet is relatively small and the benefit of a cached style sheet is too small to justify the extra request.


答:
Firstly, have both explicitly, as per @Kilian-foth's entirely sound answer.

However, I'd like to add:

Ask: Do you really have operations that are generic to both when considered as pairs of double? Note this not the same as saying that you have operations that apply to both in their own terms. For example 'plot(Coord)' cares whether the Coord is Polar or Cartesian. In the other hand, persisting to file just treats the data as it is.
If you do really have generic operations, consider either defining a base class, or defining a converter to a std::pair<double, double> or tuple or whatever you have in your language.

Further, one approach might be to treat one Coordinate type as more fundamental and the other as merely support for user or external interaction.

So you might ensure all fundamental operations are coded for Cartesian and then provide support for converting Polar to Cartesian. This avoids implementing different versions of many operations.

Title: Two structs with the same members but different naming, is it a good idea?

Body:
I am writing a program that involves working with both polar and Cartesian coordinates.

Does it make sense to create two different structs for each kind of points, one with X and Y members and one is with R and Theta members.

Or is it too much and it is better to have just one struct with first and second as members.

What I am writing is simple and it won't change much. But I am curious what is better from a design point of view.

I am thinking the first option is better. It seems more readable and I will get the benefit of type checking.


问:
Create separate GIT repository for publishing with different history?
I'm developing a project, which I'm pushing to private repository on my VPS. However, I'd like to publish it on GitHub.

I make a lot of commits(mostly as backups) which doesn't contain complete implementation of feature. I do not want to include history of these commits in public repo.

So, private history would look like:

Initial commit

Part Feature A

Part Feature A

Part Feature A

Finished Feature A

Part Feature B

Finished Feature B

... etc ...

And desired history of public repo would look like:

Initial commit

Feature A

Feature B

... etc ...

And there must be no track about partial commits made for development backup. So all internals of a GIT repository would look like there were only just Feature commits, no partial commits.

I know, that I can clone repositories to different folders, and copy-paste between these folders. However, GIT is designed for distributed development. So, I'm wondering whether there's some cleaner and more GIT-like way to solve this.

How to manage separate repositories with different histories?

The first commit on public repo can be completly squeezed, but since then I would like to have a nice commit history in public repo.

答:
Use the Gitflow Workflow

Following this model, the master branch contains only releases, the develop branch contains the WIP (work in progress) commits, and feature branches are used to develop features.

The main benefit of this approach is, if you screw up and publish a bad commit to develop you'll be able to rollback the changes without screwing up the the history of the publicly accessible version on master.

So, that doesn't answer your question...

What about combining partial features into a single feature commit?

Simple, before merging a feature branch into develop squash the commits using interactive rebase.

```<code>git rebase -i feature-branch
</code>```

It'll pop up an editor and you can change which commits you want to squash. It also concats the commit logs so you can add all/part of them into the squashed commit message.

Note: There are many ways to squash commit history. IMHO, I think interactive rebase is the most straight-forward but YMMV.

When you're ready for a release, simply create a release branch from develop and merge the release branch into `master.

Developing features can be challenging because a maintainer may require a contributor to make additional changes piecemeal prior to accepting a PR (pull request).

Using the strategy above, the contributor will still have a granular history containing all of the changes made to the feature throughout development. This makes it easy to roll-back and/or cherry-pick commits individually.

Note: The ability to cherry-pick commits is extremely valuable if the contributor runs into complicated merge conflicts.

If you want features to commit cleanly, simply have the contributor squash the changes as the last step prior to a merge.

Body:
Use the Gitflow Workflow

Following this model, the master branch contains only releases, the develop branch contains the WIP (work in progress) commits, and feature branches are used to develop features.

The main benefit of this approach is, if you screw up and publish a bad commit to develop you'll be able to rollback the changes without screwing up the the history of the publicly accessible version on master.

So, that doesn't answer your question...

What about combining partial features into a single feature commit?

Simple, before merging a feature branch into develop squash the commits using interactive rebase.

git rebase -i feature-branch

It'll pop up an editor and you can change which commits you want to squash. It also concats the commit logs so you can add all/part of them into the squashed commit message.

Note: There are many ways to squash commit history. IMHO, I think interactive rebase is the most straight-forward but YMMV.

When you're ready for a release, simply create a release branch from develop and merge the release branch into `master.

Developing features can be challenging because a maintainer may require a contributor to make additional changes piecemeal prior to accepting a PR (pull request).

Using the strategy above, the contributor will still have a granular history containing all of the changes made to the feature throughout development. This makes it easy to roll-back and/or cherry-pick commits individually.

Note: The ability to cherry-pick commits is extremely valuable if the contributor runs into complicated merge conflicts.

If you want features to commit cleanly, simply have the contributor squash the changes as the last step prior to a merge.


答:
Once you start to sell your application there might be a little something in the contract saying that you 'own' the code you're selling.

Not owning the code can have nasty side effects like a breach of contract.

Title: Do licenses matter if there's nobody around to enforce them?

Body:
Suppose that the original creators can't (or won't) enforce a license on their software/code, but that work is still popular.

I guess if you want to visualize it, I'll throw out a convoluted hypothetical:

Imagine a very small group of developers that released a code project under an open-source license. The repository was hosted on their servers. However, everybody on the immediate development team passed away in a tragic accident or something. Their servers shut down after this happened. The project had a fairly large user base, and so others began to host the last revision on their own servers for others to download.

(Yes, I have an active imagination)

Does abiding by the license simply become a matter of morality by its users, or can there still exist a legal penalty when there is no one user or group to enforce it? Could anything be done if an unscrupulous user decided to branch off the project and use it under a different license?

I am not looking for legal advice -- I am simply curious about how software licenses work. I tend to think of strange situations and wonder what would happen in those scenarios.


问:
Is opening a templating engine to users a bad idea?
My site allows users to create custom HTML templates for their profiles (very much like Tumblr and the theme system), and I picked the Twig template engine for the site.

However, I'm not sure if it's a good idea to give users the control of being able to access a template engine.

Is this a bad thing? How should I restrict access, or should I just totally rethink the strategy?

答:
From the Twig homepage:

Secure: Twig has a sandbox mode to evaluate untrusted template code. This allows Twig to be used as a template language for applications where users may modify the template design.

and farther down:

Sandboxing: Twig can evaluate any template in a sandbox environment where the user has access to a limited set of tags, filters, and object methods defined by the developer. Sandboxing can be enabled globally or locally for just some templates:

```<code> {{ include('page.html', sandboxed = true) }}
</code>```

So, all you have to do is sandbox the user templates and you should be fine

Body:
From the Twig homepage:

Secure: Twig has a sandbox mode to evaluate untrusted template code. This allows Twig to be used as a template language for applications where users may modify the template design.

and farther down:

Sandboxing: Twig can evaluate any template in a sandbox environment where the user has access to a limited set of tags, filters, and object methods defined by the developer. Sandboxing can be enabled globally or locally for just some templates:

 {{ include('page.html', sandboxed = true) }}

So, all you have to do is sandbox the user templates and you should be fine


答:
Yes, naked blocks are very rarely seen, and I think that's because they are very rarely needed.

One place I do use them myself is in switch statements:

```<code>case 'a': {
  int x = getAmbientTemperature();
  int y = getBackgroundIllumination();
  setVasculosity(x * y);
  break;
}
case 'b': {
  int x = getUltrification();
  int y = getMendacity();
  setVasculosity(x + y);
  break;
}
</code>```

I tend to do this whenever I'm declaring variables within the branches of a switch, because it keeps the variables out of scope of subsequent branches.

Title: Using compound statements ("{" ... "}" blocks) to enforce variable locality

Body:
Introduction

Many "C-like" programming languages use compound statements (code blocks specified with "{" and "}") to define a variables scope.

Here is a simple example.

```<code>for (int i = 0; i < 100; ++i) {
    int value = function(i); // Here 'value' is local to this block
    printf("function(%d) == %d\n", i, value);
}
</code>```

This is good because it limits the scope of the value to where it is used. It is hard for programmers to use value in ways that they are not meant to because they can only access it from within its scope.

I am almost all of you are aware of this and agree that it is good practice to declare variables in the block they are used to limit their scope.

But even though it is an established convention to declare variables in their smallest possible scope it is not very common to use an naked compound statement (that is an compound statement that is not connected to an if, for, while statement).

Swapping the values of two variables

Programmers often write the code like this:

```<code>int x = ???
int y = ???

// Swap `x` and `y`
int tmp = x;
x = y;
y = tmp;
</code>```

Would it not be better to write the code like this:

```<code>int x = ???
int y = ???

// Swap `x` and `y`
{
    int tmp = x;
    x = y;
    y = tmp;
}
</code>```

It looks quite ugly but I think that this is a good way to enforce variable locality and make the code safer to use.

This does not only apply to temporaries

I often see similar patterns where a variable is used once in a function

```<code>Object function(ParameterType arg) {
    Object obj = new Object(obj);
    File file = File.open("output.txt", "w+");
    file.write(obj.toString());

    // `obj` is used more here but `file` is never used again.
    ...
}
</code>```

Why don't we write it like this?

```<code>RET_TYPE function(PARAM_TYPE arg) {
    Object obj = new Object(obj);
    {
       File file = File.open("output.txt", "w+");
       file.write(obj.toString());
    }

    // `obj` is used more here but `file` is never used again.
    ...
}
</code>```

Summary of question

It is hard to come up with good examples. I am sure that there are betters ways to write the code in my examples but that is not what this question is about.

My question is why we do not use "naked" compound statements more to limit the scope of variables.

What do you think about using a compound statement like this

```<code>{
    int tmp = x;
    x = y;
    y = z;
}
</code>```

to limit the scope of tmp?

Is it good practice? Is it bad practice? Explain your thoughts.

Body:
Yes, naked blocks are very rarely seen, and I think that's because they are very rarely needed.

One place I do use them myself is in switch statements:

case 'a': {
  int x = getAmbientTemperature();
  int y = getBackgroundIllumination();
  setVasculosity(x * y);
  break;
}
case 'b': {
  int x = getUltrification();
  int y = getMendacity();
  setVasculosity(x + y);
  break;
}

I tend to do this whenever I'm declaring variables within the branches of a switch, because it keeps the variables out of scope of subsequent branches.


问:
How can we keep track of which version of our code is in each environment?
My team currently uses a fairly simple branching/deployment process that looks like this:

```<code>                ┌────────┐ ┌────┐ ┌──────┐
 Environments:  │  DEV   │ │ QA │ │ PROD │
                └────────┘ └────┘ └──────┘

                     ▲       ▲       ▲
                     │       │       │

                ┌────────┐ ┌────┐ ┌──────┐
 Builds:        │  DEV   │ │ QA │ │ PROD │
                └────────┘ └────┘ └──────┘

                     ▲       ▲       ▲
                     │       │       │

                ┌────────┐ ┌────┐ ┌──────┐
 Branches:      │ master │ │ qa │ │ prod │
                └────────┘ └────┘ └──────┘
</code>```

Each environment has its own branch (we use git) and its own build that uses that branch.  When we want to promote from one environment to another, for example, from DEV to QA, we merge the master branch into qa and kick off a new QA build (which is then automatically deployed to the QA environment).

We're considering moving to a new process that would do away with having a dedicated branch and build for each environment.  Instead, a single release build would create a "deployment package" which could then be deployed to any environment.  We're imagining a typical workflow would look something like this:

```<code>                ┌────────┐     ┌────┐     ┌──────┐
 Environments:  │  DEV   │ ──► │ QA │ ──► │ PROD │
                └────────┘     └────┘     └──────┘

                      ▲
                       \

                        ┌───────────────┐
 Builds:                │ release build │
                        └───────────────┘

                                ▲
                                │

                ┌────────┐ ┌─────────┐
 Branches:      │ master │ │ release │
                └────────┘ └─────────┘
</code>```

Promoting from one environment to another would no longer be handled in source control; rather, we'd just take the already-built binaries (the "deployment package") and drop that on the new environment.

This new system would allow us to deploy any build to any environment, which has several advantages. For example, it's trivial to test PROD bug fixes in DEV and QA.  Our current system doesn't provide an easy way to do this without rolling back a branch, which we'd obviously like to avoid.

The biggest drawback with this new system is that we no longer have an automatic way of tracking what code is in which environment.  If we need to make a fix in PROD, we no longer have a dedicated branch in sync with the current production codebase.  The same goes for QA - if we want to push a quick change to QA without dredging up in-progress work from master, we no longer have a branch that reflects the current state of the QA environment.

How can we keep track of what code is in each environment?

Some options we're considering:

utilizing git tags to keep track of which commit is in which environment

embedding the git commit used by the build into each deployment package

答: We use maven to put the version into the manifest file. Then have the application display the version if its a web app, or have a /version endpoint for web services. </p>


问:
O(1) complexity array access
I have an array of heights, with irregularly spread stations, e.g.: arrH=[100 500 1000 2500 4500]. During run-time I receive some height, h, and I need to determine which cell (index) contains the closest height to h. E.g.: h=720 -> arrH[1].
I can do any pre-processing, build any dictionary/hash table in an offline-mode.
Is there a possibility to achieve O(1) during run-time?
Thank you!

答:
If the maximum value is reasonable, then you could do it with a lookup table of length N where N is the maximum value in the array.  So, for example, your array looks like this:

```<code>[2,5,6,9]
</code>```

Then you create an array that looks like this:

```<code>[0,0,0,1,2,2,3,3,3]
</code>```

Lookups in that array is O(1)

Obviously this assumes that you will have many lookups without the array changing as I think array creation should be O(N) * O(Log(N)).

Title: O(1) complexity array access

Body:
If the maximum value is reasonable, then you could do it with a lookup table of length N where N is the maximum value in the array.  So, for example, your array looks like this:

[2,5,6,9]

Then you create an array that looks like this:

[0,0,0,1,2,2,3,3,3]

Lookups in that array is O(1)

Obviously this assumes that you will have many lookups without the array changing as I think array creation should be O(N) * O(Log(N)).


问:
Incorporating GPL content in a commercial application on iOS
Let me start by saying I do generally understand copyleft GPL, but I'm having some trouble with this particular scenario.  It's quite complicated to communicate but I'll try my best.

First I'm working on an app in iOS that supports Russian voice recognition.  The engine I use is pocketspinx which uses a BSD license so all good there.

I am trying to use within my app a voice recognition acoustic model that is distributed under GPLV2.  The model is from VoxForge.  An acoustic model is kind of like a script that tells the app how to run.

It is located here : http://www.repository.voxforge1.org/downloads/Russian/Trunk/AcousticModels/

My understanding, and please correct me if I'm wrong is that I can not distribute this acoustic model bundled in my iOS app, though I would be able to if it had been licensed as LGPL instead.  (Please tell me if this is correct)

My next question is whether I could download this acoustic model from within the iOS app and use it that way?  The user would press a big download button, the acoustic model would be downloaded and then the system would work.

Last question is if the last thing is ok, am I allowed under GPL to rehost that acoustic on my own server (for faster download speed), and would that rehosting have to open to public downloads.

答:
The GPL is not compatible with the App Store, because the store's Terms of Service impose additional restrictions which violate the GPL.  Any additional downloads or enhancements to the software would have to be done through the store, probably under the guise of "In-App Purchases."

Whether it's GPL or LGPL probably doesn't matter, as it is not the "linking provision" that is the problem here, but rather the ability of the consumer to swap out the library as he sees fit (a capability that the App Store will not give him).

Applications distributed through the Mac Store might be compatible with the GPL, since it is possible to modify and distribute the application outside of the Mac store.

Further Reading

GPL Enforcement in Apple's App Store

Is it possible to have GPL software in the Mac App Store?


答:
In the general case (that is, where Steven Burnap's small-max-height assumption doesn't hold, or alternatively where you have to accommodate floating-point values as inputs), I believe the answer to your question is no. You're describing a single pass through an algorithm that populates a histogram with nonuniform bins. (For a discussion of various tradeoffs in histogram construction, see this stackoverflow question.)

The naive implementation of a histogram-population algorithm with nonuniform bins known in advance runs in O(log n), with n the number of bins, which is equivalent to the length of arrH - this is simply binary search.

As the link above suggests, though, interpolation search will allow a best-case time of O(1) and an average time less than O(log n). Moreover, depending on how nonuniform your bin distribution is, you could achieve best-case results a large proportion of the time.

On the other hand, because "constant" doesn't necessarily mean "small", you could very well wind up doing better with the naive binary search if arrH is relatively small or your bin distribution is particularly pathological. The inflection point where interpolation search begins to do appreciably better would need to be determined via profiling.

Long story short: binary search - O(log n) - may be the best you can do, but take a look at interpolation search. Which is better will depend intimately on your data.

Title: O(1) complexity array access

Body:
I have an array of heights, with irregularly spread stations, e.g.: arrH=[100 500 1000 2500 4500]. During run-time I receive some height, h, and I need to determine which cell (index) contains the closest height to h. E.g.: h=720 -> arrH[1].
I can do any pre-processing, build any dictionary/hash table in an offline-mode.
Is there a possibility to achieve O(1) during run-time?
Thank you!


问:
A proper way to work with MVC
I got into a debate at work today, I hope you can help me to settle it up.

My colleague wants to separate UI, Model, DB, and Network like so:

Create an API level between UI and controller, that will allow the UI
to query all the models in the APP.

There will be another controller that will break the models into
their DB representations (Ex: UserTablesModel, ScoreTableModel...),
It will be a singleton called DBControler and it will
also provide some utility methods to query the DB (Ex:
insert(tableName, value...).

The ModelTables will use events hub to notify UI with state changes,
and they will be updated from the network layer using DBControler
reference.

I don't like this idea as it creates a coupling between unrelated models in the controller layer. I think it would be wiser to allow the UI to have direct access to Models (maybe make them singletons) and it's up to the model to offer a proper API to access its data and provide an events callback to notify his state change (no events hub). I like the part that models need to be directly updated from the network layer.

Also I don't like the name TableModel, I think the DB needs to be a service accessible by the model, one model can access multiple tables.

What is the proper way to work with MVC?

答:
I'd recommend Knockoutjs(simplyfy dynamic Javascript UIs), Model View-View Model(MVVM) architecture pattern.

Usually in MVC pattern, Model will hold all data, View is for UIs, and Controller will connect UI and Model.

In MVVM pattern, Model-View will display data from your database, View-Model will hold data temporarily based on UI input, once submit or save, Controller now do its work to validate and save it to your Database.

Analogy: 1. I give you candy and you hold it in your hands (MVVM) but you can

            return it to me, loop..
         2. If you eat it, and its done (Controller)

Title: A proper way to work with MVC


问:
Make a big deal out of == true?
There is a colleague of mine who constantly writes:

```<code>if (someBool == true)
</code>```

It drives me up the wall!  Should I make a big deal of it or just drop it?

答: One can develop this habit when do a lot of programming in WPF. It uses lots of bool? (nullable bool) variables to you have to write either if (someBool == true) or if (someBool ?? false)

Title: Make a big deal out of == true?


问:
How do I approach a complicated merge
Here is the deal, I have joined a new company and have been asked to finish off the work on a branch which hasn't been touched for almost a year. In the meanwhile, the master branch has been growing with a steady pace. Ideally I would like to merge all of the changes from the master branch into the feature branch and continue the work from there, but I'm not too sure how to approach this.

How do I perform this merge safely while preserving important changes on both sides of the branch?

答:
At its heart, how to combine two (possibly non-compatible) pieces of code is a development problem, not a version control problem.  The Git merge command may help in this process, but it depends on the shape of the problem.

Comparing both versions with the base first makes the most sense.  This will give you an idea of the best strategy for taking this forward.  Your approach might be different based on the nature and overlap of the changes in each branch.

Imagine the ideal scenario: you would discover that the main branch and the feature branch each only modified mutually exclusive parts of the code, so you could just commit all the changes in and be good to go.

Of course, that will almost certainly not be the case, but the question is: how far removed from this ideal scenario will it be?  i.e. how intermingled are the changes?

Also, how mature was the old feature branch?  Was it in a good working state, or not (or unknown)?  How much of the feature was finished?

If the relevant code in the main branch has changed a lot in the past year, or the feature is not in a very mature state, I might consider creating a new fork of the latest and manually incorporating the old feature in again.  This will allow you to take an incremental approach to getting it working.

If you do a messy merge of lots of code and it doesn't work, it will be quite hard to debug. If the main branch has changed a lot over the past year, major design changes may be needed to the feature to get it working.  It would not be appropriate to  make these changes via "resolve conflicts", since this would require making all the changes at once and hoping it works.  This problem would be compounded by the possibility of bugs in the old partially finished branch.

Title: How do I approach a complicated merge


问:
Eliminating the bad cases in if to get a nicer code
I have read this link Should I return from a function early or use an if statement? and it triggered a conflict in my head. I agree that it looks nicer and cleaner and I guess that would be the way I would write it. But I remember that there was something saying that we should always check the the conditions under which we should DO stuff rather than trying to eliminate all the bad cases.

```<code>if (case_that_allows_to_do_stuff1 && case_that_allows_to_do_stuff2 ) {}
</code>```

is preferable over

```<code>if (!this_case && !that_case && !oh_and_also_this_case) {}
</code>```

Is this what I am saying related to the link above or is it a separate case?

答:
we should always check the the conditions under which we should DO staff rather than trying to eliminate all the bad cases.

No.

If that were true, there would be no such thing as Guard Clauses, and guard clauses are considered a best practice.

That said, guard clauses look a bit different in Javascript than in some other programming languages, due to the presence of first-class functions and the unique role that function scoping has in Javascript.

Further Reading

Guard and Default operators in Javascript

No ifs…alternatives to statement branching in JavaScript


答:
The answers in the linked question, when taken as a whole, amount to it depends.  Often having a single point of return is preferable, but there are times when early return greatly simplifies code.  The mistake would be relying on a rote rule rather than focusing on good design.

The same applies in your case.  There is no reason to always prefer checking whether something is true rather than check whether it is false.  You need to think about what constitutes good design in any specific case.

if (!something) can be slightly less clear than if (something), particularly when checking more than a single condition.  However, refactoring the code so that all your conditionals check for truth may make the code much less understandable in practice.

As a starting point, I would try to write it in the way that I would intuitively describe what the function is doing.

Title: Eliminating the bad cases in if to get a nicer code

Body:
I have read this link Should I return from a function early or use an if statement? and it triggered a conflict in my head. I agree that it looks nicer and cleaner and I guess that would be the way I would write it. But I remember that there was something saying that we should always check the the conditions under which we should DO stuff rather than trying to eliminate all the bad cases.

```<code>if (case_that_allows_to_do_stuff1 && case_that_allows_to_do_stuff2 ) {}
</code>```

is preferable over

```<code>if (!this_case && !that_case && !oh_and_also_this_case) {}
</code>```

Is this what I am saying related to the link above or is it a separate case?


答:
The cases are related. However, neither the first nor the second approach is bad.

In an ideal scenario, your functions are no longer than a few lines, which in the end means it does not really matter whether you use the first or the second approach, as both of them are very easy to read.

The problem occurs, when you end up with a function which is really long, which usually means something isn't right in your code in the first place and should be probably refactored.

As long as you keep functions separated, simple, it's mostly up to you whether to use an early return statement or do a guard if block.

I, personally, like an early return better, because when you leave the function, you don't need to scan the rest of it wondering, whether another piece of code does not alter the result.


答:
1. Switch to the branch which is used as a main developer/release branch.

This is the branch which contains the latest changes to the system. Can be master, core, dev, it depends on the company. In your case it is probably master directly.

```<code>git checkout master
git pull
</code>```

Pull to make sure you have the latest version of the main development branch aquired.

2. Checkout and pull the branch which contains the work you are supposed to finish.

You pull to make sure you indeed have the latest contents of the branch. By checking it out directly, without creating it locally first, you ensure not to have the new contents from master (or the main dev branch respectively) in it.

```<code>git checkout <name of the obsolete branch>
git pull origin <name of the obsolete branch>
</code>```

3. Merge the main development branch to the obsolete branch.

Before running the following command, make sure, either by typing git
  branch or git status that you are on the obsolete branch.

```<code>git merge master
</code>```

The git merge command will try to merge the contents from the specified branch, in this case master, to the branch you are currently at.

Emphasis on will try to. There might be merge conflicts, which will need to be resolved by you and you only.

4. Fix the merge conflicts, commit and push the conflict fix

After fixing the merge conflict in all the files where there is, stage, commit and push the conflict resolution to origin.

```<code>git add .
git commit -m "fixed the merge conflict from the past year to update the branch"
git push
</code>```

You can generally call git add . to stage all the files for commit. When dealing with merge conflicts, you want all the necessary files to be updated.

Additional note

Resolving merge conflict can be a tedious work. Especially if you are new at a company. You might not even have the proper knowledge to resolve all the merge conflicts alone, yet.

Take your time to carefully inspect all the conflicts that have occured and fix them appropriately, before continuing your work.

It can happen so, you start working on an one year old branch, merge the current development state into it and won't have any merge conflicts at all.

This happens when even though the system has changed a lot in the year, nobody has touched the files which were actually altered in the one year old branch.

Title: How do I approach a complicated merge

Body:
Here is the deal, I have joined a new company and have been asked to finish off the work on a branch which hasn't been touched for almost a year. In the meanwhile, the master branch has been growing with a steady pace. Ideally I would like to merge all of the changes from the master branch into the feature branch and continue the work from there, but I'm not too sure how to approach this.

How do I perform this merge safely while preserving important changes on both sides of the branch?

Body:
1. Switch to the branch which is used as a main developer/release branch.

This is the branch which contains the latest changes to the system. Can be master, core, dev, it depends on the company. In your case it is probably master directly.

git checkout master
git pull

Pull to make sure you have the latest version of the main development branch aquired.

2. Checkout and pull the branch which contains the work you are supposed to finish.

You pull to make sure you indeed have the latest contents of the branch. By checking it out directly, without creating it locally first, you ensure not to have the new contents from master (or the main dev branch respectively) in it.

git checkout <name of the obsolete branch>
git pull origin <name of the obsolete branch>

3. Merge the main development branch to the obsolete branch.

Before running the following command, make sure, either by typing git
  branch or git status that you are on the obsolete branch.

git merge master

The git merge command will try to merge the contents from the specified branch, in this case master, to the branch you are currently at.

Emphasis on will try to. There might be merge conflicts, which will need to be resolved by you and you only.

4. Fix the merge conflicts, commit and push the conflict fix

After fixing the merge conflict in all the files where there is, stage, commit and push the conflict resolution to origin.

git add .
git commit -m "fixed the merge conflict from the past year to update the branch"
git push

You can generally call git add . to stage all the files for commit. When dealing with merge conflicts, you want all the necessary files to be updated.

Additional note

Resolving merge conflict can be a tedious work. Especially if you are new at a company. You might not even have the proper knowledge to resolve all the merge conflicts alone, yet.

Take your time to carefully inspect all the conflicts that have occured and fix them appropriately, before continuing your work.

It can happen so, you start working on an one year old branch, merge the current development state into it and won't have any merge conflicts at all.

This happens when even though the system has changed a lot in the year, nobody has touched the files which were actually altered in the one year old branch.


答:
In my limited git experience I can say that sometimes it's faster to restart the feature branch over again if the master has gone too far from the detach point.

Merging two branches without knowing the history behind the code (given that you've just joined the project) is really difficult, and I bet that even a developer who followed the project from the beginning would likely make some mistakes in the merge.

This of course makes sense if the feature branch is not huge, but you could simply keep the old feature branch opened, branch again from master and manually re-introduce changes that compose that feature. I know it's the most manual approach, but it allows you to be in complete control in case of missing or moved code.

Pair programming with a senior in this case would be the best case scenario, helping you to get to know the code better.

It could even turn out to be faster too, if you take into account merge conflicts and testing time!

I kinda of assumed that at least trying to do a merge is obviously the best thing to do. If that fails or turns out to be too difficult, then try the cherry picking, if that goes wrong go the manual way.

Title: How do I approach a complicated merge


问:
How to organize my module
This is currently the way I'm organizing it.

```<code>myProject/
    README
    subproject1/
        __init__.py
        classA.py
        classB.py
        driver.py
        basicTest.py
</code>```

Driver imports from classA and classB and provides some additional functionality. basicTest also imports from Driver and classA.

I've been using nosetests to discover and run all the tests from basicTest.py. That works great if I'm in the subproject1 directory. However, it doesn't work if I'm in the toplevel myProject directory. The imports fail since the relative paths are then all wrong. I need to run nosetests from the top directory since I'm integrating Travis-CI and it runs nosetests from the top level.

It seems like numpy does all imports relative to the top directory. But, then I can't run the tests from any of the subdirectories, which can be annoying.

Looking around it seems like the only way to make the tests runnable from both directories would be to mess with sys.path at the top of basicTest.py. That seems like a bad idea. This suggests what also seems to be a hacky solution.

Is there a clean solution out there, or is the best approach to just import everything relative to the root and run all the tests from there?

Update: I decided a temporary solution would be to tell Travis-CI to cd into subproject1 and then run nosetests. This required the fewest number of changes on my part to get everything working. It feels funny though and I'm still looking for a better layout.

答:
I recommend you to use py.test : it's a good testing framework

and  you have two way to structure your project, 1st one is:

```<code>myProject/
    README
    subproject1/
        __init__.py
        classA.py
        classB.py
        driver.py
        tests/
            basicTest.py
</code>```

and the 2nd one is:

```<code>myProject/
    README
    subproject1/
        __init__.py
        classA.py
        classB.py
        driver.py
    tests/
        subproject1/
            basicTest.py
        subproject2/
            test2.py
</code>```

it depends on your needs, personally I always the second method

Title: How to organize my module

Body:
I recommend you to use py.test : it's a good testing framework

and  you have two way to structure your project, 1st one is:

myProject/
    README
    subproject1/
        __init__.py
        classA.py
        classB.py
        driver.py
        tests/
            basicTest.py

and the 2nd one is:

myProject/
    README
    subproject1/
        __init__.py
        classA.py
        classB.py
        driver.py
    tests/
        subproject1/
            basicTest.py
        subproject2/
            test2.py

it depends on your needs, personally I always the second method


问:
Persistence models for Event Sourcing
I am intrigued by the Event Sourcing pattern but am struggling to design an event sourcing model and put it in concrete form.

First off, I want to make sure that I understand the main use cases of this pattern. As I understand it, one uses event sourcing is to capture state changes in your app at different points in time so that you can:

Replay events to rewind your app to a previous state; or

Replay events in another environment to recreate production at some point in time and troubleshoot it

So first off, if I have misunderstood the main use case(s) for event sourcing, or if I am missing any major ones, please begin by correcting me!

Assuming I'm more or less on track, my real mental roadblock lies with the event persistence model.

How many databases are there in an event sourcing system? Are there two databases (one for storing main entities, and another for storing the events)? Or is there just one database where all entities are the persisted events themselves?

How do you capture events (and persist them!) for things that are totally outside the app's control? For example: the state of some 3rd party API that your app integrates with, or a message broker (and the state of all its messages/queues) that your app integrates with, runtime command-line arguments passed into your app, etc.?

How does the replay mechanism actually work? So you have some entities. You have events describing state changes to those entities. You can read those events (and/or the entities they represent) out of the database, but then you need something to actually write those events somewhere else. So does this "replayer" just treat each subsequent event as an update to an existing entity?

My best attempt (thus far):

The entity(ies):

```<code>// Groovy pseudo-code
class Order {
    Long id
    Long userId
    Long paymentMethodId    // Perhaps an ID to a 3rd party system that
                            // is PCI compliant, etc.

    // Constructors, getters/setters, etc.
}

// Each 'Order' has 1+ 'OrderLineItems'
class OrderLineItem {
    Long id
    Long orderId
    Long productId    // 'Product' is yet another entity, etc.
    Integer quantity

    // Constructors, getters/setters, etc.
}
</code>```

The event:

```<code>abstract class BaseEvent<ENTITY> {
    Date occurredOn
    Date recordedOn
    ENTITY entity

    BaseEvent(ENTITY entity) {
        super()

        this.occurredOn = new Date() // now
        this.entity = entity
    }
}

class OrderEvent extends BaseEvent<Order> {
    // Perhaps some other metadata about order events

    OrderEvent(Order order) {
        super(order)
    }
}
</code>```

OK so this is a good step in the right direction, but still doesn't help me figure out how the "replay mechanism" will be able to load OrderEvents out of a database, and actually "replay them" to put another database into a particular state representing a single point in time.

答:
I want to make sure that I understand the main use cases of this pattern.

Another nice use case described by Fowler is distributed storage. A cluster of systems with in-memory databases are kept up to date with each other through a stream of events.

How many databases are there in an event sourcing system? Are there two databases (one for storing main entities, and another for storing the events)? Or is there just one database where all entities are the persisted events themselves?

Main entities and events are separate objects and both are persisted, either in the same or in different databases.

How do you capture events (and persist them!) for things that are totally outside the app's control?

You'll need to wrap any external systems with a gateway. The gateway must be able deal with any replay processing that the Event Sourcing system is doing. See sections 'External Updates/Queries/Interactions' of Fowler's description of this pattern.

How does the replay mechanism actually work?

Take Fowler's most basic example:

Each event object has a 'process' method to perform the required update.
A replay works like this:

```<code>for each Shipping Event e, in ascending order of e.occurred:
    e.process();
</code>```

Title: Persistence models for Event Sourcing

Body:
I want to make sure that I understand the main use cases of this pattern.

Another nice use case described by Fowler is distributed storage. A cluster of systems with in-memory databases are kept up to date with each other through a stream of events.

How many databases are there in an event sourcing system? Are there two databases (one for storing main entities, and another for storing the events)? Or is there just one database where all entities are the persisted events themselves?

Main entities and events are separate objects and both are persisted, either in the same or in different databases.

How do you capture events (and persist them!) for things that are totally outside the app's control?

You'll need to wrap any external systems with a gateway. The gateway must be able deal with any replay processing that the Event Sourcing system is doing. See sections 'External Updates/Queries/Interactions' of Fowler's description of this pattern.

How does the replay mechanism actually work?

Take Fowler's most basic example:

Each event object has a 'process' method to perform the required update.
A replay works like this:

for each Shipping Event e, in ascending order of e.occurred:
    e.process();


问:
What would break if there was an option to make undefined not convert to any other type in JavaScript?
The biggest issue I run into in JavaScript is silent typos. For example, the other day I had a variable inIframe. Somewhere else I typed isIFrame. 10-15 mins of debugging later I found it and changed it to inIFrame. It was yet another 5+ mins until I figured out it was still wrong. Should have been lowercase f.

That got me wondering. What would happen if there qas the option to make undefined not convert to any other type? So for example

```<code>var a;
var b = a + 1;  // currently will become NaN.
</code>```

What if I could go

```<code>"using strict undefined";
var a;
var b = a + 1;  // throws because undefine does not convert to number
</code>```

Many things would still work

```<code>function foo(options) {
  var value = options.value || 27; // the default is 27?
</code>```

Or maybe that's a conversion to bool and would be disallowed? You'd have to do

```<code>function foo(options) {
  var value = options.value !== undefined ? options.value : 27;
</code>```

I love that JavaScript is free-form but I hate every time I spent 15-30 minutes tracking down typos.

Are there things that would just totally no longer work that I'm missing and that would now be super cumbersome? Of course like shown above it would be opt-in just like "use strict" is now, so using it wouldn't break existing code.

Maybe this particular idea wouldn't solve that many issues. Is there some way to keep most of the flexibility but lower the chances for errors? Maybe something that could be proposed to standards bodies?

To be clearer as an opt in feature the suggestion wouldn't break any existing code. The question is rather would it break the language itself. Would it make some part of the language impossible to use. A quick glance seems like no it wouldn't. Certain things you'd have to do differently. If undefined does not convert then

```<code>"use strict undefined";
var obj = {};
console.log(obj.c);  // Throws, can't convert undefined to string
</code>```

would throw. But you could easily write

```<code>console.log(JSON.stringify(obj));
</code>```

If want to see all of it or

```<code>console.log((obj.c === undefined ? "not defined" : obj.c);
</code>```

or even

```<code>function unToStr(a) {
   return a === undefined "**not defined**" : a;
}

console.log(unToStr(obj.c));
</code>```

I'm not really concerned with that because that's not breaking the language. It's just requiring a little more care (about the same amount of care as say python)

I like JavaScript quite a bit but I hate when I spent 45 minutes tracking down a math bug only to find that a tiny typo has introduced NaN somewhere.

Another way to phrase this question is could this feature be introduced in ES8 or is there something about it that's fundamentally incompatible with JavaScript as a language?

答:
There are two possible cases where such typo could be an issue:

Names of variables

Such as in:

```<code>var inIframe = ...
...
console.log(isIFrame); // Throws `ReferenceError: isIFrame is not defined`
</code>```

The fact that you discover the mistake at run time can eventually be disturbing. The case is straightforward if the declaration of a variable and the use of it wrongly typed are close to each other, but could be much more problematic if the typo is buried inside conditional statements, loops and functions.

The fact is that in JavaScript, it's perfectly legal to use variables without declaring them first:

```<code>a = 5; // See, no `var` here.
console.log(a);
</code>```

But the fact that the current JavaScript interpreter doesn't check that a variable was declared before being used really doesn't matter that much: such typos are very easy to avoid by using linters.

JavaScript has a great linter tool jslint written by Douglas Crockford. The following code:

```<code>/*jslint browser: true, devel: true*/

var a = function () {
    'use strict';
    var b = 123;
    console.log(b);
};
</code>```

produces no errors, but if you change:

```<code>console.log(b);
</code>```

to:

```<code>console.log(c);
</code>```

you'll see the following errors:

Unused 'b'.

  Undeclared 'c'.

making it obvious to figure out the typo.

In your case, jslint will immediately figure out that isIFrame is unused and point you out to it. Obviously, it won't be able to understand that you wanted to write inIframe, but at least, you won't waste twenty minutes debugging your code.

See also:

An answer, which, among others, compares jsLint and jsHint and explains why jsHint should be avoided.

My article explaining why is it crucial to use linters and static checkers.

Names of properties

Such as in:

```<code>var something = {
    "inIframe": true
};

...
console.log(something.isIFrame); // Shows `undefined`
</code>```

The dynamic nature of JavaScript prevents both the interpreter and the linter from determining that something.isIFrame doesn't point to anything. In fact, there could be an isIFrame inside, coming from multiple sources, like prototypes or direct assignment. Also, something can be initialized like this:

```<code>var something = JSON.parse('{"inIframe": true}');
</code>```

where the actual string could be a result of a REST call, meaning that the interpreter (or the linter) couldn't possibly know what's inside. Google Closure Compiler may help here, but at a cost of requiring you to manually describe the structure of something, similarly to what one would do in a static strongly-typed programming language.

The next thing is to determine why is JavaScript actually returning undefined instead of throwing ReferenceError (or a similar exception) at run time when encountering an access to a property which doesn't exist.

Technically, until the apparition of proxy in ECMAScript6, nothing prevents to actually throw an exception, since, I imagine, the JavaScript engine knows that a given property doesn't exist. It should also be a possibility for the engine to make a difference between getting the property and setting it (like it's already done for variables; a = 123; is legal, but console.log(b); throws an exception).

On the other hand, the choice of actually returning undefined makes sense too, for two reasons:

If you expect isIFrame to be either false or true, receiving undefined gives you a good hint that there is something wrong with the name of the property. The same applies to most cases where you expect a value, would it be a number, a string, or an object representing some business entity.

The case which worries me much more is when, expecting a boolean, you write:

```<code>if (something.isIFrame) {
    // This will never execute, since `isIFrame` doesn't exist.
} else {
    // This will execute every time.
}
</code>```

Here, JavaScript doesn't help you much, since it silently swallows the undefined and simply executes the elseblock every time. This being said, it shouldn't take much time to figure out that there is something wrong around theif/else. The next step is to run a debugger and check for the actual values: as soon as you see theundefined` instead of a boolean, you have a hint.

You may on the other hand expect the situation where the value may simply not be here.

For instance, I'm currently working on a node.js application which receives messages about servers. Sometimes, a message is sent not by the server itself (a virtual machine), but by the host: in this case, the message contains a replacementIP property with the IP address of the concerned virtual machine.

If I want to display the IP address, all I have to do is:

```<code>var ipToDisplay = message.replacementIP || context.senderIP;
</code>```

If JavaScript was throwing exceptions when accessing non-existent property, this would force me to write this instead:

```<code>var getActualIP = function (message, context) {
    try {
        return message.replacementIP;
    } catch {
        return context.senderIP;
    }
};

[...]
var ipToDisplay = getActualIP(message, context);
</code>```

I find it much more difficult to follow.

So you have two cases here: in the first one, the choice of the designers of JavaScript appears problematic in a specific case, and causes you to launch your debugger. Not that nice, indeed. On the other hand, the second case shows that the designers' choice makes it possible to write very compact code in a lot of situations; I find it very nice.

So what about an opt-in "using strict undefined"?

Not sure it's a good idea, for the simple reason that adding features to a language should be taken very, very seriously.

Any additional feature takes literally months, and given the nature of JavaScript, would need to be implemented in every browser. As usual, the one with the name starting by “I” will be late, and so you'll find yourself including "using strict undefined" in your code, while knowing that this browser will plainly ignore it: not fun when it comes to debugging.

Compare this to, for instance, ECMAScript 6th String Interpolation feature. String interpolation brings a huge benefit in terms of code readability and maintainability: most developers who used Python or Java are familiar with this feature, and they will happily use it in JavaScript. It will break existent code, but given its importance, it's worth the risk, and worth the time spent implementing it.

Default parameter values? Same thing: great benefit for everyone, and no risk of breaking existent code.

But "using strict undefined"? I'm not convinced that the edge case illustrated below is not that important, especially since it's easy to find what's happening with the help of a debugger. If you write software for which it is not acceptable to access non-existent properties, Google Closure Compiler is an option. Switching to a different language is another option.

Body:
There are two possible cases where such typo could be an issue:

Names of variables

Such as in:

var inIframe = ...
...
console.log(isIFrame); // Throws `ReferenceError: isIFrame is not defined`

The fact that you discover the mistake at run time can eventually be disturbing. The case is straightforward if the declaration of a variable and the use of it wrongly typed are close to each other, but could be much more problematic if the typo is buried inside conditional statements, loops and functions.

The fact is that in JavaScript, it's perfectly legal to use variables without declaring them first:

a = 5; // See, no `var` here.
console.log(a);

But the fact that the current JavaScript interpreter doesn't check that a variable was declared before being used really doesn't matter that much: such typos are very easy to avoid by using linters.

JavaScript has a great linter tool jslint written by Douglas Crockford. The following code:

/*jslint browser: true, devel: true*/

var a = function () {
    'use strict';
    var b = 123;
    console.log(b);
};

produces no errors, but if you change:

console.log(b);

to:

console.log(c);

you'll see the following errors:

Unused 'b'.

  Undeclared 'c'.

making it obvious to figure out the typo.

In your case, jslint will immediately figure out that isIFrame is unused and point you out to it. Obviously, it won't be able to understand that you wanted to write inIframe, but at least, you won't waste twenty minutes debugging your code.

See also:

An answer, which, among others, compares jsLint and jsHint and explains why jsHint should be avoided.

My article explaining why is it crucial to use linters and static checkers.

Names of properties

Such as in:

var something = {
    "inIframe": true
};

...
console.log(something.isIFrame); // Shows `undefined`

The dynamic nature of JavaScript prevents both the interpreter and the linter from determining that something.isIFrame doesn't point to anything. In fact, there could be an isIFrame inside, coming from multiple sources, like prototypes or direct assignment. Also, something can be initialized like this:

var something = JSON.parse('{"inIframe": true}');

where the actual string could be a result of a REST call, meaning that the interpreter (or the linter) couldn't possibly know what's inside. Google Closure Compiler may help here, but at a cost of requiring you to manually describe the structure of something, similarly to what one would do in a static strongly-typed programming language.

The next thing is to determine why is JavaScript actually returning undefined instead of throwing ReferenceError (or a similar exception) at run time when encountering an access to a property which doesn't exist.

Technically, until the apparition of proxy in ECMAScript6, nothing prevents to actually throw an exception, since, I imagine, the JavaScript engine knows that a given property doesn't exist. It should also be a possibility for the engine to make a difference between getting the property and setting it (like it's already done for variables; a = 123; is legal, but console.log(b); throws an exception).

On the other hand, the choice of actually returning undefined makes sense too, for two reasons:

If you expect isIFrame to be either false or true, receiving undefined gives you a good hint that there is something wrong with the name of the property. The same applies to most cases where you expect a value, would it be a number, a string, or an object representing some business entity.

The case which worries me much more is when, expecting a boolean, you write:

if (something.isIFrame) {
    // This will never execute, since `isIFrame` doesn't exist.
} else {
    // This will execute every time.
}

Here, JavaScript doesn't help you much, since it silently swallows the undefined and simply executes the elseblock every time. This being said, it shouldn't take much time to figure out that there is something wrong around theif/else. The next step is to run a debugger and check for the actual values: as soon as you see theundefined` instead of a boolean, you have a hint.

You may on the other hand expect the situation where the value may simply not be here.

For instance, I'm currently working on a node.js application which receives messages about servers. Sometimes, a message is sent not by the server itself (a virtual machine), but by the host: in this case, the message contains a replacementIP property with the IP address of the concerned virtual machine.

If I want to display the IP address, all I have to do is:

var ipToDisplay = message.replacementIP || context.senderIP;

If JavaScript was throwing exceptions when accessing non-existent property, this would force me to write this instead:

var getActualIP = function (message, context) {
    try {
        return message.replacementIP;
    } catch {
        return context.senderIP;
    }
};

[...]
var ipToDisplay = getActualIP(message, context);

I find it much more difficult to follow.

So you have two cases here: in the first one, the choice of the designers of JavaScript appears problematic in a specific case, and causes you to launch your debugger. Not that nice, indeed. On the other hand, the second case shows that the designers' choice makes it possible to write very compact code in a lot of situations; I find it very nice.

So what about an opt-in "using strict undefined"?

Not sure it's a good idea, for the simple reason that adding features to a language should be taken very, very seriously.

Any additional feature takes literally months, and given the nature of JavaScript, would need to be implemented in every browser. As usual, the one with the name starting by “I” will be late, and so you'll find yourself including "using strict undefined" in your code, while knowing that this browser will plainly ignore it: not fun when it comes to debugging.

Compare this to, for instance, ECMAScript 6th String Interpolation feature. String interpolation brings a huge benefit in terms of code readability and maintainability: most developers who used Python or Java are familiar with this feature, and they will happily use it in JavaScript. It will break existent code, but given its importance, it's worth the risk, and worth the time spent implementing it.

Default parameter values? Same thing: great benefit for everyone, and no risk of breaking existent code.

But "using strict undefined"? I'm not convinced that the edge case illustrated below is not that important, especially since it's easy to find what's happening with the help of a debugger. If you write software for which it is not acceptable to access non-existent properties, Google Closure Compiler is an option. Switching to a different language is another option.


问:
Is there a performance benefit to using the method reference syntax instead of lambda syntax in Java 8?
Do method references skip the overhead of the lambda wrapper?  Might they in the future?

According to the Java Tutorial on Method References:

Sometimes... a lambda expression does nothing but call an existing method.
In those cases, it's often clearer to refer to the existing method by
name. Method references enable you to do this; they are compact,
easy-to-read lambda expressions for methods that already have a name.

I prefer the lambda syntax to the method reference syntax for several reasons:

Lambdas are clearer

Despite Oracle's claims, I find the lambda syntax easier-to-read than the object method reference short-hand because the method reference syntax is ambiguous:

```<code>Bar::foo
</code>```

Are you calling a static one-argument method on the class of x and passing it x?

```<code>x -> Bar.foo(x)
</code>```

Or are you calling a zero-argument instance method on x?

```<code>x -> x.foo()
</code>```

The method reference syntax could stand in for either one.  It hides what your code is actually doing.

Lambdas are safer

If you reference Bar::foo as a class method and Bar later adds an instance method of the same name (or vice-versa), your code will no longer compile.

You can use lambdas consistently

You can wrap any function in a lambda - so you can use the same syntax consistently everywhere.  The method reference syntax won't work on methods that take or return primitive arrays, throw checked exceptions, or have the same method name used as an instance and a static method (because the method reference syntax is ambiguous about which method would be called).  They don't work when you have overloaded methods with the same number of arguments, but you shouldn't do that anyway (see Josh Bloch's item 41) so we can't hold that against method references.

Conclusion

If there's no performance penalty for doing so, I'm tempted to turn off the warning in my IDE and use the lambda syntax consistently without sprinkling the occasional method reference into my code.

P.S.

Neither here nor there, but in my dreams, object method references look more like this and apply invoke-dynamic against the method directly on the object without a lambda wrapper:

```<code>_.foo()
</code>```

答:
In many scenarios, I think lambda and method-reference is equivalent. But the lambda will wrap the invocation target by the declaring interface type.

For example

```<code>public class InvokeTest {

    private static void invoke(final Runnable r) {
        r.run();
    }

    private static void target() {
        new Exception().printStackTrace();
    }

    @Test
    public void lambda() throws Exception {
        invoke(() -> target());
    }

    @Test
    public void methodReference() throws Exception {
        invoke(InvokeTest::target);
    }
}
</code>```

You will see the console output the stacktrace.

In lambda(), the method calling target() is lambda$lambda$0(InvokeTest.java:20), which has traceable line info. Obviously, that is the lambda you write, the compiler generates an anonymous method for you. And then, the caller of the of the lambda method is something like InvokeTest$$Lambda$2/1617791695.run(Unknown Source), that is the invokedynamic call in JVM, it means the call is linked to the generated method.

In methodReference(), the method calling target() is directly the InvokeTest$$Lambda$1/758529971.run(Unknown Source), it means the call is directly linked to the InvokeTest::target method.

Conclusion

Above all, compare to method-reference, using lambda expression will only cause  one more method call to the generating method from lambda.

Body:
In many scenarios, I think lambda and method-reference is equivalent. But the lambda will wrap the invocation target by the declaring interface type.

For example

public class InvokeTest {

    private static void invoke(final Runnable r) {
        r.run();
    }

    private static void target() {
        new Exception().printStackTrace();
    }

    @Test
    public void lambda() throws Exception {
        invoke(() -> target());
    }

    @Test
    public void methodReference() throws Exception {
        invoke(InvokeTest::target);
    }
}

You will see the console output the stacktrace.

In lambda(), the method calling target() is lambda$lambda$0(InvokeTest.java:20), which has traceable line info. Obviously, that is the lambda you write, the compiler generates an anonymous method for you. And then, the caller of the of the lambda method is something like InvokeTest$$Lambda$2/1617791695.run(Unknown Source), that is the invokedynamic call in JVM, it means the call is linked to the generated method.

In methodReference(), the method calling target() is directly the InvokeTest$$Lambda$1/758529971.run(Unknown Source), it means the call is directly linked to the InvokeTest::target method.

Conclusion

Above all, compare to method-reference, using lambda expression will only cause  one more method call to the generating method from lambda.

ContentLicense: CC BY-SA 4.0


问:
Two structs with the same members but different naming, is it a good idea?
I am writing a program that involves working with both polar and Cartesian coordinates.

Does it make sense to create two different structs for each kind of points, one with X and Y members and one is with R and Theta members.

Or is it too much and it is better to have just one struct with first and second as members.

What I am writing is simple and it won't change much. But I am curious what is better from a design point of view.

I am thinking the first option is better. It seems more readable and I will get the benefit of type checking.

答:
A possible solution, depending on the language and if you know that both classes will have similar methods and operations, would be to define the class once and use type aliases in order to explicitly name the types differently.

This also has the advantage that as long as the classes are exactly the same, you can maintain only one, but as soon as you need to change them, you don't need to modify the code using them since the types have already been used distincly.

Another option, depending again on the usage of the classes (if you need polymorphism and such) is to use public inheritance to both new types, so they have the same public interface as the common type they both represent. This also allows for separate evolution of the types.


答: git-imerge is designed exactly for this purpose. It is a git tool which provides a method for incremental merging. By merging incrementally, you only need to deal with the collisions between two versions, never more. Furthermore, a far larger number of merges can be performed automatically as the individual changesets are smaller.

Title: How do I approach a complicated merge


问:
Using compound statements ("{" ... "}" blocks) to enforce variable locality

Introduction

Many "C-like" programming languages use compound statements (code blocks specified with "{" and "}") to define a variables scope.

Here is a simple example.

```<code>for (int i = 0; i < 100; ++i) {
    int value = function(i); // Here 'value' is local to this block
    printf("function(%d) == %d\n", i, value);
}
</code>```

This is good because it limits the scope of the value to where it is used. It is hard for programmers to use value in ways that they are not meant to because they can only access it from within its scope.

I am almost all of you are aware of this and agree that it is good practice to declare variables in the block they are used to limit their scope.

But even though it is an established convention to declare variables in their smallest possible scope it is not very common to use an naked compound statement (that is an compound statement that is not connected to an if, for, while statement).

Swapping the values of two variables

Programmers often write the code like this:

```<code>int x = ???
int y = ???

// Swap `x` and `y`
int tmp = x;
x = y;
y = tmp;
</code>```

Would it not be better to write the code like this:

```<code>int x = ???
int y = ???

// Swap `x` and `y`
{
    int tmp = x;
    x = y;
    y = tmp;
}
</code>```

It looks quite ugly but I think that this is a good way to enforce variable locality and make the code safer to use.

This does not only apply to temporaries

I often see similar patterns where a variable is used once in a function

```<code>Object function(ParameterType arg) {
    Object obj = new Object(obj);
    File file = File.open("output.txt", "w+");
    file.write(obj.toString());

    // `obj` is used more here but `file` is never used again.
    ...
}
</code>```

Why don't we write it like this?

```<code>RET_TYPE function(PARAM_TYPE arg) {
    Object obj = new Object(obj);
    {
       File file = File.open("output.txt", "w+");
       file.write(obj.toString());
    }

    // `obj` is used more here but `file` is never used again.
    ...
}
</code>```

Summary of question

It is hard to come up with good examples. I am sure that there are betters ways to write the code in my examples but that is not what this question is about.

My question is why we do not use "naked" compound statements more to limit the scope of variables.

What do you think about using a compound statement like this

```<code>{
    int tmp = x;
    x = y;
    y = z;
}
</code>```

to limit the scope of tmp?

Is it good practice? Is it bad practice? Explain your thoughts.

答:
The following java code shows what I believe to be one of the best examples of how naked blocks can be useful.

As you can see, the compareTo() method has three comparisons to make, and the results of the first two need to be temporarily stored in a local.  The local is just a 'difference' in both cases, but re-using the same local variable is a bad idea, and as a matter of fact on a decent IDE you can configure local variable reuse to cause a warning.

```<code>class MemberPosition implements Comparable<MemberPosition>
{
    final int derivationDepth;
    final int lineNumber;
    final int columnNumber;

    MemberPosition( int derivationDepth, int lineNumber, int columnNumber )
    {
        this.derivationDepth = derivationDepth;
        this.lineNumber = lineNumber;
        this.columnNumber = columnNumber;
    }

    @Override
    public int compareTo( MemberPosition o )
    {
        /* first, compare by derivation depth, so that all ancestor methods will be executed before all descendant methods. */
        {
            int d = Integer.compare( derivationDepth, o.derivationDepth );
            if( d != 0 )
                return d;
        }

        /* then, compare by line number, so that methods will be executed in the order in which they appear in the source file. */
        {
            int d = Integer.compare( lineNumber, o.lineNumber );
            if( d != 0 )
                return d;
        }

        /* finally, compare by column number.  You know, just in case you have multiple test methods on the same line.  Whatever. */
        return Integer.compare( columnNumber, o.columnNumber );
    }
}
</code>```

Note how in this particular case you cannot offload the work to a separate function, as Kilian Foth's answer suggests.  So, in cases like this, naked blocks are always my preference.  But even in cases where you can in fact move the code to a separate function, I prefer a) keeping things in one place as to minimize the scrolling necessary in order to make sense of a piece of code, and b) not bloating my code with lots of functions.  Definitely a good practice.

(Side note: one of the reasons why egyptian curly bracket style truly sucks is that it does not work with naked blocks.)

(Another side note that I remembered now, a month later: the code above is in Java, but I actually picked up the habit from my days of C++, where the closing curly bracket causes destructors to be invoked. This is the RAII bit that rachet freak also mentions in his answer, and it is not just a good thing, it is pretty much indispensable.)

Body:
The following java code shows what I believe to be one of the best examples of how naked blocks can be useful.

As you can see, the compareTo() method has three comparisons to make, and the results of the first two need to be temporarily stored in a local.  The local is just a 'difference' in both cases, but re-using the same local variable is a bad idea, and as a matter of fact on a decent IDE you can configure local variable reuse to cause a warning.

class MemberPosition implements Comparable<MemberPosition>
{
    final int derivationDepth;
    final int lineNumber;
    final int columnNumber;

    MemberPosition( int derivationDepth, int lineNumber, int columnNumber )
    {
        this.derivationDepth = derivationDepth;
        this.lineNumber = lineNumber;
        this.columnNumber = columnNumber;
    }

    @Override
    public int compareTo( MemberPosition o )
    {
        /* first, compare by derivation depth, so that all ancestor methods will be executed before all descendant methods. */
        {
            int d = Integer.compare( derivationDepth, o.derivationDepth );
            if( d != 0 )
                return d;
        }

        /* then, compare by line number, so that methods will be executed in the order in which they appear in the source file. */
        {
            int d = Integer.compare( lineNumber, o.lineNumber );
            if( d != 0 )
                return d;
        }

        /* finally, compare by column number.  You know, just in case you have multiple test methods on the same line.  Whatever. */
        return Integer.compare( columnNumber, o.columnNumber );
    }
}

Note how in this particular case you cannot offload the work to a separate function, as Kilian Foth's answer suggests.  So, in cases like this, naked blocks are always my preference.  But even in cases where you can in fact move the code to a separate function, I prefer a) keeping things in one place as to minimize the scrolling necessary in order to make sense of a piece of code, and b) not bloating my code with lots of functions.  Definitely a good practice.

(Side note: one of the reasons why egyptian curly bracket style truly sucks is that it does not work with naked blocks.)

(Another side note that I remembered now, a month later: the code above is in Java, but I actually picked up the habit from my days of C++, where the closing curly bracket causes destructors to be invoked. This is the RAII bit that rachet freak also mentions in his answer, and it is not just a good thing, it is pretty much indispensable.)


问:
How can I organise a better deployment process?
I work in a company of about 10 developers. When we start a project, each of the developers involved in the project have their dev environment. Once they complete a task, it is then pushed to phase two which is called "Staging", where QA takes place. Once bugs are cleared, it is then set to "Ready for UAT" and UAT (User Acceptance Testing) is done on the same phase (Staging). If the client is happy with the work it is pushed to the last stage which is called "Live".

Detailed development overflow

Specification

Development (Once specification is approved by client)

Staging QA

Staging UAT

Go Live Deployment

Stage of Support (1 month of free support, this is to give the client a change so point out things we/they didn't notice on the QA and UAT stage)

Once the stage of support ends and the client wants to change something to the software, they need to rise a CR (Change Request), and it all start's from stage one again (Big change requests, things such as new functionality to the current system)

If the change request is small then no specification is needed. It will start from development stage to go Live deployment. If the client spots something wrong after the go live for this CR, then he will have to rise a support case and it starts all over again from the development stage.

My question is, could there be a better way of doing this?

答: Your user acceptance tests are way too late. You risk expending much effort on conforming exactly to requirements which then turn out not to be what the customer needs. If at all possible, involve the actual users of the software in the quality control process as soon as there is something to test - don't wait until after your testers think it's perfect.


问:
Manage lock of a software feature
I've wrote a standalone java SE software which executes, for example, the features A, B and C.

Now, i want to that, if a lock is enabled (and this lock is a command sent remotely by my backend), the feature C has not to be longer available for execution by the user.

This lock has to be persistent, so, it has to survive to a device reboot, for example.

Another requirement is that has to be secure, so, it cannot to be just a file nor an entry on a local DB nor anything that could be manipulable by an expert user.

What is the best solution for develop something like that?

答:
As Clockwork-Muse pointed out in a comment, this ability to enable/disable features is known as DRM.

Since you want to be able to remotely disable feature C, it seems reasonable to assume your target computer is connected to the Internet.

It might be enough for your code to "call home" to a server periodically with a message "this is box XXX, license # YYY, version a.b.c.  What features should I enable?".  If it does not get a reply, it can fall back to the most restrictive answer.  It can also store an answer in memory for a short period of time if necessary.

It's not foolproof, but hopefully it's enough to help the mostly-honest people stay honest and convince the dishonest people their time is better spent on easier targets.

Title: Manage lock of a software feature