问:
Is it considered poor practice to include a bug number in a method name for a temporary workaround?
My coworker who is a senior guy is blocking me on a code review because he wants me to name a method 'PerformSqlClient216147Workaround' because it's a workaround for some defect ###. Now, my method name proposal is something like PerformRightExpressionCast which tends to describe what the method actually does. His arguments go along the line of: "Well this method is used only as a workaround for this case, and nowhere else."

Would including the bug number inside of the method name for a temporary workaround be considered bad practice?

答:
To me, naming a method after a bug suggests that the bug isn't resolved or root cause isn't identified.  In other words, it suggests there is still an unknown.  If you are working around a bug in a 3rd party system, then your workaround is a solution because you know the cause - they just can't or won't fix it.

If part of interacting with SqlClient requires you to perform a right expression cast, then your code should read "performRightExpressionCast()".  You can always comment the code to explain why.

I have spent the past 4 and a half years maintaining software.  One of the things that makes code confusing to understand when jumping in is code that is written the way it is only due to history.  In other words, that isn't how it would work if it were written today.  I'm not referring to quality, but to a point-of-view.

A co-worker of mine once said "When fixing a defect, make the code the way it should have been."  The way I interpret that is "Change the code to how it would look if this bug never existed."

Consequences:

Usually, less code as a result.

Straightforward code

Fewer references to bugs in the source code

Less risk of future regression (once code change is fully verified)

Easier to analyze because developers don't have to burden themselves with learning history that is no longer relevant.

Source code doesn't need to tell me how it got to its current state.  Version control can tell me the history.  I need the source code to simply be in the state needed to work.  That said, an occasional "// bug 12345" comment isn't a bad idea, but it gets abused.

So when deciding whether or not to name your method 'PerformSqlClient216147Workaround', ask yourself these questions:

If I had known about bug 216147 before writing the code, how would I have handled it?

What is the workaround?  If somebody who has never seen this code before were to look at it, would they be able to follow it?  Is checking the bug tracking system necessary to know how this code works?

How temporary is this code?  In my experience, temporary solutions usually become permanent, as @mattnz indicates.


问:
Is it a acceptable approach to put try catch wherever null pointer exception occurs?
There are instances where the references to objects, fields, variables etc can be null and there might be a possible occurrence of Null Pointer exception occurring at that point.

Is is a permanent solution to put these code blocks which expect Null ponter exception to be put in a try catch block?

答: There's no point in placing exception handling where you aren't really handling exceptions.  It's a lot of extra code & makes following the program difficult. If you want to show 'friendly' errors to users, just have a top-level exception handler.</p>

ContentLicense: CC BY-SA 3.0


问:
How to write useful Java programs without using mutable variables
I was reading an article about functional programming where the writer states

```<code>(take 25 (squares-of (integers)))
</code>```

Notice that it has no variables. Indeed, it has nothing more than three functions and one constant. Try writing the squares of integers in Java without using a variable. Oh, there’s probably a way to do it, but it certainly isn’t natural, and it wouldn’t read as nicely as my program above.

Is it possible to achieve this in Java? Supposing you are required to print the squares of first 15 integers, could you write a for or while loop without using variables?

Mod notice

This question is not a code golf contest. We are looking for answers that explain the concepts involved (ideally without repeating earlier answers), and not just for yet another piece of code.

答:
Is it possible to implement such an example in Java without using destructive updates?  Yes.  However, as @Thiton and the article itself mentioned, it will be ugly (depending on one's taste).  One way is using recursion; here's a Haskell example that does something similar:

```<code>unfoldr      :: (b -> Maybe (a, b)) -> b -> [a]
unfoldr f b  =
  case f b of
   Just (a,new_b) -> a : unfoldr f new_b
   Nothing        -> []
</code>```

Note 1) the lack of mutation, 2) the use of recursion, and 3) the lack of loops.  The last point is very important -- functional languages don't need looping constructs built into the language, since recursion can be used for most (all?) cases where loops are used in Java.  Here's a well-known series of papers showing how incredibly expressive function calls can be.

I found the article unsatisfying and would like to make a couple of additional points:

That article is a very poor and confusing explanation of functional programming and its benefits.  I would strongly recommend other sources for learning about functional programming.

The most confusing part about the article is that it doesn't mention that there are two uses for assignment statements in Java (and most other mainstream languages):

binding a value to a name: final int MAX_SIZE = 100;

destructive update:  int a = 3; a += 1; a++;

Functional programming eschews the second, but embraces the first (examples: let-expressions, function parameters, top-level defineitions).  This is a very important point to grasp, because otherwise the article just seems silly and might leave you wondering, what are take, squares-of, and integers if not variables?

In addition, the example is meaningless.  It doesn't show the implementations of take, squares-of, or integers.  For all we know, they are implemented using mutable variables.  As @Martin said, you can trivially write this example in Java.

Once again, I would recommend avoiding this article and others like it if you really want to learn about functional programming.  It seems to be written more with the goal of shocking and offending rather than teaching concepts and fundamentals.  Instead, why not check out one of my all-time favorite papers, by John Hughes.  Hughes tries to tackle some of the same issues that the article covered (although Hughes doesn't talk about concurrency/parallelization); here's a teaser:

This paper is an attempt to demonstrate to the larger community of
  (nonfunctional) programmers the signiﬁcance of functional programming,
  and also to help functional programmers exploit its advantages to the
  full by making it clear what those advantages are.

[...]

We shall argue in the remainder of this paper that functional
  languages provide two new, very important kinds of glue. We shall give
  some examples of programs that can be modularized in new ways and can
  thereby be simpliﬁed. This is the key to functional programming’s
  power — it allows improved modularization. It is also the goal for
  which functional programmers must strive — smaller and simpler and
  more general modules, glued together with the new glues we shall
  describe.

Body:
Is it possible to implement such an example in Java without using destructive updates?  Yes.  However, as @Thiton and the article itself mentioned, it will be ugly (depending on one's taste).  One way is using recursion; here's a Haskell example that does something similar:

unfoldr      :: (b -> Maybe (a, b)) -> b -> [a]
unfoldr f b  =
  case f b of
   Just (a,new_b) -> a : unfoldr f new_b
   Nothing        -> []

Note 1) the lack of mutation, 2) the use of recursion, and 3) the lack of loops.  The last point is very important -- functional languages don't need looping constructs built into the language, since recursion can be used for most (all?) cases where loops are used in Java.  Here's a well-known series of papers showing how incredibly expressive function calls can be.

I found the article unsatisfying and would like to make a couple of additional points:

That article is a very poor and confusing explanation of functional programming and its benefits.  I would strongly recommend other sources for learning about functional programming.

The most confusing part about the article is that it doesn't mention that there are two uses for assignment statements in Java (and most other mainstream languages):

binding a value to a name: final int MAX_SIZE = 100;

destructive update:  int a = 3; a += 1; a++;

Functional programming eschews the second, but embraces the first (examples: let-expressions, function parameters, top-level defineitions).  This is a very important point to grasp, because otherwise the article just seems silly and might leave you wondering, what are take, squares-of, and integers if not variables?

In addition, the example is meaningless.  It doesn't show the implementations of take, squares-of, or integers.  For all we know, they are implemented using mutable variables.  As @Martin said, you can trivially write this example in Java.

