问:
Is there any particular reason for the use of lists over queues in functional programming languages?
Most functional programming languages such as Scheme and Haskell use lists as their main data structure. Queues are identical to lists, except for the fact appending to the end - not to the begin - has constant time. Every algorithm that is written elegantly using lists with head and tail can be written elegantly using queues with init and last.

Considering appending to the end is more common than the opposite, I'd guess queues are more natural than lists. Is there any reason lists have always been preferred?

答:
Queues are identical to lists, except for the fact appending to the end - not to the begin - has constant time.

Queues are commonly understood to be FIFO structures, which are not "identical to lists apart from appending to the end".  With queues, you typically write to the tail and read from the head; this is an entirely different semantic.

If you mean a LIFO structure, then you're really talking about a stack, which is how Lists are most commonly used in recursive/functional code.  In which case, why do you care that we call the location that we read from and write to the head or the tail?  The way of working with it would be the same either way.  The only context in which it would make a difference is where the list is also being used as a string (a rather mundane concern).

Lists/stacks are very useful structures in functional programming:

The head can represent the state of a computation.

The structure is persistent, minimizing copying while preserving immutability.

head and tail access in constant time with a much simpler structure than any indexed type (simpler underlying code etc).

Queues lose some of these benefits (e.g. persistence) and add complexity to no gain.  If the main benefit is that you find queues easier to understand, try harder.


问:
Force users to update to the latest version of my app on the Google Play Store
Is there a way to have a "critical update" for my app on the Google Play Store that would require the user to update the app to keep using it?

For instance, let say I push an update that brings a few bugfixes. Nothing mandatory, the user updates it if he wants to: that's a non-critical update.

Now, say I correct a very serious security issue on my app and want all the users to update to this version to keep using the app: this is a critical update.

Basically, if there is a critical update and the user has not updated yet, he cannot use the app until he does so.

Is this possible using the Play Store?

Thanks for your feedback!

答:
Application Licensing

The only way to force a user to update to the latest version is to use a licensing schema. There already exists the Application Licensing SDK that will allow you to register user's. Once they are registered you can revoke the license of old versions. Forcing the user to update if they want to continue to use the application.

You have to check the terms and conditions for licensing to see if Google allow licenses to be used in that fashion.

What you can do, what the user can do and who should do it. Is all technical/legal issues around the usage of your application. Did the user click an agreement for terms/conditions before using the application? Did you specify that the user agrees to accept updates, and to stop using old versions?

Unless you have put these terms in place for the user to agree to, and these terms don't conflict with Google's terms/conditions for apps, then I don't see a problem with forcing them to update.

With that said, I wouldn't agree to those terms and won't use the app ;)

ContentLicense: CC BY-SA 3.0


问:
What is meant by a step-by-step refactoring plan describing implementation of design

What is meant by a step-by-step refactoring plan describing how to
  implement a certain design?

As little as I know about refactoring it regards improving a (UML) design model and has nothing to do with the implementation of it. Therefore I'm pretty much confused by what this question means. Does anyone know and willing to explain?

EDIT: In the context the design corresponds to a UML diagram with classes, methods and underlying associations.

答:
You questions contains IMHO three misconceptions:

"design" does not necessary mean "UML model". On the contrary, in the context of software development "design" most often just means "the overall structure of a program, program system, or program code". Parts of that structure can be visualized by UML diagrams, but don't interchange the visualiziation of a design (UML model) with the design (code structure) itself.

