答:
According to the Open Source Initiative, no. In order for a license to be considered open source, there are 10 clauses. One of them is that an open source license can not discriminate against a person or group:

The license must not discriminate against any person or group of persons.

The Free Software Foundation also provides a description of free software. It appears that such restrictions would also make the software nonfree according to them. It's not explicitly mentioned, but since nonfree software is any software license that prevents use, redistribution, or modification or requires for permission first. Since you are preventing at least one individual from using, redistributing, or modifying the software, I believe it would fall under their definition of nonfree:

Nonfree software is any software that is not free. Its use, redistribution or modification is prohibited, or requires you to ask for permission, or is restricted so much that you effectively can't do it freely.

The software license is the formal location for the terms of acquiring, using, and distributing the software, putting it in there would likely be what is invoked in any kind of legal discussion regarding the software. In addition, if you included such a restriction in your license, you may not be able to use services that are freely available to free and/or open source projects, such as Coverity Scan or hosting on Google Code.

Title: Can one deny specific parties the right to use and modify otherwise open source software?

Body:
I have an open source project that has the attention of some peers, and several of them are eager to contribute. There is one amongst them, however, who I wish (largely for comedic purposes; it's a long story) to keep from contributing.

Is it valid to put in the license a clause to the effect of "Anyone is free to modify this software, except for Andrew?"


问:
is it realistic to make use of HTML5 local storage to store CSS, and JavaScript
The idea is to make use of HTML5 local storage to store frequently accessed CSS and JavaScript.

For example (pseudo-code):

```
var load_from_cdn = true;
if (detect local storage)
{
  if (cache of css, js found)
  {
     load the local storage cache
     load_from_cdn = false;
  }
}
if (load_from_cdn)
{
   document.write('<script>...');
}
```

Is this possible or realistic?

I do aware browser cache, there will be still some header access checking,

I assuming no HTTP access is better (in my thinking)

PS : It seems that local storage only support key-value pair, can someone prove it ?

(best with some examples)

答:
Using localStorage is fast(er)! My test showed

Loading jQuery from CDN: Chrome 268ms, FireFox: 200ms

Loading jQuery from localStorage:  Chrome 47ms, FireFox 14ms

I guess saving the HTTP request already brings a big speed advantage. Everybody here seems to be conviced of the opposite, so please prove me wrong.

If you want to test my results I crated a tiny library that caches scripts in  localStorage. Check it out on Github https://github.com/webpgr/cached-webpgr.js or just copy  it from the example below.

The complete library:

```<code>function _cacheScript(c,d,e){var a=new XMLHttpRequest;a.onreadystatechange=function(){4==a.readyState&&(200==a.status?localStorage.setItem(c,JSON.stringify({content:a.responseText,version:d})):console.warn("error loading "+e))};a.open("GET",e,!0);a.send()}function _loadScript(c,d,e,a){var b=document.createElement("script");b.readyState?b.onreadystatechange=function(){if("loaded"==b.readyState||"complete"==b.readyState)b.onreadystatechange=null,_cacheScript(d,e,c),a&&a()}:b.onload=function(){_cacheScript(d,e,c);a&&a()};b.setAttribute("src",c);document.getElementsByTagName("head")[0].appendChild(b)}function _injectScript(c,d,e,a){var b=document.createElement("script");b.type="text/javascript";c=JSON.parse(c);var f=document.createTextNode(c.content);b.appendChild(f);document.getElementsByTagName("head")[0].appendChild(b);c.version!=e&&localStorage.removeItem(d);a&&a()}function requireScript(c,d,e,a){var b=localStorage.getItem(c);null==b?_loadScript(e,c,d,a):_injectScript(b,c,d,a)};
</code>```

Calling the library

```<code>requireScript('jquery', '1.11.2', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function(){
    requireScript('examplejs', '0.0.3', 'example.js');
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Using localStorage is fast(er)! My test showed

Loading jQuery from CDN: Chrome 268ms, FireFox: 200ms

Loading jQuery from localStorage:  Chrome 47ms, FireFox 14ms

I guess saving the HTTP request already brings a big speed advantage. Everybody here seems to be conviced of the opposite, so please prove me wrong.

If you want to test my results I crated a tiny library that caches scripts in  localStorage. Check it out on Github https://github.com/webpgr/cached-webpgr.js or just copy  it from the example below.

The complete library:

function _cacheScript(c,d,e){var a=new XMLHttpRequest;a.onreadystatechange=function(){4==a.readyState&&(200==a.status?localStorage.setItem(c,JSON.stringify({content:a.responseText,version:d})):console.warn("error loading "+e))};a.open("GET",e,!0);a.send()}function _loadScript(c,d,e,a){var b=document.createElement("script");b.readyState?b.onreadystatechange=function(){if("loaded"==b.readyState||"complete"==b.readyState)b.onreadystatechange=null,_cacheScript(d,e,c),a&&a()}:b.onload=function(){_cacheScript(d,e,c);a&&a()};b.setAttribute("src",c);document.getElementsByTagName("head")[0].appendChild(b)}function _injectScript(c,d,e,a){var b=document.createElement("script");b.type="text/javascript";c=JSON.parse(c);var f=document.createTextNode(c.content);b.appendChild(f);document.getElementsByTagName("head")[0].appendChild(b);c.version!=e&&localStorage.removeItem(d);a&&a()}function requireScript(c,d,e,a){var b=localStorage.getItem(c);null==b?_loadScript(e,c,d,a):_injectScript(b,c,d,a)};

Calling the library

requireScript('jquery', '1.11.2', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function(){
    requireScript('examplejs', '0.0.3', 'example.js');
});


问:
Can you "stop" a C program from being reverse engineered?
I'm sure that many of the middle to high level languages can be reverse engineered. But if a C program can be reverse-engineered, and turned back into editable source code, how do I discourage such a thing?</p>

答:
To make C almost impossible to reverse engineer?   It is possible - write your C such that the entire logic is dependent on the input AT RUNTIME (perhaps now you have to protect your input, which hold the secret to your logic in the C program).   So reading the C source code really has no meaning.

How?   One way:   Using lots of function pointers.   So reading:

```<code>a->function1();
c->function2();
</code>```

it is impossible to guess what function1() does, as it is a dynamically allocated pointer assigned only during runtime - depending on the input.

If you create lots of basic functions like the above, and then dynamically construct your logic by arranging the input token, it is possible to implement any logic.

In assembly language, the analogous equivalent is called "Return-oriented programming" - where you can construct almost any logic possible using carefully selected hexadecimal number from the original program:

http://en.wikipedia.org/wiki/Return-oriented_programming

In a way, what I am proposing is something like an "interpreter":   eg, A javascript interpreter program itself, being written in C, can behave in many different ways, depending on the "javascript" program as an input.   So there is no point reversing the interpreter itself - as the "javascript" input program is the ultimate logic machine.

Update:

Assuming you have the input, to RE it dynamically can be very difficult as well, because if you use software breakpoints (assuming 0xcc instrumented into the code) then by self-checksumming the code area, plus checksum of many randomly selected small block, and compare the checksum with original uninstrumented code, you can easily detect any software breakpoint.   And if you use hardware breakpoint?   well, timing analysis between any randomly selected pieces of code will easily detect that someone is trying to analyse the code.   And if you use a software emulator like Boch/pintool/Intel branch tracing that does not use software breakpoint, and can deceive the clock enough to bypass timing analysis, well, it is possible it can be done.   But perhaps the amount of data to analyse may amount many gigs of data.   Not easy.

But to be able to do the above two tasks, it is no longer C - you have to take the binary output and instrument it with checksum-checking codes, plus timing analysis code between any two points - all these inserted randomly as well.

A real world example of binary that is difficult to analyse (or taken years and big Anti-Virus companies are still trying to understand it):   Stuxnet.   And this binary (not sure?) does not connect to internet, run standalone.

Body:
To make C almost impossible to reverse engineer?   It is possible - write your C such that the entire logic is dependent on the input AT RUNTIME (perhaps now you have to protect your input, which hold the secret to your logic in the C program).   So reading the C source code really has no meaning.

How?   One way:   Using lots of function pointers.   So reading:

a->function1();
c->function2();

it is impossible to guess what function1() does, as it is a dynamically allocated pointer assigned only during runtime - depending on the input.

If you create lots of basic functions like the above, and then dynamically construct your logic by arranging the input token, it is possible to implement any logic.

In assembly language, the analogous equivalent is called "Return-oriented programming" - where you can construct almost any logic possible using carefully selected hexadecimal number from the original program:

http://en.wikipedia.org/wiki/Return-oriented_programming

In a way, what I am proposing is something like an "interpreter":   eg, A javascript interpreter program itself, being written in C, can behave in many different ways, depending on the "javascript" program as an input.   So there is no point reversing the interpreter itself - as the "javascript" input program is the ultimate logic machine.

Update:

Assuming you have the input, to RE it dynamically can be very difficult as well, because if you use software breakpoints (assuming 0xcc instrumented into the code) then by self-checksumming the code area, plus checksum of many randomly selected small block, and compare the checksum with original uninstrumented code, you can easily detect any software breakpoint.   And if you use hardware breakpoint?   well, timing analysis between any randomly selected pieces of code will easily detect that someone is trying to analyse the code.   And if you use a software emulator like Boch/pintool/Intel branch tracing that does not use software breakpoint, and can deceive the clock enough to bypass timing analysis, well, it is possible it can be done.   But perhaps the amount of data to analyse may amount many gigs of data.   Not easy.

But to be able to do the above two tasks, it is no longer C - you have to take the binary output and instrument it with checksum-checking codes, plus timing analysis code between any two points - all these inserted randomly as well.

A real world example of binary that is difficult to analyse (or taken years and big Anti-Virus companies are still trying to understand it):   Stuxnet.   And this binary (not sure?) does not connect to internet, run standalone.


问:
Is setting "permanent" persistent login cookies a bad practice?
I realized that in Rails there is a built in permanent method for its persistent login cookies (aka. "remember me" cookies) method to give the client a cookie that expires in 20 years:

cookies.permanent[:remember_token] = remember_token

However it seems that in a lot of websites the cookies are set to expire in a far shorter time period, say 3 months or 2 weeks, after which the client will have to log in again.

Is it really a markedly bad practice to set a persistent login cookie to be stored permanently? Why or why not? If it's bad, why does it seem that a considerable number of developers are doing so, such that Rails has provided a built-in method to support the practice.

答:
Remember me cookies are a special kind of cookie because they allow the user to bypass providing the authentication information, while other cookies may just track what pages you have been on or what is in your shopping cart as a non logged in (unauthenticated) user and aren't really risky except to the extent that such information is assumed to be private.

First I would say that all platforms have things that are not best practices, and they have them for all kinds of reason (backward compatibility, inertia, etc) Everyone is also much more aware of a variety of attack vectors than they were in the past. In the case of remember me cookies because you are storing information that can be used to login you have to think carefully about the trade-offs of security and convenience.

So in thinking about remember cookies you have to consider (at minimum)

The risks of someone having access to the browser who is not the
original user. For example, what if the cookie is dropped on a
computer in a public library and one user leaves and the next sits
down.

The risks associated with someone copying the cookie and using it on
a different computer (especially a problem where you see people using
remember cookies on in house computers to avoid dealing with password
resets and postits

The risk of someone being able to decrypt the authentication
information in the cookie and use it either to gain access to your
site or, if it contains (like many used to be and probably still are)
some version of the user name and password does that not only make it
possible to get access to your site but also potentially give access
to other sites where the same password is used by the same user.

Personally, I would not use a permanent/20 year remember me cookie because of these problems and others like them. Yes, they are user errors (using the same password, checking remember me in the library, etc) but they are the kinds of human errors that happen. Not to mention that exceeds the life expectancy of the hardware. If you really have a user who has not logged in for 20 years I would think you would want him or her to provide credentials.  (If they login in, you always should update and drop a new cookie, active users of remember me should not keep the same cookie for 20 years.)

Further if you use remember me you need to make sure to force real authentication when changing passwords, email address, other contact information and any ecommerce activities.


问:
Can I include mongod.exe in my commercial destop based or user self hosted app withou open sourcing it?
I have read the doc and the apgl blog post, but I still have some concerns:
Can I include mongodb.exe in my commercial desktop based app?
Can I include mongodb.exe in my commercial user self hosted web app？</p>

答:
Read the web page.  It says:

The goal of the server license is to require that enhancements to
  MongoDB be released to the community. Traditional GPL often does not
  achieve this anymore as a huge amount of software runs in the cloud.
  For example, Google has no obligation to release their improvements to
  the MySQL kernel – if they do they are being nice.

To make the above practical, we promise that your client application
  which uses the database is a separate work. To facilitate this, the
  mongodb.org supported drivers (the part you link with your
  application) are released under Apache license, which is copyleft
  free.

Seems pretty clear to me.

Personally, if I were MongoDB, I would have simply written my own license that states their intent in plain English, rather than trying to tack on a highly-restrictive license like AGPL, and then provide exceptions.


问:
Can I use GPL libraries temporarily for prototyping and make the future code closed source?
I am working on a prototype for a software system, which (at least at the start) will be closed source.

In order to save time, I'm thinking of using (that is, statically linking) a library that is licensed under GPLv3, so I can test my design quickly. If I distributed the software at this stage, I'd have to distribute source code along with it.

What if I don't, but satisfy myself that my system works, and then replace the GPL library with my own code before distributing? Would the result be "contaminated" by the GPL?

I have a feeling that retaining the GPL library in my Git history or not may make a difference.

答:
The GPL is only triggered on distribution... you can do whatever you want if you don't release a modified version or derivative work.

I have a feeling that retaining the GPL library in my Git history or
  not may make a difference.

If you mean publishing your source to a public repository like GitHub, then yes, you may have an issue.  Just using git is irrelevant if it's private.


问:
When should I subclass an exception in Python?
In my code there are about seven places where I raise an exception. All of these exceptions are treated the same: print an error to log file, return software state to default and exit.

During code review my senior engineer, whom I value a lot, said I should subclass all of these exceptions. His argument is that in the future we may want to handle the exceptions differently and that will be easier.

My argument is that currently it will only clutter our code and, since we don't know whether we will ever handle the exceptions differently, we should leave the code terse and, if and when the time comes, then and only then we should subtype.

I would like to hear any argument for each case.

答:
You're right

The argument for your side is already mentioned by Robert Harvey: don't add code you don't need right now, especially since it's easy to add it later.

Your reviewer is right, too

On the other hand, the reviewer's point is understandable as well:

Returning a generic Exception() is not very helpful to the caller: while the exception description indicates to an human what's going on, treating exceptions differently programmatically may be impossible. The developer using your code may be reluctant changing the types of exceptions, including by fear (justified or not) of breaking something.

Note that adding custom exceptions right now is not that difficult:

```<code>class MyCustomException(Exception):
    pass
</code>```

is all you need. That's only two lines of code (given that you may not even need to create a separate file if you put custom exceptions in one file).

The code itself looks better, more readable.

```<code>if price < self.PriceMinValue:
    raise OutOfRangeException("The price is inferior to zero.")
</code>```

looks slightly more readable compared to:

```<code>if price < self.PriceMinValue:
    raise Exception("The price is inferior to zero.")
</code>```

because of the indication of the type of exception:

In the second piece of code, I need to read the description and guess that the price is out of range (or maybe it's not? Maybe there are cases where price can be negative, such as rebates?)

In the first piece of code, a glimpse over the type gives an immediate indication about the error. It looks like there is a set of allowed values for a price, and the current value is outside this set.

So?

So:

Both approaches are valid. If you don't subclass the exceptions when you don't need custom types, you're right. When you do subclass the exceptions because it costs nothing to do it and may be useful later, you're right to.

Be consistent with your team. If your team uses custom exceptions extensively, use them.

Body:
You're right

The argument for your side is already mentioned by Robert Harvey: don't add code you don't need right now, especially since it's easy to add it later.

Your reviewer is right, too

On the other hand, the reviewer's point is understandable as well:

Returning a generic Exception() is not very helpful to the caller: while the exception description indicates to an human what's going on, treating exceptions differently programmatically may be impossible. The developer using your code may be reluctant changing the types of exceptions, including by fear (justified or not) of breaking something.

Note that adding custom exceptions right now is not that difficult:

class MyCustomException(Exception):
    pass

is all you need. That's only two lines of code (given that you may not even need to create a separate file if you put custom exceptions in one file).

The code itself looks better, more readable.

if price < self.PriceMinValue:
    raise OutOfRangeException("The price is inferior to zero.")

looks slightly more readable compared to:

if price < self.PriceMinValue:
    raise Exception("The price is inferior to zero.")

because of the indication of the type of exception:

In the second piece of code, I need to read the description and guess that the price is out of range (or maybe it's not? Maybe there are cases where price can be negative, such as rebates?)

In the first piece of code, a glimpse over the type gives an immediate indication about the error. It looks like there is a set of allowed values for a price, and the current value is outside this set.

So?

So:

Both approaches are valid. If you don't subclass the exceptions when you don't need custom types, you're right. When you do subclass the exceptions because it costs nothing to do it and may be useful later, you're right to.

Be consistent with your team. If your team uses custom exceptions extensively, use them.


答:
Don't let anyone else access the program. Run it in a secure* server you control, and let users interface with it only by providing the input over the network and receiving back the output.

See http://en.wikipedia.org/wiki/Software_as_a_service

The downside is that you now have to manage the server.

*Securing a server is far from trivial. For truly high security, hire a professional.

Title: Can you "stop" a C program from being reverse engineered?

Body: I'm sure that many of the middle to high level languages can be reverse engineered. But if a C program can be reverse-engineered, and turned back into editable source code, how do I discourage such a thing?</p>


问:
Can someone relicense my code, then sue me for distributing it?
Let's say I have published some code, and have relinquished all copyright interest to that code by some extremely permissive license (e.g. unlicense).

Can a corporation take my code, republish it under a proprietary license, then sue me for being in breach of that new license?

答:
A license generally affects you when you acquire, use, or distribute a piece of software that comes with the license. If you never acquire, use or distribute Evil Corp's version of your project, then there's simply no way any sane license they apply to it could possibly affect you.

Now, if they release a modified version of your project under a proprietary license, and you do something like incorporate their improvements into your permissively licensed version, then Evil Corp has every right to come after you for that. But as long as you don't do anything silly like that, you should have nothing to worry about.


答:
If you can prove that you published the code prior to when they did and you had no access to it when it was unreleased then you can counter plea that they took it from you.

The result is a open/shut case where they will end up paying all legal fees (plus reimbursement for slander if applicable) and the only cost to you is the time spent defending yourself.

If the code is stored online and both parties are in the USA then this will fall under OCILLA which means that they first need to notify you (with a DMCA takedown request) and give you the chance to take it offline. You then have the chance to counter file and then if you were in the clear (or don't hear back in 2/3 weeks) you can put the code up again.

Title: Can someone relicense my code, then sue me for distributing it?

Body:
Let's say I have published some code, and have relinquished all copyright interest to that code by some extremely permissive license (e.g. unlicense).

Can a corporation take my code, republish it under a proprietary license, then sue me for being in breach of that new license?


问:
Naming conventions: camelCase versus underscore_case ? what are your thoughts about it?
I've been using underscore_case for about 2 years and I recently switched to camelCase because of the new job (been using the later one for about 2 months and I still think underscore_case is better suited for large projects where there are alot of programmers involved, mainly because the code is easier to read).

Now everybody at work uses camelCase because (so they say) the code looks more elegant .

What are you're thoughts about camelCase or underscore_case

p.s. please excuse my bad english

Edit

Some update first:

platform used is PHP (but I'm not expecting strict PHP platform related answers , anybody can share their thoughts on which would be the best to use , that's why I came here in the first place)

I use camelCase just as everibody else in the team (just as most of you recomend)

we use Zend Framework which also recommends camelCase

Some examples (related to PHP) :

Codeigniter framework recommends underscore_case , and honestly the code is easier to read .

ZF recomends camelCase and I'm not the only one who thinks ZF code is a tad harder to follow through.

So my question would be rephrased:

Let's take a case where you have the platform Foo which doesn't recommend any naming conventions and it's the team leader's choice to pick one. You are that team leader, why would you pick camelCase or why underscore_case?

p.s. thanks everybody for the prompt answers so far

答: May seem silly, but I don't like underscores because the underscore is thin, and hides in multiple line text and I miss it.  Also, in some (many) text editors and/or dev environments, when you double click on a token name to highlight it so as to copy or drag and drop it, the system will not highlight the entire token, it only highlights one portion of the token, between adjacent underscores.  That drives me nuts. </p>

ContentLicense: CC BY-SA 2.5


问:
System for deducting velocity against sources pf gravity
Say I have a particle-based physics engine (which I do) that uses lots of particles with a x and y coordinate and velocity. These particles can also have a mass, which means that these particles (with a large enough mass) can attract each other based off their masses. My question is how and where should the program work out the deduction of velocity when moving against a source of gravity, should it check every time a particle gets a new velocity? Or should it check every tick? And also, how would it calculate the deduction of velocity, since I don't know how it would work with a x and y system</p>

答:
As with pretty much any physics simulation, yes you have to calculate everything on every tick. The forces the objects exert on each other are constantly changing (as long as at least one of them is moving), so you can't really avoid it.

I have no idea what you're asking specifically about "deduction of velocity", since the law of gravity works exactly the same way in all direction. It's also a really simple law to calculate:

F = G * (m1*m2)/r^2

G is a constant, you can probably get away with pretending particles have constant mass, and all that's left is computing the distance (r) between each pair of particles.


问:
Is the Single Responsibility Principle applicable to functions?
According to Robert C. Martin, the SRP states that:

There should never be more than one reason for a class to change.

However, in his book Clean Code, chapter 3: Functions, he shows the following block of code:

```<code>    public Money calculatePay(Employee e) throws InvalidEmployeeType {
        switch (e.type) {
            case COMMISSIONED:
                return calculateCommissionedPay(e);
            case HOURLY:
                return calculateHourlyPay(e);
            case SALARIED:
                return calculateSalariedPay(e);
            default:
                throw new InvalidEmployeeType(e.type);
        }
    }
</code>```

And then states:

There are several problems with this function. First, it’s large, and when new employee types are added, it will grow. Second, it very clearly does more than one thing. Third, it violates the Single Responsibility Principle (SRP) because there is more than one reason for it to change. [emphasis mine]

Firstly, I thought the SRP was defined for classes, but it turns out it's also applicable to functions. Secondly, how is that this function has more than one reason to change? I can only see it changing because of a change on Employee.

答:
One often missed detail of the Single Responsibility Principle is that the "reasons for change" are grouped by use-case actors (you can see a full explanation here).

So, in your example, the calculatePay method will need to be changed whenever new types of Employees are required. Since one type of employee may have nothing to do with another, it would be a violation of the principle if you keep them together, since the change would affect different user-groups (or use-case actors) in the system.

Now, about whether the principle applies to functions: Even if you have a violation in only one method, you are still changing a class for more than one reason, so it is still a violation of SRP.


答:
You are right @Enrique. No matter if it's a function or a method of a class, the SRP means that in that code block you only do one thing.

The 'reason to change' statement is sometimes a bit misleading, but if you change calculateSalariedPay or calculateHourlyPay or the enum of Employee.type you have to change this method.

In your example the function:

checks the type of the employee

calls another function which calculates the money according to the type

In my opinion it's not directly a SRP violation, since the switch-cases and the calls cannot be written shorter, if you think of Employee and the methods already exists. Anyway it's a clear open-closed principle (OCP) violation as you must append 'case' statements if you add employee types, so it's a bad implementation: refactor it.

We don't know how the 'Money' should be calculated, but the easiest way is to have Employee as interface and some concrete implementations with getMoney methods. In that case the whole function is needless.

If it's more complicated to calculate it, one could use the visitor-pattern which is also not 100% SRP but it's more OCP than a switch case.

Title: Is the Single Responsibility Principle applicable to functions?

Body:
According to Robert C. Martin, the SRP states that:

There should never be more than one reason for a class to change.

However, in his book Clean Code, chapter 3: Functions, he shows the following block of code:

```<code>    public Money calculatePay(Employee e) throws InvalidEmployeeType {
        switch (e.type) {
            case COMMISSIONED:
                return calculateCommissionedPay(e);
            case HOURLY:
                return calculateHourlyPay(e);
            case SALARIED:
                return calculateSalariedPay(e);
            default:
                throw new InvalidEmployeeType(e.type);
        }
    }
</code>```

And then states:

There are several problems with this function. First, it’s large, and when new employee types are added, it will grow. Second, it very clearly does more than one thing. Third, it violates the Single Responsibility Principle (SRP) because there is more than one reason for it to change. [emphasis mine]

Firstly, I thought the SRP was defined for classes, but it turns out it's also applicable to functions. Secondly, how is that this function has more than one reason to change? I can only see it changing because of a change on Employee.


问:
Building CMS from components
I have a design decision problem and would like to have some thoughts on it.

I'm building a CMS to use for my projects and want to incorporate existing components in it, like Doctrine, Monolog and any other i find suitable.

The question is, should I allow in code to access this each component directly, or should I have a buffer (proxy) class that acts as an API to underlying component?

In terms of performance/ease and access to full functionality i think it is better to allow this access, but in this case I lose control when component behavior changes (major version upgrade etc.). If I had a buffer class, i don't lock myself to particular component, and even can replace it with another, while not breaking backwards compatibility, but in this case I have to almost duplicate code from the component (I mean, function from my buffer class calls functions from component)

The CMS is written in PHP, if that matters.

答:
Why don't you have a look (for example) at Symfony DBAL or Templating interface? If you want to provide components with different underlying extern implementation you will define your interface components and then provide a couple of adapters for those other libraries.

To keep it backward compatible simply don't change the interface. If something for example Doctrine changes you can change the adapters.

Title: Building CMS from components


答:
As the other answers say, if you can see the binary you can reverse engineer the function of the program, although possibly with difficulty. The cutting edge is therefore to prevent the user from getting at the binary.

Old arcade systems did this by storing the program or critical parameters in battery-backed RAM linked to tamper switches. Open the case and the program evaporates. Modern iPhones use ARM "TrustZone" to load a microkernel from encrypted bootrom with privileged hardware access; this is used for the fingerprint sensor and some of the payment functions.

(Of course, this means the phone may be factory-compromised with no way for the user to detect or recover..)

Myself I've reported a couple of bugs in manufacturer firmware from ARM disassembly, and considered how much work it might be to write a decompilation assistant program.


答:
On page 176, Chapter 12: Emergence, in the section titled Minimal Classes and Methods the book provides somewhat of a correction, by stating:

In an effort to make our classes and methods small, we might create
  too many tiny classes and methods. So this rule suggests that we also
  keep our function and class counts low

and

High class and method counts are sometimes the result of pointless dogmatism.

Obviously, he is talking about dogmatism in following the SRP to break down perfectly fine innocent little methods like calculatePay() above.


问:
Logic behind an 'undo' for painting on a canvas
I'm working on a module that allows users a basic paint function. I want to support undoing any modifications done to the painting surface. Assuming that we have one layer (for the sake of simplicity), what is a reasonable way to store painting done so they can be undone?

An idea I had was to encapsulate draw events as a kind of Undoable object. If someone presses, draws, and releases, the new data added would be contained in an object of what actions were carried out. This event might contain something like "color ARBG of size X at [array of points the user dragged over]".

I'm unsure of this being the optimal way to do it. If there's a lot edit commands done, my logic here would be to rewind back to the beginning and then re-apply every 'edit' done to the scene, render and display, without the UI becoming laggy (excluding fringe cases).

Is this feasible? Is there a better/more optimal way? This is the first time I've attempted such a thing and I'd like to make sure I'm going to learn the best way I can do it.

Note: My goal is not to use any libraries and handle this through my own coding.

答:
Simplest method? Just limit the undo buffer size. Like you only allow the last 20 actions to be undone and keep a copy of the state 20 actions ago.

If you undo then there will be 19 actions in the undo buffer and redoing those is simpler than all since the beginning.

However extending from that you can keep copies of the state every X actions. This is the same idea of diff backups in databases, every month a full backup is done then a daily diff is taken. Then when needing to restore you just need to grab the latest full backup and reapply the diffs stored from that last backup on.


答:
The only way that a copyright can be created is by creating a work. If you create the software, you have the copyright. If you then relinquish the copyright (although I'm not quite sure if that is really possible), then there is no copyright for the work, and there is no possibility of creating one. So nobody can sue you successfully. </p>

<p>Of course they can sue you. Anybody can sue you if they feel like it. </p>

Body:
The only way that a copyright can be created is by creating a work. If you create the software, you have the copyright. If you then relinquish the copyright (although I'm not quite sure if that is really possible), then there is no copyright for the work, and there is no possibility of creating one. So nobody can sue you successfully.

Of course they can sue you. Anybody can sue you if they feel like it.


答:
A license agreement is a kind of contract. Wikipedia writes:

In order for a contract to be formed, the parties must reach mutual assent (also called a meeting of the minds). This is typically reached through offer and an acceptance which does not vary the offer's terms, which is known as the "mirror image rule".

That is, unless you sign (or otherwise accept) the offered license, no contract is formed, and nothing can be breached ... and unless you wanted to do something with the proprietary code, there is no reason for you to accept such an agreement.


问:
angularjs best practice by example
I am trying to get my head around how to better structure my angularjs applications by not overloading my controllers with too much logic. I feel like I have read just about every article on the subject but was hoping someone might be able to provide advice based on a specific example. I have put the requirements below for a job listing (as in jobs for a service company) screen and the functionality required.

Requirements:

Jobs are listed in a table and contain the following columns: id, customer, value ($), due date

Data is coming from a backend api (laravel/php) which provides a json array of objects with nested related objects and array of objects. Data is raw e.g. value ($) is 123.23 and due date is 2015-03-09.

The screen contains several filters for selecting a customer from a drop down list/autocomplete or selecting a date range for due date. Filtering is done server side, and server expects query params with a filter object e.g. filters={due_date_from='2015-03-07', due_date_to='2015-03-09',customer_id=123}

Filters are only applied when the user clicks on a filter button

Each column is sortable and sorting is done server side, so server expects query params with a sort object e.g. sort=[{by:'due_date', dir:'asc'}, {by:'customer_id',dir:'desc'}]

25 jobs per page, paging is done server side e.g. page=2

Where jobs are overdue, the row should be red

The state of filters, paging, sorts should be stored in the URL and read upon initialisation.

A reset button should clear all filters

I am using the Restangular 3rd party module for pulling data from the server side and have used the extendModel methods to added helper functions such as isOverdue() which returns true/false.

Currently I have created the following properties and methods in my JobsListController.

```<code>$scope.jobs = [];
$scope.filters = [];
$scope.sorts = [];
$scope.loadData = function(){}; //build data packet to send to server
$scope.sort = function(); // checks if column is currently sort in order to reverse direction
$scope.reset = function(){}; //clears filters, sorts and paging to send to server
</code>```

In my html I have the following things:

```<code><input type="date" ng-model="filters.due_from" />

<td>on-click="sortBy('customer_id')"></td>
</code>```

Ultimately I think my question is, should I be creating a service/factory called JobsListModel rather than having all this functionality in the controller?

答:
I'll speak out of my own little experience with AngularJS. I would definitely not say that that's a lot of logic, and anyway it seems to be all dealing with the server side API, where the business logic is, I suppose, so it's all view logic. It seems perfectly fine to me.

If you're worried about having too much logic, anyway, I would really consider adding some automated tests.

Title: angularjs best practice by example

Body:
I am trying to get my head around how to better structure my angularjs applications by not overloading my controllers with too much logic. I feel like I have read just about every article on the subject but was hoping someone might be able to provide advice based on a specific example. I have put the requirements below for a job listing (as in jobs for a service company) screen and the functionality required.

Requirements:

Jobs are listed in a table and contain the following columns: id, customer, value ($), due date

Data is coming from a backend api (laravel/php) which provides a json array of objects with nested related objects and array of objects. Data is raw e.g. value ($) is 123.23 and due date is 2015-03-09.

The screen contains several filters for selecting a customer from a drop down list/autocomplete or selecting a date range for due date. Filtering is done server side, and server expects query params with a filter object e.g. filters={due_date_from='2015-03-07', due_date_to='2015-03-09',customer_id=123}

Filters are only applied when the user clicks on a filter button

Each column is sortable and sorting is done server side, so server expects query params with a sort object e.g. sort=[{by:'due_date', dir:'asc'}, {by:'customer_id',dir:'desc'}]

25 jobs per page, paging is done server side e.g. page=2

Where jobs are overdue, the row should be red

The state of filters, paging, sorts should be stored in the URL and read upon initialisation.

A reset button should clear all filters

I am using the Restangular 3rd party module for pulling data from the server side and have used the extendModel methods to added helper functions such as isOverdue() which returns true/false.

Currently I have created the following properties and methods in my JobsListController.

```<code>$scope.jobs = [];
$scope.filters = [];
$scope.sorts = [];
$scope.loadData = function(){}; //build data packet to send to server
$scope.sort = function(); // checks if column is currently sort in order to reverse direction
$scope.reset = function(){}; //clears filters, sorts and paging to send to server
</code>```

In my html I have the following things:

```<code><input type="date" ng-model="filters.due_from" />

<td><a on-click="sortBy('customer_id')"></td>
</code>```

Ultimately I think my question is, should I be creating a service/factory called JobsListModel rather than having all this functionality in the controller?


问:
Where to put css media queries in a CSS file?
Where to put CSS media queries?
Each after the related element class style or pack them at the bottom of the CSS files?
which one is standard? or which one do you prefer?</p>

答:
It mostly depends on your project because at the end of the day it is all about maintenance and adding more stuff to it easily.

So, if you are working on a project which only has a few media queries I would suggest leaving them all in one stylesheet but putting comments on top of it to make it explicit and also easier for you to find it later.

However, if you know you are going to have a lot of properties meticulously defined in your media queries and also have various devices defined then I would suggest separating them out just for readability/maintenance reasons.

ContentLicense: CC BY-SA 4.0


答:
When Mr. Martin applies the SRP to a function, he's implicitly extending his definition of SRP.  As the SRP is an OO-specific wording of a general principle, and since it's a good idea when applied to functions, I don't see a problem with that (although it might have been nice if he'd explicitly included it in the definition).

I don't see more than one reason to change either, and I don't believe that thinking of the SRP in terms of "responsibilities" or "reasons to change" is helpful.  Essentially what the SRP is getting at is that software entities (functions, classes, etc.) should do one thing and do it well.

If you take a look at my definition, it's not any less vague than the usual wording of the SRP.  The problem with usual definitions of the SRP is not that they're too vague, but that they try to be too specific about something that is essentially vague.

If you look at what calculatePay does, it is clearly doing a single thing: dispatch based on type.  Since Java has built-in ways of doing type based dispatch, calculatePay is inelegant and non-idiomatic, so it should be rewritten, but not for the stated reasons.


问:
Robot in a grid
This was recently asked to someone I know.

A robot has to move in a grid which is in the form of a matrix. It can go to

A(i,j)--> A(i+j,j) (Down)

A(i,j)--> A(i,i+j) (Right)

Given it starts at (1,1) and it has to go to A(m,n), find the minimum number of STEPS it has to take to get to (m,n) and write

```<code>    public static int minSteps(int m,int n)
</code>```

For instance to go from (1,1) to m=3 and n=2 it has to take (1, 1) ->
  (1, 2) -> (3, 2) i.e. 2 steps

Unfortunately for my friend answered it as though it was the other well known question of finding number of unique paths.

How to solve to find min number of steps taken to reach m,n?

答:
Something interesting happens when we ask, "What happens if we go backwards?".

So we want to go from A(i+j, j) -> A(i, j) to go left, and A(i, i+j) -> A(i, j) to go up.  Since things could get confusing if I kept using i and j, I'm going to use x and y, and say that we're going backward from A(x, y) whether we're going left or up.

We get these formulas:

Left: A(x, y) -> A(x-y, y)

Up: A(x, y) -> A(x, y-x)

First thing to notice: if x=y, then we get a 0 coordinate in both formulas, so we know that anything on the diagonal that isn't our starting point is unreachable.

Second thing to notice: we have x-y in one formula and y-x in the other.  Since x and y are always positive, at least one of the two possible locations we could have come from is impossible.

That means we can figure out exactly which square we came from, unless the square is unreachable, in which case it either is a diagonal square, or it came from a diagonal square.  By backtracking all the way from a reachable square, we get the only path, which must be the path with the smallest length.

The following is my solution to the problem that was originally presented:

There is only one way for j to change, and when it does, it increases by 1 because the robot stepped to the right.  We know j started at 1 and ended at n, so we know how many steps to the right it took.

Same thing with i and steps down.

Which path it took is irrelevant.

Title: Robot in a grid


问:
What is the ettiquite for releasing a Perl module based on someone else's module?
I have written a Perl module by starting with an existing Perl module of related functionality and modifying heavily. In fact, acccording to git blame I have changed (or created) every line of non-biolerplate code in the module. Of course, I have also changed the name of the module, so if I uploaded it to CPAN, it would not directly conflict with the original module.

Anyway, despite my heavy modifications, the module is still conceptually based on its predecessor, and I would like to give credit to its authors. However, I can see how they might not appreciate having their names and emails slapped on what appears to be a new module without their knowing. So should I just put myself as the sole author and put the original module's authors in an "Acknowledgements" section? What is the best way to credit the original authors in my module?

答: Since you based your work on his work, chances are you have no choice but to acknowledge him in the copyright notice. (Depending on the open source license he choosed)</p>


问:
The dream of declarative programming
Why hasn't the dream of declarative programming been realized? What are some concrete obstacles getting in the way? For a simple example why can't I say

```<code>sort(A) is defined by sort(A) in perm(A) && asc(sort(A))
</code>```

and automatically get a sorting algorithm out of it. perm means permutations and asc means ascending.

答:
Logical languages already do this. You can define sort similarly like you are doing it.

The main problem is performance. Computers might be great at computing lots of stuff, but they are inherently dumb. Every "clever" decision a computer might make was programmed into it by a programmer. And this decision is usually described not by how the end result looks like, but by how to achieve, step by step, this end result.

Imagine the story of a Golem. If you try to give him an abstract command, then at best, he will do it inefficiently and at worst, will hurt himself, you or someone else. But if you describe what you want in the greatest detail possible, you are guaranteed that task will be completed effectively and efficiently.

It is the programmer's job to decide on what level of abstraction to use. For the application you are making, are you going to go high-level and describe it in abstract way and take the performance hit or go low and dirty, spend 10x more time on it, but get algorithm that is 1000x more performant?

Title: The dream of declarative programming


答:
In addition to Euphoric's excellent point, I'd like to add that we already are using declarative languages in many places where they work well, i.e. describing state that isn't likely to change or requesting something for which the computer actually can generate efficient code on its own:

HTML declares what the content of a web page is.

CSS declares what various types of elements in a web page should look like.

Every relational database has a data definition language that declares what the structure of the database is.

SQL is much closer to declarative than imperative, since you tell it what you want to see and the database's query planner figures out how to actually make it happen.

One could argue that most configuration files (.vimrc, .profile, .bashrc, .gitconfig) are using a domain-specific language that's largely declarative

Title: The dream of declarative programming

Body:
Why hasn't the dream of declarative programming been realized? What are some concrete obstacles getting in the way? For a simple example why can't I say

```<code>sort(A) is defined by sort(A) in perm(A) && asc(sort(A))
</code>```

and automatically get a sorting algorithm out of it. perm means permutations and asc means ascending.


答:
Mostly the problem is how you model the data; and declarative programming isn't helping here. In imperative languages you already have tons of libraries that does lots of stuff for you, so you only need to know what to call. In a particular way one might consider this declarative programming (probably the best example for this is Stream API in Java 8). Having this, the abstraction is already resolved and declarative programming isn't necessary.

Also, as it has been said, logic programming languages already do exactly what you want. One might say the problem is performance, but with today's hardware and research in this area, things can be improved to be ready for production use; actually Prolog is used for AI stuff, but I believe only by academia.

It is to be noted that it applies for general-purpose programming languages. For domain specific languages, declarative languages are way better; SQL probably is the best example.

Title: The dream of declarative programming


问:
Would there be any benefit to writing synchronous code using the syntax of promises
Is there such a concept as a synchronous promise? Would there be any benefit to writing synchronous code using the syntax of promises?

```<code>try {
  foo();
  bar(a, b);
  bam();
} catch(e) {
  handleError(e);
}
</code>```

...could be written something like (but using a synchronous version of then);

```<code>foo()
  .then(bar.bind(a, b))
  .then(bam)
  .fail(handleError)
</code>```

答:
Absolutely!  For several reasons:

Promises provide an excellent error checking system.  You can return a promise and let the caller deal with the promise however he or she wishes (or not at all).

Many would argue that promises make your code cleaner and easier to read, which is no small thing.  I would argue that promises are worth using if for no other reason than the fact that it is elegant.

Last, but certainly not least, your implementation now is synchronous but should that ever change, you don't have to change a big section of code in order to make synchronous work asynchronously, but just the actual implementation.

Now, please don't get me wrong, I don't think you should use promises for every thing you do in the program, though for something that is even mildly cpu-intensive or complicated, I would get into the habit of using promises to implement these operations.

The main drawback is that promises are not fully supported in older browsers, so if you decide to go this route, consider using some polyfill library like bluebird or q to make it work both in newer browsers as well as older browsers.

Hope that helps!


答:
This is a dynamic programming problem. The idea is to try all paths and return the minimum number of steps taken each time.

```<code>int MinSteps( int posX, int posY, int destX, int destY)
{
    // if we reached the destination
    if (posX == destX && posY == destY)
      return 0;

     // if we didn't reach the dest we need to penalize this path so we return INT_MAX
    if (posX >= arraySizeX || posY >= arraySizeY )
     return INT_MAX;

  return min( MinSteps(posX+posY, posY), MinSteps(posX, posY+posX) ) + 1;
}
</code>```

Since we are recalculating the same path several times, An obvious optimization is to use memoization to store the min steps take so far.

```<code>// Table should be init with INT_MAX except the first column with 0.
int MinSteps( int posX, int posY, int destX, int destY, int** table)
{
    // if we reached the destination
    if (posX == destX && posY == destY)
      return 0;

     // if we didn't reach the dest, we need to penalize this path so we return INT_MAX
    if (posX >= arraySizeX || posY >= arraySizeY )
     return INT_MAX;

   // If we already calculate this paths min steps we only look it up
   if (table[posX][posY] != INT_MAX)
    return table[posX][posY];

  table[posX][posY]= min( MinSteps(posX+posY, posY), MinSteps(posX, posY+posX) ) + 1;
}
</code>```

Title: Robot in a grid

Body:
This was recently asked to someone I know.

A robot has to move in a grid which is in the form of a matrix. It can go to

A(i,j)--> A(i+j,j) (Down)

A(i,j)--> A(i,i+j) (Right)

Given it starts at (1,1) and it has to go to A(m,n), find the minimum number of STEPS it has to take to get to (m,n) and write

```<code>    public static int minSteps(int m,int n)
</code>```

For instance to go from (1,1) to m=3 and n=2 it has to take (1, 1) ->
  (1, 2) -> (3, 2) i.e. 2 steps

Unfortunately for my friend answered it as though it was the other well known question of finding number of unique paths.

How to solve to find min number of steps taken to reach m,n?

Body:
This is a dynamic programming problem. The idea is to try all paths and return the minimum number of steps taken each time.

int MinSteps( int posX, int posY, int destX, int destY)
{
    // if we reached the destination
    if (posX == destX && posY == destY)
      return 0;

     // if we didn't reach the dest we need to penalize this path so we return INT_MAX
    if (posX >= arraySizeX || posY >= arraySizeY )
     return INT_MAX;

  return min( MinSteps(posX+posY, posY), MinSteps(posX, posY+posX) ) + 1;
}

Since we are recalculating the same path several times, An obvious optimization is to use memoization to store the min steps take so far.

// Table should be init with INT_MAX except the first column with 0.
int MinSteps( int posX, int posY, int destX, int destY, int** table)
{
    // if we reached the destination
    if (posX == destX && posY == destY)
      return 0;

     // if we didn't reach the dest, we need to penalize this path so we return INT_MAX
    if (posX >= arraySizeX || posY >= arraySizeY )
     return INT_MAX;

   // If we already calculate this paths min steps we only look it up
   if (table[posX][posY] != INT_MAX)
    return table[posX][posY];

  table[posX][posY]= min( MinSteps(posX+posY, posY), MinSteps(posX, posY+posX) ) + 1;
}


问:
Where should the following business logic be written?
I have a C# console application. This application has many different projects/C# class files, each of them dedicated to parsing a certain kind of XML and creating an object, called 'Response'. Now, each of these individual projects parses the XML, and gets an error msg field (stores it in the 'Response' object) from these different xmls. Now, based on this error msg, I want to set the value of an other field of the 'Response' object. This processing logic is the same for all the projects.
So my question is, should that processing be done just before saving the 'Response' object in the DB, and hence making changes to only 1 single file?
Or, should this be a common method in a base class, invoked on all the 30 projects/C# class files?</p>

答: So just going purely on the limited information in your description, the common base class seems like an appropriate place to put common processing logic.</p>


答:
This can easily be brute-forced using breadth-first search.

Simplest algorithm using queue. The performance could be improved by remembering points that were already visited. And because you are using breath-first, you are sure the previously visited locations were closer. (sorry for C# code).

```<code>    private struct Location
    {
        public int X { get; set; }
        public int Y { get; set; }
        public int Distance { get; set; }
    }

    public static int minSteps(int m, int n)
    {
        Queue<Location> locations = new Queue<Location>();
        locations.Enqueue(new Location(){X = 1, Y = 1, Distance = 0});

        while(locations.Count > 0)
        {
            var loc = locations.Dequeue();

            // if it reached the target location
            if(loc.X == m && loc.Y == n)
            {
                return loc.Distance;
            }

            // if we went past the location then this path is invalid
            if(loc.X > m || loc.Y > n)
                continue;

            locations.Enqueue(new Location{ X = loc.X + loc.Y, Y = loc.Y, Distance = loc.Distance+1});
            locations.Enqueue(new Location{ X = loc.X, Y = loc.X + loc.Y, Distance = loc.Distance + 1 });
        }

        throw new Exception("No path found!");
    }
</code>```

Title: Robot in a grid

Body:
This can easily be brute-forced using breadth-first search.

Simplest algorithm using queue. The performance could be improved by remembering points that were already visited. And because you are using breath-first, you are sure the previously visited locations were closer. (sorry for C# code).

    private struct Location
    {
        public int X { get; set; }
        public int Y { get; set; }
        public int Distance { get; set; }
    }

    public static int minSteps(int m, int n)
    {
        Queue<Location> locations = new Queue<Location>();
        locations.Enqueue(new Location(){X = 1, Y = 1, Distance = 0});

        while(locations.Count > 0)
        {
            var loc = locations.Dequeue();

            // if it reached the target location
            if(loc.X == m && loc.Y == n)
            {
                return loc.Distance;
            }

            // if we went past the location then this path is invalid
            if(loc.X > m || loc.Y > n)
                continue;

            locations.Enqueue(new Location{ X = loc.X + loc.Y, Y = loc.Y, Distance = loc.Distance+1});
            locations.Enqueue(new Location{ X = loc.X, Y = loc.X + loc.Y, Distance = loc.Distance + 1 });
        }

        throw new Exception("No path found!");
    }


答:
Abstractions are leaky

You can implement a declarative system where you declare what you want, and the compiler or interpretator figures out an order of execution. The theoretical benefit is that it frees you from having to think about the 'how', and you don't have to detail this implementation. However, in practice for general purpose computing you still have to think about the 'how' and write all kinds of tricks while keeping in mind how this will be implemented, since otherwise the compiler can (and often will) choose an implementation that will be very, very, very slow (e.g. n! operations where n would suffice).

In your particular example, you will get A sorting algorithm - it doesn't mean that you will get a good or even a somewhat usable one. Your given definition, if implemented literally (as a compiler likely would) results in http://en.wikipedia.org/wiki/Bogosort which is unusable for larger datasets - it is technically correct, but needs an eternity to sort a thousand numbers.

For some limited domains you can write systems that almost always do well in figuring out a good implementation, for example, SQL. For general purpose computing that doesn't work particularly well - you can write systems in, say, Prolog but you have to visualize how exactly your declarations will be converted to an imperative execution order in the end, and that loses much of the expected declarative programming benefits.

Title: The dream of declarative programming


答:
Computational decidability is the most important reason declarative programming has not proven to be as easy as it seems to be.

Many problems that are relatively easy to state have proven to be undecidable or have NP-complete complexity to solve. This often occurs when we take into account negative classes and classification, countability and recursion.

I'd like to examplify this with some domains that are well known.

Decision on which CSS class to use needs knowledge and consideration of all CSS rules. Adding new rules might invalidate all other decisions. Negative CSS classes are intentionally not added to the language, because of NP-complete problems, but the lack of negative classes complicates CSS design decisions.

Within an (SQL) query optimizer, there is the nettlesome problem of deciding in which order to join, which indices to use and which memory to allocate to which temporary results. This is a known NP-complete problem and complicates database-design and query formulation. To formulate it differently: when designing a database or a query, the designer needs to know the actions and order of actions the query optimizer is likely to take. An experienced engineer needs knowledge of the heuristics used by major database vendors.

Configuration files are declarative, but certain configurations are hard to declare. For example, to properly configure features one needs to take into account versioning, deployment (and deployment history), possible manual overrides and possible conflicts with other settings. To properly validate a configuration might become an NP-complete problem.

The result is that these complications take beginners by surprise, they break the 'beauty' of declarative programming and they cause some engineers to search for other solutions. The migration of inexperienced engineers from SQL to NoSQL might have been triggered by the underlying complexities of relational databases.

Title: The dream of declarative programming


问:
Is there any plan to take out "features" from next versions of javascript?
I'm looking to learn javascript (now for real) and I've had a look on the latest version of ES6 which is supposed to be frozen in terms of features set.
It seems to be the pretty much same as ES5 plus new stuff(features). My main complain is that there so many ways to accomplish the same thing so I'm wondering if there is any plan to take out some of the old "features" or if it keeps building up on top of the old specs(i.e. until it becomes a big mess).  </p>

答:
I disagree, the main goal of ES6 is not to introduced new ways "to accomplish the same thing" but actually cover some areas that were not covered at all.

Generators are extremely helpful for the class of tasks where you should iterate through a big list of items but you don't need to keep all this items in memory at one time. This is something that just was very hard to emulate.

Or let's take a look on Sets and Maps - before now you were limited by the fact that there was impossible to have any keys in hash other than strings.

Varargs, optional arguments, arrow functions, string interpolation, destructuring assignment - all these, yes, actually can be treated as a sugar syntax but from my experience I hardly can treat current approaches competitive with new ones, new one are better and most likely will always be used instead.

So, saying all this I can actually think of features that can be excluded "in exchange". Even if the maximum compatibility won't be treated as crucial aspect (it does), there's nothing much to throw away.

As of small incositencies, they are actually get fixed by introducing new stricter mini APIs - check out, for example, Number.isNaN. From time to time older APIs are deprecated and even excluded but this not a fast process and actually it should not be.


问:
Can I update an attached object using a detached but equal object?
I retrieve movie data from an external API. In a first phase I will scrape each movie and insert it into my own database. In a second phase I will periodically update my database by using the API's "Changes" API which I can query to see what movies have had their information changed.

My ORM layer is Entity-Framework. The Movie class looks like this:

```<code>class Movie
{
    public virtual ICollection<Language> SpokenLanguages { get; set; }
    public virtual ICollection<Genre> Genres { get; set; }
    public virtual ICollection<Keyword> Keywords { get; set; }
}
</code>```

The problem arises when I have a movie that needs to be updated: my database will think of the object being tracked and the new one that I receive from the update API call as different objects, disregarding .Equals().

This causes a problem because when I now try to update the database with the updated movie, it will insert it instead of updating the existing Movie.

I had this issue before with the languages and my solution was to search for the attached language objects, detach them from the context, move their PK to the updated object and attach that to the context. When SaveChanges() is now executed, it will essentially replace it.

This is a rather smelly approach because if I continue this approach to my Movie object, it means I'll have to detach the movie, the languages, the genres and the keywords, look up each one in the database, transfer their IDs and insert the new objects.

Is there a way to do this more elegantly? Ideally I just want to pass in the updated movie to the context and have that select the correct movie to update based on the Equals() method, update all its fields and for each complex object: use the existing record again based on its own Equals() method and insert if it doesn't exist yet.

I can skip the detaching/attaching by providing .Update() methods on each complex object which I can use in combination of retrieving all the attached objects but this will still require me to retrieve every single existing object to then update it.

答: Since you are dealing with different fields id and tmbid, i suggest that updating the API to make a single and separate index of all the info like genres,languages,keywords etc... And then make a call to index and check for info rather than gathering the whole info about specific object in your Movie class.


问:
Secure Rest api from authenticated user
Let's say that my Rest api is secured using OAuth 2. Let's say my client is a mobile App. Let's say that i have an Api call:

```<code>@Post /increasePoints host:https://www.example.com/increasePoints  amout=10
</code>```

Now Using this api call, one should have a valid Access Token. from my app i have control when to call this function so there is no problem. but Let's say the authenticated user get a hold of the access token. how can i stop him from posting to this api using his access token?

Few options that i thought of:

sign each call with a special header.

use client_authentication with scope points - i've just read about this type of authentication but the user can get the access token with same ease for what i understand.

答:
You need to store the API token in your sever and need to validate it in database for each API call ,
So when u need to revoke access , remove the API token from the database , so it will invalid during next call</p>

Title: Secure Rest api from authenticated user


问:
Is setting "permanent" persistent login cookies a bad practice?
I realized that in Rails there is a built in permanent method for its persistent login cookies (aka. "remember me" cookies) method to give the client a cookie that expires in 20 years:

cookies.permanent[:remember_token] = remember_token

However it seems that in a lot of websites the cookies are set to expire in a far shorter time period, say 3 months or 2 weeks, after which the client will have to log in again.

Is it really a markedly bad practice to set a persistent login cookie to be stored permanently? Why or why not? If it's bad, why does it seem that a considerable number of developers are doing so, such that Rails has provided a built-in method to support the practice.

答: The usage of permanent cookies depends on how you use it. It can be an asset for improving user experience such as automatic login etc.. But remember that leaving a cookie for a long time might even turn into a vulnerability. So it's best to set the cookie to remain for how long you actually need it rather than opting for permanent thing. </p>


问:
Is it wise for a high level developer to spend time studying assembly?
It is clear that the knowledge of low level stuff is very important in our work.

But in a situation where you're already developing commercial software on a high level, and when you already have a chosen direction but don't have any assembly skill, isn't it more reasonable to focus on studying stuff related to your direction? Or is there a reason you should spend some time to learn the low-level basics anyway?

When is it too late, and when it is not? And if it is not too late, then how would one go about learning optimally (in the sense of not spending excessive time to get some depth and understanding)?

答:
In the Teaching profession, at least here in the UK, teachers have to be qualified far in excess of what they teach.  A Secondary (High School) teacher would be expected to have a degree in the subject they taught, and Primary (Elementary) school teachers have degrees too, and have to be proficient in all major subjects up to a good grade GCSE level (high school exit exams?, no real US wide equivalent).

Why? Because in order to teach something well, or indeed use something well, you have to understand it.  This requires understanding the underlying structure, the chain of decisions before the one you are working with that led to it.  In order to properly understand high level code, you must understand the layer upon which it is built, how it operates, where its strengths and weaknesses lie.  This is recursive, to understand the layer beneath, you must understand the layer beneath that as well.

In the end, this is why the decent university/college courses in Computing ask for good maths ability before everything else, as that is effectively the bottom rung.

```<code>Maths -> Physics                ->
      -> Chemistry -> Materials -> Hardware Design -> Microcode      -> Assembler
                                                   -> Bus Interfaces -> Peripherals

... Assembler    -> Low Level      -> High Level   ->
... OS / Drivers -> API Level      -> Applications -> User
</code>```

If you lack knowledge in these areas, then your understanding is compromised beneath it.  The closer to the level you operate another layer is, the more important it is to have a grounding in it.

So: Do you need to know assembler as a high-level coder?  It will help.

Body:
In the Teaching profession, at least here in the UK, teachers have to be qualified far in excess of what they teach.  A Secondary (High School) teacher would be expected to have a degree in the subject they taught, and Primary (Elementary) school teachers have degrees too, and have to be proficient in all major subjects up to a good grade GCSE level (high school exit exams?, no real US wide equivalent).

Why? Because in order to teach something well, or indeed use something well, you have to understand it.  This requires understanding the underlying structure, the chain of decisions before the one you are working with that led to it.  In order to properly understand high level code, you must understand the layer upon which it is built, how it operates, where its strengths and weaknesses lie.  This is recursive, to understand the layer beneath, you must understand the layer beneath that as well.

In the end, this is why the decent university/college courses in Computing ask for good maths ability before everything else, as that is effectively the bottom rung.

Maths -> Physics                ->
      -> Chemistry -> Materials -> Hardware Design -> Microcode      -> Assembler
                                                   -> Bus Interfaces -> Peripherals

... Assembler    -> Low Level      -> High Level   ->
... OS / Drivers -> API Level      -> Applications -> User

If you lack knowledge in these areas, then your understanding is compromised beneath it.  The closer to the level you operate another layer is, the more important it is to have a grounding in it.

So: Do you need to know assembler as a high-level coder?  It will help.


问:
Is public final completely (not) ok in constant enum fields?
When I make enums that hold some fields, like my Settings enum, I like to make them public final to avoid lots of ( and ) keystrokes:

```<code>public enum Settings {
  SETTING_TEST("bool_setting1", false),
  USERNAME("user_name", "me")
  ;

  public final String name;
  public final Object default_val;
  Setnames(String n, Object d) {
    name = n;
    default_val = d;
  }
}
</code>```

This enum is then applied to look up (or set the default) settings in some  hashmap (encapsulated in more sophistiated class). This design allows to control the setting names over the whole project (since enum names can be refactored, unlike strings).

My teacher warned me about this design though, and there are some answers suggesting that you can regret designing your project with public final without encapsulation.

I'm not only asking for rules and conventions but also your experience (the help center doesn't say anything negative about asking for opinions, so I do so). While I'd gladly even expand the question on other languages that support features in question, I'm not sure this wouldn't make the question too broad - which is why I think we should stick to Java only.

Edit:

The SE GUI asks me to explain how is my question different from the one I linked to. Other people already pointed out in comments the difference, but let's repeat it:

Most answers on the other question point out problems not applicable to enums. Often we use getXXX encapsulation to allow classes extend our class properly. But we cannot extend from enum. Generally, despite similar syntax, enums are substantially different from classes and interfaces.

答:
My personal opinion is that public final is generally fine everywhere, not just on enums.

In my book, there are only two reasons for not using public final, and these are:

Allowing for future changes which might require altering the nature of the fields while maintaining binary compatibility with external code. (A getter would allow this.)

Typing 'get' and letting autocomplete show me everything that I can read from an object without having to scroll up and down in the autocomplete list to see if besides getter methods there are also any public final fields that I can read (whose names presumably do not start with get.)

As for the points made by the answer that you linked to, none of them are applicable to enums.

So, even if you don't agree that public final is generally fine everywhere, still, at least for enums, it is really-really fine.


问:
Physics/Game Engine in C++ for mobile app
First post so be gentle.

I am a junior seeking a Comp Sci major and was looking into making a mobile game. I wanted to use this for my thesis project next year, and possibly a way to pay back college loans. I do know how to make android apps since I have done some for a class.

My idea is to make a shuffle board game using my own physics engine in C++. Obviously this is a huge undertaking, but I think it will look pretty good on my resume.

I need help understanding how to connect my C++ engine to an android application. Should I code the whole app in C++, or how do I use the Android SDK to import this?

How would I go about making graphics for the game? Any good programs? I might have this covered since YouTube is a good starting point; just looking for some suggestions. This is my weakest point since I am not heavily invested in graphic design, but I have dabbled in some photoshop before.

Since I want to use c++ for the engine, would this be pretty easy to port over to iOS?

Also, would I rather make a physics or game engine in this circumstance? And what would be my first step.

Thanks for any help!

答:
I wanted to use this for my thesis project next year, [...]

Using a mobile game for your thesis is non-trivial (you will probably need your project's documentation to include game theory and what not (I think this is how Tetris was invented). Good luck!

[...] and possibly a way to pay back college loans.

Steps:

write game

???

proffit

In short, do not make a plan that relies on the financial success of your game. It is very probable your game will not achieve financial success of any kind. Also, if you solve step 2 above, please let us know ;)

My idea is to make a shuffle board game using my own physics engine in C++. Obviously this is a huge undertaking, but I think it will look pretty good on my resume.

Creating a physics engine sounds ... big. Very big! (as in "five years of effort to get stability and feature completeness" big).

I need help understanding how to connect my C++ engine to an android application.

Create a library in C++, export it's interface as JNI, create Dalvik application that uses said interface; rinse, repeat; Basically, you would have a Dalvik application that uses internal libraries (like all other applications that use libraries).

Should I code the whole app in C++, or how do I use the Android SDK to import this?

Your call!

Since I want to use c++ for the engine, would this be pretty easy to port over to iOS?

Not by itself, no. To achieve portability you need to depend on the same libraries on both systems. You could make the application easier to port to iOS, by choosing what libraries to use based on how available they are on both systems, but getting it to "pretty easy to port" will probably take a lot of effort.

Also, would I rather make a physics or game engine in this circumstance? And what would be my first step.

Your first step should probably be to check out existing game/physics engines and their capabilities, and choose an existing one (which is fine, unless you plan your thesis to be on physics engines - then you should write your own).


问:
Why aren't `void *`'s implicitly cast in C++?
In C, there is no need to cast a void * to any other pointer type, it is always safely promoted. However, in C++, this is not the case. E.g.,

```<code>int *a = malloc(sizeof(int));
</code>```

works in C, but not in C++. (Note: I know that you shouldn't use malloc in C++, or for that matter new, and should instead prefer smart pointers and/or the STL; this is asked purely out of curiosity) Why does the C++ standard not allow this implicit cast, while the C standard does?

答:
In C, there is no need to cast a void * to any other pointer type, it is always safely promoted.

It's always promoted, yes, but hardly safely.

C++ disables this behaviour precisely because it attempts to have a safer type system than C, and this behaviour is not safe.

Consider in general these 3 approaches to type conversion:

force the user to write everything out, so all conversions are explicit

assume the user knows what they're doing and convert any type to any other

implement a complete type system with type-safe generics (templates, new-expressions), explicit user-defined conversion operators, and force explicit conversions only of things the compiler can't see are implicitly safe

Well, 1 is ugly and a practical obstacle to getting anything done, but might genuinely be used where great care is needed. C roughly opted for 2, which is easier to implement, and C++ for 3, which is harder to implement but safer.


答:
Because implicit type conversions are usually unsafe, and C++ takes a more safe stance to typing than C does.

C will usually allow implicit conversions, even if most chances are that the conversion is an error. That's because C assumes that the programmer knows exactly what they are doing, and if not, it is the programmer's problem, not the compiler's problem.

C++ will usually disallow things that could potentially be errors, and require you to explicitly state your intention with a type cast.  That's because C++ is trying to be programmer-friendly.

You might ask how come it is friendly when it is actually requiring you to type more.

Well, you see, any given line of code, in any program, in any programming language, will generally be read many more times than it will be written (*). So, ease of reading is much more important than ease of writing.  And when reading, having any potentially unsafe conversions stand out by means of explicit type casts helps to understand what is going on and to have a certain level of certainty that what is happening is in fact what was intended to happen.

Besides, the inconvenience of having to type the explicit cast is trivial compared to the inconvenience of hours upon hours of troubleshooting to find a bug which was caused by a mistaken assignment that you could have been warned about, but never were.

(*) Ideally it will be written only once, but it will be read every time someone needs to review it to determine its suitability for reuse, and every time there is troubleshooting going on, and every time someone needs to add code near it, and then every time there is troubleshooting of nearby code, and so on. This is true in all cases except for "write-once, run, then throw away" scripts, and so it is no wonder that most scripting languages have a syntax which facilitates ease of writing with complete disregard to ease of reading. Ever thought that perl is completely incomprehensible? You are not alone. Think of such languages as "write-only" languages.

Title: Why aren't `void *`'s implicitly cast in C++?

Body:
In C, there is no need to cast a void * to any other pointer type, it is always safely promoted. However, in C++, this is not the case. E.g.,

```<code>int *a = malloc(sizeof(int));
</code>```

works in C, but not in C++. (Note: I know that you shouldn't use malloc in C++, or for that matter new, and should instead prefer smart pointers and/or the STL; this is asked purely out of curiosity) Why does the C++ standard not allow this implicit cast, while the C standard does?


答:
public final is OK in my book when you're implementing something that's just a data container. Making all the fields public final makes it clear that once the object is constructed, all the fields are available and there'll be no funny business going on behind the scenes (lazy initialization, computed values, values retrieved from I/O or whatever.)

The usual reasoning behind getters is that some day you might need your object to be a little "smarter". But you've already committed to using an enum, which presupposes that all the data is statically available and that your objects have value semantics. I'd bet that if you ever need to undo decision to use public final fields, an enum will probably no longer be right choice either.

The one time getters are absolutely necessary is when the class you're writing is part of the public API of a publicly available library, because you want to maintain binary compatibility at all costs. You don't want to introduce a backwards-incompatible change for something as trivial as changing a getter.

Title: Is public final completely (not) ok in constant enum fields?

Body:
When I make enums that hold some fields, like my Settings enum, I like to make them public final to avoid lots of ( and ) keystrokes:

```<code>public enum Settings {
  SETTING_TEST("bool_setting1", false),
  USERNAME("user_name", "me")
  ;

  public final String name;
  public final Object default_val;
  Setnames(String n, Object d) {
    name = n;
    default_val = d;
  }
}
</code>```

This enum is then applied to look up (or set the default) settings in some  hashmap (encapsulated in more sophistiated class). This design allows to control the setting names over the whole project (since enum names can be refactored, unlike strings).

My teacher warned me about this design though, and there are some answers suggesting that you can regret designing your project with public final without encapsulation.

I'm not only asking for rules and conventions but also your experience (the help center doesn't say anything negative about asking for opinions, so I do so). While I'd gladly even expand the question on other languages that support features in question, I'm not sure this wouldn't make the question too broad - which is why I think we should stick to Java only.

Edit:

The SE GUI asks me to explain how is my question different from the one I linked to. Other people already pointed out in comments the difference, but let's repeat it:

Most answers on the other question point out problems not applicable to enums. Often we use getXXX encapsulation to allow classes extend our class properly. But we cannot extend from enum. Generally, despite similar syntax, enums are substantially different from classes and interfaces.


答:
By definition, A void pointer can point to anything. Any pointer can be converted to a void pointer and thus, you will be able to convert back arriving at the exact same value. However, pointers to other types may have constraints, such as alignment restrictions. For example, imagine an architecture where characters can occupy any memory address but integers must start on even address boundaries. In certain architectures, integer pointers might even count 16, 32 or 64 bits at a time so that a char * might actually have a multiple of the numeric value of int * while pointing to the same place in memory. In this case, converting from a void * actually would round off bits which can not be recovered and is therefore not reversible.

Put simply, the void pointer can point to anything, including things that other pointers may not be capable of pointing to. Thus, the conversion to the void pointer is safe but not the other way around.


问:
Can i create a function with variable parameters in C?
I've always wondered where a single function such as printf(); can take in variable parameters and provide the right results. For example,

```<code>printf("Number is %d",a);
</code>```

which has two parameters, and

```<code>printf("Numbers are %d and %d",a,b);
</code>```

which has three variables.
So, is there any possibilities for creating a user-defined function like these functions in C? If so, how can i do it?
Thanks in advance.

答:
Interestingly, the C standard defines what variadic function declarations should look like, but no guidance in how to implement them.

The mechanics for accessing arguments to variadic functions are therefore implementation-dependent. GNU C provides this via stdarg.h.


问:
MVC with Post/Redirect/Get
I have a question in mind for the MVC pattern for a long time now. When using the Post/Redirect/Get principle then it doesn't make sense to use ONE model in the sense of MVC, right? Why should I modify the data in the model if I don't use it anymore? Am I missing something?

So I need one model for the actions in the controller and one with the data for the view?

My current pattern:

controller

-> call and init model used for actions

-> handle actions using the action model, if an action has been executed, use P/R/G to reload

-> call and init model used for the view

-> call view with template and pass view model

The point is, I don't want to load all the data for the view if I possibly don't need it due to the redirect. Or am I just caring about that too much?

答:
All the data in your view is from the last GET, it has already been loaded, processed, and forgotten.  The POST action is just updating some of it.  What is reloaded during the POST just depends on the model and how it is used.

The reason for the Post/Redirect/Get approach in my experience is to prevent the common issue of re-posting data when using the "back" and "forward" buttons in a browser.  The redirects happen server side and the browser just tosses out the POST from its history.  This also keeps the user from bookmarking the POST URL because it is displaying the GET view they want to reference later.

Once that redirect happens, any state you had in the POST action is lost, this includes any models that was called up.  However, it could also be that the POST action model didn't have all the data loaded anyways (such as updating an order address), therefore the GET would have to enrich it with another model (such as the line items in an order).

This assumes that you are not doing a lot of AJAX and/or client side dynamic stuff here.  That each view is all the data retrieved in one request.

Title: MVC with Post/Redirect/Get


问:
Groovy date/time compare
I have this string got from JIRA as the date/time I need to compare which one is earlier:"21/Sep/12 2:01 PM". How can I do this in Groovy?

Thanks
Jirong

答:
Based on the requirements you have put down I assume that you already have the date somewhere in code (if not check out com.atlassian.jira.component.ComponentAccessor). As for comparing the dates here is a short script and if you need more dates then just stack them up in an array and loop through them.

```<code>    import java.text.SimpleDateFormat;
    import java.util.*;

    class DateTimeComparer
    {
        public Date convertDateTime(String element) throws Exception
        {
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MMM/yy HH:mm a");
            return dateFormat.parse(element);
        }

        public static String compareDateTimes(Date date1, Date date2)
        {
            if (date1.after(date2)) return "date1 is after date2";

            if (date1.before(date2)) return "date1 is before date2";

            if (date1.equals(date2)) return "date1 is equal to date2";
        }

        public static void main(String[] args) throws Exception
        {
            DateTimeComparer dateTimeComparer = new DateTimeComparer();

            Date convertedDate = dateTimeComparer.convertDateTime("21/Sep/12 2:01 PM");
            Date today = new Date();

            String comparedDates = dateTimeComparer.compareDateTimes(today, convertedDate);

            println comparedDates;
        }
   }
</code>```

Title: Groovy date/time compare

Body:
Based on the requirements you have put down I assume that you already have the date somewhere in code (if not check out com.atlassian.jira.component.ComponentAccessor). As for comparing the dates here is a short script and if you need more dates then just stack them up in an array and loop through them.

    import java.text.SimpleDateFormat;
    import java.util.*;

    class DateTimeComparer
    {
        public Date convertDateTime(String element) throws Exception
        {
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MMM/yy HH:mm a");
            return dateFormat.parse(element);
        }

        public static String compareDateTimes(Date date1, Date date2)
        {
            if (date1.after(date2)) return "date1 is after date2";

            if (date1.before(date2)) return "date1 is before date2";

            if (date1.equals(date2)) return "date1 is equal to date2";
        }

        public static void main(String[] args) throws Exception
        {
            DateTimeComparer dateTimeComparer = new DateTimeComparer();

            Date convertedDate = dateTimeComparer.convertDateTime("21/Sep/12 2:01 PM");
            Date today = new Date();

            String comparedDates = dateTimeComparer.compareDateTimes(today, convertedDate);

            println comparedDates;
        }
   }


问:
Creating one-line method for the single purpose of self-documenting code
Given the following two snippets:

Snippet 1:

```<code>public void foo(Data data, AbstractNode node)
{
    int originalId = data.getCurrentId;
    node.execute(data);

    //If node changed currentId reset it to the original.
    data.setCurrentId(originalId);
}
</code>```

Snippet 2:

```<code>public void foo(Data data, AbstractNode node)
{
    int originalId = data.getCurrentId;
    node.execute(data);

    resetCurrentIdIfChangedByNode(data, originalId);
}

private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    data.setCurrentId(originalId);
}
</code>```

In both cases it is not be known whether node.execute() changes the currentId or not.

Does the one-line method in Snippet 2 make the code more readable? Or is it preferable to use comments as in Snippet 1?

EDIT: I understand that node has side effects. This is why I'm resorting to creating a method that explains (or tries to explain) that the data.currentId might be changed by node. Depending on which subclass of AbstractNode is being used, it might be changed or not.

EDIT 2: The reason there is no if statement around the reset in Snippet 2 is that it would be pointless, since the result would be the same whether we check or not.

```<code>private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    data.setCurrentId(originalId);
}
</code>```

same result as

```<code>private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    if(data.getCurrentId() != originalId)
    {
        data.setCurrentId(originalId);
    }
}
</code>```

答:
I'd say that the method name is actively misleading. After all, it always sets the ID, not only if node changed it!

To method 1, I'd add a comment explaining that node.execute(data) can change the ID, and why it is necessary to keep the old one.

Thirdly, consider making this a method on either node or data. Can't tell from this snippet whether that makes sense, but it might.


答:
Does the one-line method in Snippet 2 make the code more readable?

A little. The problem is that the new name is very tightly coupled to this specific code. Surely there are other reasons to reset the id to the original?

Or is it preferable to use comments as in Snippet 1?

No, that comment is worthless. You might put into a comment about why execute might change the id, or why you're resetting the id in the first place. Comment why, not what.

It's always best to eliminate the weird code in the first place, but how to do that will vary from situation to situation; and might not always be possible. If it's not possible, functions are preferable to comments, since you'll often need this sort of functionality in more than one place. Copy/pasting comments around is no good.

Title: Creating one-line method for the single purpose of self-documenting code

Body:
Given the following two snippets:

Snippet 1:

```<code>public void foo(Data data, AbstractNode node)
{
    int originalId = data.getCurrentId;
    node.execute(data);

    //If node changed currentId reset it to the original.
    data.setCurrentId(originalId);
}
</code>```

Snippet 2:

```<code>public void foo(Data data, AbstractNode node)
{
    int originalId = data.getCurrentId;
    node.execute(data);

    resetCurrentIdIfChangedByNode(data, originalId);
}

private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    data.setCurrentId(originalId);
}
</code>```

In both cases it is not be known whether node.execute() changes the currentId or not.

Does the one-line method in Snippet 2 make the code more readable? Or is it preferable to use comments as in Snippet 1?

EDIT: I understand that node has side effects. This is why I'm resorting to creating a method that explains (or tries to explain) that the data.currentId might be changed by node. Depending on which subclass of AbstractNode is being used, it might be changed or not.

EDIT 2: The reason there is no if statement around the reset in Snippet 2 is that it would be pointless, since the result would be the same whether we check or not.

```<code>private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    data.setCurrentId(originalId);
}
</code>```

same result as

```<code>private void resetCurrentIdIfChangedByNode(Data data, int originalId)
{
    if(data.getCurrentId() != originalId)
    {
        data.setCurrentId(originalId);
    }
}
</code>```


答:
The node.execute call is not a side-effect free function and you should probably change the implementation and avoid the need to reset the id altogether.

If for some reason you can't, the second version has a very confusing method name as it implies that method actually checks if the id was changed by the node, which is doesn't. So simply use the first example but add a comment that explains the execute might have changed the id and you need to keep it.