Once again, I would recommend avoiding this article and others like it if you really want to learn about functional programming.  It seems to be written more with the goal of shocking and offending rather than teaching concepts and fundamentals.  Instead, why not check out one of my all-time favorite papers, by John Hughes.  Hughes tries to tackle some of the same issues that the article covered (although Hughes doesn't talk about concurrency/parallelization); here's a teaser:

This paper is an attempt to demonstrate to the larger community of
  (nonfunctional) programmers the signiﬁcance of functional programming,
  and also to help functional programmers exploit its advantages to the
  full by making it clear what those advantages are.

[...]

We shall argue in the remainder of this paper that functional
  languages provide two new, very important kinds of glue. We shall give
  some examples of programs that can be modularized in new ways and can
  thereby be simpliﬁed. This is the key to functional programming’s
  power — it allows improved modularization. It is also the goal for
  which functional programmers must strive — smaller and simpler and
  more general modules, glued together with the new glues we shall
  describe.


问:
What is a practical level of abstraction in a web application?
(Originally asked on StackOverflow - https://stackoverflow.com/questions/14896121/what-is-a-practical-level-of-abstraction-in-a-web-application)

I still consider myself a newcomer to OO programming, especially in php, so forgive me if I have missed some fundamental principle!

Say I have an intranet application with a staff object with properties and methods unique to being a member of staff:

```<code>class staff {
    ...
    private $job_title;
    private $start_date;
    etc...
}
</code>```

In the quest to keep the maintainable parts of my code in one place, make my data model more intelligent and make my code less tightly-coupled, is it reasonable to abstract each object property to another level?

For example, I expect each property to have a value, but to complicate matters, I'm also interested in what label and description to use when referring to it in human-readable applications. More of interest is which type it is, as well as the capability of the object to validate itself, if its member properties can validate themselves also. It seems then, that properties of the majority of objects have a lot in common. So, the $start_date property might actually be an object in itself:

```<code>abstract class property {
    public $value = NULL;
    protected $label; // A simple label which can be used on user forms, reports, etc.
    protected $description; // Some detail to describe what this property is used for
    protected $type; // Helps choose the right HTML form control and validate user input
    protected $regex; // Regular expression to prompt user entry and validate return value
    protected $unique = FALSE; // If TRUE, check for duplicates in the persistence layer
    protected $default_value; // Prompt the user when entering new values
    protected $HTML_form_element; // Which form element suits this field best?
    etc....
}

class start_date extends property {
    ...
    public function __construct(){
        ...
        $this->label = 'Start date'; // Might be an i18n entry
        $this->description = 'Enter the date on which the contract starts for this staff member'; // Might be an i18n entry
        $this->type = 'VARCHAR(512)'; // Better to use persistence layer's requirements?
        $this->regex = '/^([0-9]{1,2})[/.-]([0-9]{1,2})[/.-]([0-9]{2,4})$/'; // UK date
        $this->default_value = date('Y-m-d'); // Depends on the business policy of the company
        $this->HTML_form_element= 'datepicker'; // Chooses the correct HTML element when building forms automatically
        ...
    }
    etc...
}

class staff {
    ...
    public function __construct(){
        ...
        $start_date = new start_date();
        ...
    }
    etc...
}
</code>```

In previous applications, these related things have lived in different places; random global variables, commented code, decorator objects, a config file, embeded in HTML, a database table, a scrap of paper. It makes sense to bring all an objects properties together in one place, but is this the right way?

答:
The data you are describing is meta data. Many languages have clean ways to store this information, such as annotations. The PHP team as rejected native annotations time and time again, but Symfony2 and Doctrine2 have a home-grown implementation using doc-block comments. This is far from the ideal solution, but it's the best work around we have at the moment. This is the same way annotations were created in Java before native annotations were implemented by Sun in Java 5.

I'm not sure if the Symfony/Doctrine solution is available as a stand alone component or not. I think Symfony relies on the doctrine-common library to parse annotations.

Either way, check out Symfony2 Form Vaidation

```<code>// Acme/TaskBundle/Entity/Task.php
use Symfony\Component\Validator\Constraints as Assert;

class Task
{
    /**
     * @Assert\NotBlank()
     */
    public $task;

    /**
     * @Assert\NotBlank()
     * @Assert\Type("\DateTime")
     */
    protected $dueDate;
}
</code>```

The information you're trying to describe with a has-a relationship above is cleanly described here without muddying up the code. Internally, these comments are parsed and cached in pure PHP so they can be looked up at run-time.

Body:
The data you are describing is meta data. Many languages have clean ways to store this information, such as annotations. The PHP team as rejected native annotations time and time again, but Symfony2 and Doctrine2 have a home-grown implementation using doc-block comments. This is far from the ideal solution, but it's the best work around we have at the moment. This is the same way annotations were created in Java before native annotations were implemented by Sun in Java 5.

I'm not sure if the Symfony/Doctrine solution is available as a stand alone component or not. I think Symfony relies on the doctrine-common library to parse annotations.

Either way, check out Symfony2 Form Vaidation

// Acme/TaskBundle/Entity/Task.php
use Symfony\Component\Validator\Constraints as Assert;

class Task
{
    /**
     * @Assert\NotBlank()
     */
    public $task;

    /**
     * @Assert\NotBlank()
     * @Assert\Type("\DateTime")
     */
    protected $dueDate;
}

The information you're trying to describe with a has-a relationship above is cleanly described here without muddying up the code. Internally, these comments are parsed and cached in pure PHP so they can be looked up at run-time.


问:
Which license for an open source project which may be, but is not intended to be, used as a bot in some apps?
I'm wondering if there is some license which I could put on my website on which I could publish an open-source application that potentially could be used for purposes of cheating in one game for smartphones.

Now, I have to stress that the goal of the application is in no way cheating, so with this license I want to eliminate the possibility that the authors of the smartphone game (in which my bot could be used) could sue me if someone else starts using the application to get better at their game.

I may be too paranoid, but with all the weird laws you just never know.

I did a little research and came up with Creative Commons Attribution 3.0 (CC BY 3.0), but was wondering whether any of you guys were ever in a similar situation, and what you did in that case?

By the way, I did read and consider the moral implications of the possible app appearing on my site, so now I just need some license as stated in the question.

答:
First and foremost, you should be consulting with a lawyer.  Just as you've spent years learning your trade, they've spent years learning the ins and outs of law & liability.  They know what you can and can't say, what will hold up in court, what is actually en forcible and WHAT MUST BE WRITTEN IN ALL CAPS.

That said, if your product is some sort of general-purpose tool (e.g. packet sniffer, debugger...), you're probably pretty safe as long as you're not promoting it as being used for cheating.  Definitely don't make reference to any particular game.  On top of that, it's pretty common to have a "we're not responsible for what you do with our software" clause.


问:
organising classes / folder structure for TDD-based development
Due to test-driven development, one ends up with many classes doing just one thing.  It is quite a headache just to see where such classes would be placed inside the folder structure.

First of all, is it considered a bad-pattern, to put related classes in the same file?

Any suggestion on what one uses in actual-production environments?

答:
Generally, you should put one class in one file.  That way it is easy to find the pertinent code when making changes.  I think that it would be more of a headache to have to try to remember how the classes were organized when looking for the code that I am trying follow.  You aren't creating these files for the computer but for the future developer (it might be you) that is going to be trying to find some bug or add a new feature.  And files make that easier to do because A.class is an easier to look for than Stuff.class.

If you create a directory structure that groups similar classes together, that can reduce some of your headache.

OwnerDisplayName: Karl Cassar


问:
Should you version web applications?
I've recently had a discussion with a coworker about versioning web applications.

I don't think you need it at all, and if you just want a sanity check to confirm your latest release is live, I think a date (YYMMDD) is probably good enough.

Am I off base?  Am I missing the point?  Should I use web application version numbers

答:
If you can automate version number on your application's DLLs, it couldn't hurt.  It will help you keep track of versions.

Generally, web apps are released only at one location where you are hosting it, so it's not as important as say a desktop application.  It can help with roll-backs, bug tracking (i.e. which version was this in) and keeping track of the difference between developer, staging, and production servers, if applicable.

I'd look into automating it - it's the kind of thing you can setup once and use it if/when you need it.

ContentLicense: CC BY-SA 2.5

Title: Should you version web applications?


答: In languages that support it, why not use namespaces? That should make it clear what the organization is, regardless of the folder structure.</p>

Title: organising classes / folder structure for TDD-based development

Body:
Due to test-driven development, one ends up with many classes doing just one thing.  It is quite a headache just to see where such classes would be placed inside the folder structure.

First of all, is it considered a bad-pattern, to put related classes in the same file?

Any suggestion on what one uses in actual-production environments?


问:
Strategy for keeping up with (Python) language changes

Writing code that will still run years from now

Programming languages change.
Libraries change.
Some code from 5, 10, or even 20 years ago might still run and produce expected results, whereas some code from 2 years might fail with a syntax error.
This is partly inevitable, since languages evolve (at least, most do).
Developers have a responsibility to maintain their code. But sometimes, stability is an important requirement in production code, and code should simply run for 10 years without the need for someone going through the code every year to adapt it for language changes.
Or I might have small scripts, for example for scientific data analysis, that I need to revisit after not touching them for years.
For example, at meteorological offices there is a lot of operational Fortran code even for non-speed-essential parts, and code stability is one of the reasons.
I've heard fear for instability is one of the objects they have against moving to Python (apart from language inertia of course; it's only possible for new code not dependent on old code).
Of course, one strategy for stable code is to freeze the entire operating system. But that is not always feasible.

I'm using Python as on example, but the issue is not limited to Python in particular.

Documents on Python compatibility issues

In the case of Python, there are several documents outlining policy for backward-incompatible changes.

PEP-5

According to PEP 5:

There must be at least a one-year transition period between the
  release of the transitional version of Python and the release
  of the backwards incompatible version.  Users will have at
  least a year to test their programs and migrate them from use
  of the deprecated construct to the alternative one.

Personally, I consider that one year is rather short. It means I might write some code, and 1½ years from now it won't run anymore.

PEP 291

PEP 291 contains an incomplete lists of guidelines of things that should be avoided in order to maintain backward compatibility. However, it relates only to Python 2.x. As Python 2.7 is the final release in the 2.x series and Python 2.7 is bugfix-only, this PEP is now only of historical interest.

PEP 387

There is also PEP 387 on backward-incompatible changes. PEP 387 is a draft and not official policy. In June 2009, this was discussed on the Python-ideas mailing-list. Part of the discussion focussed on how developers can write code that is robust against language changes. One post listed some advice on what not to do:

Along with this there are several rules you can infer that are probably
  true most of the time: don't call stuff starting with "_", don't monkey-
  patch anything, don't use dynamic class replacement on objects from
  classes other than your own, don't depend on the depth of inheritance
  hierarchies (for example, no ".__bases__[0].__bases__[0]"), make sure
  your tests run without producing any DeprecationWarnings, be mindful of
  potential namespace conflicts when adding attributes to classes that
  inherit from other libraries.  I don't think all these things are
  written down in one place though.

In addition, there were some points about "mine fields" (new features likely to change) and "frozen areas" (very sold APIs virtually guaranteed not to change). Quoting Antoine Pitrou:

I think the "frozen area" should be defined positively (explicit public APIs and
  explicitly guaranteed behaviour) rather than negatively (an explicit "mine
  field"). Otherwise, we will forget to put some important things in the minefield
  and get bitten later when we need to change those things in a
  backwards-incompatible way.

There doesn't seem to be any conclusion from this thread, but it gets pretty close to the core of what I'm looking for. The thread is almost four years old, so perhaps the situation has changed or improved. What kind of code is likely to survive, and what kind of code is more fragile?

Porting guidelines

In addition to the documents outlined above, each Python version comes with a porting guideline: porting to Python 3.2, porting to Python 3.3, etc.

Useful compatibility

PEP 3151 introduced me to the concept of useful compatibility. In my own words, this boils down to the idea that only if code is carefully written language developers need to be careful to maintain compatibility. It doesn't really define useful compatibility, but I think it's similar to the ideas I quoted from the PEP 387 discussion above.

From the programmers' point of view

As a programmer, I know that Python will change in the future and that people — most notably myself — will try to run my code perhaps several years from now in a Python version that is one, two, or perhaps three minor versions up. Not everything will be compatible, and in fact it's easy to come up with code that will fail (I once encountered code stating if sys.version[:3] != '2.3': print 'Wrong version, exiting'). What I'm looking for is a set of guidelines on what to do and what not to do to enhance the chances that my code will still run unaltered in the future.

Are there any such guidelines? How do I write Python code that will still run in the future?

My question relates both to the Python core, to its standard library, but also to commonly used add-on libraries, in particular numpy, scipy, matplotlib.

EDIT: So far, two of the answers relate to python2 vs. python3. This is not what I mean. I know about tools to migrate from Python2 to Python3. My question relates to language changes yet to come. We can do better than a crystal ball in finding coding guidelines that are more stable. For example:

import module is more future-proof than from module import *, because the latter can break code if module grows one or more new functions/classes.

Using undocumented methods may be less future-proof than using documented methods, as something being undocumented may be a sign of something being not stable yet.

It's this kind of practical coding advices that I'm after. Since it's about present→future, we can limit ourselves to Python3, because Python2 is not going to change anymore.

答:
For Python 2 --> Python 3, there is a Python 2to3 library already installed (it comes with the original Python package).

Based off of that, soon after new versions are released, there should be similar libraries that come with each new version. However, as Martijn stated, libraries like these will only be released for major versions (like version 3.0) but not for minor versions (such as 3.2). However, between 3.0 and 3.2 (or any other minor versions), there shouldn't be any compatibility issues, so converting to version 3.0 should be fine.

Also, I suggest you look at this question.

OwnerDisplayName: gerrit


答:
If you're using third party code that is returning null, it's much better to check the return value.

```<code>ThirdPartyValue thirdPartyValue = thirdParty.getValue();
if (null == thirdPartyValue) {
    ...
}
</code>```

Edit: Java 8 is out! This should now be

```<code>Optional<ThirdPartyValue> thirdPartyValue = Optional.ofNullable(thirdParty.getValue());
</code>```

A NullPointerException is insidious and misleading, because it means you have an error somewhere else, where a variable was set to null without you expecting it to be.

I repeat, the bug isn't where the NullPointerException was thrown, the bug is earlier in your code, where a variable was set to null without you expecting it to be.

Catching the NullPointerException means you're hiding or excusing the actual bug.

In your own code, it is much better to do away with null whereever possible, and for that matter, also mutable variables.

If you get an exception, don't catch it and return null, instead wrap and rethrow the exception.

If you have a method that should sometimes not return a value, you could return an empty Collection, or an Optional, which is new in Java 8.

If you never set a variable to null you can never have an unexpected null.

Don't allow null parameters:

```<code>public void method(A param1, B param2, C param3) {
    requireNonNull(param1, param2, param3);
    ...
}

public static void requireNonNull(Object... parameters) {
    Stream.of(parameters).forEach(Objects::requireNonNull);
}
</code>```

Avoid creating "result" variables that are temporarily null:

Instead of:

```<code>public Result method() {
    Result result = null;    // <- this smells
    try {
        result = ...;
    } catch (SomeException e) {
        LOGGER.log(Level.WARNING, "Exception "+e.getMessage(), e);
    }
    return result;
}
</code>```

you should:

```<code>public Result method() {
    try {
        return ...;
    } catch (SomeException e) {
        throw new MyPossiblyRuntimeException(e);
    }
}
</code>```

Sooner or later you will start to see usage of null (and mutable variables) as a code smell.

I'm sure you can come up with other smart ways to avoid null, be creative!

tl;dr: NullPointerException should never be thrown in the first place, so don't catch it, because that means you're hiding the actual bug.

Title: Is it a acceptable approach to put try catch wherever null pointer exception occurs?

Body:
There are instances where the references to objects, fields, variables etc can be null and there might be a possible occurrence of Null Pointer exception occurring at that point.

Is is a permanent solution to put these code blocks which expect Null ponter exception to be put in a try catch block?

Body:
If you're using third party code that is returning null, it's much better to check the return value.

ThirdPartyValue thirdPartyValue = thirdParty.getValue();
if (null == thirdPartyValue) {
    ...
}

Edit: Java 8 is out! This should now be

Optional<ThirdPartyValue> thirdPartyValue = Optional.ofNullable(thirdParty.getValue());

A NullPointerException is insidious and misleading, because it means you have an error somewhere else, where a variable was set to null without you expecting it to be.

I repeat, the bug isn't where the NullPointerException was thrown, the bug is earlier in your code, where a variable was set to null without you expecting it to be.

Catching the NullPointerException means you're hiding or excusing the actual bug.

In your own code, it is much better to do away with null whereever possible, and for that matter, also mutable variables.

If you get an exception, don't catch it and return null, instead wrap and rethrow the exception.

If you have a method that should sometimes not return a value, you could return an empty Collection, or an Optional, which is new in Java 8.

If you never set a variable to null you can never have an unexpected null.

Don't allow null parameters:

public void method(A param1, B param2, C param3) {
    requireNonNull(param1, param2, param3);
    ...
}

public static void requireNonNull(Object... parameters) {
    Stream.of(parameters).forEach(Objects::requireNonNull);
}

Avoid creating "result" variables that are temporarily null:

Instead of:

public Result method() {
    Result result = null;    // <- this smells
    try {
        result = ...;
    } catch (SomeException e) {
        LOGGER.log(Level.WARNING, "Exception "+e.getMessage(), e);
    }
    return result;
}

you should:

public Result method() {
    try {
        return ...;
    } catch (SomeException e) {
        throw new MyPossiblyRuntimeException(e);
    }
}

Sooner or later you will start to see usage of null (and mutable variables) as a code smell.

I'm sure you can come up with other smart ways to avoid null, be creative!

tl;dr: NullPointerException should never be thrown in the first place, so don't catch it, because that means you're hiding the actual bug.


答:
I don't have a lot to add, the "program for 2, and use 2to3" seems to be a common addage around the internet lately. However there is something you should look at:

It's called six (pypi page). It's a python library devoted to helping write code that runs on both python 2 & python 3. I've seen it employed in a number of projects while perusing around the net, but the names escape me at the moment.

Title: Strategy for keeping up with (Python) language changes

Body:
Writing code that will still run years from now

Programming languages change.
Libraries change.
Some code from 5, 10, or even 20 years ago might still run and produce expected results, whereas some code from 2 years might fail with a syntax error.
This is partly inevitable, since languages evolve (at least, most do).
Developers have a responsibility to maintain their code. But sometimes, stability is an important requirement in production code, and code should simply run for 10 years without the need for someone going through the code every year to adapt it for language changes.
Or I might have small scripts, for example for scientific data analysis, that I need to revisit after not touching them for years.
For example, at meteorological offices there is a lot of operational Fortran code even for non-speed-essential parts, and code stability is one of the reasons.
I've heard fear for instability is one of the objects they have against moving to Python (apart from language inertia of course; it's only possible for new code not dependent on old code).
Of course, one strategy for stable code is to freeze the entire operating system. But that is not always feasible.

I'm using Python as on example, but the issue is not limited to Python in particular.

Documents on Python compatibility issues

In the case of Python, there are several documents outlining policy for backward-incompatible changes.

PEP-5

According to PEP 5:

There must be at least a one-year transition period between the
  release of the transitional version of Python and the release
  of the backwards incompatible version.  Users will have at
  least a year to test their programs and migrate them from use
  of the deprecated construct to the alternative one.

Personally, I consider that one year is rather short. It means I might write some code, and 1½ years from now it won't run anymore.

PEP 291

PEP 291 contains an incomplete lists of guidelines of things that should be avoided in order to maintain backward compatibility. However, it relates only to Python 2.x. As Python 2.7 is the final release in the 2.x series and Python 2.7 is bugfix-only, this PEP is now only of historical interest.

PEP 387

There is also PEP 387 on backward-incompatible changes. PEP 387 is a draft and not official policy. In June 2009, this was discussed on the Python-ideas mailing-list. Part of the discussion focussed on how developers can write code that is robust against language changes. One post listed some advice on what not to do:

Along with this there are several rules you can infer that are probably
  true most of the time: don't call stuff starting with "_", don't monkey-
  patch anything, don't use dynamic class replacement on objects from
  classes other than your own, don't depend on the depth of inheritance
  hierarchies (for example, no ".__bases__[0].__bases__[0]"), make sure
  your tests run without producing any DeprecationWarnings, be mindful of
  potential namespace conflicts when adding attributes to classes that
  inherit from other libraries.  I don't think all these things are
  written down in one place though.

In addition, there were some points about "mine fields" (new features likely to change) and "frozen areas" (very sold APIs virtually guaranteed not to change). Quoting Antoine Pitrou:

I think the "frozen area" should be defined positively (explicit public APIs and
  explicitly guaranteed behaviour) rather than negatively (an explicit "mine
  field"). Otherwise, we will forget to put some important things in the minefield
  and get bitten later when we need to change those things in a
  backwards-incompatible way.

There doesn't seem to be any conclusion from this thread, but it gets pretty close to the core of what I'm looking for. The thread is almost four years old, so perhaps the situation has changed or improved. What kind of code is likely to survive, and what kind of code is more fragile?

Porting guidelines

In addition to the documents outlined above, each Python version comes with a porting guideline: porting to Python 3.2, porting to Python 3.3, etc.

Useful compatibility

PEP 3151 introduced me to the concept of useful compatibility. In my own words, this boils down to the idea that only if code is carefully written language developers need to be careful to maintain compatibility. It doesn't really define useful compatibility, but I think it's similar to the ideas I quoted from the PEP 387 discussion above.

From the programmers' point of view

As a programmer, I know that Python will change in the future and that people — most notably myself — will try to run my code perhaps several years from now in a Python version that is one, two, or perhaps three minor versions up. Not everything will be compatible, and in fact it's easy to come up with code that will fail (I once encountered code stating if sys.version[:3] != '2.3': print 'Wrong version, exiting'). What I'm looking for is a set of guidelines on what to do and what not to do to enhance the chances that my code will still run unaltered in the future.

Are there any such guidelines? How do I write Python code that will still run in the future?

My question relates both to the Python core, to its standard library, but also to commonly used add-on libraries, in particular numpy, scipy, matplotlib.

EDIT: So far, two of the answers relate to python2 vs. python3. This is not what I mean. I know about tools to migrate from Python2 to Python3. My question relates to language changes yet to come. We can do better than a crystal ball in finding coding guidelines that are more stable. For example:

import module is more future-proof than from module import *, because the latter can break code if module grows one or more new functions/classes.

Using undocumented methods may be less future-proof than using documented methods, as something being undocumented may be a sign of something being not stable yet.

It's this kind of practical coding advices that I'm after. Since it's about present→future, we can limit ourselves to Python3, because Python2 is not going to change anymore.


答:
This is an unsolved problem in our field.  There's no way to be sure that your code will indefinitely work.  Even if your code was truly perfect in the forwards-compatible sense (and if it is, please come work for my company! ;) ), if it runs on, uses, or is used by any other software which gets a bug or changes in any way, your code may not work.

So I can't give you a list of things to do that, if you follow them, will guarantee success.  But what you can do is minimize the risk of future breakages and minimize their impacts.  A more knowledgeable Pythonist would be able to give you advice more specific to Python, so I will have to be more general:

write unit tests.  Even for things that you know don't need them.

using popular/well-designed/stable libraries and technologies, avoiding unpopular (and thus likely to soon be unsupported) ones

avoid writing code that exploits implementation details.  Code to interfaces, not implementations.  Code against multiple implementations of the same interface.  For example, run your code in CPython, Jython, and IronPython and see what happens.  This will give you some great feedback about your code.  This might not be helpful for Python3 though -- last I heard, some implementations were still in Python2.

write simple, clear code that is explicit about its assumptions

write modular, composable code.  If some code must do something dangerous (in the future-proof sense), separate it so that even if it has to change, the rest of the code doesn't.

have a specification of some form.  This is similar to the points about unit tests, if you use tests as a spec, and interfaces, which can also be used as specs.  (I mean interface in the general sense, not the Java keyword sense).

Doing any of these things may/will increase the amount of work you have to do.  I think that makes sense -- a lot of these points can also be made for how to write good code, which is quite difficult (in my opinion).  Sometimes you may need to violate some of these suggestions.  That is perfectly acceptable, but be aware of the costs.

It's great that the Python team is thinking about this, and for sure they are far more talented and skilled than I will ever be.  Still, I would estimate there's a 100% that somebody's code somewhere will stop working the way the want it's intended to when Python is upgraded.


答:
If you resell the same web application to multiple customers, you absolutely should version it.

If it's a website that's only ever installed in one location, then the need is less dire, but it still likely couldn't hurt. You'd be less susceptible to timezone problems and such, too. Diagnosing an issue in a library version 1.0.2.25 is a lot nicer than hunting down the library build on November 3, 2010 11:15 a.m.

Title: Should you version web applications?

Body:
I've recently had a discussion with a coworker about versioning web applications.

I don't think you need it at all, and if you just want a sanity check to confirm your latest release is live, I think a date (YYMMDD) is probably good enough.

Am I off base?  Am I missing the point?  Should I use web application version numbers


答:
The simplest I can do with recursion is a function with one parameter. It's not very Java-esque, but it does work:</p>

```<code>public class squares
{
    public static void main(String[] args)
    {
        squares(15);
    }

    private static void squares(int x)
    {
        if (x>0)
        {
            System.out.println(x*x);
            squares(x-1);
        }
    }
}
</code>```

Title: How to write useful Java programs without using mutable variables

Body:
I was reading an article about functional programming where the writer states

```<code>(take 25 (squares-of (integers)))
</code>```

Notice that it has no variables. Indeed, it has nothing more than three functions and one constant. Try writing the squares of integers in Java without using a variable. Oh, there’s probably a way to do it, but it certainly isn’t natural, and it wouldn’t read as nicely as my program above.

Is it possible to achieve this in Java? Supposing you are required to print the squares of first 15 integers, could you write a for or while loop without using variables?

Mod notice

This question is not a code golf contest. We are looking for answers that explain the concepts involved (ideally without repeating earlier answers), and not just for yet another piece of code.

Body:
The simplest I can do with recursion is a function with one parameter. It's not very Java-esque, but it does work:

public class squares
{
    public static void main(String[] args)
    {
        squares(15);
    }

    private static void squares(int x)
    {
        if (x>0)
        {
            System.out.println(x*x);
            squares(x-1);
        }
    }
}


答:
I've previously tried to create an interpreter for a lisp-like language in Java, ( a few years ago and all the code was lost as it was in CVS at sourceforge ), and the Java util iterators are a bit verbose for functional programming on lists.

Here's something based on a sequence interface, which just has the two operations you need to get the current value and get the sequence starting at the next element. These are named head and tail after the functions in scheme.

It's important to use something like the Seq or Iterator interfaces as it means the list is created lazily. The Iterator interface can't be an immutable object, so is less suited to functional programming - if you can't tell if the value you pass into a function has been changed by it, you lose one of the key advantages of functional programming.

Obviously integers should be a list of all the integers, so I started at zero and alternately returned positive and negative ones.

There's two version of squares - one creating a custom sequence, the other using map which takes a 'function' - Java 7 doesn't have lambdas so I used an interface - and applies it to each element in the sequence in turn.

The point of the square ( int x ) function is only to remove the need to call head() twice - normally I would have done this by putting the value into a final variable, but adding this function means there are no variables in the program, only function parameters.

The verbosity of Java for this sort of programming led me to write the second version of my interpreter in C99 instead.

```<code>public class Squares {
    interface Seq<T> {
        T head();
        Seq<T> tail();
    }

    public static void main (String...args) {
        print ( take (25, integers ) );
        print ( take (25, squaresOf ( integers ) ) );
        print ( take (25, squaresOfUsingMap ( integers ) ) );
    }

    static Seq<Integer> CreateIntSeq ( final int n) {
        return new Seq<Integer> () {
            public Integer head () {
                return n;
            }
            public Seq<Integer> tail () {
                return n > 0 ? CreateIntSeq ( -n ) : CreateIntSeq ( 1 - n );
            }
        };
    }

    public static final Seq<Integer> integers = CreateIntSeq(0);

    public static Seq<Integer> squaresOf ( final Seq<Integer> source ) {
        return new Seq<Integer> () {
            public Integer head () {
                return square ( source.head() );
            }
            public Seq<Integer> tail () {
                return squaresOf ( source.tail() );
            }
        };
    }

    // mapping a function over a list rather than implementing squaring of each element
    interface Fun<T> {
        T apply ( T value );
    }

    public static Seq<Integer> squaresOfUsingMap ( final Seq<Integer> source ) {
        return map ( new Fun<Integer> () {
            public Integer apply ( final Integer value ) {
                return square ( value );
            }
        }, source );
    }

    public static <T> Seq<T> map ( final Fun<T> fun, final Seq<T> source ) {
        return new Seq<T> () {
            public T head () {
                return fun.apply ( source.head() );
            }
            public Seq<T> tail () {
                return map ( fun, source.tail() );
            }
        };
    }

    public static Seq<Integer> take ( final int count,  final Seq<Integer> source ) {
        return new Seq<Integer> () {
            public Integer head () {
                return source.head();
            }
            public Seq<Integer> tail () {
                return count > 0 ? take ( count - 1, source.tail() ) : nil;
            }
        };
    }

    public static int square ( final int x ) {
        return x * x;
    }

    public static final Seq<Integer> nil = new Seq<Integer> () {
        public Integer head () {
            throw new RuntimeException();
        }
        public Seq<Integer> tail () {
            return this;
        }
    };

    public static <T> void print ( final Seq<T> seq ) {
        printPartSeq ( "[", seq.head(), seq.tail() );
    }

    private static <T> void printPartSeq ( final String prefix, final T value, final Seq<T> seq ) {
        if ( seq == nil) {
            System.out.println("]");
        } else {
            System.out.print(prefix);
            System.out.print(value);
            printPartSeq ( ",", seq.head(), seq.tail() );
        }
    }
}
</code>```

Body:
I've previously tried to create an interpreter for a lisp-like language in Java, ( a few years ago and all the code was lost as it was in CVS at sourceforge ), and the Java util iterators are a bit verbose for functional programming on lists.

Here's something based on a sequence interface, which just has the two operations you need to get the current value and get the sequence starting at the next element. These are named head and tail after the functions in scheme.

It's important to use something like the Seq or Iterator interfaces as it means the list is created lazily. The Iterator interface can't be an immutable object, so is less suited to functional programming - if you can't tell if the value you pass into a function has been changed by it, you lose one of the key advantages of functional programming.

Obviously integers should be a list of all the integers, so I started at zero and alternately returned positive and negative ones.

There's two version of squares - one creating a custom sequence, the other using map which takes a 'function' - Java 7 doesn't have lambdas so I used an interface - and applies it to each element in the sequence in turn.

The point of the square ( int x ) function is only to remove the need to call head() twice - normally I would have done this by putting the value into a final variable, but adding this function means there are no variables in the program, only function parameters.

The verbosity of Java for this sort of programming led me to write the second version of my interpreter in C99 instead.

public class Squares {
    interface Seq<T> {
        T head();
        Seq<T> tail();
    }

    public static void main (String...args) {
        print ( take (25, integers ) );
        print ( take (25, squaresOf ( integers ) ) );
        print ( take (25, squaresOfUsingMap ( integers ) ) );
    }

    static Seq<Integer> CreateIntSeq ( final int n) {
        return new Seq<Integer> () {
            public Integer head () {
                return n;
            }
            public Seq<Integer> tail () {
                return n > 0 ? CreateIntSeq ( -n ) : CreateIntSeq ( 1 - n );
            }
        };
    }

    public static final Seq<Integer> integers = CreateIntSeq(0);

    public static Seq<Integer> squaresOf ( final Seq<Integer> source ) {
        return new Seq<Integer> () {
            public Integer head () {
                return square ( source.head() );
            }
            public Seq<Integer> tail () {
                return squaresOf ( source.tail() );
            }
        };
    }

    // mapping a function over a list rather than implementing squaring of each element
    interface Fun<T> {
        T apply ( T value );
    }

    public static Seq<Integer> squaresOfUsingMap ( final Seq<Integer> source ) {
        return map ( new Fun<Integer> () {
            public Integer apply ( final Integer value ) {
                return square ( value );
            }
        }, source );
    }

    public static <T> Seq<T> map ( final Fun<T> fun, final Seq<T> source ) {
        return new Seq<T> () {
            public T head () {
                return fun.apply ( source.head() );
            }
            public Seq<T> tail () {
                return map ( fun, source.tail() );
            }
        };
    }

    public static Seq<Integer> take ( final int count,  final Seq<Integer> source ) {
        return new Seq<Integer> () {
            public Integer head () {
                return source.head();
            }
            public Seq<Integer> tail () {
                return count > 0 ? take ( count - 1, source.tail() ) : nil;
            }
        };
    }

    public static int square ( final int x ) {
        return x * x;
    }

    public static final Seq<Integer> nil = new Seq<Integer> () {
        public Integer head () {
            throw new RuntimeException();
        }
        public Seq<Integer> tail () {
            return this;
        }
    };

    public static <T> void print ( final Seq<T> seq ) {
        printPartSeq ( "[", seq.head(), seq.tail() );
    }

    private static <T> void printPartSeq ( final String prefix, final T value, final Seq<T> seq ) {
        if ( seq == nil) {
            System.out.println("]");
        } else {
            System.out.print(prefix);
            System.out.print(value);
            printPartSeq ( ",", seq.head(), seq.tail() );
        }
    }
}


答:
In Java you could do this (esp. the infinite list part) with iterators.  In the following code sample, the number supplied to the Take constructor can be arbitrarily high.

```<code>class Example {
    public static void main(String[] a) {
        Numbers test = new Take(25, new SquaresOf(new Integers()));
        while (test.hasNext())
            System.out.println(test.next());
    }
}
</code>```

Or with chainable factory methods:

```<code>class Example {
    public static void main(String[] a) {
        Numbers test = Numbers.integers().squares().take(23);
        while (test.hasNext())
            System.out.println(test.next());
    }
}
</code>```

Where SquaresOf, Take and Integers extend Numbers

```<code>abstract class Numbers implements Iterator<Integer> {
    public static Numbers integers() {
        return new Integers();
    }

    public Numbers squares() {
        return new SquaresOf(this);
    }

    public Numbers take(int c) {
        return new Take(c, this);
    }
    public void remove() {}
}
</code>```

Body:
In Java you could do this (esp. the infinite list part) with iterators.  In the following code sample, the number supplied to the Take constructor can be arbitrarily high.

class Example {
    public static void main(String[] a) {
        Numbers test = new Take(25, new SquaresOf(new Integers()));
        while (test.hasNext())
            System.out.println(test.next());
    }
}

Or with chainable factory methods:

class Example {
    public static void main(String[] a) {
        Numbers test = Numbers.integers().squares().take(23);
        while (test.hasNext())
            System.out.println(test.next());
    }
}

Where SquaresOf, Take and Integers extend Numbers

abstract class Numbers implements Iterator<Integer> {
    public static Numbers integers() {
        return new Integers();
    }

    public Numbers squares() {
        return new SquaresOf(this);
    }

    public Numbers take(int c) {
        return new Take(c, this);
    }
    public void remove() {}
}


问:
Is HTML5 usable for syncing data between devices?
I work for an insurance company. They have a contact database that gets pushed to the field agents by Lotus Notes. We're trying to move away from Lotus Notes, but we first have to remove our dependency on it.

It has been suggested that a HTML5 solution could provide offline access to agent contacts and be used to sync changed from the server down and the client up.

It is my understanding that the SQL storage capabilities of HTML5 aren't fully implemented (IE and Firefox apparently don't support yet per one site I read.) LocalStorage may not be robust enough for the data we need to sync since the size limit is relatively small.

Is HTML5 a feasible solution to this issue or should we track down some kind of syncing solution? (I've been reading about one from the Ubuntu folks and Microsoft's, as well.)

Thanks!

答:
Check out caniuse.com.  For WebSQL, it's deprecated:

However, if key-value stores are an option that might do:

Also check out this great listing of options.


问:
What is this variation of MVC in JavaScript?
I am working on sorting out my Javascript code. Currently I have views implemented without any Model or collection. Now I working on separating Model from View. So for this transformation, I am planning as follows:

```<code>         View --->  X  <--- | ---> Server
          <  Client side  >
</code>```

Assumptions:

View will not have any data that is to be loaded form server.

X will talk to server and get the required data. Then X will fire event.

View will listen to events and update themselves accordingly.

X is not an exact replica of some entity on server. X will just take those entities/ data from server and then View can request this data from X.

There will be exactly one X for each View.

Now question is -- What is X called?

Options -- Model, Controller, ViewModel, Presenter, or anything else.

Or Is this very crude thing which can not have terminology?

答:
As far as I know, you're not following any of the MV* patterns (yet).

In (very) loose terms:

A View is strictly for presenting information and receiving input from the user.

A Controller, Presenter, or ViewModel may have business logic as well as being the go-between for the Model and the View.

A Model is a representation of the system's data.  It might be a direct access to the data store, or it might go through a data access layer instead.

"Model" is the closest layer that X seems to be approaching.  The Model layer does not need to be a direct representation of the information in the data store.  It just needs to present the data in alignment with the application / business domain.

You may find Martin Fowler's article on GUI Architecture worth reading.  Please note that he has updated the MVP pattern and moved it into two patterns, but you'll run across that while reading through his site.


答:
X is most commonly called a ViewModel. Controllerless MVVM is what your implementation most closely resembles.

If your view is handling the events from X, it's similar to Model-View-Binder, kind of like Knockout.js, maybe without the declarative style.

I wouldn't worry so much about what it's called.  Worry about  how/if it works.

Title: What is this variation of MVC in JavaScript?

Body:
I am working on sorting out my Javascript code. Currently I have views implemented without any Model or collection. Now I working on separating Model from View. So for this transformation, I am planning as follows:

```<code>         View --->  X  <--- | ---> Server
          <  Client side  >
</code>```

Assumptions:

View will not have any data that is to be loaded form server.

X will talk to server and get the required data. Then X will fire event.

View will listen to events and update themselves accordingly.

X is not an exact replica of some entity on server. X will just take those entities/ data from server and then View can request this data from X.

There will be exactly one X for each View.

Now question is -- What is X called?

Options -- Model, Controller, ViewModel, Presenter, or anything else.

Or Is this very crude thing which can not have terminology?


问:
how do I form a team which is remote?
I've got a bit of a challenge.  While I'm not "in charge" I'm certainly lead developer on a project and my team will be scattered to high heaven.

I've got someone who works on Fridays only, and probably 2 people who will be 3-4 hours away in another state. (One of the lovely side effects of partnering with multiple universities).

Anyway, how can I get them all on the same "team"?? I've read a bunch of Joel Spolsky's stuff, but I can't create the same kind of environment that he uses.  This is also the first project I'll be lead on, so it's kindof make-or-break.

Specifically I'm looking for managing styles (personality), process models, project management  (scrum?), video conferencing tools, and the like.  I just don't have any resources for this kind of thing, and I'm afraid I'm going to be stuck doing too much work.

Thanks,

答:
There are many things that you need to consider.

To add to @karianna's first point:
make yourself available.  Make sure that people see your presence and vice versa - through some sort of IM system for example.  The hardest thing is not knowing if/when you can get in touch with someone.

Also, have a weekly meeting that is mandatory for everyone - and hold the meeting regardless if it only takes 2 minutes to say "nothing new, we're all good".

There are lots of tools for time-tracking, project management, etc... look at things like the suite of tools provided by 37signals, and things that integrate with these tools.

Title: how do I form a team which is remote?


问:
Do I include association links for Objects that only have method scope in UML class diagrams
For example I have a utility Class which contains a few constants (GCMConstants), this class is used in one method in the application. However as it is not a member of the Class it should not be modeled via an association link. Should I continue as is and not include a link or should I include one?

I've checked my UML books but none of them seem to cover stuff like this.

答: It sounds like the class should be a private inner class of the class that uses it. As such it is an implementation detail. Depending on what level of detail your overall diagram is, I would leave it out of the bigger picture.</p>


问:
Text Editor Document Model
I am working on a text editor in javascript. I have created the front end and i need to prototype a backend. I need to model the structure of the document using this as hierarchy:

Character
 , Word
 , Tag
 , Document

I am trying to create objects based on this hierarchy.

For example:

Characters are represented a linked list. Word are pointers to the first and last characters. Tags are another linked list of words, and a document is a collection of words and tags.

I am was wondering if anyone has a better suggestion to model these relationships as classes. I receive a character from the keyboard and i need to store this as an object in my document model.

thanks

答:
You'll want to take a look at Data Structures for Text Sequences, by Charles Crowley.

These 5 notes: 1, 2, 3, 4, 5, have a lot of information on Old School text editor data structures.  They may interest you for a number of reasons. First, performance was limited when those were written, so they may end up as very high speed structures today.  Second, programs were a lot harder to write, so the very simplicity may appeal to you if you're just trying to get a working back end.

Title: Text Editor Document Model


答:
In short: Your question seems to be discussed with pros and cons in the following SO posts. Look at the following references:

Best way to synchronize local HTML5 DB (WebSQL Storage, SQLite) with a server (2 way sync)

Offline storage - db sync

How to synchronize HTML5 local/webStorage and server-side storage?

I would add my 2 cents with pointing to the security concern of letting collected data to remain un-encrypted in local storage. Because the way how data is collected in a device/tablet may have some personal/commercial sensitive data whose storage should comply with varies compliance rules.

Title: Is HTML5 usable for syncing data between devices?

Body:
I work for an insurance company. They have a contact database that gets pushed to the field agents by Lotus Notes. We're trying to move away from Lotus Notes, but we first have to remove our dependency on it.

It has been suggested that a HTML5 solution could provide offline access to agent contacts and be used to sync changed from the server down and the client up.

It is my understanding that the SQL storage capabilities of HTML5 aren't fully implemented (IE and Firefox apparently don't support yet per one site I read.) LocalStorage may not be robust enough for the data we need to sync since the size limit is relatively small.