"refactoring" means "restructuring an existing body of code, altering its internal structure without changing its external behavior" (cited from http://refactoring.com/). So refactoring has pretty much to do with the implementation of a design in code.

"implement a design" does not necessarily mean "coding in green field". It can also mean "achieve a certain design by any means" (for example, starting with some mediocre designed code and applying refactoring until its structure fits to a design described by a given UML model).

Refactoring can be used to change or improve code to change a code structure (so its design). Ideally this is achieved in many small steps (as opposed to one big "rewrite"). Typically, when doing this, you want to achieve some goal (a better design than before, or a design described with the help of a UML model), so it makes sense to make yourself a plan before you start with the actual refactoring.

For example, lets say you have a class A which has become too big over time and has too many responsibilities. Your goal is to break it down to classes B, C, and D to distribute the responsibilies among them. Before starting with that, you make a plan like this:

add some unit tests for method A.m1, which calls A.m2 internally.

add empty class B

move method m2 from A to B, change A.m1 to call B.m2 instead of A.m2

run all unit tests to make sure you did not break anything

add empty class C, and so on

The new class structure of B, C, and D can be described by a UML model, the steps in which order you apply the refactoring to go from A to (B,C,D) have typically to be described separately.


问:
Return values for CRUD methods?
I'm writing a basic web API in Java that does what almost all others do: take input, validate it, then do CRUD operations on the DB. I've written several APIs before, and I've pretty much already figured out what constitutes a good response back to the client.

However, like most APIs, there are several layers of objects invoked between the front-door client API object and the code that actually executes queries against the database. I've always struggled to know what those database interaction objects should return back to the functions calling them.

I imagine that on errors I'll be throwing exceptions and catching them farther up the call stack. However, what do I return on successes? Here's what I've used before:

Create - Return a boolean telling whether the create was successful or not

Read - Return the object requested

Update - Return a boolean telling whether the update was successful or not

Delete - Return a boolean telling whether the delete was successful or not

I feel comfortable with the Read and Delete returns, because I can't think of what else you'd return in those situations. However, I have no idea what the best practice would be for return values from create and update functions. Should I return a new object with the updated values? Should I modify the object that was passed in? Should I just return a boolean value denoting success or failure?

答:
On create, I usually return the ID of the entity I just created.  On an update, I return the object I just updated.  Delete I usually don't return anything.

In the case of create, the most interesting part is the id of what was created.  You throw an error if you couldn't create, so the boolean value you use isn't that interesting.  You could also return the entire object with the ID.

On an update, returning the object with any modified fields (either by the updater or someone else) makes the most sense.

Delete either works or you throw an exception, no need for a return value.

Title: Return values for CRUD methods?


问:
Framework in which views are defined in the database - design flaw or reasonable?
I'm working with a framework where the fields displayed on each web page are defined in the application database. Administrators can add new fields to pages or hide/completely delete old fields. The logic for each page is in a Java class - sometimes there's a one-to-one relationship between a page and a class, sometimes several pages use the same class.

The issue

This framework design creates a hidden dependency between the page data in the database and the logic in the Java class. If a new field is added to a page, the matching Java class must provide that field - or the page will break. The Java code has no compile-time knowledge of how the page is configured in the database (each customer database may have different configurations), which increases brittleness.

A typical solution has been to SELECT * from one or more database tables, allowing a degree of configuration as to which fields can be displayed. This leads to database-centric Java code with plenty of embedded SQL and little object-oriented design or domain models.

Solution plans

We've introduced a three-tier MVC-like architecture (controller -> service -> repository) with object-oriented models to the framework. It limits the ability to add fields to the pages without changing the underlying code. However, the change makes it possible to program in an object-oriented way and create domain models. Next up, we're planning to do something about the dependency between the database and code.

My long-term plan would be to move the page definitions from the database into the code (your standard HTML&JS views), limiting configurability but reducing brittleness. Any incompatibilities between the pages and Java would then become compiler errors when building the application instead of runtime errors.

Question(s)

Do you consider the framework practice of defining the view in the database and the controller in the code as sound design or something that should be addressed?

If you think the situation should be addressed, does my long-term plan seem reasonable?

Edit:

In addition to defining the layout, the view definitions in the database define which fields are expected to exist - "get field 'foobar' from the controller and show it here". The views themselves don't really contain logic. The Java classes backing up the views typically contain thousands of rows of UI and business logic.

答:
I can imagine a database-driven view representation that allows to edit views dynamically, without recompilation of any code. If this is your case, I suspect that the design has some merit.

If the Java code needs to be updated when the data describing a view in the DB has changed, I don't think the design is good; the description is better be held in the code.

In any case, 'plenty of embedded SQL' sounds bad enough. I'd think of some kind of an ORM.


问:
Do Scrum sprints mean to work at the fastest pace possible?
I recently interviewed with some companies that do Agile, Scrum to be more precise and there are some things that don't quite seem like Agile to me. I'll take one case that particularly interests me right now, that of Scrum sprints.

One particular project manager I talked to (yes, I said project manager) proudly stated that people in her team understand ("were told" is what I picked up from the context) that you don't go home when the working hours are over, you go home when the job is done, no matter how much it takes. What I've read in between the lines is that we pack as much features as possible into a sprint and work overtime to make it happen.

Now, I haven't done Agile by now (worked with financial and governmental institutions which most still do prefer waterfall) but my understanding is that:

sprint in Scrum is the name for the generic iteration in Agile;

the team should work at a sustainable pace and try to avoid long term overtime as that has effects only on the short time and the effects are dwarfed by the problems they incur in the long time.

Are my statements right? And, should I take the manager's presentation as a red flag?

答: Scrum is broken into sprints where you estimate out a set of tasks to be completed in the duration of that sprint (typically 2 weeks, but I've seen anywhere from 1 day to 4 weeks). I think this creates an incentive to misestimate tasks. POs (product owner) will want low estimates to get a big committment per sprint. The team will put big estimates to generate nice burndown charts for the PMs to see. These are, of course, indicative of a crappy organization. You really want to get accurate estimates and not be afraid to either fall short and carry stories over to the next sprint or finish early and pull extra tasks off the backlog. I think the term "sprint" creates this image of people working faster.</p>


答:
If your actual software requirement is that views be customizable by the customer, then storing the view definitions in the database is not an unreasonable approach at all.

I think you will find that the conventional Model-View-Controller design breaks down when your requirement is user customization, for all but the simplest of scenarios.  Consequently, converting your application into a more orthodox design is going to be an exercise in frustration, unless you carefully weigh the pros and cons.

I envision some sort of hybrid system whereby the SQL and the views are dynamically generated, so that only the required information is passed across the wire.  You can also use some sort of Javascript templating system in the browser.  But it won't look anything like a conventional MVC system, because MVC is designed to aid the programmer, not the user.

In a perfect world, your customized views are constrained to a small part of the system, and most of the application is actually "hard-wired."  In other words, you won't custom generate all of your views, but only some of them, leaving the more orthodox views in MVC's capable hands, and custom generating views only as needed.

Title: Framework in which views are defined in the database - design flaw or reasonable?

Body:
I'm working with a framework where the fields displayed on each web page are defined in the application database. Administrators can add new fields to pages or hide/completely delete old fields. The logic for each page is in a Java class - sometimes there's a one-to-one relationship between a page and a class, sometimes several pages use the same class.

The issue

This framework design creates a hidden dependency between the page data in the database and the logic in the Java class. If a new field is added to a page, the matching Java class must provide that field - or the page will break. The Java code has no compile-time knowledge of how the page is configured in the database (each customer database may have different configurations), which increases brittleness.

A typical solution has been to SELECT * from one or more database tables, allowing a degree of configuration as to which fields can be displayed. This leads to database-centric Java code with plenty of embedded SQL and little object-oriented design or domain models.

Solution plans

We've introduced a three-tier MVC-like architecture (controller -> service -> repository) with object-oriented models to the framework. It limits the ability to add fields to the pages without changing the underlying code. However, the change makes it possible to program in an object-oriented way and create domain models. Next up, we're planning to do something about the dependency between the database and code.

My long-term plan would be to move the page definitions from the database into the code (your standard HTML&JS views), limiting configurability but reducing brittleness. Any incompatibilities between the pages and Java would then become compiler errors when building the application instead of runtime errors.

Question(s)

Do you consider the framework practice of defining the view in the database and the controller in the code as sound design or something that should be addressed?

If you think the situation should be addressed, does my long-term plan seem reasonable?

Edit:

In addition to defining the layout, the view definitions in the database define which fields are expected to exist - "get field 'foobar' from the controller and show it here". The views themselves don't really contain logic. The Java classes backing up the views typically contain thousands of rows of UI and business logic.


答:
Do you consider the framework practice of defining the view in the database and the controller in the code as sound design or something that should be addressed?

I think that storing user-specific information in the data layer is an excellent design principle, and is perfectly compatible with good programming practices.  Especially if the expected audience will be provided some tool, even if only SQL, to manage their "views."

That said, I agree that you do have an issue, although it's more abstract than you stated.  Your framework needs to have some clear and sensible way to handle unexpected user choices.

If you think the situation should be addressed, does my long-term plan seem reasonable?

If it's causing problems, it should definitely be addressed.  But the appropriate plan depends on what the actual problem is, rather than the issue you've identified.

If the problem is how your site behaves if the database is not as expected, you should include tests and exceptions to that effect in your java data layer, and make sure you have a database-construction program, written in Java or whatever, that can create the necessary views and tables in your target database.

If the problem is users creating invalid views, you should consider if it's possible to provide a default behavior in your site.  It's hard to be specific without knowing if your "views" are database views or the results of database queries, but either handling standard SQL column-types or limiting "field" rows to a list of "field types" should be part of the framework's design.  (Gracefully omitting an invalid field is not a terrible solution, fwiw.)

If your problem is SQL code in Java, you may not have a problem at all.  Such code should be moved to a dedicated database-connection class as part of your refactoring, but the choice between a Java-generated SQL string and a database-stored-procedure is an implementation detail, and you should only take the risk of moving from one to the other if you have a clear expectation of increased performance.

Lastly, if your problem is difficulty or delay in creating new pages, you should evaluate the process of how these pages are created.  If most work isn't actually being done by your user base but are instead being done by your Java team, moving the necessary code into Java may make sense.  Especially if your Java team isn't all familiar with SQL.

As I mentioned above, it's difficult to diagnose the appropriateness of a course of action without knowing the specifics of the framework in question.  All software, especially application frameworks, is a means to an end and a shifting of complexity from run-time to design time.  The specifics of an appropriate course are affected far more by "what are you trying to do" than "what should be done".


答:
You don't have to search far to see that these practices goes contrary to the principles behind Agile. One of the principles behind the Agile Manifesto states:

Agile processes promote sustainable development.  The sponsors,
  developers, and users should be able  to maintain a constant pace
  indefinitely.

A few years ago, Scrum made a subtle but important change. Instead of teams committing to the work that can be achieved they forecast what they think they can get done.

The change comes because of abuse, which sounds very much like the don't-go-home-until-its-done attitude you describe. In development, there are many factors outside the teams control that they can't commit to - to use the a weather analogy, you can't "commit" that it will be rainy tomorrow.

To directly answer your questions:

yes, Sprint is the name for an iteration in Scrum see this answer for the difference

yes, teams should work at a sustainable pace. The only certainty of overtime is that it will reduce the teams productivity long term.

yes, it is a red flag!

Title: Do Scrum sprints mean to work at the fastest pace possible?

Body:
I recently interviewed with some companies that do Agile, Scrum to be more precise and there are some things that don't quite seem like Agile to me. I'll take one case that particularly interests me right now, that of Scrum sprints.

One particular project manager I talked to (yes, I said project manager) proudly stated that people in her team understand ("were told" is what I picked up from the context) that you don't go home when the working hours are over, you go home when the job is done, no matter how much it takes. What I've read in between the lines is that we pack as much features as possible into a sprint and work overtime to make it happen.

Now, I haven't done Agile by now (worked with financial and governmental institutions which most still do prefer waterfall) but my understanding is that:

sprint in Scrum is the name for the generic iteration in Agile;

the team should work at a sustainable pace and try to avoid long term overtime as that has effects only on the short time and the effects are dwarfed by the problems they incur in the long time.

Are my statements right? And, should I take the manager's presentation as a red flag?


答:
Agile processes promote sustainable development.
  The sponsors, developers, and users should be able
  to maintain a constant pace indefinitely.

From the Agile Manifesto folks

Working overtime all the time doesn't sound sustainable to me.

That said, I see no issue with a spring commitment being a strong one (if that's the way the team wants to work), and having to work overtime when you overcommit or screw up estimates is a good incentive to get better at estimating or communicating expectations to PO.


答:
One particular project manager I talked to (yes, I said project manager) proudly stated that people in her team understand ("were told" is what I picked up from the context) that you don't go home when the working hours are over, you go home when the job is done, no matter how much it takes. What I've read in between the lines is that we pack as much features as possible into a sprint and work overtime to make it happen.

That's not Scrum. The proposed workload for a timebox is based on the team velocity, not on the manager's wish list. They are simply trying to trick you into believing that working endless overtime is "Agile", which it isn't. The team will get more efficient while working undisturbed and focused, but Scrum is not a magic wand for endless efficiency gains.

Either the manager has a slight misunderstanding of Agile, or (more likely) he thinks that developers are that stupid. On the other hand, when the team accepts the sprint again and again, knowing that they will need to do overtime work, maybe they are indeed stupid and don't deserve it any better?

I guess, you know the answer ... ;-)


问:
argument grouping with parenthesis are valid in C++?
On python I can group arguments into a tuple, something like

```<code>def func((a, b, c, d), x):
    print a, b, c, d, x
</code>```

I was wondering if it is possible to group arguments in the same way on C++, something like:

```<code>void func((int a, int b, int c, int d), float x)
{
    cout << a << b << c << d << x << endl;
};
</code>```

答:
it can be done with std::tuple

```<code>#include <iostream>
#include <tuple>
using namespace std;

void func(tuple<int, int, int, int> tup, float x)
{
    int a, b, c, d;
    tie(a, b, c, d) = tup;
    cout << a << b << c << d << x << endl;
}

int main() {
    func(make_tuple(1, 2, 3, 4), 5.5f);
    return 0;
}
</code>```

Body:
it can be done with std::tuple

#include <iostream>
#include <tuple>
using namespace std;

void func(tuple<int, int, int, int> tup, float x)
{
    int a, b, c, d;
    tie(a, b, c, d) = tup;
    cout << a << b << c << d << x << endl;
}

int main() {
    func(make_tuple(1, 2, 3, 4), 5.5f);
    return 0;
}


问:
conditional expressions, correct usage
I've recently become quite taken with conditional expressions in Python. Apparently some people consider it unpythonic and whether or not conditional/ternary expressions are even A Good Thing seems to be up for debate -- but I've been digging them lately.

```<code>x if C else y
</code>```

So far I've noted there are two ways Python will appear to 'let' you use this syntax, though I only see a pointer to the first in its official docs, so I'm a little uncertain if the second method (which I've not used, yet) is considered a good practice or not.

The first, being:

```<code>myvariable = x if C else y ##also, "return x if C else y"
</code>```

Seems fairly common; one finds it in JavaScript and Ruby and basically any other language where you'd be impelled to drop a one-liner instead of three lines of

```<code>if C:
    myvariable = x
else:
    myvariable = y
</code>```

However, I do see that Python will let you 'get away' with a line such as this, without assigning anything:

```<code>foo() if C else bar()
</code>```

I'm a fairly new programmer, really, and so I try to hesitate implementing the wrong tool for the job. This to me looks like an interesting method for controlling the flow of a program, if not the typical way for doing so. For example, if we get the high score on Stick's Asteroid's Clone v.001:

```<code>record_score() if currentscore > highestscore else display_scores()
</code>```

I find it readable (others may not) and descriptive. However, in my non-exhaustive independent research of being able to use conditional expressions in a way besides assignment, I don't really see a whole lot of precedent for it. That leads me to think that one wouldn't really use it in this way in the first place, regardless of the language you're in, because it just isn't the right way to handle the state of your program.

Additionally, I recognize that the difference between a 'good' implementation of this and a 'bad' one may just be to make use of return and reconsider the relevant code.

```<code>return record_score if currentscore > highestscore else display_scores ##and then the state machine takes over
</code>```

That's fine too, but the question still stands in my mind if the suggested wording would ever be acceptable in the first place.

So I ask, is it even good practice to use conditional expressions apart from assignment? Or to put a finer point on it, is it acceptable to use it as a means of controlling the flow of a program?

答:
In general, ternary if/else statements in Python are used to shortcut simple statements, as you mention in your question. They save three lines of code and are more transparent than Boolean operators and and or (especially when the latter two are combined). They are used for assignments, and they can also be used in other ways such as in list comprehensions:

```<code>['odd' if i % 2 else 'even' for i in range(10)]
['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']
</code>```

'odd' if i % 2 else 'even' is technically a ternary if/else statement rather than part of list comprehension syntax per se.

Regarding your question about calling a function with a ternary if/else statement, I find that usage to be a little more difficult to manage from the standpoint of readability. Often if I see a function call at the beginning of a line, I don't usually suspect that another function may be hiding in its wings further to the right. I may very well miss that fact on the first pass and be left wondering how a function was called only to find out that it was called at the end of a line with a ternary if/else statement.

That being said, calling a function with a ternary if/else statement might be more natural in something like a list comprehension or a generator expression, where I am already reading through the line in order to process what is taking place. In these cases, however, map() is usually a better way to go performance-wise, so the point may be moot.

Using it in a return statement might also be more natural, since I expect these lines to be statements and because they are so important. But I don't see ternary if/else statements used in return statements all that often.

At the end of the day, I would prefer not to use ternary if/else statements as a means to control the flow of a program, since the ternary if/else statement can push important details to a place of less prominence. I would prefer to use them in scenarios where they preserve space and are relatively simple. (In this regard, they are somewhat like list comprehensions, which sometimes can be abused; list comprehensions sometimes contain very complex logic and become a nightmare for others to maintain down the road.) But ternary if/else statements still have a variety of simpler uses, for which I am often grateful.

Title: conditional expressions, correct usage

Body:
In general, ternary if/else statements in Python are used to shortcut simple statements, as you mention in your question. They save three lines of code and are more transparent than Boolean operators and and or (especially when the latter two are combined). They are used for assignments, and they can also be used in other ways such as in list comprehensions:

['odd' if i % 2 else 'even' for i in range(10)]
['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']

'odd' if i % 2 else 'even' is technically a ternary if/else statement rather than part of list comprehension syntax per se.

Regarding your question about calling a function with a ternary if/else statement, I find that usage to be a little more difficult to manage from the standpoint of readability. Often if I see a function call at the beginning of a line, I don't usually suspect that another function may be hiding in its wings further to the right. I may very well miss that fact on the first pass and be left wondering how a function was called only to find out that it was called at the end of a line with a ternary if/else statement.

That being said, calling a function with a ternary if/else statement might be more natural in something like a list comprehension or a generator expression, where I am already reading through the line in order to process what is taking place. In these cases, however, map() is usually a better way to go performance-wise, so the point may be moot.

Using it in a return statement might also be more natural, since I expect these lines to be statements and because they are so important. But I don't see ternary if/else statements used in return statements all that often.

At the end of the day, I would prefer not to use ternary if/else statements as a means to control the flow of a program, since the ternary if/else statement can push important details to a place of less prominence. I would prefer to use them in scenarios where they preserve space and are relatively simple. (In this regard, they are somewhat like list comprehensions, which sometimes can be abused; list comprehensions sometimes contain very complex logic and become a nightmare for others to maintain down the road.) But ternary if/else statements still have a variety of simpler uses, for which I am often grateful.


答:
Ternary operators are acceptable in a minority of cases, where the reduced lines of code outweighs the additional complexity of having the branch. This means it works well in list comprehensions or lambdas where the reader is expecting more complexity, but it would harm readability if it is used in place of a normal if/else statement, as the reader is likely not expecting a branch.

In my opinion, Python ternary statements are slightly worse than usual though, because they do not take the conventional form. For this reason, I would avoid ternary statements in more places than in other languages. Try to spot the odd one out:

```<code>Conventional branch:
if <cond> then <true-val> else <false-val>

C ternary:
<cond> ? <true-val> : <false-val>

Python ternary:
<true-val> if <cond> else <false-val>
</code>```

Some people prefer the Python ternary because it is more natural to the way they think, but obviously this varies among people, so I do not prefer it for the simple reason that it doesn't conform to the expected <cond>/<true-val>/<false-val> order.

Of course, there are several ways of doing ternary statements in Python, but they get weirder and I would not recommend them more than the standard Python ternary, e.g.:

```<code>Tuple trick:
(<false-val>, <true-val>)[<cond>]

Boolean trick:
<cond> and <true-val> or <false-val>
</code>```

I wouldn't re commend the last one, even though the operands are in the expected order, because it is non-intuitive for those not well-versed in Boolean algebra.

Title: conditional expressions, correct usage

Body:
I've recently become quite taken with conditional expressions in Python. Apparently some people consider it unpythonic and whether or not conditional/ternary expressions are even A Good Thing seems to be up for debate -- but I've been digging them lately.

```<code>x if C else y
</code>```

So far I've noted there are two ways Python will appear to 'let' you use this syntax, though I only see a pointer to the first in its official docs, so I'm a little uncertain if the second method (which I've not used, yet) is considered a good practice or not.

The first, being:

```<code>myvariable = x if C else y ##also, "return x if C else y"
</code>```

Seems fairly common; one finds it in JavaScript and Ruby and basically any other language where you'd be impelled to drop a one-liner instead of three lines of

```<code>if C:
    myvariable = x
else:
    myvariable = y
</code>```

However, I do see that Python will let you 'get away' with a line such as this, without assigning anything:

```<code>foo() if C else bar()
</code>```

I'm a fairly new programmer, really, and so I try to hesitate implementing the wrong tool for the job. This to me looks like an interesting method for controlling the flow of a program, if not the typical way for doing so. For example, if we get the high score on Stick's Asteroid's Clone v.001:

```<code>record_score() if currentscore > highestscore else display_scores()
</code>```

I find it readable (others may not) and descriptive. However, in my non-exhaustive independent research of being able to use conditional expressions in a way besides assignment, I don't really see a whole lot of precedent for it. That leads me to think that one wouldn't really use it in this way in the first place, regardless of the language you're in, because it just isn't the right way to handle the state of your program.

Additionally, I recognize that the difference between a 'good' implementation of this and a 'bad' one may just be to make use of return and reconsider the relevant code.

```<code>return record_score if currentscore > highestscore else display_scores ##and then the state machine takes over
</code>```

That's fine too, but the question still stands in my mind if the suggested wording would ever be acceptable in the first place.

So I ask, is it even good practice to use conditional expressions apart from assignment? Or to put a finer point on it, is it acceptable to use it as a means of controlling the flow of a program?

Body:
Ternary operators are acceptable in a minority of cases, where the reduced lines of code outweighs the additional complexity of having the branch. This means it works well in list comprehensions or lambdas where the reader is expecting more complexity, but it would harm readability if it is used in place of a normal if/else statement, as the reader is likely not expecting a branch.

In my opinion, Python ternary statements are slightly worse than usual though, because they do not take the conventional form. For this reason, I would avoid ternary statements in more places than in other languages. Try to spot the odd one out:

Conventional branch:
if <cond> then <true-val> else <false-val>

C ternary:
<cond> ? <true-val> : <false-val>

Python ternary:
<true-val> if <cond> else <false-val>

Some people prefer the Python ternary because it is more natural to the way they think, but obviously this varies among people, so I do not prefer it for the simple reason that it doesn't conform to the expected <cond>/<true-val>/<false-val> order.

Of course, there are several ways of doing ternary statements in Python, but they get weirder and I would not recommend them more than the standard Python ternary, e.g.:

Tuple trick:
(<false-val>, <true-val>)[<cond>]

Boolean trick:
<cond> and <true-val> or <false-val>

I wouldn't re commend the last one, even though the operands are in the expected order, because it is non-intuitive for those not well-versed in Boolean algebra.


问:
How do you handle supporting Chrome versions?
I'm working on a site for my company which, up until a certain point, was an Internet Explorer-only site for various reasons, mainly that when the site was originally conceived IE had a 90%+ market share so the work to get it working in other browsers just didn't make sense.

Now that we live in a more diverse browser economy we're doing the work to get the site working everywhere, and as luck would have it a decent chunk of it just happens to already work.

However, one issue we're struggling with is the issue of what to support and what not to support. For starters, non-IE browsers release much more frequently than IE did, and you don't know which versions are still in the wild. There's been basically three versions of IE released in the last decade, and IE6 is still supported until 2014. But there's an update for Firefox every other day, Apple updates Safari more or less annually. And then there's Chrome.

Chrome has gone from 0.2 to 9.0 in a little over two years. 7.0.517 was released a month and a half after 6.0.472. There's three different versions out right now, a stable, a beta, and a dev. And the dev version of 9.0.587 was actually released before the latest beta version of 8.0.552.

With IE we've had the situation arise where we have to support an old version because the IT department of the company in question does not allow the employees to upgrade. With non-IE browsers I'm thinking we'll adopt the line of "update to the latest or we can't help you" but I'm not sure how effective that is.

Also, my company does some amount of artificial limitations. For example we have a product aimed at companies so we don't support "Home" versions of Windows (i.e., XP Home, 7 Home Premium) even though there's no technical reason we couldn't.

When my company starts asking "what version or versions of Chrome do we support", how should I answer?

答:
The thing about Microsoft's browsers is that IE6 was largely broken in terms of web standards and general quality. Getting to version 9 has been like turning a cruise liner round and each major version has been a significant change to get there.

Chrome has had great standards support from day one. Chrome also has a different versioning model to IE. Its major versions aren't that drastically different from version to version compared with IE. From a day to day perspective users don't even notice they're using a different version.

This is pretty much true for Safari (which also uses Webkit) and Firefox. Be a bit more careful with Opera.

In a nutshell, most major none IE browsers won't cause you any problems. Focus resources on managing 4 different versions of IE!

The answer to the question is: we support the latest version

ContentLicense: CC BY-SA 2.5


问:
Side Effects Breaking Referential Transparency
Functional Programming in Scala explains a side effect’s impact on breaking referential transparency:

side effect, which implies some violation of referential transparency.

I’ve read part of SICP, which discusses using the “substitution model” to evaluate a program.

As I roughly understand the substitution model with referential transparency (RT), you can de-compose a function into its simplest parts. If the expression is RT, then you can de-compose the expression and always get the same result.

However, as the above quote states, using side effects can/will break the substitution model.

Example:

```<code>val x = foo(50) + bar(10)
</code>```

If foo and bar do not have side effects, then executing either function will always return the same result to x. But, if they do have side effects, they will alter a variable that disrupts/throws a wrench into the substitution model.

I feel comfortable with this explanation, but I don’t fully grok it.

Please correct me and fill in any holes with respect to side effects breaking RT, discussing the effects on the substitution model as well.

答:
Let's begin with a definition for referential transparency:

An expression is said to be referentially transparent if it can be
  replaced with its value without changing the behavior of a program (in
  other words, yielding a program that has the same effects and output
  on the same input).

What that means is that (for example) you can replace 2 + 5 with 7 in any part of the program, and the program should still work.  This process is called substitution.  Substitution is valid if, and only if, 2 + 5 can be replaced with 7 without affecting any other part of the program.

Let's say that I have a class called Baz, with the functions Foo and Bar in it.  For simplicity, we'll just say that Foo and Bar both return the value that is passed in.  So Foo(2) + Bar(5) == 7, as you would expect.  Referential Transparency guarantees that you can replace the expression Foo(2) + Bar(5) with the expression 7 anywhere in your program, and the program will still function identically.

But what if Foo returned the value passed in, but Bar returned the value passed in, plus the last value provided to Foo?  That's easy enough to do if you store the value of Foo in a local variable within the Baz class.  Well, if the initial value of that local variable is 0,  the expression Foo(2) + Bar(5) will return the expected value of 7 the first time you invoke it, but it will return 9 the second time you invoke it.

This violates referential transparency two ways. First, Bar can not be counted on to return the same expression each time it is called. Second, a side-effect has occurred, namely that calling Foo influences the return  value of Bar.  Since you can no longer guarantee that Foo(2) + Bar(5) will equal 7, you can no longer substitute.

This is what Referential Transparency means in practice; a referentially transparent function accepts some value, and returns some corresponding value, without affecting other code elsewhere in the program, and always returns the same output given the same input.


问:
Generic rule parser for RPG board game rules - how to do it?
I want to build a generic rule parser for pen and paper style RPG systems. A rule can involve usually 1 to N entities 1 to N roles of a dice and calculating values based on multiple attributes of an entity.

For example:

Player has STR 18, his currently equipped weapon gives him a bonus of +1 STR but a malus of DEX -1. He attacks a monster entity and the game logic now is required to run a set of rules or actions:

Player rolls the dice, if he gets for example 8 or more (base attack value he needs to pass is one of his base attributes!) his attack is successfull. The monster then rolls the dice to calculate if the attack goes through it's armor. If yes the damage is taken if not the attack was blocked.

Besides simple math rules can also have constraints like applying only to a certain class of user (warrior vs wizard for example) or any other attribute. So this is not just limited to mathematical operations.

If you're familiar with RPG systems like Dungeon and Dragons you'll know what I'm up to.

My issue is now that I have no clue how to exactly build this the best possible way. I want people to be able to set up any kind of rule and later simply do an action like selecting a player and a monster and run an action (set of rules like an attack).

I'm asking less for help with the database side of things but more about how to come up with a structure and a parser for it to keep my rules flexible. The language of choice for this is php by the way.

Edit I:

Let me refine my goal: I want to create a user friendly interface (that does not require somebody to learn a programming language) to build more or less complex game rules. The simple reason: Personal use to not need to remember all the rules all the time, we simply do not play that often and it's a stopper to look them up each time. Also: Looks like a fun task to do and learn something. :)

What I've tried so far: Just thinking about a concept instead of wasting time building a wrong architecture. So far I have the idea to allow a user to create as many attributes as they want and then assign as many attributes as they want to any kind of entity. An entity can be a player, a monster, an item, anything. Now when calculating something the data is made available to the rule parser so that the rule parser should be able to do things like if Player.base_attack + dice(1x6) > Monster.armor_check then Monster.health - 1; The question here is about how to create that parser.

Edit II:

Here is an example of pretty basic value but to calculate it properly there are lots of different things and variables to take into account:

Base Attack Bonus (Term) Your base attack bonus (commonly referred to
  as BAB by the d20 community) is an attack roll bonus derived from
  character class and level. Base attack bonuses increase at different
  rates for different character classes. A character gains a second
  attack per round when his base attack bonus reaches +6, a third with a
  base attack bonus of +11 or higher, and a fourth with a base attack
  bonus of +16 or higher. Base attack bonuses gained from different
  classes, such as for a multiclass character, stack. A character’s base
  attack bonus does not grant any more attacks after reaching +16,
  cannot be less than +0, and does not increase due to class levels
  after character level reaches 20th. A minimum base attack bonus is
  required for certain feats.

You can read it here http://www.dandwiki.com/wiki/Base_Attack_Bonus_(Term) including the links to classes and feats which have again their own rules to calculate the values that are required for the base attack.

I began to think that keeping it as generic as possible will also make it pretty hard to get a good rule parser done.

答:
I think that you need to be able to be able to think abstractly about what things are going to be in your problem space, come up with some sort of model and then base your DSL on that.

For example you might have the entities entity, action and event at the top level. Die rolls would be events that occur as a result of actions. Actions would have conditions that determine whether they are available in a given situation and a "script" of things that occur when the action is taken. More complex things would be the ability to define a sequence of phases where different actions can occur.

Once you have some sort of conceptual model (and I suggest you write it down and/or draw diagrams to represent it) you can start to look at different means of implementing it.

One route is to define what is called an external DSL where you define your syntax and use a tool such as antlr to parse it and call your logic. Another route is to use the facilities present in a programming language to define your DSL. Languages such as Groovy and Ruby are particularly good in this space.

One trap you need to avoid is mixing your display logic with your implemented game model. I would vote to have the display read your model and display appropriately rather than mixing your display code intermixed with your model.


问:
UI requires data of certain types. Can it go in a SPROC?
I'm actually arguing against this, but want to see if I'm out of line.

We have a PaymentQueue table and a simple UI. This table is, at the moment, primarily used by the UI and no other business logic. The UI requires data that is only in a subset of possible statuses.

One developer put this status restriction in the SPROC itself. I'm arguing to put it into the website UI layer, since it's view dependent.

The benefit if his approach is it returns less data over the wire, but messes up other processes that may, in the future, utilize this SP, since it now always restricts to certain types. The benefit of my approach is it keeps view logic out of the database, but pulls across more data on the wire (I plan to narrow by date range to minimize this).

My thought was to introduce a flag in the SPROC that, if enabled, would filter by these types, thus allowing the SPROC to be more flexible for either case.

What is the best approach? Thanks.

答:
Creating a SP (or better, a View) that returns a subset of data from a table is workable, but overloading the SP with a flag to allow it to be used again in a different way isn't a good option.  The key decisions revolve around deciding where the business logic for filtering the returned data should exist; and weighing the trade-offs between code reuse, readability, and maintainability.  The worst thing that you can do is to duplicate the logic in both places, because that make maintenance and issue resolution hard when the rules get out of sync which they inevitably will.  I will outline four general options, though there are surely others.

At one extreme, you let all the logic live in the database (which it sounds like your DBAs would like) and make calls and get back data through program specific SPROCs.  It should make your job as a UI developer easier, as you can ignore the underlying schema and treat the SPROCs as a an API for the data.  Just remember that the DBA will need the same set of good requirements and acceptance criteria that you need to succeed.  The down side to this is that you can get overrun with SPROCs if the database needs to support multiple systems with different needs.  Microsoft SQL Server introduced Schemas as part of SQL Server 2005 to help manage this, but it is still an added complexity.  Each UI is tightly coupled to its own set of stored procedures so deployment of changes isn't a problem as the SPROCs are isolated from each other (by Schema or naming convention).

In the middle, you can create generic SPROCs that return all data of a given type and filter in the consuming program.  This is the safest, as it keeps the filter logic isolated to the programs that need it and reduces most of the procedures to simple select statements with joins and no parameters.  Using column names rather than ordinal indexes to access data in the results can even somewhat isolate programs from schema changes in the returned results.  The down side here (as you noted above) is that additional data is returned for every call, which can impact performance.

Another middle option is to build more complex SPROCs that take in parameters which aid in filtering the data.  The stored procedures in this case can become quite complex. Also, the coupling between the front ends and database can cause deployment and maintenance issues, especially if you are needing to alter the parameter list on a shared stored procedure and all dependent programs are not on a synchronized release schedule.

At the other extreme, you can let all of the logic live above the database and use an ORM to handle all access to the underlying data.  If you are interested in using Linq to SQL as your ORM, look at https://stackoverflow.com/questions/1075540/linq-to-sql-how-to-do-where-column-in-list-of-values and see how they are passing a list of values into a method.  You could easily pass a list of statuses from the UI into a method and let the Linq to SQL generate appropriate SQL for you. Think about the responsibilities of your tiers and don't be afraid to have helper methods that call GetPaymentList with the appropriate status lists to hide that complexity.

My order of preference is 1, 4, 2, 3.  If (as you state in a comment) you are forced to SPROC by your DBAs, I would suggest going with the first option and building SPROCs specific for your application.  This assumes that you either have the DBAs writing the stored procedures for you, or you have SQL talent on your team.  If neither assumption holds, fall back to the first middle ground with generic SPROCs and filter in the UI.  The third option (trying to build a flexible set of stored procedures that can work for any possible future use) is over-engineering.  Rather than solving a problem that doesn't exist yet, I would much rather see you spend that extra time building a good set of regression tests for the code/interface so that you can refactor it with confidence when the problem (or some other requirement) arises.

The fourth option won't work for you because of the DBA requirement, but is also a very valid alternative for use in a different environment.


答:
The two expressions put emphasis on different things.  The common expression

```<code>if C then x else y
</code>```

puts emphasis on C and sets x and y on an equal foot, while

```<code>x if C else y
</code>```

highlights x and lets C and y on the side, implying a lesser importance than x has.

As a programmer, you then need to decide what is more important, of x or C.

I would for instance use the first form in the following contexts:

A process forked and C tells if we are in the parent or the child.

A security policy is being implemented and C tells if we are operating with appropriate privileges.

A request has been sent to a peer and C tells if it succesfully completed.

A recursive function is being written and C tells if the recurrence stops.

These are cases where I would want to put emphasis on the conditional C either because I think it is really governing the logic or because I expect other persons reading the code to think so.  In the latter case, you can think about the idiom as to a cliché, which fits mostly because it is expected there.

I would for instance use the second form in the following contexts:

A variables might need initialisation and C tells if it is actually the case.

A system resource should be deallocated, if has not already been.

These are cases where I would recognise x as the common case and y as a marginal case.  This is only a rule of thumb, however, because in recursing functions the recurrence is the common case, still the emphasis should be put on the recurrence condition.

Which one to use is a matter of style, either yours or the style used by the community you are working with.  If you are new to programming, it is fine to let your style maturate. Give yourself time.

Title: conditional expressions, correct usage

Body:
The two expressions put emphasis on different things.  The common expression

if C then x else y

puts emphasis on C and sets x and y on an equal foot, while

x if C else y

highlights x and lets C and y on the side, implying a lesser importance than x has.

As a programmer, you then need to decide what is more important, of x or C.

I would for instance use the first form in the following contexts:

A process forked and C tells if we are in the parent or the child.

A security policy is being implemented and C tells if we are operating with appropriate privileges.

A request has been sent to a peer and C tells if it succesfully completed.

A recursive function is being written and C tells if the recurrence stops.

These are cases where I would want to put emphasis on the conditional C either because I think it is really governing the logic or because I expect other persons reading the code to think so.  In the latter case, you can think about the idiom as to a cliché, which fits mostly because it is expected there.

I would for instance use the second form in the following contexts:

A variables might need initialisation and C tells if it is actually the case.

A system resource should be deallocated, if has not already been.

These are cases where I would recognise x as the common case and y as a marginal case.  This is only a rule of thumb, however, because in recursing functions the recurrence is the common case, still the emphasis should be put on the recurrence condition.

Which one to use is a matter of style, either yours or the style used by the community you are working with.  If you are new to programming, it is fine to let your style maturate. Give yourself time.


问:
Style guide for C++
Right now I am using Google C++ Style Guide in my C++ code and I was pretty happy with it.

Recently I was told that this guide is very bad: it is used internally by Google (I knew that), is outdated, and promotes some very bad practices. So I want to use another coding style.

What good and fairly used C++ style guides are there? I write code for both gcc and Visual Studio, and I use a lot of the C++11 features.

What I liked very much about Google C++ Style Guide was the indentation, the whitespace and the naming conventions (specially naming all classes, types - including typedefs, type aliases and template aliases - with capital first letter).

I know any answer is subjective (I hope this is ok on this site) and I would appreciate any opinion, but I am interested which guides are used these days.

答: If you haven't read Bjarne Stroustrup's Programming and Principles I strongly recommend you to read it because you can learn a lot from the language's creator. I have watched and read a lot from the C++ author and I can say that he has this fixation for style and is always telling people to write good, beautiful code that according to him is easier to debug and read. I believe that he is the greatest tutor and the best guide to writing stylish and beautiful C++ code.</p>

Title: Style guide for C++


问:
Requirement refinement between two levels of specification
I am currently working on the definition of the documentation architecture of a system, from customers needs to software/hardware requirements.
I encounter a big problem with the level of refinement of requirements.

The classic architecture is : PTS --> SSS --> SSDD --> SRS/HRS
with PTS : Purshaser Technical Specification
SSS : Supplier System Specification
SSDD : System Segment Design Description
SRS / HRS : Software / Hardware Requirement Specification.

Requirements from PTS are reworked in SSS, this document only expressed the needs (no design requirements are defined at this level). Then, the system design is described in SSDD : we allocate requirements from the SSS to functions from the design and functions are then allocated to component (Software or hardware) (we are still at the SSDD level). Finally, for each component, we write one SRS or one HRS. Requirements in SRS or HRS are refinement of requirements from SSS (and traceability matrix are made between these two levels).

My problem is the following one :

Our system is a complex one, and some of the requirements in the SSS needs to be refined twice to be at the right level in the SRS (means that software people can understand the requirement to make their coding). But, with this document architecture, I can only refine once the requirements from the SSS. The second problem is that only a part of the requirements from the SSS needs to be refined twice. The other part only need one refinement.

On the picture below, the green boxes are requirements at the right level for SRS or HRS. And purple boxes are intermediate requirements which can not be included in SSS since they are design requirements. Where can I put these purple requirements ??

Is there someone who has already encountered this problem ? Should I write two documents at SRS level ? Should I include intermediate requirements in SSDD ? Should I includes the two refinement levels (purple and green) in the same SRS document (not sure that's possible since a SRS is only for one component) ???

Thanks for your help and expertise ;-)

答:
The purpose of specification refinement is twofold:

Translate higher level requirements to something usable by developers: e.g., from I want a "Google Maps" with space imagery to The spacecraft shall follow a polar orbit to a bunch of equipements --sensors and actuators-- and a software implemented control loop involving quaternions and some real time OS.

Provide a way to check that every customer need has been implemented, through traceability.

Therefore, you only have to make clear whether Req 3.1 is entirely implemented by Req 4.1, so that the developer either focuses on Req 4.1 (and I would put Req 3.1 in SSS) or has to implement both Req 3.1 and Req 4.1 (and I would put Req 3.1 in SRS).


答: As @user113896 earlier wrote, Bjarne Strostrup gave us a lot of style guidance. One of his fine achievements is JSF-C++ Coding style book. Beware, it's not for regular c++, more for embedded use, but it shows how things should be done to be clear and functional. Of course - You don't have to take everything into account - its a guide, not an order-book :). </p>

Title: Style guide for C++

Body:
Right now I am using Google C++ Style Guide in my C++ code and I was pretty happy with it.

Recently I was told that this guide is very bad: it is used internally by Google (I knew that), is outdated, and promotes some very bad practices. So I want to use another coding style.

What good and fairly used C++ style guides are there? I write code for both gcc and Visual Studio, and I use a lot of the C++11 features.

What I liked very much about Google C++ Style Guide was the indentation, the whitespace and the naming conventions (specially naming all classes, types - including typedefs, type aliases and template aliases - with capital first letter).

I know any answer is subjective (I hope this is ok on this site) and I would appreciate any opinion, but I am interested which guides are used these days.


问:
Can I rename a portion of code released under Apache 2.0?
Is it possible to rename a portion of code extracted from a Apache 2.0 licensed software, releasing it as a new repository under a new name?</p>

答:
Certainly.

As all open-source licenses, Apache license allows publishing derived work. Some allow using different license too (Apache license does), some don't (GPL).


问:
Python: How to decide which class' methods should provide behavior (functionality) affecting multiple classes
I have a question about object oriented design that is not specific to Python but since my code is in Python, I tagged it as such. How do I decide which of my classes should be responsible for implementing certain functionality that may affect more than one class? What are some good guidelines >(if any) or considerations?

In the below example of a Town class, the behavior of moving to/from a town is split up among the Town class and Inhabitant class. The code works. But I am wondering if there are compelling reasons to assign this behavior to only one class, e.g. allow the Town method addpeople to update the Inhabitant attribute town so it's possible to track each inhabitant's place of residence.

Just trying to get a sense of what would be good practice or smart object oriented design.

```<code>class Town():

    def __init__(self,name):
        self.name = name
        self.inhab = []

    def addpeople(self,person):
        self.inhab.append(person)

    def removepeople(self, person):
        self.inhab.remove(person)

class Inhabitant():

    def __init__(self,name):
        self.name = name
        self.town = ""

    def move(self,town):
        if self.town:
            print self.name,"is moving from",self.town.name, "to",town.name
            self.town.removepeople(self)
        else:
            print self.name,"is moving to",town.name
        self.town = town
        town.addpeople(self)
</code>```

答:
I don't see anything wrong with either. This is a question which has different answers for different cases - just do what seems more natural to you.

In some cases, you should stick to one of the methods. In other cases, both methods may be applicable to use in parallel, but you should be careful if you choose to do so:

Make sure that both have exactly the same outcome.

I've already identified a potential bug in your sample: The addpeople of Town doesn't update the inhabitant's town. If the Inhabitant doesn't have a town yet, the town attribute is set. If you choose to move the person using Inhabitant.move though, the town is set. This is a typical way to introduce bugs, so please be careful if you choose this path!

OwnerDisplayName: Arne

OwnerDisplayName: Steinar Lima


答:
Q. How do I decide which of my classes should be responsible for implementing certain functionality that may affect more than one class?  What are some good guidelines (if any) or considerations?

A. The General Responsibility Assignment Software Patterns (or Principles), abbreviated GRASP, consists of guidelines for assigning responsibility to classes and objects in object-oriented design.

These guidelines help you balance the trade-offs and advantages for writing class methods with behaviors that affect multiple classes.  In general, you are trying to put the methods in a class that has the most knowledge of how to implement the method, in the class that serves as a controller for other classes, and in a way the minimizes the number of cross-dependencies between each class.

Title: Python: How to decide which class' methods should provide behavior (functionality) affecting multiple classes

Body:
I have a question about object oriented design that is not specific to Python but since my code is in Python, I tagged it as such. How do I decide which of my classes should be responsible for implementing certain functionality that may affect more than one class? What are some good guidelines >(if any) or considerations?

In the below example of a Town class, the behavior of moving to/from a town is split up among the Town class and Inhabitant class. The code works. But I am wondering if there are compelling reasons to assign this behavior to only one class, e.g. allow the Town method addpeople to update the Inhabitant attribute town so it's possible to track each inhabitant's place of residence.

Just trying to get a sense of what would be good practice or smart object oriented design.

```<code>class Town():

    def __init__(self,name):
        self.name = name
        self.inhab = []

    def addpeople(self,person):
        self.inhab.append(person)

    def removepeople(self, person):
        self.inhab.remove(person)

class Inhabitant():

    def __init__(self,name):
        self.name = name
        self.town = ""

    def move(self,town):
        if self.town:
            print self.name,"is moving from",self.town.name, "to",town.name
            self.town.removepeople(self)
        else:
            print self.name,"is moving to",town.name
        self.town = town
        town.addpeople(self)
</code>```

OwnerDisplayName: Raymond Hettinger


答:
In the below example of a Town class, the behavior of moving to/from a town is split up among the Town class and Inhabitant class. The code works. But I am wondering if there are compelling reasons to assign this behavior to only one class, e.g. allow the Town method addpeople to update the Inhabitant attribute town so it's possible to track each inhabitant's place of residence.

There is actually a good reason to not assign this behavior to only one class and keep it similar to what you have - in object-oriented programming you really want to have each object maintain control over its own data. Your code can easily become very complicated and hard to debug if you change variables outside of the object that the variable belongs to. This is part of the concept of encapsulation that is central to object-oriented programming.

Another part of OOP that is relevant here is abstraction, i.e you want the interaction between objects in your code to make sense at a higher level. Just from looking at this sample code, I would guess that the inhabitants of the towns are more the focus of your program than the towns themselves. If the user is interacting more with the town, I would expect the town to be doing more of the work (Town.addpeople calling Inhabitant.move, for example).

So as you are writing your program, think about which entities will be the ones doing the work. When your code matches your intuitive abstraction of what is happening, it will be much easier for you to keep track of what is going on and not introduce bugs into your code.

One other piece of advice I would give you may or may not be helpful, depending on what this project is for. If this is a program you are going to be actually using, maintaining, and upgrading, write a throwaway prototype first. As Joel Cornett mentioned in the comment, "It depends on the use case", meaning that in order to know the best way to write the code you have to understand the situation. Some of this comes from experience, but unless you are perpetually writing pretty much the same program time and again, you will run into a situation that is not entirely familiar. Writing a prototype is an excellent way to get some experience with the specific problem that you are facing, because you often will not be able to see why one way or another will work better until you are fairly far into writing the program.

One thing that prevents people from creating a good system is that they get attached to their code. So if you choose to write a prototype, realize that it is a throwaway - something you write rapidly just for the purpose of getting a good feel for the problem. It can also help if you realize while you're writing it that it doesn't even have to work, as long as it helps you figure out what it would take for it to work well. Once you've written your prototype, you will have a much better feel for how you should have written your code. Then you can start over and write it correctly much faster.

In short, "It depends on the use case", so make sure you understand the use case and have the code match your understanding.

OwnerDisplayName: Rob Watts


答:
You can use the guideline from this book for general usage:

http://www.amazon.com/Coding-Standards-Rules-Guidelines-Practices/dp/0321113586

from Herb Sutter and Andrei Alexandrescu. It does not take into account C++11 though, but I think there will be a new edition.

But it will not answer about number of space instead of tabs or what kind of esoteric notation you want to enforce. But these are not the most important thing, most of the time just to have some consistency is the key.

Title: Style guide for C++


问:
Should I use JavaFx properties?
I'm usually very careful to keep my Model, View, and Controller code separate. The thing is JavaFx properties are so convenient to bind them all together. The issue is that it makes my entire code design dependent on JavaFx, which I feel I should not being doing. I should be able to change the view without changing too much of the model and controller.

So should I ignore the convenience of JavaFx properties, or should I embrace them and the fact that it reduces my codes flexibility.

答:
I think that you can use JavaFX properties without rest of JavaFX. If thats true, your model would depend on one more library. And if you only privide hooks for gui, but without knowing the gui (to be sure, develop it separately), it would be OK.

Something other is depending on actual properties of your gui objects. That forces you to change model when you do trivial changes to gui and vice versa.

Title: Should I use JavaFx properties?


答:
As I roughly understand the substitution model (with referential transparency(RT)), you can de-compose a function into its simplest parts. If the expression is RT, then you can de-compose the expression and always get the same result.

Yes, the intuition is quite right. Here are a few pointers to get more precise:

Like you said, any RT expression should have a single "result". That is, given a factorial(5) expression in the program, it should always yield the same "result". So, if a certain factorial(5) is in the program and it yields 120, it should always yields 120 regardless of which "step order" it is expanded/computed -- regardless of time.

Example: the factorial function.

```<code>def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)
</code>```

There are a few considerations with this explanation.

First of all, keep in mind the different evaluation models (see applicative vs. normal order) may yield different "results" for the same RT expression.

```<code>def first(y, z):
  return y

def second(x):
  return second(x)

first(2, second(3)) # result depends on eval. model
</code>```

In the code above, first and second are referentially transparent, and yet, the expression at the end yields different "results" if evaluated under normal order and applicative order (under the latter, the expression does not halt).

....which leads to the use of "result" in quotes. Since it is not required of an expression to halt, it may not produce a value. So using "result" is kind of blurry. One can say an RT expression always yields the same computations under an evaluation model.

Third, it may be required to see two foo(50) appearing in the program in different locations as different expressions -- each one yielding their own results that might differ from each other. For instance, if the language allows dynamic scope, both expressions, though lexically identical, are different. In perl:

```<code>sub foo {
    my $x = shift;
    return $x + $y; # y is dynamic scope var
}

sub a {
    local $y = 10;
    return &foo(50); # expanded to 60
}

sub b {
    local $y = 20;
    return &foo(50); # expanded to 70
}
</code>```

Dynamic scope misleads because it make it easy for one to think x is the only input for foo, when in reality, it is x and y. One way to see the difference is to transform the program into an equivalent one without dynamic scope -- that is, passing explicitly the parameters, so instead of defining foo(x), we define foo(x, y) and pass y explicitly in the callers.

The point is, we are always under a function mindset: given a certain input for an expression, we are given a corresponding "result". If we give the same input, we should always expect the same "result".

Now, what about the following code?

```<code>def foo():
   global y
   y = y + 1
   return y

y = 10
foo() # yields 11
foo() # yields 12
</code>```

The foo procedure breaks RT because there are redefinitions. That is, we defined y in one point, and latter on, redefined that same y. In the perl example above, the ys are different bindings though they share the same letter name "y". Here the ys are actually the same. That's why we say (re)assignment is a meta operation: you are in fact changing the definition of your program.

Roughly, people usually depict the difference as follows: in a side-effect free setting, you have a mapping from input -> output. In an "imperative" setting, you have input -> ouput in the context of a state that can change through time.

Now, instead of just substituting expressions for their corresponding values, one also has to apply transformations to the state at each operation that requires it (and of course, expressions may consult that same state to perform computations).

So, if in a side-effect free program all we need to know to compute an expression is its individual input, in an imperative program, we need to know the inputs and the entire state, for each computational step. Reasoning is the first to suffer a big blow (now, to debug a problematic procedure, you need the input and the core dump). Certain tricks are rendered impractical, like memoization. But also, concurrency and parallelism becomes much more challenging.

Title: Side Effects Breaking Referential Transparency

Body:
Functional Programming in Scala explains a side effect’s impact on breaking referential transparency:

side effect, which implies some violation of referential transparency.

I’ve read part of SICP, which discusses using the “substitution model” to evaluate a program.

As I roughly understand the substitution model with referential transparency (RT), you can de-compose a function into its simplest parts. If the expression is RT, then you can de-compose the expression and always get the same result.

However, as the above quote states, using side effects can/will break the substitution model.

Example:

```<code>val x = foo(50) + bar(10)
</code>```

If foo and bar do not have side effects, then executing either function will always return the same result to x. But, if they do have side effects, they will alter a variable that disrupts/throws a wrench into the substitution model.

I feel comfortable with this explanation, but I don’t fully grok it.

Please correct me and fill in any holes with respect to side effects breaking RT, discussing the effects on the substitution model as well.

Body:
As I roughly understand the substitution model (with referential transparency(RT)), you can de-compose a function into its simplest parts. If the expression is RT, then you can de-compose the expression and always get the same result.

Yes, the intuition is quite right. Here are a few pointers to get more precise:

Like you said, any RT expression should have a single "result". That is, given a factorial(5) expression in the program, it should always yield the same "result". So, if a certain factorial(5) is in the program and it yields 120, it should always yields 120 regardless of which "step order" it is expanded/computed -- regardless of time.

Example: the factorial function.

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)

There are a few considerations with this explanation.

First of all, keep in mind the different evaluation models (see applicative vs. normal order) may yield different "results" for the same RT expression.

def first(y, z):
  return y

def second(x):
  return second(x)

first(2, second(3)) # result depends on eval. model

In the code above, first and second are referentially transparent, and yet, the expression at the end yields different "results" if evaluated under normal order and applicative order (under the latter, the expression does not halt).

....which leads to the use of "result" in quotes. Since it is not required of an expression to halt, it may not produce a value. So using "result" is kind of blurry. One can say an RT expression always yields the same computations under an evaluation model.

Third, it may be required to see two foo(50) appearing in the program in different locations as different expressions -- each one yielding their own results that might differ from each other. For instance, if the language allows dynamic scope, both expressions, though lexically identical, are different. In perl:

sub foo {
    my $x = shift;
    return $x + $y; # y is dynamic scope var
}

sub a {
    local $y = 10;
    return &foo(50); # expanded to 60
}

sub b {
    local $y = 20;
    return &foo(50); # expanded to 70
}

Dynamic scope misleads because it make it easy for one to think x is the only input for foo, when in reality, it is x and y. One way to see the difference is to transform the program into an equivalent one without dynamic scope -- that is, passing explicitly the parameters, so instead of defining foo(x), we define foo(x, y) and pass y explicitly in the callers.

The point is, we are always under a function mindset: given a certain input for an expression, we are given a corresponding "result". If we give the same input, we should always expect the same "result".

Now, what about the following code?

def foo():
   global y
   y = y + 1
   return y

y = 10
foo() # yields 11
foo() # yields 12

The foo procedure breaks RT because there are redefinitions. That is, we defined y in one point, and latter on, redefined that same y. In the perl example above, the ys are different bindings though they share the same letter name "y". Here the ys are actually the same. That's why we say (re)assignment is a meta operation: you are in fact changing the definition of your program.

Roughly, people usually depict the difference as follows: in a side-effect free setting, you have a mapping from input -> output. In an "imperative" setting, you have input -> ouput in the context of a state that can change through time.

Now, instead of just substituting expressions for their corresponding values, one also has to apply transformations to the state at each operation that requires it (and of course, expressions may consult that same state to perform computations).

So, if in a side-effect free program all we need to know to compute an expression is its individual input, in an imperative program, we need to know the inputs and the entire state, for each computational step. Reasoning is the first to suffer a big blow (now, to debug a problematic procedure, you need the input and the core dump). Certain tricks are rendered impractical, like memoization. But also, concurrency and parallelism becomes much more challenging.


问:
Use null object as argument to method
Consider the following piece of code

```<code>class Foo
    {
    public:
    //...
        bool valueFirstGet(int& value) const
            {
            if(this==nullptr)
                {return 0;}
            value=values[0];
            return 1;
            }
    //...

    private:
        int* values;
        size_t n_values;
    };

int main()
    {
    Foo* obj=findObject("key");
    int value;
    if(!obj->valueFirstGet(value))
        {printf("key does not exist\n");}

    return 0;
    }
</code>```

findObject returns nullptr if it cannot find the object. Is it ok to let the member function do the null check instead of its caller. In my code, there are several calls to findObject directly followed by a call to valueFirstGet so leaving the check to the caller makes the code ugly.

EDIT:

Is there a cleaner way to avoid all null checking besides having findObject to throw an exception instead of returning null?

EDIT 2:

What about a static wrapper?

答:
The null-check in valueFirstGet can not yield true without there being undefined behavior in the program, because you must dereference a null-pointer (which causes UB) to let that test yield true. The nasty thing about undefined behavior is that any behavior is fully sanctioned and that behavior might change between compiler versions or even optimization levels without notice.

The correct way to go about this is to have the check in the caller or in a helper method. If the findObject/valueFirstGet calls are commonly paired with no further use for the object returned by findObject, you can even do something like this:

```<code>bool tryValueFirstGet(const std::string& key, int& value)
{
    Foo* obj=findObject(key);
    return obj && obj->valueFirstGet(value);
}
</code>```

The short-circuit behaviour of && ensures that valueFirstGet will only be called if the object could be found.

Title: Use null object as argument to method

Body:
The null-check in valueFirstGet can not yield true without there being undefined behavior in the program, because you must dereference a null-pointer (which causes UB) to let that test yield true. The nasty thing about undefined behavior is that any behavior is fully sanctioned and that behavior might change between compiler versions or even optimization levels without notice.

The correct way to go about this is to have the check in the caller or in a helper method. If the findObject/valueFirstGet calls are commonly paired with no further use for the object returned by findObject, you can even do something like this:

bool tryValueFirstGet(const std::string& key, int& value)
{
    Foo* obj=findObject(key);
    return obj && obj->valueFirstGet(value);
}

The short-circuit behaviour of && ensures that valueFirstGet will only be called if the object could be found.


问:
Advertisements & GPL
I'm planning on providing some GPL software to visitors after they interact with an advertisement. This advertisement will generate revenue for our company, so this would fall under commercial usage. I understand the GPL requires us to either provide the source or a written promise to provide the source upon request when distributing the software commercially.

I'd like to know if providing a link to the the software creator's website, with instructions on getting the source, would be sufficient to satisfy this clause in the GPL?

答:
There is a big difference between GPLv2 and GPLv3 here.

GPLv2

When distributing GPLv2-licensed programs/libraries (in executable form), you must

provide a download link to the same server as where the executables are downloaded from (to satisfy the clause below), or

If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, [...].

provide a written offer to deliver the source code to the asker. This option seems to be intended for use with physical products that contain embedded software, but might work for downloadable software as well.

GPLv3

Compared to GPLv2, you are now officially allowed to separate the locations where the binaries and the source can be obtained from, but you are still responsible for providing access to the source. This means that you can link to the original site to get the source from, but you need to have a fall-back scenario in place for when that site goes down.

Additionally, the 'written offer' option is only available if the software is part of a physical product.

Title: Advertisements & GPL


问:
How should I mark types in C and C++ programs?
In this answer of mine, I used _t at end of types, which ended at best, controversial. This is the practice I use in my current projects.

```<code>typedef struct {
    int x;
    int y;
} point_t;
</code>```

This was intended to be consistent with C types from stddef.h like size_t or ptrdiff_t. However, according to certain comments in my questions, _t postfix appears to be reserved for POSIX. What should I use instead of _t? Or should I continue using _t anyway?

This question is for both C and C++.  If these languages have different conventions, feel free to answer so.

答:
There is no consensus within the C and C++ communities with regard to naming types.

Although the _t suffix is indeed reserved by POSIX, some will advocate using the _t suffix for your own types as well, while others will equally adamantly argue that you should not tempt fate by risking duplicate names with POSIX.

Alternative naming conventions suggest the use of a prefix for types, such as C or T.

OwnerDisplayName: xfix


问:
C# dynamically linking different libraries and/or external classes

tl;dr

Is it possible to include an external library (and create instances of objects represented within that library) based on some condition? This must be done at compile-time, so separate builds?

Background information

Warning: Wall of text.

If I have some code that requires a link to an external class:

```<code>using myExternalLibrary;
namespace myNamespace
{
  public class Engine
  {
     public Engine()
     {
       // external class is contained
       // within myExternalLibrary
       public externalClass instanceOfExternalClass
              = new externalClass();
     }
  }
}

// external class
namespace myExternalLibrary
{
  public class externalClass
  {
     public externalClass()
     {
       // constructor logic
     }
  }
}
</code>```

By providing references to myExternalLibrary in the project that contains myClass and providing a using statement in a relevant place, I can create an instance of externalClass as and when I need it within myClass. This I am fine with. If I have some very common code that requires several different external libraries, I can do the same thing but with each of the external libraries that are required (i.e add a reference and a using statement for each one of the external libraries).

However, due to the design of the software I am working on, I am required to use an external library only when certain conditions are met. I am also not to include references to those external libraries if they are not required.

Class Detail

I can't go into specifics about the class design, but this is basically what I have: I have a class (this is the Engine class) that is required to act as a bridge between the GUI and some hardware. The Engine class requires external libraries to allow it to communicate with external hardware.

I have two external libraries for two separate types of hardware:

InternallyDevelopedHardwareControlLibrary (our internally developed hardware library for controlling our internally developed hardware)

LicensedHardwareControlLibrary (a library that we have licensed for controlling some hardware we have bought in).

By default, the Engine will communicate via InternallyDevelopedHardwareControlLibrary to our internally developed hardware. However, Engine also needs to be able to communicate via LicensedHardwareControlLibrary to the licensed hardware, if (and only if) the end-user has licensed our software to run along side the externally developed hardware.

LicensedHardwareControlLibrary will be licensed to the end-user with our software to some of our end-users. In this instance, LicensedHardwareControlLibrary is required to be shipped with our software. However, if the end-user has is not licensed to use LicensedHardwareControlLibrary, we are not permitted to ship that library with out software.

Since Engine is taking the place of communicating with the external hardware via InternallyDevelopedHardwareControlLibrary by default, it requires a reference to it. However if a user is licensed to utilise LicensedHardwareControlLibrary, I need to add a reference to that, but only if the user is licensed to use that library.

Question

Since Engine is required to be generic, I need to figure out a way of conditionally including this second library.

My initial thought was to move all of the elements of Engine to an abstract class, and to have two separate Engines (one for each of the libraries) that extend the abstract Engine class. Something like:

```<code>public class Engine
{
  // all common code for each Engine
  // type in here
}

public class StandardEngine : Engine
{
  // the engine that will utilise
  // InternallyDevelopedHardwareControlLibrary
}

public class LicensedEngine : Engine
{
  // the engine that will utilise
  // LicensedHardwareControlLibrary
}
</code>```

The StandardEngine code will make use of an instance of the objects represented in InternallyDevelopedHardwareControlLibrary, and LicensedEngine will make use of an instance of the objects represented in LicensedHardwareControlLibrary.

Or more simply put: Each of the less-abstract versions of Engine require to operate on a representation of an object that is contained within either InternallyDevelopedHardwareControlLibrary (StandardEngine) or LicensedHardwareControlLibrary (LicensedEngine).

The standard build will only contain the StandardEngine class, however for some users we will need to run a separate build which also contains the LicensedEngine class.

However, I feel that this will not be optimal because LicensedEngine will need to be external from the main project/library because it cannot be shipped in our standard build. What are the ways in which I can achieve this?

答:
Make a big decision first: compile time or runtime?

If you do want to use assembly references, they are compile-time only. Then you can use #if directives in your code and you can use MSBuild tricks (edit the csproj file outside Visual Studio) to conditionally have the assembly reference. MSBuild is a very powerful tool, and if you are careful, it won't mess too much with Visual Studio. Or you can just have multiple csproj files, living in the same directory, using (almost) the same source files, and different references. This all happens at compile time.

A completely different approach is doing the reference loading during runtime, that's why they invented reflection. You are lucky if the external reference implements a common interface because once you get the type with reflection, you can cast it to your interface and use it normally. Otherwise, you are stuck with Invoke()-ing MethodInfo-s. Or, if your requirements allow it, you can create a very small adapter layer assembly between the external library and yours, as a 3rd assembly. If you need to use the external library, you load your adapter assembly dynamically, cast it to an interface, and use the external library through that layer, no Invoke() anywhere.


答: I find suffixes rather ugly and so avoid _t etc.  A good alternative is to use a capital letter to start type names, so Point in your example above.

Title: How should I mark types in C and C++ programs?

Body:
In this answer of mine, I used _t at end of types, which ended at best, controversial. This is the practice I use in my current projects.

```<code>typedef struct {
    int x;
    int y;
} point_t;
</code>```

This was intended to be consistent with C types from stddef.h like size_t or ptrdiff_t. However, according to certain comments in my questions, _t postfix appears to be reserved for POSIX. What should I use instead of _t? Or should I continue using _t anyway?

This question is for both C and C++.  If these languages have different conventions, feel free to answer so.


问:
APIs, Versioning and Models
I have my (JSON) API structured like this (which I'm pretty happy with):

API Project

```<code>/_V1
    /Controllers
        V1EntityController.cs        // Applies to version 1 only
/_V2
    /Controllers
        V2OtherEntityController.cs   // Applies to versions 2 and below
/Controllers/
    EntityController.cs              // Applies to versions 2 and above
    OtherEntityController.cs         // Applies to versions 3 and above
</code>```

Core Project

```<code>/Data/Entity.cs
/Data/OtherEntity.cs
</code>```

But as the project has progressed both the Entity and OtherEntity classes has become full of legacy properties and a bunch of ShouldSerializexxx methods. They also then also contain properties and sub-classes which are only for serialization.

Would a better solution for this be to create "Models" in the API project like so:

API Project

```<code>/_V1
    /Controllers
        V1EntityController.cs
    /Models
        V1EntityModel.cs
/_V2
    /Controllers
        V2OtherEntityController.cs
    /Models
        V2OtherEntityModel.cs
/Controllers
    EntityController.cs
    OtherEntityController.cs
/Models
    EntityModel.cs
    OtherEntityModel.cs
</code>```

Then convert to and from the classes in the core project? What's the industry recognised practice for handling this scenario?

答:
My vote is on trying to avoid such scenarios. Normally, I don't care when I add new members to a class, because most consumer don't care about newly appearing stuff either. But of course, removing members is a breaking change, but these things happen all the time, you just have to communicate it. I would say breaking changes are the industry standard, it's just cheaper, and doesn't end up with messy code.

My favorite solution is in WCF, see for example here: http://msdn.microsoft.com/en-us/library/ms733832%28v=vs.110%29.aspx. Basically, when you add a new property to your data class, the clients won't bother at all, and you'll even get that data back in a round-trip, thanks to the IExtensibleDataObject infrastructure.

If you really have to support different data class versions at the same time, then I would try to separate the classes, one new class for each new version. I would use interfaces, inheritance, view-models for different versions, or even tools like AutoMapper to decrease the amount of copy-pasted code.

OwnerDisplayName: Jamie

Title: APIs, Versioning and Models


问:
How do I bootstrap a P2P service so that users can locate each other?
My P2P app needs to locate peers, but I don't want to hard-code a DNS address...

One example I've seen is bootstrapping via IRC, but I'd like to do this over HTTP/s if possible.

What are my options and techniques for bootstrapping a P2P app?

答:
It's the easiest if you have a "mothership". Nowadays it doesn't have to be a single server, a SPOF, there are tons of cheap CDN (content delivery network) and cloud solutions.

Otherwise, borrow an idea from a software that is the most successful: bittorrent. Distributed hash tables (DHT) are simply beautiful. And if I'm not mistaken, you can piggyback your own software on the DHT network. DHT doesn't have to be bittorrent-specific, but there are millions of hosts in the bittorrent DHT network already, so why not use it for anything that you like? It's a huge free resource, the protocol is trivial, but there are already lots of libraries for it, it's like a gold mine.

Of course, DHT needs to be bootstrapped as well, but it's an already solved problem. You can collect a big list of known DHT hosts, or just probe randombly, it is so huge that either can work.

Bittorrent's DHT is simple: every torrent has a hash, and the DHT network stores a peer list for each hash. All you have to do is make up a fake, fixed hash for your needs and store that in the DHT. You can help bootstrapping if you create a few DHT nodes yourself that are close to your fixed hash, but it won't be necessary.

Well, it's actually not a completely free resource, if you participate in the DHT network, then you should also participate in the storage of other hashes, and other peers will use your peers as a service.