Is HTML5 a feasible solution to this issue or should we track down some kind of syncing solution? (I've been reading about one from the Ubuntu folks and Microsoft's, as well.)

Thanks!


问:
Does the lack of states on HTTP make the protocol unfit for modern applications?
I changed from PHP to ASP.NET, now I’m working with webforms in a somewhat large company. I given some though and research to back my impressions on ASP.NET webforms and I came to the conclusion that Webforms is an attempt to make web applications easier to write for those who came from the "desktop programming"  world.

But before shunning WebForms I decided to analyze the needs of the software we write and bumped on the issue of maintaining application states on the Web.

I understand that HTTP is a stateless protocol, and ASP.NET tries to simulate states with  session variables , hiddenfields and viewstates, it is in my understanding also that all of the above cited have flaws and are not perfect ways to keep the state in my application, But I also understand the need to keep a state on my app.

Which raises the questions, is the HTTP really fit for this type of job (making applications that require state)?  Are the tools currently available to webdevelopers enough? Are the new tools available with HTML5 effective at the job or are they just workarounds for the limitations to HTTP.

I love developing for the web, and I’m much more familiar with the web than with the desktop, I just been wondering about this HTTP statelessness thing for some time and i want to understand if I’m missing some point or if I’m right on my notions.

答:
HTTP is certainly an older technology that has become quite ubiquitous as the web became so. As a result people are extending this technology to do many things now with modern web apps were it can appear the statelessness of HTTP is an issue. Hence you see a lot of conveniences like viewstates. </p>

<p>However it is also possible to code modern web apps in a stateless way and this is often preferred, RESTful web development is based on this idea. Many web API's that form the basis for modern web apps are truly stateless and should be. It is a different way to think and architect. Your needs may vary depending on what you are doing. </p>

Body:
HTTP is certainly an older technology that has become quite ubiquitous as the web became so. As a result people are extending this technology to do many things now with modern web apps were it can appear the statelessness of HTTP is an issue. Hence you see a lot of conveniences like viewstates.

However it is also possible to code modern web apps in a stateless way and this is often preferred, RESTful web development is based on this idea. Many web API's that form the basis for modern web apps are truly stateless and should be. It is a different way to think and architect. Your needs may vary depending on what you are doing.


答: The protocol may be stateless, but the app you write could maintain any state :)</p>

Title: Does the lack of states on HTTP make the protocol unfit for modern applications?

Body:
I changed from PHP to ASP.NET, now I’m working with webforms in a somewhat large company. I given some though and research to back my impressions on ASP.NET webforms and I came to the conclusion that Webforms is an attempt to make web applications easier to write for those who came from the "desktop programming"  world.

But before shunning WebForms I decided to analyze the needs of the software we write and bumped on the issue of maintaining application states on the Web.

I understand that HTTP is a stateless protocol, and ASP.NET tries to simulate states with  session variables , hiddenfields and viewstates, it is in my understanding also that all of the above cited have flaws and are not perfect ways to keep the state in my application, But I also understand the need to keep a state on my app.

Which raises the questions, is the HTTP really fit for this type of job (making applications that require state)?  Are the tools currently available to webdevelopers enough? Are the new tools available with HTML5 effective at the job or are they just workarounds for the limitations to HTTP.

I love developing for the web, and I’m much more familiar with the web than with the desktop, I just been wondering about this HTTP statelessness thing for some time and i want to understand if I’m missing some point or if I’m right on my notions.


答:
Many protocols are stateless when you get down to the raw protocol layer. Statefulness is not the primary obstacle to Web Development. The primary obstacle is that HTTP by default is Sessionless. That is, by default a series of requests by a browser to a server are unrelated to each other.

We get around this by using cookies to denote a session. The ASP.NET server gives a cookie to the browser, who then returns it on subsequent request. Behind the scenes ASP.NET looks for that cookie and connects it to the Session that it has cached (assuming the session hasn't timed out).

From there, other data can be associated with the session and used to create a customized experience for each user. Web Servers and frameworks have become so good at this that rich clients can be built on top of the HTTP protocol. Case in point, Twitter clients use http for everything from retrieving a list of friends and tweets, to sending direct messages to other users. (I'm simplifying somewhat, there is a fully connected, TCP streaming protocol available through twitter, but for the most part, HTTP is at the core of everything.

HTML to a degree has reached its limits as an adequate display technology, but the HTML 5 standard along with JavaScript and CSS 3 have made it possible to create rich UIs that rival what's possible with native clients. In fact, HTML 5 has come so far, it is supported as a native technology for Windows 8 apps. With libraries such as JQuery for the client and NodeJS for the server, one can create an application that uses JavaScript for it's logic on the client and server and HTML for the display and pure HTTP for communications.

So, while the argument in the past that HTML/HTTP has reached its limit might have had some merit, it's just not the case anymore.


答: In addition to what the others have said, I'd add that versioning is also important from a marketing perspective.  A new version is something new that can be marketed to potential or existing customers.  It lets customers know something is 'new' and see that things are moving forward.  It provides nice groupings of new features.  And it looks more professional.</p>

Title: Should you version web applications?


问:
Is there anything special to consider when writing my own exception class in C++?
If I wanted to implement my own version of the std::exception for no good reason, are there any special things about implementing this kind of object that I should be aware of? It seems like a fairly simple thing that is mostly a string wrapper...

Here is my implementation so far:

```<code>#pragma once;

#include <string>

class MyException
{
public:
    MyException(const std::wstring&);
    virtual ~MyException(){}

    virtual MyException& operator=(const MyException& rhs);
    virtual const std::wstring& what(){return msg;};

private:
    std::wstring msg;
};

MyException::MyException(const std::wstring& message)
:msg(message)
{
}

MyException& MyException::operator=(const MyException& rhs)
{
    if(this == &rhs)
    {
        return *this;
    }
    msg = rhs.msg;
    return *this;
}
</code>```

答: The best advice I could give you is to base your code on the standard exception classes. It will make your code simpler and will allow you and your users to interact with existing code, the standard library or third party libraries.</p>


答: It's called Configuration Management.  If the system is never changed, it shouldn't break.  So don't change the system.  Worried about new Python releases?  Don't upgrade.  Worried about new device drivers?  Don't upgrade.  Worried about Windows patches?  ...


答: Not particularly. Exception handling is already an expensive routine, so it's difficult to cock things up from that perspective, and the language doesn't treat thrown objects notably different to any other. In fact, you could simply throw a string if you wanted to. But you should design the more derived classes to contain more information, IMO.</p>

Title: Is there anything special to consider when writing my own exception class in C++?

Body:
If I wanted to implement my own version of the std::exception for no good reason, are there any special things about implementing this kind of object that I should be aware of? It seems like a fairly simple thing that is mostly a string wrapper...

Here is my implementation so far:

```<code>#pragma once;

#include <string>

class MyException
{
public:
    MyException(const std::wstring&);
    virtual ~MyException(){}

    virtual MyException& operator=(const MyException& rhs);
    virtual const std::wstring& what(){return msg;};

private:
    std::wstring msg;
};

MyException::MyException(const std::wstring& message)
:msg(message)
{
}

MyException& MyException::operator=(const MyException& rhs)
{
    if(this == &rhs)
    {
        return *this;
    }
    msg = rhs.msg;
    return *this;
}
</code>```


答: Your users doesn't care about version numbers as they always have the latest and greatest release anyway, but you owe it to yourself (and your team) to know exactly what version is running live. Eventually your development source gets out of sync with the live code and then you definitely must know. So label your releases in your svn/git tree and mark the web app with that tag.

Title: Should you version web applications?


问:
What is the most cross-browser/system compatible option for 3d graphics on a web page?
I would like to develop a bit of functionality for a web site that involves a bit of 3D - the user can move around objects, rotate them and texture them.

So far I've looked into:

WebGL (in particular three.js) and it looks great, but it's not supported in IE nor IOS.

IOS supports the <canvas> tag, but only 2d. It looks like three.js has an unsupported hack to make a 3d thing use the 2d canvas instead without textures, but this looks like a hack.

I also considered resorting to Flash which works on most browsers, but that won't work on IOS.

What's my best option for doing 3d web graphics on the vast array of browsers and interfaces?

At the moment I'm thinking WebGL for web (and ask people to use chrome or firefox, and take the hit on IE) and then maybe write a native app for IOS, but I am not sure if there are better alternatives available that I don't know of.

答:
There is no, and likely never will be any approach that is cross browser and cross system when one considers multiple mobile (phone size and tablet size) operating systems and browsers out there for desktop systems.

To that extent, there is no answer that can be given that will be the right answer - there are pros and cons to each approach.

The best/most cross-browses metric is also one that is poorly defined.  Is it raw page hits by browser type?  Is it sheer number of browsers out there? or does it take into consideration the browsing habits of people on the different systems? Are certain geographies to be prioritized higher than others?

You mention WebGL - but thats not well supported on android either - does this mean an android version should be considered too?  Flash is likewise an 'interesting' framework to target when looking at mobile devices.

A common approach undertaken by businesses is to make a spreadsheet - list the criteria and weight each criteria.  If browsing numbers are key, weight that.  If ease of use of the framework is key, weight it that way, if variety of current browsers, etc...

Once you identify the frameworks and weights, research each one and toss in a number (0 - 10) in each of the cells for that framework and see which one comes out to be the 'best'.

Outside of that, business decisions are best made by the person responsible for them and taking the risks.  Asking random people on the internet to make them for you can be problematic - we aren't aware of all of the factors that are being considered for a particular solution set (the time, the resources).


问:
Configuration file for an API - should it be web.config?
I have a remote procedure call API where the connection parameters need to be stored somewhere that the API code can access. This API is expected to be used mainly to create web services.

I originally planed to store these parameters in a separate xml file, and require users of the API to define the path to that file in code. A coworker has suggested that I should find a way to store these parameters in the web.config file instead.

Without a lot of WCF experience, I am under the impression that the web.config file should not be used here, because it contains many settings necessary for a web service or web app to function. I don't want my API to mess with that file. I feel it is too risky.

What is your opinion on this? Is web.config an appropriate place for storing settings for my API, or should it be left alone?

答:
In my experience with .NET programming, the web.config (for WCF and ASP.NET) or the app.config (for all other .NET projects) are used for anything that is related to the configuration of the application or framework. There are exceptions such as when the amount of configurations is just too exceedingly large to organize well into one file, however I'd recommend that you try to stay away from that if at all possible.

You would be correct that a lot of WCF-specific configuration (service endpoints and what not) are currently in the web.config file. However, the web.config file is meant to hold much much more including configurations for any plugins you may be using like cache-solutions or db-connection info (Entity Framework being what comes to mind).

I would recommend that you explore what you can do (by default) with the web.config outside of WCF. Also, it may be worth noting that you can define your own configuration elements so that you're not just throwing everything into appSettings. Check out this link for a simple tutorial on creating your own config sections:

As far as your particular scenario is concerned, I feel that it would be an excellent idea to define your configurations within the Web.config file. Just make sure that you keep it cleaned and organized as it grows with your application (so you don't inadvertently make unwanted changes).

ContentLicense: CC BY-SA 4.0


问:
Advice on App/Service Architecture
I'm starting a project that will have a web front end for the users coupled with a database. There will then be a stand-alone service running that will, on a specified interval, poll an API and update the database with the changes it found.

What I need advice on is how the service should be setup. When a user creates an account on the site, I"ll need to create a "hook" in the service that will then go poll the API for that specific user.

I looked at building the service using NodeJS because I could use the non-blocking structure of it along with callbacks then the API returns data that needs to be reflected in the database. I don't know how I will be able to create more monitors when a user creates an account since it's already running. Can NodeJS run in a continuous loop as as service?

I am familiar with .Net and could use a Windows Service, but how would that scale with polling when the user numbers grow?

答:
I'm still a fuzzy on exactly what you are asking, but based on your comment, I think I can offer some advice. As I understand it, you're mainly asking what you can be called by a "hook" and then ran in the background (not in real-time) to perform some sort of db-related update based on calls made to an in-house API. I imagine a simple diagram like the following:

```<code> +----------------+                    +------------------+
 |                |                    |                  |
 |   web app      |    after-signup    |    background    |
 |                |+------------------>|    service       |
 |                |   async-call or    |                  |
 +----------------+      "hook"        +------------------+
                                      +  ^       +
                                      |  |       |
                                      |  |       |
                                      |  |       | update db
                             call API |  |       |
                                      |  |       |
                                      |  |       |
                                      v  +       v
                               +----------+     +------------+
                               |          |     |            |
                               |  API     |     |   Database |
                               +----------+     +------------+
</code>```

So, in regards to how this "async-call" is made, there are a couple of common options that come to mind.

1. Using a Queue

Perhaps something like Redis or RabbitMQ. In this scenario, after the user has signed up,  you're web-application will push some values into the queue (all the data the background service would need). Your background service would then be a program that simply watches the queue in a continuous loop and processes an item when something is found on the queue.

While this is a very simple approach, it does require that you install some sort of queue server inside your infrastructure. In that case, the diagram would change sightly:

```<code> +----------------+                 +---------+             +------------------+
 |                |                 |         |    pop      |                  |
 |   web server   |    push         |         |<-----------+|    background    |
 |                |+--------------->| queue   |+----------->|    service       |
 |                |   async-call    |         |   process   |                  |
 +----------------+                 |         |             +------------------+
                                    +---------+             + ^       +
                                                            | |       |
                                                            | |       |
                                                            | |       | update db
                                                   call API | |       |
                                                            | |       |
                                                            | |       |
                                                            v +       v
                                                     +---------+     +------------+
                                                     |         |     |            |
                                                     |  API    |     |   Database |
                                                     +---------+     +------------+
</code>```

Fire and Forget

The other approach is to setup a simple web-server as your processing service. All your web-application will need to do is send a fire and forget HTTP request to your service. By fire and forget I mean that you do not wait for a response when you make the HTTP call. You'll have to check what libraries you'll need to use for your language of choice to make this happen.

Then your background service, another web service in this case, will accept the request and start it's processing. Since the calling service is not waiting for a response, there is no rush here.

Node

In either of these scenarios, you can use NodeJS if you'd like. It will work fine for both approaches. However, Ruby's EventMachine and Python's Twisted frameworks will do equally as good if evented IO is your goal, in which case I would have to assume that you are planning on handling a high-volume of requests/queue-items from your we application.

Let me know if this answers your question. Like I had mentioned previously, the question seems kind of broad but I answered what I could.

Title: Advice on App/Service Architecture

Body:
I'm still a fuzzy on exactly what you are asking, but based on your comment, I think I can offer some advice. As I understand it, you're mainly asking what you can be called by a "hook" and then ran in the background (not in real-time) to perform some sort of db-related update based on calls made to an in-house API. I imagine a simple diagram like the following:

 +----------------+                    +------------------+
 |                |                    |                  |
 |   web app      |    after-signup    |    background    |
 |                |+------------------>|    service       |
 |                |   async-call or    |                  |
 +----------------+      "hook"        +------------------+
                                      +  ^       +
                                      |  |       |
                                      |  |       |
                                      |  |       | update db
                             call API |  |       |
                                      |  |       |
                                      |  |       |
                                      v  +       v
                               +----------+     +------------+
                               |          |     |            |
                               |  API     |     |   Database |
                               +----------+     +------------+

So, in regards to how this "async-call" is made, there are a couple of common options that come to mind.

1. Using a Queue

Perhaps something like Redis or RabbitMQ. In this scenario, after the user has signed up,  you're web-application will push some values into the queue (all the data the background service would need). Your background service would then be a program that simply watches the queue in a continuous loop and processes an item when something is found on the queue.

While this is a very simple approach, it does require that you install some sort of queue server inside your infrastructure. In that case, the diagram would change sightly:

 +----------------+                 +---------+             +------------------+
 |                |                 |         |    pop      |                  |
 |   web server   |    push         |         |<-----------+|    background    |
 |                |+--------------->| queue   |+----------->|    service       |
 |                |   async-call    |         |   process   |                  |
 +----------------+                 |         |             +------------------+
                                    +---------+             + ^       +
                                                            | |       |
                                                            | |       |
                                                            | |       | update db
                                                   call API | |       |
                                                            | |       |
                                                            | |       |
                                                            v +       v
                                                     +---------+     +------------+
                                                     |         |     |            |
                                                     |  API    |     |   Database |
                                                     +---------+     +------------+

Fire and Forget

The other approach is to setup a simple web-server as your processing service. All your web-application will need to do is send a fire and forget HTTP request to your service. By fire and forget I mean that you do not wait for a response when you make the HTTP call. You'll have to check what libraries you'll need to use for your language of choice to make this happen.

Then your background service, another web service in this case, will accept the request and start it's processing. Since the calling service is not waiting for a response, there is no rush here.

Node

In either of these scenarios, you can use NodeJS if you'd like. It will work fine for both approaches. However, Ruby's EventMachine and Python's Twisted frameworks will do equally as good if evented IO is your goal, in which case I would have to assume that you are planning on handling a high-volume of requests/queue-items from your we application.

Let me know if this answers your question. Like I had mentioned previously, the question seems kind of broad but I answered what I could.


问:
How to properly document functionality in an agile project?
So recently, we've just finished the first phase of our project.

We used agile with fortnightly sprints. And whilst the application turned out well, we're now turning our eyes on some of the maintenance tasks.

One maintenance task is that all of our documentation appears in the form of specs. These specs describe 1 or more stories and generally are a body of work which a few devs could knock over in a week.

For development, that works really well - every two weeks, the devs get handed a spec and it's a nice discrete chunk of work that they can just do.

From a documentation point of view, this has become a mess. The problem with writing specs that are focused on delivering just-in-time requirements to developers is we haven't placed much emphasis on the big picture.

Specs come from all different angles - it could be describing a standard function, it could describing parts of a workflow, it could be describing a particular screen...

And now, we have business rules about our application scattered across 120 documents. Looking for any document for a particular business rule or function in particular is quite hard because you don't know which document has this information, and making a change request is equally hard because once again, we are unsure about which spec to make the change.

So we have maybe a couple of weeks of lull before it's back to specing out functionality for the next phase but in this time, I'd like to re-visit our processes. I think the way we have worked so far in terms of delivering fortnightly specs works well.

But we also need a way to manage our documentation so that our business rules for a given function / workflow are easy to locate / change.

I have two ideas.

One is we compile all of our specs into a series of master specs broken by a few broad functional areas. The specs describe the sprint, the master spec describe the system. The only problem I can see is
1) Our existing 120 specs are not all neatly defined into broad functional areas. Some will require breaking up, merging etc. which will take a lot of time.
2) We'll be writing specs and updating master specs in each new sprint. Seems like double the work, and then do the devs look at the spec or the master spec?

My other suggestion is to concede that our documentation is too big of a mess, and manage that mess going forward. So we go through each spec, assign like keywords to it, and then when we want to search for a function, we search for that keyword. Problems I can see
1) Still the problem of business rules scattered everywhere, keywords just make it easier to find it.

anyway, if anyone has any decent ideas or any experience to share about how best to manage documentation, would really appreciate it.

答:
Aren't you forgetting about about the non functional requirements?

Do you have an Architecture Diagram, Deployment Process, Database Schema, Disaster Recovery Plan and System Admin manual that are up to date?

Perhaps some of the above mentioned documents are not needed in your context but I come from a maintenance background.

In the maintenance world we look after mature systems and in many cases there are no technical staff members around who understand the non functional requirements.

In such cases, complete and up to date non functional documentation really matters.


问:
Whats the greatest most impressive programing feat you ever witnessed?
Everyone knows of the old adage that the best programmers can be orders of magnitude better than the average. I've personally seen good code and programmers, but never something so absurd. So the questions is, what is the most impressive feat of programming you ever witnessed or heard of?

You can define impressive by:

The scope of the task at hand e.g. John single handedly developed the framework for his company, a work comparable in scope to what the other 200 employed were doing combined.

Speed e.g. Stu programmed an entire real time multi-tasking app OS on an weekened including  its own C compiler and shell command line tools

Complexity e.g. Jane rearchitected our entire 10 millon LOC app to work in a cluster of servers. And she did it in an afternoon.

Quality e.g. Charles's code had a rate of defects per LOC 100 times lesser than the company average. Furthermore he code was clean and understandable by all.

Obviously, the more of these characteristics combined, and the more extreme each of them, the more impressive is the feat.

So, let me have it. What's the most absurd feat you can recount? Please provide as much detail as possible and try to avoid urban legends or exaggerations. Post only what you can actually vouch for.

Bonus questions:

Was the herculean task a one-of, or did the individual regularly amazed people?

How do you explain such impressive performance?

How was the programmer recognized for such awesome work?

答:
Miguel de Icaza - the Mono project.  </p>

<p>(He's also incredibly funny, witty and entertaining - at least from the brief talk I saw him give and in listening to some podcast interviews)</p>

Body:
Miguel de Icaza - the Mono project.

(He's also incredibly funny, witty and entertaining - at least from the brief talk I saw him give and in listening to some podcast interviews)


问:
What is the most egregious waste of money you have seen, and what did you do about it?
Often we as programmers see large organisations wasting huge sums of money on bloated and inefficient solutions to problems. This pains me greatly because I like organisations to benefit from best of breed solutions. However, my abilities as a programmer are limited when it comes to influencing the key decision makers and often my perspective on the matter is constrained to my own little technical world.

So, my question is this. After encountering an egregious waste of money on some software and/or hardware that really got your goat, what did you do about it to get it fixed or were you doomed to bite the bullet and mutter forever under your breath? I'm interested in hearing your overall experiences and especially what lessons you learned about how to tackle this sort of thing in the future. Let's not name names, the experience of how to tackle the problem is more important than the actual offending product.

答:
Limiting Long-term Raises and Bonuses

I think its taught in Business 101 to not give employees raises. A secondary case is to limit salaries of star performers because they need to fit inside of some certain salary range.

Eventually employees will realise their pay-scale is not in-line with their industry (or output). The people that have the resume and skills will eventually leave, and take with them all their knowledge and probably a few of their friends. The people remaining (who are the bottom performers) will have to pick up the slack and then spend more time hiring a new person (at market rate). So the company just traded a star employee for JR level one, and just lost all the "savings" of keeping the salaries low.

As this continues, the development team will struggle to stay on par, and will probably get worse and worse until something drastic is done.


问:
Multiple Display of a Document and persist each viewer change in a single document
i have a scenario where i have to make available a document for viewing and editing to multiple users, the users can edit and view the document at the same time. Now the problem arises here if for example user A and user B are viewing a document at the same time and if both the user change the state of the document and user A saves it at x instant of time and user B saves it at y instant of time where y>z in the time dimension. The changes by the user A will be overridden by changes made by the user B.

Possible solutions that i have in mind

(1) i'll keep a bit e.g. isViewedCurrently and only allow a single user to view/edit the document,

(2) save changes of every user separately and then appoint a role who will merge those
changes (impractical)

please suggest some solution that i can implement, can anyone explain how google does it, the google docs are shared, viewed and edit by multiple users and changes of each user is persisted.

im using SQL server 2008 R2 for persisting the application data.

EDIT:

google has implemented an editing surface from scratch and that too in JavaScript

http://googledocs.blogspot.com/2010/05/whats-different-about-new-google-docs.html#!/2010/05/whats-different-about-new-google-docs.html

http://googledocs.blogspot.com/2010/05/whats-different-about-new-google-docs.html#!/2010/05/whats-different-about-new-google-docs.html

答:
The solution that springs to my mind is like this:

Store the document in a version control system

When viewing, the user gets the latest version as of that moment

When saving, a new version gets created. If the VCS changes have been committed in the meantime, an automatic merge is attempted.

If the merge fails, the user is alerted that conflicting changes have been made and is asked to resolve the conflicts.

If the merge succeeds, the merged version is stored.

This assumes that the document is stored in a format that allows comparissons and merges.


问:
How does if/else work internally in all programming languages?
```<code>if(true/false){
     //if condition is true
}else {
     // if condition is false
}
</code>```

Everyone knows about the structure of if-else. But what is if actually? Is it a class method, static method or keyword? I'm little confused about this.

答:
This in fact depends on the language you are talking about.

There are excellent answers here on how if and else are keywords and form control flow statements because when compiled to a sequence of instructions, these statements control the execution flow of the instruction sequence - which of course is sequential by default, but can have jumps in order to allow execution to depend on the current state. And this is certainly true for a whole set of languages.

But there are a couple of languages, such as Smalltalk and Lisp (probably the most prominent examples), that actually implement their equivalent of control flow statements as methods or macros respectively, over a very basic mechanism for conditional execution/jumps.