问:
How to get a Web Application to communicate between users
I am developing a multipalyer web Application for Anti-Chess. It would be hosted on Google App Engine.

I have a few questions:

How do I get two different users who have opened the webapp on their browser to communicate moves with each other. P2P or through the server. If through the server, can I store some moves on it (specifically talking about GAE), to test bots later?

How to implement this P2P/Server connection. As a developer I know jack about Networking. But I hav heard of things like Socket programming, HTTP request etc, what can/should I use. And where can I read up on that!

If I don't go for GAE, would it cost me too much to get some server space and hosting capabilities? And people tell me that then deploying the application is tougher than on GAE. Is that so. Where can I read up on deploying the web Application on Servers.

Where does the code for networking go? I will be using Django with python as the web framework, front-end would be HTML, CSS, and JavaScript. Should I make a separate module for the networking methods and then introduce a method calls wherever needed in the game play?

Someone suggested me on using Unity software for developing. Is it good, Does it make it simple to do work? Will it cover all the parts of the development, the front end and the back end and the deployment?

Note: I am a first timer in web Application, I have coded games before, but always without GUI. And also with no multiplayer over the network capabilities!

答:
If you want to communicate state between two participants in a game, one relatively simple way to do it would be to have a web service which allows each player to PUT the resource that represents the shared game state, with verification to make sure that they don't make illegal moves (or modify the other player's moves).  This is an example of the logical flow:

Assign each player a token, after they've authenticated (using an email, for example).

Allow a player to invite another to play a game.  This could take the form of sending a message to the other player, to which the other player could respond.

If the invitee accepts, create a shared resource to which those two users have permissions, and communicate the URL to both player resources.

Allow the web app to PUT representations of the game state to the shared resource.  In the case of chess, a simple example would be to have a shared PGN file to which both users could write.

If you're interested in this approach, which would be an example of "SOA," or "service-oriented architecture," you might try SOA with REST or RESTful Web Services. This architecture is server-client oriented, not peer-to-peer; that has the advantage of being much simpler to implement.

You could implement your web services as separate routes within your Django project, and have AJAX calls from your Javascript front end which actually perform the actions related to the game state.  I think Unity would be overkill for what you're trying to do; it's more about graphical games.


问:
What does "if w in [1..5, 8, 11]" mean in pseudo code?
In some pseudocode, I saw the following:

```<code>if w in [1..5,8,11]
</code>```

Does it mean that if w is from 1 to 5 or 8 or 11? Or is it something else?

ContentLicense: CC BY-SA 3.0

Body: It means "if W is 1, 2, 3, 4, 5, 8, or 11".


问:
Can I convert ALL CAPS sections of an OSI license to regular case (and bold)?
Update: I've got a response from the FSF on this down in the answers

From the answer to Can I remove all-caps and shorten the disclaimer on my License?, it appears that the APP CAPS sections of a software license are largely to provide extra legal ammo and increase the weight of those sections.

On the flip side, ALL CAPS TEXT is more difficult to read in paragraph form.  Furthermore, with formats like markdown, we can provide cleaner alternatives to all-caps "bolding" of text.

So, I'd like to convert (for example) the warranty clause of the MIT license from:

```<code>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
</code>```

to (markdown):

```<code>**The software is provided "as is", without warranty of any kind, express or
implied, including but not limited to the warranties of marchantability,
fitness for a particular purpose and noninfringement. In no event shall the
authors or copyright holders be liable for any claim, damages or other
liability, whether in an action of contract, tort or otherwise, arising from,
out of or in connection with the software or the use or other dealings in the
software.**
</code>```

Is this legally murky territory?  (particularly w/ GPL?)

答: All-caps text is a form much loved by lawyers in legal documents when they wish to emphasize an element.  Some elements of a legal document do not take effect unless they are emphasized.  A license is a legal document.  Don't mess with it.</p>


问:
Writing OOPS code in Non Object Oriented Language
I was reading some article on the internet as I was preparing for interview and I found out below statement-

Writing object oriented code, even in non-object oriented language?

Is this statement true??

Can anybody provide an example to justify the above statement if somebody asked me this question in the interview.

And when do we write object oriented code in non object oriented language?

I mainly worked in Java. So any example corresponding to that will be helpful.

Thanks in advance.

答:
There's a rough way to do it in any language using something like a struct. You just need to make sure to have some variables local to that struct and a set of functions (methods) that operate on them. You'd store functions via pointers to those functions and only accessing things via a given struct. There's an extensive book written on doing such programming in ANSI-C as referenced in this Stack Overflow post.

Python's objects are dictionaries of variables and functions in a similar vein. Other languages also use this approach and languages that support dictionaries can be made to work similarly. Even languages that don't could be made to if you figure out how to make a dictionary in them.


答:
I disagree with Ross Patterson (but I'm not a lawyer). A legal document is just text, no matter how is it presented. Putting things in bold or in uppercase indicates that this is important and that the reader should carefully read that (funny as it is, writing text in uppercase would have an opposite effect, and people would skip such unreadable sections), but doesn't increase or decrease the legal value of the content.

There is no such a thing as a relative legal value which fluctuates depending on the formatting. Otherwise, every piece of legal text would be in Arial Black 100 bold all caps underlined, displayed in blinking red.

If text in all capitals was "importantly mandatory", what would this mean about the text not in all capitals? Is it "mandatory, but not too much"? Or "mandatory only if you want it to be"? Or not mandatory at all? Nonsense.

Example:

YOU ARE NOT AUTHORIZED TO SELL THIS SOFTWARE PRODUCT AS YOUR OWN.

  You are neither authorized to decompile or change it, including for personal purposes like learning.

So, can you decompile or change it? Or maybe you can, but only for personal purposes, despite what is said in the text above? If you can't decompile or change it, what does it change that the text is not in all capitals?

All capitals are generally used in those texts for technical reasons: you can't use bold in .txt files. Replacing all capitals by bold, given that you can ensure that it will always be displayed in bold, makes no difference.

Of course, as indicated in the comments, you should contact (and you had contacted) FSF to have a definitive response.

Title: Can I convert ALL CAPS sections of an OSI license to regular case (and bold)?

Body:
Update: I've got a response from the FSF on this down in the answers

From the answer to Can I remove all-caps and shorten the disclaimer on my License?, it appears that the APP CAPS sections of a software license are largely to provide extra legal ammo and increase the weight of those sections.

On the flip side, ALL CAPS TEXT is more difficult to read in paragraph form.  Furthermore, with formats like markdown, we can provide cleaner alternatives to all-caps "bolding" of text.

So, I'd like to convert (for example) the warranty clause of the MIT license from:

```<code>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
</code>```

to (markdown):

```<code>**The software is provided "as is", without warranty of any kind, express or
implied, including but not limited to the warranties of marchantability,
fitness for a particular purpose and noninfringement. In no event shall the
authors or copyright holders be liable for any claim, damages or other
liability, whether in an action of contract, tort or otherwise, arising from,
out of or in connection with the software or the use or other dealings in the
software.**
</code>```

Is this legally murky territory?  (particularly w/ GPL?)


答:
Yes. Early C++ compilers translated the code to C before compiling with a normal C compiler. Today, that's how Vala works. Vala is based on the GLib Object System, which provides object-oriented features for C, but is apparently quite cumbersome. Vala streamlines the process.

As for an example, the following would be loosely equivalent:

Java:

Person.java:

```<code>public class Person {
    private String name;
    private int age;

    public Person(String name, int age) { /* code */ }

    int getAge () {
        return age;
    }

    String getName () {
        return name;
    }

    void setAge (int age) {
        this.age = age;
    }

    void setName (String name) {
        this.name = name;
    }
}
</code>```

C:

person.h:

```<code>/*
    This line serves two purposes:

      a. Declare the struct without revealing its attributes; this is
         called an "opaque struct."

      b. Let us use just `Person` instead of `struct Person` to refer to
         the struct.
*/
typedef struct Person Person;

/* Constructor */
Person* person_new (const char *name, int age);

/* Destructor -- just a wrapper around free() for simple cases */
void person_free (Person *obj);

/* Other methods */
int person_get_age (const Person *obj);
const char* person_get_name (const Person *obj);

void person_set_age (Person *obj, int age);
void person_set_name (Person *obj, const char *name);
</code>```

person.c:

```<code>#include <stdlib.h>
#include "person.h"

/* Now we define the struct. */
struct Person
{
    int age;
    char *name;
};

Person* person_new (const char *name, int age)
{
    Person *obj = (Person*) malloc (sizeof(Person));

    obj->name = name;
    obj->age = age;

    return obj;
}

void person_free (Person *obj)
{
    free (obj);
}

int person_get_age (const Person *obj)
{
    return obj->age;
}

const char* person_get_name (const Person *obj)
{
    return obj->name;
}

void person_set_age (Person *obj, int age)
{
    obj->age = age;
}

void person_set_name (Person *obj, const char *name)
{
    obj->name = name;
}
</code>```

Then to use this you'd do something like the following:

```<code>Person *me = person_new ("James Jensen", 27);
printf ("Hi, I'm %s and I'm %i years old.\n",
        person_get_name (me),
        person_get_age (me));
person_free (me);
</code>```

You can also do inheritance, but it's quite a bit trickier and I'm not really confident in my abilities to do it. Neverthless, the basic approach is something like the following (corrections welcome):

importantperson.c:

```<code>#include <stdlib.h>
#include "person.h"

/* Please just imagine I wrote this. */
#include "importantperson.h"

struct ImportantPerson
{
    Person super; /* Note that this is NOT a pointer. */
    int importance;
};

ImportantPerson* importantperson_new (const char *name, int age,
                                      int importance)
{
    ImportantPerson *obj = (ImportantPerson*) malloc (sizeof(ImportantPerson));

    person_set_name(&(obj->super), name);
    person_set_age(&(obj->super), age);
    obj->importance = importance;

    return obj;
}

void importantperson_free (ImportantPerson *obj)
{
    free (obj);
}

int importantperson_get_age (ImportantPerson *obj)
{
    return person_get_age (&(obj->super));
}

/* ...other getters... */

void importantperson_set_age (ImportantPerson *obj, int age)
{
    person_set_age (&(obj->super), age);
}

/* ...other setters... */
</code>```

If I'm not mistaken, due to the way C organizes data, having a non-pointer Person object as the first attribute of ImportantPerson also allows you to do this:

```<code>ImportantPerson *me = importantperson_new ("James Jensen", 27, 9001);

/* Now I humble myself a bit... */
Person *p = (Person*) me;

printf ("Hi, my name is %s and I'm %i years old.\n",
        person_get_name (p),
        person_get_age (p));

/*
    Now, destructors can be a bit of a problem. If they weren't both just
    wrapping free(), this would do the wrong thing:

        person_free (p);
*/
importantperson_free (me);
</code>```

I hope that clears things up. As always, I welcome corrections from more experienced programmers.

Title: Writing OOPS code in Non Object Oriented Language

Body:
I was reading some article on the internet as I was preparing for interview and I found out below statement-

Writing object oriented code, even in non-object oriented language?

Is this statement true??

Can anybody provide an example to justify the above statement if somebody asked me this question in the interview.

And when do we write object oriented code in non object oriented language?

I mainly worked in Java. So any example corresponding to that will be helpful.

Thanks in advance.

Body:
Yes. Early C++ compilers translated the code to C before compiling with a normal C compiler. Today, that's how Vala works. Vala is based on the GLib Object System, which provides object-oriented features for C, but is apparently quite cumbersome. Vala streamlines the process.

As for an example, the following would be loosely equivalent:

Java:

Person.java:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) { /* code */ }

    int getAge () {
        return age;
    }

    String getName () {
        return name;
    }

    void setAge (int age) {
        this.age = age;
    }

    void setName (String name) {
        this.name = name;
    }
}

C:

person.h:

/*
    This line serves two purposes:

      a. Declare the struct without revealing its attributes; this is
         called an "opaque struct."

      b. Let us use just `Person` instead of `struct Person` to refer to
         the struct.
*/
typedef struct Person Person;

/* Constructor */
Person* person_new (const char *name, int age);

/* Destructor -- just a wrapper around free() for simple cases */
void person_free (Person *obj);

/* Other methods */
int person_get_age (const Person *obj);
const char* person_get_name (const Person *obj);

void person_set_age (Person *obj, int age);
void person_set_name (Person *obj, const char *name);

person.c:

#include <stdlib.h>
#include "person.h"

/* Now we define the struct. */
struct Person
{
    int age;
    char *name;
};

Person* person_new (const char *name, int age)
{
    Person *obj = (Person*) malloc (sizeof(Person));

    obj->name = name;
    obj->age = age;

    return obj;
}

void person_free (Person *obj)
{
    free (obj);
}

int person_get_age (const Person *obj)
{
    return obj->age;
}

const char* person_get_name (const Person *obj)
{
    return obj->name;
}

void person_set_age (Person *obj, int age)
{
    obj->age = age;
}

void person_set_name (Person *obj, const char *name)
{
    obj->name = name;
}

Then to use this you'd do something like the following:

Person *me = person_new ("James Jensen", 27);
printf ("Hi, I'm %s and I'm %i years old.\n",
        person_get_name (me),
        person_get_age (me));
person_free (me);

You can also do inheritance, but it's quite a bit trickier and I'm not really confident in my abilities to do it. Neverthless, the basic approach is something like the following (corrections welcome):

importantperson.c:

#include <stdlib.h>
#include "person.h"

/* Please just imagine I wrote this. */
#include "importantperson.h"

struct ImportantPerson
{
    Person super; /* Note that this is NOT a pointer. */
    int importance;
};

ImportantPerson* importantperson_new (const char *name, int age,
                                      int importance)
{
    ImportantPerson *obj = (ImportantPerson*) malloc (sizeof(ImportantPerson));

    person_set_name(&(obj->super), name);
    person_set_age(&(obj->super), age);
    obj->importance = importance;

    return obj;
}

void importantperson_free (ImportantPerson *obj)
{
    free (obj);
}

int importantperson_get_age (ImportantPerson *obj)
{
    return person_get_age (&(obj->super));
}

/* ...other getters... */

void importantperson_set_age (ImportantPerson *obj, int age)
{
    person_set_age (&(obj->super), age);
}

/* ...other setters... */

If I'm not mistaken, due to the way C organizes data, having a non-pointer Person object as the first attribute of ImportantPerson also allows you to do this:

ImportantPerson *me = importantperson_new ("James Jensen", 27, 9001);

/* Now I humble myself a bit... */
Person *p = (Person*) me;

printf ("Hi, my name is %s and I'm %i years old.\n",
        person_get_name (p),
        person_get_age (p));

/*
    Now, destructors can be a bit of a problem. If they weren't both just
    wrapping free(), this would do the wrong thing:

        person_free (p);
*/
importantperson_free (me);

I hope that clears things up. As always, I welcome corrections from more experienced programmers.


问:
Map of functions vs switch statement
I'm working on a project that processes requests, and there are two components to the request: the command and the parameters. The handler for each command is very simple (< 10 lines, often < 5). There are at least 20 commands, and likely will have more than 50.

I've come up with a couple of solutions:

one big switch/if-else on commands

map of commands to functions

map of commands to static classes/singletons

Each command does a little error checking, and the only bit that can be abstracted out is checking for the number of parameters, which is defined for each command.

What would be the best solution to this problem, and why? I'm also open to any design patterns I may have missed.

I've come up with the following pro/con list for each:

switch

pros

keeps all commands in one function; since they're simple, this makes it a visual lookup table

don't need to clutter up source with tons of small functions/classes that will only get used in one place

cons

very long

hard to add commands programmatically (need to chain using default case)

map commands -> function

pros

small, bite-size chunks

can add/remove commands programmatically

cons

if done in-line, same visually as switch

if not done in-line, lots of functions only used in one place

map commands -> static class/singleton

pros

can use polymorphism to handle simple error checking (only like 3 lines, but still)

similar benefits to map -> function solution

cons

lots of very small classes will clutter project

implementation not all in the same place, so it's not as easy to scan implementations

Extra notes:

I'm writing this in Go, but I don't think the solution is language-specific. I'm looking for a more general solution because I may need to do something very similar in other languages.

A command is a string, but I can easily map this to a number if convenient. The function signature is something like:

```<code>Reply Command(List<String> params)
</code>```

Go has top-level functions, and other platforms I'm considering also have top-level functions, hence the difference between the second and third options.

答:
Whenever I find myself asking whether I should use a switch statement or OO-style polymorphism I refer to the Expression Problem. Basically, if you have different "cases" for your data and wand to support different "actions" (where each action does something different for each case) then its really hard to make a system that naturally lets you add both new cases and new actions in the future.

If you use switch statements (or the Visitor pattern) then its easy to add new actions (because you wite everything in a single function) but hard to add new cases (because you need to go back and edit the old functions)

Conversely, if you use OO-style polymorphism its easy to add new cases (just make a new class) but hard to add methods to an interface (because then you need to go back and edit a bunch of classes)

In your case you only have one method that you need to support (proccess a request) but lots of possible cases (each different command). Since making it easy to add new cases is more important than adding new methods, just make a separate class for each different command.

By the way, from the point of view of how extensible things are, it doesn't make a big difference whether you use classes or functions. If we are comparing against a switch statement what matters is how things get "dispatched" and both classes and functions get dispatched the same way. Therefore, just use whatever is more convenient in your language (and since Go has lexical scoping and closures, the distinction between classes and functions is actually very small).

For example, you can usually use delegation to do the error checking part instead of relying on inheritance (my example is in Javascript because O don't know Go syntax, I hope you don't mind)

```<code>function make_command(real_command){
    return function(x){
        if(check_arguments(x)){
            return real_command(x);
        }else{
            //handle error here
        }
    }
 }

 command1 = make_command(function(x){
     //do something
 })

 command2 = make_command(function(x){
     //do something else
 })

 command1(17);
 commnad2(42);
</code>```

Of course, this example assumes that there is a sensible way to have the wrapper function or parent class check arguments for every case. Depending on how things go it might be simpler to put the call to check_arguments inside the commands themselves (since each command might need to call the checking function with different arguments, due to a different number of arguments, different command types, etc)

tl;dr: There is no best way to solve all problems. From a "making things work" perspective, focus on creating your abstractions in ways that enforce important invariants and protect you from mistakes. From a "future-proofing" perspective, keep in mind what parts of the code are more likely to be extended.

Title: Map of functions vs switch statement

Body:
Whenever I find myself asking whether I should use a switch statement or OO-style polymorphism I refer to the Expression Problem. Basically, if you have different "cases" for your data and wand to support different "actions" (where each action does something different for each case) then its really hard to make a system that naturally lets you add both new cases and new actions in the future.

If you use switch statements (or the Visitor pattern) then its easy to add new actions (because you wite everything in a single function) but hard to add new cases (because you need to go back and edit the old functions)

Conversely, if you use OO-style polymorphism its easy to add new cases (just make a new class) but hard to add methods to an interface (because then you need to go back and edit a bunch of classes)

In your case you only have one method that you need to support (proccess a request) but lots of possible cases (each different command). Since making it easy to add new cases is more important than adding new methods, just make a separate class for each different command.

By the way, from the point of view of how extensible things are, it doesn't make a big difference whether you use classes or functions. If we are comparing against a switch statement what matters is how things get "dispatched" and both classes and functions get dispatched the same way. Therefore, just use whatever is more convenient in your language (and since Go has lexical scoping and closures, the distinction between classes and functions is actually very small).

For example, you can usually use delegation to do the error checking part instead of relying on inheritance (my example is in Javascript because O don't know Go syntax, I hope you don't mind)

function make_command(real_command){
    return function(x){
        if(check_arguments(x)){
            return real_command(x);
        }else{
            //handle error here
        }
    }
 }

 command1 = make_command(function(x){
     //do something
 })

 command2 = make_command(function(x){
     //do something else
 })

 command1(17);
 commnad2(42);

Of course, this example assumes that there is a sensible way to have the wrapper function or parent class check arguments for every case. Depending on how things go it might be simpler to put the call to check_arguments inside the commands themselves (since each command might need to call the checking function with different arguments, due to a different number of arguments, different command types, etc)

tl;dr: There is no best way to solve all problems. From a "making things work" perspective, focus on creating your abstractions in ways that enforce important invariants and protect you from mistakes. From a "future-proofing" perspective, keep in mind what parts of the code are more likely to be extended.


问:
How important is it to reduce the number of lines in code?
I am a Software developer who works on J2SE (core java).

Often during our code reviews we are asked to reduce the number of lines in our code.

It's not about removing redundant code, it's about following a style that focuses on doing the same things with fewer lines in the code, while I believe in having clarity in code even if it means increasing the number of lines.

What do you think is the right way of doing things?

If LOC (lines of code) is a small number, how does it affect the code?
If LOC is a larger number, how does it affect the code?

example from the website : "javaranch"  -

```<code>public static void happyBirthday(int age)
{
    if ((age == 16) || (age == 21) || ((age > 21) && (((age % 10) == 0) || ((age % 25) == 0))))
    {
        System.out.println("Super special party, this year!");
    }
    else
    {
        System.out.println("One year older. Again.");
    }
}
</code>```

VS

```<code>public static void happyBirthday(int age)
{

    boolean sweet_sixteen = (age == 16);
    boolean majority = (age == 21);
    boolean adult = (age > 21);
    boolean decade = (age % 10) == 0;
    boolean quarter = (age % 25) == 0;

    if (sweet_sixteen || majority || (adult && (decade || quarter)))
    {
        System.out.println("Super special party, this year!");
    }
    else
    {
        System.out.println("One year older. Again.");
    }
}
</code>```

答:
LOC is a way more useful metric at the beginning of a project than during actual implementation, I think. Knowing the LOC per function point allows you to estimate project effort, and from that how long the project will take and the optimal number of developers.

It can also influence design and language choice: reducing function points or switching to a language with a lower LOC/FP should reduce project effort, all else being equal.


问:
Possible Damerau-Levenshtein improvement?
I recently implemented the Damerau-Levenshtein distance algorithm from the pseudocode on Wikipedia. I couldn't find any explanation of exactly how it works and the pseudocode uses completely uninformative variable names like DA, DB, i1, and j1 that left me scratching my head.

Here's my implementation in Python: https://gist.github.com/badocelot/5327337

The Python implementation helped me walk through the program and figure out what was happening, renaming the variables to more helpful names. I was familiar enough with the Wagner-Fischer approach to calculating the Levenshtein distance that I had a frame of reference.

At the risk of being overly lengthy, here's how I understand Damerau-Levenshtein:

The mystery variables:

DA (last_row in my code) is a kind of map holding the last row each element was seen on; in my code it's an actual Python dictionary

DB (last_match_col) holds the last column where the letter in b matched the letter in a for the current row

i1 (last_matching_row) is the row number from DA for the current letter in b

j1 is just a copy of the value of DB/last_match_col before it's potentially updated; in my code I just moved where last_match_col is updated and eliminated this variable

The transposition cost:

```<code>H[i1][j1] + (i-i1-1) + 1 + (j-j1-1)
</code>```

is calculating the cost of swapping the current character in b with the last character in b known to be in a (the last match), treating all characters in between as either additions or deletions.

Components of the cost:

H[i1][j1] reverts the base cost to the point in the calculations before the transposition, since finding a transposition invalidates previous work

(i-i1-1) is the distance between the current row  and last row matching the current character, which is the number of deletions that would be required

(j-j1-1) is the distance between the current column and the last column with a match, which is the number of additions

The extra + 1 is just the cost of the transposition itself

If this analysis is incorrect, I'd love to know where I went wrong. As I said, I couldn't find any detailed explanation of how the algorithm works online.

Improved version?

Having figured that out, though, it struck me that by calculating the cost of both additions and deletions between transposed letters seemed flawed: one addition and one deletion is equivalent to a substitution, which this isn't checking for.

If all that's correct, the solution should be trivial: the cost of the letters between transposed letters should be the higher of the additions and deletions: convert as many into substitutions as possible and add in any additions or deletions left over.

So the cost would be:

```<code>H[i1][j1] + max((i-i1-1), (j-j1-1)) + 1
</code>```

Here's my code for this version: https://gist.github.com/badocelot/5327427

From some simple tests, this seems correct. For example, "abcdef" -> "abcfad" gives an edit distance of 2 (transpose "d" and "f", change "e" to "a"), while the original algorithm gives a distance of 3 (either last three letters are substitutions, or 1 transposition + 1 addition + 1 deletion).

Now, I cannot be the first person to have thought of this. So, why didn't I run across it? Did I just not search long enough? Or is there some subtle flaw that prevents this from actually working?

答: I had to look up the Damerau-Levenshtein distance on wikipedia, so forgive me if this is wrong. But it looks like it only allows for transposing adjacent letters and not any arbitrary ones. So your example "abcdef" -> "abcfad" with transpose of d and f doesn't work. It seems to me you have modified the definition of the algorithm and are no longer calculating the Damerau-Levenshtein distance.</p>


问:
HTTP Session or Database approach
I am confused a little as what should be my approach, Working on a design of shopping cart and i need to store shopping cart either in session or in database but not sure which approach would be best.here are the use case

User is not logged in and adding product to cart (Anonymous user)

User is logged in and adding product to cart.

First case is more confusing to me, since there can be many cases where user just visiting web-shop and adding product without logging in and can be quite possible that he might not going for a checkout process.

But still we need to create a Shopping-Cart for this user, in order to create and save shopping-cart i have two option.

When user adding a product, create a cart in the database and associate this cart with this user, moment he logged in move this cart to logged in user.

Create Cart, add product to it and save it to the Session, when user logged in create Cart in the database and associated logged in user with this cart with User.

I know that both database driven Cart system as well Session based can have there positive as well negative aspects, but not sure which one might be the best approach taking in to account following points

Scalability

Flexibility

Extensibility

Application Should take care of speed

Looking for input on this aspect to decide the path.

答:
I would go for a solution where an unique ID is assigned to all visitors when they first hit the site. It doesn't matter if they're anonymous or authenticated. When anonymous users register, retain the unique ID.

Store the shopping cart in the database. Storage is cheap, and it shouldn't be a problem performance-wise to do a query for the cart every now and then.

OwnerDisplayName: Umesh Awasthi

Title: HTTP Session or Database approach


答:
There's a lot of answers here that address the technical pros and cons of keeping LOC down and whether or not it's a meaningful quality software metric.  That's not what this question is about.  What it's about is how to deal with management that insists on a naive dogmatic adherence to a particular coding rule of thumb.

Sadly, it's fairly common for people to latch onto things that are good advice when used in the proper context and applied pragmatically, take them out of that context and apply them dogmatically while failing to appreciate the issues the advice exists to mitigate in the first place.

The intent of advice regarding keeping LOC down is to avoid the creation of methods that try to do too much in one go, and to discourage the creation of "god classes", which know too much about aspects of a design that aren't their direct responsibility and which all other classes in the system are dependant on.   Another advantage of shorter code is that it's more readable, though as you've pointed out, you can overdo it to the point where readability actually starts to suffer.

There are obvious advantages to low LOC counts (small methods fit into your head more easily than big ones, fewer things in the code means fewer things to go wrong, etc), but it is also subject to the law of diminishing returns.  Refactoring a 150 line method into a number of 20 line methods is a much bigger win than refactoring a 10 line method into a 7 line method.

When such refactoring comes at the expense of some other facet of good software design (such as readability) then you have reached a point where you can justify not doing it. Removing variables that give context to what the code means and replacing them with literals that don't is a very very bad thing to do.  Good code has almost no literals in it.  However, these variables (and named constants) are lines of code that don't directly contribute to the program and so if LOC is being worshipped as some kind of god then such clarification lines are in great peril of being pruned for a quick win and some misguided praise from management.

I believe you're smart enough to realise this, in fact that's pretty much the thrust of your original question.  The problem isn't your understanding of when code reduction is good and when it's not, the problem is dogmatism in applying what is normally a reasonable practice indiscriminately.

I would recommend taking the time to chat with your management, explaining your position and why you feel that what you're being asked to do harms the code rather than helps it.  Try to avoid being confrontational, but do try to remain rational and calm during such a discussion.  It's important that your management understands that programming is a pragmatic activity, and best practice advice is only useful if it's applied in a pragmatic way.  Best practice is written in a book, not carved in stone, and when it conflicts (short code versus readable code) then it's up to the programmer to apply their judgement as to which best practice to follow.  Hopefully they are reasonable people who appreciate input such as this.

You also need to be a bit brave, because if you're being pressured to reduce LOC where you think it's unnecessary or inappropriate then it's only natural that you'd make the change anyway for the sake of a quiet life.  You need to resist doing this, and you have to "own" that decision.  In a situation where management are reasonable you shouldn't have to adhere to their guidelines exactly, but you should be able to justify any circumstances where you don't.

Sadly, people can be irrational, especially when it comes to people lower on the pecking order questioning their decisions and the rules they've imposed on you.  They may choose not to be reasonable.  You need to be prepared for that too.  If you can demonstrate cases where the LOC best practice comes into direct conflict with other best practice and why that's hurting the product, and if you can do it in portions of the code base for which they had little or no personal involvement (so it doesn't seem like a personal attack on their work or work they supervised) then this may help bolster your argument.  Again, you have to be prepared to justify yourself in a calm, rational way and be able to "own" the arguments you're making.

Provided your management are reasonable people then they must appreciate that what you're saying has merit if you can provide evidence to back your claims up.

Title: How important is it to reduce the number of lines in code?

Body:
I am a Software developer who works on J2SE (core java).

Often during our code reviews we are asked to reduce the number of lines in our code.

It's not about removing redundant code, it's about following a style that focuses on doing the same things with fewer lines in the code, while I believe in having clarity in code even if it means increasing the number of lines.

What do you think is the right way of doing things?

If LOC (lines of code) is a small number, how does it affect the code?
If LOC is a larger number, how does it affect the code?

example from the website : "javaranch"  -

```<code>public static void happyBirthday(int age)
{
    if ((age == 16) || (age == 21) || ((age > 21) && (((age % 10) == 0) || ((age % 25) == 0))))
    {
        System.out.println("Super special party, this year!");
    }
    else
    {
        System.out.println("One year older. Again.");
    }
}
</code>```

VS

```<code>public static void happyBirthday(int age)
{

    boolean sweet_sixteen = (age == 16);
    boolean majority = (age == 21);
    boolean adult = (age > 21);
    boolean decade = (age % 10) == 0;
    boolean quarter = (age % 25) == 0;

    if (sweet_sixteen || majority || (adult && (decade || quarter)))
    {
        System.out.println("Super special party, this year!");
    }
    else
    {
        System.out.println("One year older. Again.");
    }
}
</code>```


问:
How does API design differ from general web application development design?
If I was working on a web application designing and writing an API how does that differ from a general web application development?

What things would I need to consider and take into account? Are there any standard processes to follow when creating an API that could be used by thousands of clients?

答: You could, for instance, have a web application that is entirely client side, and therefor does not require an API.  One particular gotcha, is that browsers will limit you to only initiate HTTP GETs or POSTs, where as a RESTful API, for instance, may additionally require HTTP PUTs and DELETEs.  As an example, the Ruby on Rails framework has a piece of Rack middleware that translates HTTP POSTs with a _method=[PUT|DELETE] parameter to the corresponding PUT|DELETE API call.</p>


问:
Understanding Package Management Systems
I am attempting to understand what a Package Management System. I grasp the main concept of it but I have some queries.

Does a package management system install features(compilers, libraries, virtual machines) necessary to run an application AND install an application or does it just install features necessary to run an application?

Are package management systems external applications that you run with command line arguments or are they API libraries that you integrate into your installer code?

To use an example; if my application uses python 2.7 and wxPython would a Package Management System ensure that python 2.7 is installed and wxPython is installed then finally install my application(python script files)?

答:
Package management systems and installers (the latter found on windows systems) can and should ensure that the whole working environment, especially libraries and the program itself are installed on a system. This normally includes all direct dependencies, but not things like compilers or linkers that are only required during development. There are source packages meant to be build on the target system in this case it may sometimes check if certain things are available, but normally would not install them. You normally will get error messages or warning during the build process.

So if possible the package will directly install everything necessary to run a program (If you run a package manager on Linux you quite often get info like "15 additional packages need to be installed. Continue?" These additional packages are libraries and other dependencies). When creating your packages you can define any kind of dependency you like, you are not limited to libraries but could have packages for graphics or documentation or any other resource you may choose to keep independent from the program itself.

There are command line tools like apt-get (the tool used for package management on Debian based systems), but there are also GUI programs to run those tasks (but those often only provide a GUI and actually call the cl tools). But those cl tools itself are using functions from some library which in theory you could include in any program you like.

So package managers behave somewhat similar to installers. The main difference is that a pm is part of the operating system and keep information about installed packages in a central place. You will find installers more likely on windows and they behave slightly more independent and are programs of their own (using system functionality too, like the registry). Installers are rather uncommon on Linux systems but nothing would prevent you from writing one if your software would need it and base it on the libraries used on your target system to ensure integrity with the package management.


问:
Is argument or parameter considered more appropriate for a function/method argument/parameter?
Hopefully the topic is not too confusing, I am curious though as lately I have seen more and more use of the word parameter to denote a function's passed in values, whereas during my studies I feel as if argument was used almost exclusively.

Is parameter more appropriate as argument is more specific to a programs arguments specific at runtime whereas when a function is called, the values passed to it are parameters to the function itself?

From a curious programmer.

答: In college, I was taught that the correct term is "argument".  I think either are appropriate and both definitions are obvious to most developers, but, from a technical standpoint, I generally stick with "argument".</p>

ContentLicense: CC BY-SA 2.5


问:
how to stay efficient when a build is almost always broken
I work in a middle sized team which shares the same source code and while have a continues integration in place, but as all of us has to work in the same branch, the build is almost always broken.

As we also have a rule, which has been introduced recently to alleviate the broken builds, which states that no one is allowed to check-in while to build is red.

Having said that, during a day everyone have a handful of 10-15 minutes windows where we allowed to check-in.

And as the team is growing, the windows of check-in opportunities shrinking even more. That forces developers to accumulate their changes locally, which results in a bigger change sets which even more difficult to ensure that the changes are not breaking anything. You can see the vicious cycle.

What can you recommend to allow me to stay effective working in environment like this.
Also, please keep in mind that I am a developer, not a manager, and can't change the process or other people behavior much.

答: A simple change to the CI system would do it: any change that breaks the build gets rolled back automatically. Even better, let the CI repository become a staging area, where changes only get pushed through to the authoritative repository when the build is green. Tools like Gerrit can help here.</p>


问:
User stories are too high level and conceptual, management expects developers to fill in the blanks
I am employed in a very brilliant company with a true intention of doing XP. Communication is good and management is open to constructive discussion but due to pressing time constraints, some certain things are considered too RUP to be discussed.

At the moment I'm a little troubled with the volume of change that becomes necessary while implementing the stories. I believe many of these discoveries (which take time and effort of course) are the responsibilities of the story writers (customers, end users and product owners) and not the developers. To put is short, user-stories are too conceptual and just convey the underlying intention but lack enough details (specially pre-conditions and post-conditions, relevance to other stories, dependencies and alike). The developer is expected to fill in the blanks at his own discretion by the virtue of XP developers being designers and analysts at the same time. The problem is many of these blanks are discovered after some wrong assumptions have made made their way into evaluation time and code since noticing added complexities emerge than initially anticipated. Even then finding the right thing to fill in takes time which is - to various degrees - considered as deviation from the initial estimations.

I'm looking for a constructive way of conveying these implications to the management in a way that would not pose me as someone who is trying to unnecessarily complicate things. I'm new and as yet I have not established much credibility.

You insights are most welcome.

Closely related and somehow gives an answer : How much detail about a user story can a developer expect?

答:
Even then finding the right thing to fill in takes time which is - to various degrees - considered as deviation from the initial estimations.

That does not sound very "XP"ish to me.

I am in no way an XP expert, but AFAIK the XP idea is to adapt your specs and your  estimation continuously whenever you got feedback from the process. And the process is "analyse a little - design a little - code a little - test a little - and then get user feedback to correct your wrong assumptions as early as possible. You can also try to get user feedback even more early, for example, after designing some parts of your software (like the UI), on a sheet of paper or a whiteboard and discuss that with a user or customer. I don't think the "XP way" forbids such an approach just because of having "user stories".

Here is a nice article about how to get feedback more early by using specs. I think this kind of thinking is "methodology"-independent, and the arguments presented there will help you with your debate with management.


答:
If you are asked to estimate a story that seems incomplete to you, make it known that you have questions about the story and that you can't give a proper estimation before those questions are answered.

Then, ask your questions and make sure the answers become part of the story.

If you are forced to give an estimation even when your questions are not (all) answered, you can choose to either refuse to give an estimation or to clearly indicate that you are assuming the worst possible outcomes for the remaining blanks in your estimation (which probably will make your estimation a high outlier).

Title: User stories are too high level and conceptual, management expects developers to fill in the blanks

Body:
I am employed in a very brilliant company with a true intention of doing XP. Communication is good and management is open to constructive discussion but due to pressing time constraints, some certain things are considered too RUP to be discussed.

At the moment I'm a little troubled with the volume of change that becomes necessary while implementing the stories. I believe many of these discoveries (which take time and effort of course) are the responsibilities of the story writers (customers, end users and product owners) and not the developers. To put is short, user-stories are too conceptual and just convey the underlying intention but lack enough details (specially pre-conditions and post-conditions, relevance to other stories, dependencies and alike). The developer is expected to fill in the blanks at his own discretion by the virtue of XP developers being designers and analysts at the same time. The problem is many of these blanks are discovered after some wrong assumptions have made made their way into evaluation time and code since noticing added complexities emerge than initially anticipated. Even then finding the right thing to fill in takes time which is - to various degrees - considered as deviation from the initial estimations.

I'm looking for a constructive way of conveying these implications to the management in a way that would not pose me as someone who is trying to unnecessarily complicate things. I'm new and as yet I have not established much credibility.

You insights are most welcome.

Closely related and somehow gives an answer : How much detail about a user story can a developer expect?


答:
What you do is not an agile way of development. Instead, you are working with low quality requirements. It is false that an agile way of development is not to specify requirements.

Instead, they need to initially specify as much as possible, and if needed change later. Then you split your work into parts and implement in iterations. After each iteration, you have something finished.

Difference to waterfall development, is in waterfall development, everything is implemented with initial requirements, and changed at the end.


答:
I'm sensitive to the notion that you feel powerless to change the environment, but I think this situation is a serious challenge to your professionalism as a programmer.

What would happen if a surgeon stored dirty scalpels with the clean ones?  What would happen if a plumber didn't test the pipes he installed?  What would happen if a violinist always played out of tune with the orchestra?

Why should programmers be exempt from teamwork and common courtesy?  As a member of that team, you share responsibility for the result.  It's irresponsible to ignore the team as it sabotages it's own efforts.

I'm curious where the rule that "no one is allowed to check-in while to build is red" comes from?  It's a good rule if that then focuses everyone on fixing the build.  I would try to lead by example and help fix the build whenever it's broken.  Let's face it, you're not getting anything else done anyway.  If this annoys you, then I would suggest voicing those concerns.  The voice of someone actively trying to improve a situation has more influence than the guy who grumbles in the corner.

Title: how to stay efficient when a build is almost always broken

Body:
I work in a middle sized team which shares the same source code and while have a continues integration in place, but as all of us has to work in the same branch, the build is almost always broken.

As we also have a rule, which has been introduced recently to alleviate the broken builds, which states that no one is allowed to check-in while to build is red.

Having said that, during a day everyone have a handful of 10-15 minutes windows where we allowed to check-in.

And as the team is growing, the windows of check-in opportunities shrinking even more. That forces developers to accumulate their changes locally, which results in a bigger change sets which even more difficult to ensure that the changes are not breaking anything. You can see the vicious cycle.

What can you recommend to allow me to stay effective working in environment like this.
Also, please keep in mind that I am a developer, not a manager, and can't change the process or other people behavior much.


问:
Why does JavaScript count array lengths by the last index?
JavaScript seems to calculate the array length property by the number of the last index in the array rather than counting the number of items in the array. Example:

```<code>var testArray = ['a', 'b', 'c'];
console.log(testArray.length); //3
testArray[8] = 'i';
console.log(testArray.length); //9
</code>```

Normally I would use push() and wouldn't add a value to an array using bracket notation, but this was a bit of a surprise. Is there any reason for this implementation of assigning a value to Array.length? The only thing I can seem to come up with is that it just uses the last index as a performance optimization to avoid counting the array items.

答:
I rather think it is the other way around: last index is based on the length. I think JS may just be setting the length for you behind the scenes when you assign a value to an (as yet) non-existing index. Which means that you could read your:

```<code>testArray[8] = 'h';
</code>```

as

```<code>SetLength(testArray, 9); // or something similar (I'm not too familiar with JS)
testArray[8] = 'h';
</code>```

There are a few language out there that allow for arrays with other starting indices, but most arrays that allow for dynamic allocation/sizing will have zero-based indices. And that means that there is always a fixed relation between the length of the array and the last index number:

```<code>Last index number = Length - 1
</code>```

Update

JS doesn't do a last index + 1 to get the count. When you do testArray[8] = 'h'; JS doesn't just set the length to 8 + 1. It first checks how many elements are already in the array. When the array does not yet have enough elements to store something at index 8, it will resize. It resizes the array to just large enough to hold something at index 8, which, because arrays are zero-based, means resizing to 8 + 1.

Length <> number of stored elements

That doesn't mean the array then holds 9 elements. It just means that the array has enough room to do so. If you create an array by just testArray[8] = 'h';, you are essentially telling JS to allocate enough room for 9 elements and store 'h' at the element with index 8.

Body:
I rather think it is the other way around: last index is based on the length. I think JS may just be setting the length for you behind the scenes when you assign a value to an (as yet) non-existing index. Which means that you could read your:

testArray[8] = 'h';

as

SetLength(testArray, 9); // or something similar (I'm not too familiar with JS)
testArray[8] = 'h';

There are a few language out there that allow for arrays with other starting indices, but most arrays that allow for dynamic allocation/sizing will have zero-based indices. And that means that there is always a fixed relation between the length of the array and the last index number:

Last index number = Length - 1

Update

JS doesn't do a last index + 1 to get the count. When you do testArray[8] = 'h'; JS doesn't just set the length to 8 + 1. It first checks how many elements are already in the array. When the array does not yet have enough elements to store something at index 8, it will resize. It resizes the array to just large enough to hold something at index 8, which, because arrays are zero-based, means resizing to 8 + 1.

Length <> number of stored elements

That doesn't mean the array then holds 9 elements. It just means that the array has enough room to do so. If you create an array by just testArray[8] = 'h';, you are essentially telling JS to allocate enough room for 9 elements and store 'h' at the element with index 8.


答:
The length of an array is the number of elements it contains whereby it does not matter if those elements are valid objects or values or just "undefined". If you add an element at position 8 you automatically generate 5 additional elements between your first three elements and the new one as you can see if you run

```<code>for(var i = 0; i < testArray.length; i++){console.log(testArray[i]);}
</code>```

(Those may or may not take real space in memory, depending on the actual implementation)

Being "equaly spaced" is somewhat the definition of an array (compared to other container types like lists or dictionaries).

Title: Why does JavaScript count array lengths by the last index?

Body:
JavaScript seems to calculate the array length property by the number of the last index in the array rather than counting the number of items in the array. Example:

```<code>var testArray = ['a', 'b', 'c'];
console.log(testArray.length); //3
testArray[8] = 'i';
console.log(testArray.length); //9
</code>```

Normally I would use push() and wouldn't add a value to an array using bracket notation, but this was a bit of a surprise. Is there any reason for this implementation of assigning a value to Array.length? The only thing I can seem to come up with is that it just uses the last index as a performance optimization to avoid counting the array items.

Body:
The length of an array is the number of elements it contains whereby it does not matter if those elements are valid objects or values or just "undefined". If you add an element at position 8 you automatically generate 5 additional elements between your first three elements and the new one as you can see if you run

for(var i = 0; i < testArray.length; i++){console.log(testArray[i]);}

(Those may or may not take real space in memory, depending on the actual implementation)

Being "equaly spaced" is somewhat the definition of an array (compared to other container types like lists or dictionaries).


答:
Two other things could help here:

can your team smoke test a CI build locally? If you check that you don't break the build -- or at least don't break the build in common ways without having to commit and trigger management and team ire.

there are many ways to define broken builds depending on how you architect CI. This includes defining broken -- under heavy development we don't consider failing tests a break but rather another goal to work towards.

But you should really look at branches.


问:
MVC4 Service > Controller Models
I'm working on a MVC4 N-tier application and have a quick question about Service to Controller relation and using Domain/ViewModel.

```<code>   public ActionResult Details(int id = 0)
    {
        TenantDomainModel tenant = _tenantService.GetById(id);
        TenantViewModel tenantViewModel = Mapper.Map<TenantViewModel>(tenant);
        return View(tenantViewModel);
    }
</code>```

As you can see my service return a DomainModel that my controller use to create a ViewModel using Automapper.

Is there a better way to do that ? Ideally I would like to have no domain model referenced in my Presentation/Web layer but i'm not what are the exact best practice on this specific point.

Thanks

答:
The answer is... it depends on what you're intending. If you're looking to achieve scalable code then the best practice is generally to create a Domain Transfer Object (DTO) that is a view into the current state. This is done in the services themselves usually and are regenerated every time the domain object changes (Eventual consistency is key, as trying to keep consistency at all times won't happen). The DTO is optimized for the query that it serves as well as the data it is intended to display, it may be a composite of more than one domain object. But most importantly it is independent of the domain object and is unaware of the domain object. That might sound contradictory, but it's not. I would highly suggest reading up on Command Query Response Segregation (CQRS) as it is probably the best approach to what you're doing.

CQRS allows you to make your web site (or any client) agnostic to your domain. This is important as your domain model needs to manage its own business rules internally and should not rely on an external consumer to ensure consistency and correctness. As far as the website is concerned the domain to it is the DTOs that are designed specifically for its queries. When you need your website to be able to change your domain you expose commands that it sends to the  services with the domain entity id and the relevant data just for that command. The services then execute the command or return a result saying that they were unable to.

Now the fully qualified answer here must come with the caveat of: if this is an internal only low usage application you need to decide whether having a scalable domain/query model matters more than speed of completion. Do you need the system fast, or do you need the system to be fast and scalable.

Title: MVC4 Service > Controller Models


答: One good way to keep these concerns out of your service models is to create extension methods in the web project to handle the mapping tasks. Also makes them much more easily testable in isolation.</p>

Title: MVC4 Service > Controller Models

Body:
I'm working on a MVC4 N-tier application and have a quick question about Service to Controller relation and using Domain/ViewModel.

```<code>   public ActionResult Details(int id = 0)
    {
        TenantDomainModel tenant = _tenantService.GetById(id);
        TenantViewModel tenantViewModel = Mapper.Map<TenantViewModel>(tenant);
        return View(tenantViewModel);
    }
</code>```

As you can see my service return a DomainModel that my controller use to create a ViewModel using Automapper.

Is there a better way to do that ? Ideally I would like to have no domain model referenced in my Presentation/Web layer but i'm not what are the exact best practice on this specific point.

Thanks


问:
Securely storing secret data in a client-side web application
I have this web application that is going to be all client-side technology (HTML, CSS, JavaScript/AngularJS, etc...).  This web application is going to be interacting with REST API in order to access and modify data.  Right now it is undecided on what type of authentication system the REST API is going to use.

From my understanding, any type of API authentication system (API Keys, OAuth 1/2, etc...) is going to have certain data that needs to be kept secret otherwise access can be compromised.  For API Keys, they keys themselves need to be secret, for OAuth 2 the client secret/access tokens/refresh tokens need to be kept secret, I am sure a few of the 4 keys involved in OAuth 1 needs to be kept secret (not too much experience with OAuth 1).  I have been trying to think if there is a way to store this secret stuff in a pure client-side web application without a middle layer of sorts on the server side.

I have been trying to think about this and I can't think of any place to do that.  I mean I can't store it in javascript because anyone can just view the source or open up the console and get the data.  I am not 100% sure how secure localStorage is and if users can access/modify that data.  Even if local storage was secure, the two ways I can think of getting data into it are not.  One way is to just store the data in the javascript source code which is the most insecure thing I can think of.  Now if I was using something like OAuth 2 in which the rest api itself would give me the tokens, that would still not be that secure (better than the first option) because those tokens would be returned as plain text that anyone who can see the requests the computer is making could see.

Is there any way to have an application that is completely running client side be able to store secret pieces of data securely without some sort of middle layer on the server side?

答: When designing security systems, one always needs to think about the threat model.  "Make it secure" is a silly requirement, not actionable or verifiable.  "Prevent the user from extracting the access tokens from the application" is much better, and defines the boundaries of the solution.  "Prevent others from obtaining a user's access tokens" is also better, and defines a completely different solution space.  Solutions for one won't necessarily solve the other (e.g., the latter absolutely requires SSL if WiFi is involved, but that won't affect the former at all).


答:
I think that as long as you think that you are "just a developer" and therefore you cannot change things you are going to suffer from this problem.

What you need to do is that you need to revert every commit from the repository every time when someone breaks the build and then tell that guy that he just broke the build and that needs to stop. You also need to explain this situation to the manager and tell him that your team's productivity is suffering because of this problem.

You need to do whatever you can to change the process better and rather say you're sorry later instead of asking for permission.

I think that you and your team are in a situation where the process needs to be changed and you cannot work efficiently with that broken model. I also think that it's your responsibility to do something about that problem when you have recognized it. If no-one else's going to do anything about the problem, you are the one who must!


答:
The trick is not to avoid there being blanks. The trick is to fill in those blanks as early as possible in the process of development.

You are correct that, if developers make assumptions, they will invariably be wrong and that will cost time redeveloping the software later. But, equally, if business people are expected to do a full up-front design when they don't really know what they want, the same thing will happen.

It's a large part of a developer's job to figure out what the customer wants, when they often don't really know.

First, ask questions. Where the answers you get seem unsatisfactory, create a prototype. Show the customer what they're asking for, and let them tell you how it's not what they really want. Start with a paper prototype, then move onto an HTML-based one, with no code behind it. Then do the smallest amount of development you need to produce a nearly-working product and show them that. Leave the tricky bits as late in the process as you possibly can.

This might sound time-consuming in itself but, when compared to redeveloping a supposedly-finished product, it isn't.

Also, keep the stories as small as possible. Invariably, what the business wants is an epic, something that can be broken down into many deliverables. This is better because you won't have developed too much when they look at the final release candidate and scream "Oh no, that's really not what we were looking for."


问:
Most useful features of VIM that aren't standard in a IDE
I'm considering whether I should start using VIM again instead of an IDE. What are the most useful features of VIM that aren't standard in an IDE?</p>

答:
I don't think its necessarily the advanced features of VIM that make it so powerful. Its the fact that you never have to take your hands off the keyboard to do anything. Finding something in a huge file is as simple as a couple of keystrokes. Opening and closing multiple files in the same window is incredibly fast as well.

While it may not seem intuitive at first, its well worth your time. Even if you don't use it as your standard IDE (I generally use Visual Studio or Eclipse, for example), you'll find your self using VIM to quickly open and edit files because it becomes way faster than waiting for the IDE to load.

Invest the time to learn how to use VIM well and you'll never regret it. I'd say its comparable to learning to touch-type.


答:
Frankly, user stories should not have a whole lot of detail. "I want the software to do X, to meet Y business need" should be sufficient. After all, you not want business people dictating how to do that - you're the expert at the software and best practices therein.

That said, the developers also need to ask: "how do you expect this to work?", "what happens when that interacts with feature Z?". Developers don't make requirements, they make implementation.

It also sounds as though there is too much of a gap between implementation and evaluation. Stakeholders should be looking at prototypes, at half-done code every few days. That lets you get feedback before getting too far into the weeds.


问:
Why did Aiken decided to separate data and instructions in the Harvard Mark I?
When Aiken devised the Mark I, why did he decided to separate data and instructions? It was not mentioned in Wikipedia (or in any other searches I've looked) on how or why Aiken separated data and instructions.</p>

答:
According to the Wikipedia article on the Harvard Mark I, the data memory consisted of storage for 72 23-digit numbers, and instructions were read from a paper tape loop.

That's the how.

The why is most likely that he hadn't seen the advantages of putting instructions into read/write memory.  Also random access read/write memory was extremely expensive to implement ... compared with sequential and / or readonly memory.

Remember we are talking about a machine that was build from electro-magnetic switches and relays, and could do 3 additions per second.


问:
How to maintain user relationship when user un-follows another user
I have a table of user relationship which stores who follows whom, the table structure is as follows

```<code>-id
-follower
-following
</code>```

when someone follows any other user, I add a record with follower user id and id of user he is following, now my question:

When user wants to un-follow that user, I have decided rather than deleting the record I can add another column break at the end of this table, which I will set to true when user wants to un-follow, this way I can maintain consistency in the records, that is there won't be any gap like 1,2,4,7,8,9,15 if I delete records. If I don't delete the record, I can use it if that user want to follow that user again in future I can set break column of that record to false and the relationship will exist again. What do you think; should I use this approach or I should delete the record?

Tell me if the approach is good or there could be any  issues associated with it and also tell me if there is any better way you know.

答:
In general flagging records as inactive isn't uncommon and would work as you describe it, you often find flags like "deleted" when there is a good reason to keep the information that something existed at some time, for example there are other records that relate to its id.

An alternative way would be a date field that is null unless deletion, in case you need to know when deletion happened.

But in your special case it seems useless to keep old records. Why would you worry about gaps in the id? Happens all the time.


答:
I can relate to your plight, I faced a similar situation with my most recent project at work. We ended up implementing sort of a "hot potato" system where the developer that most recently broke the build had to babysit/nanny/monitor it until it was fixed AND passed all of our verification tests.

This was successful because the build and verification tests routinely took ~4 hours, so breaking the build meant you lose half a day in doing real work. Needless to say this resulted in developers using branches more efficiently before merging them into the trunk. For most developers, the previous mindset was "I'll just let the CI build system notify me if my code is broken."


答:
See this article in wikipedia with a good explanation.
The difference is that parameters appear in method/function definitions, while arguments are concrete values you pass to a method/function.</p>

Title: Is argument or parameter considered more appropriate for a function/method argument/parameter?

Body:
Hopefully the topic is not too confusing, I am curious though as lately I have seen more and more use of the word parameter to denote a function's passed in values, whereas during my studies I feel as if argument was used almost exclusively.

Is parameter more appropriate as argument is more specific to a programs arguments specific at runtime whereas when a function is called, the values passed to it are parameters to the function itself?

From a curious programmer.


问:
Bayes filtering and data storage with expansive data sets
I am looking to write a Bayes filter that will act as an indicator of topic for a number of topics with a variable number of sources. Given a really big number of RSS feeds and here really big might only be a few hundred only few percent (let's say 2%) are interesting to a given group.

What I want to write (in PHP) is a filter I can train to say this is Topic X and this is not. Then I want selected users to be able to further train the filter. But I want to use only the base training for picking topics to mark as interesting for Topic X and then refine that collection based on the training the user has provided to give the most interesting results for that user by reassessing the probabilities including the user supplied training on the short list per user. Or maybe scoring the short list and picking the "best" items to show first.

So over time I am going to gain a fairly large collection of data (all of the headlines and blurbs from hundreds of feeds) and I am going to have flagged the feed items "yes" and "no" on an unspecified number of topics and have had users have likewise done so.

The headline and blurb will be stored for easy display later but I don't want to hold on to too many items that are "no" (up to 98% I imagine). Given I go with, say, this implementation from GitHub that I found earlier today https://github.com/benwaine/BayesPHP (or can be talked into rolling my own) what is the most efficient way to go about storing the data needed to carry out an assessment? Am I asking for trouble if simply try and store any news headlines etc flagged "yes" but store some sort of summary for the base "no" assessments and then just work it out on the fly each time storing the resultant "yes".

The server I have to work with is already doing a fair amount and is not going to spare me much horse power for this.

So balancing processing efficiency and storage needs what can you recommend?

答:
Wouldn't it be more efficient to store why it is yes rather than the reason for no? Or no because the filter is basically checking to see if it shares any attribute with a no rather than checking against yesses...

So if I understand you correctly, you want to store both the data and a list for each of why it is not a member of a specific topic? Perhaps you should store it in a relational database like MySQL. You could have one primary table containing the summaries, and a table for each containing the reasons why it is not, linked to the primary on an id as primary key. The full text of the data probably would be better stored in a text file or otherwise outside the database, unless you intend to search within it directly.

I hope that helps and I didn't totally misunderstand what you are asking.


答:
Lines of code themselves are not very important. One way to look at it is to compare it with prose. The first realization is that an important property of both code and prose (assuming correctness) is readability. Readability (and understandability) helps with other properties such as maintainability and correctness.

There are advantages to being able to fit a function in a small number of lines. But having text without paragraphs reduces its legibility. Using difficult concepts, difficult(rare) words and complex ways of expression does generally reduce the amount of words needed to express an idea, but at the same time moves the reading level of the text from secondary school level up to professional academics (in the case of prose).

In general it is helpful to add abstractions in your code and use helpers etc. but again, those abstractions can become too numerous. What can also happen is that the move the complexity to another part of the code. Sometimes, like when you as an expert are designing a framework/library for use by junior programmers (or students), it is a good idea to do this. But don't expect the juniors to be able to make sense of how your code works, just make it very hard for them to use it incorrectly.

When writing code, especially do not shy away from adding empty lines in your code. They function as paragraphs and help you separate different parts of your function (even if they should not be put into helpers yet).


答:
I think it's more important to focus on clean, auto-documented code, than LOC. I don't really like your example, though, because it explains what the code is doing, without saying why. For example, this:

boolean sweet_sixteen = (age == 16);

is pretty redundant. Anybody reading "age == 16" knows that. I would rather write the code like this:

```<code>public static boolean companyShouldThrowABigParty(int age) {
    return (age == 16) || (age == 21) || ((age > 21) && (((age % 10) == 0) || ((age % 25) == 0)));
}

public static void happyBirthday(int age)
{
    System.out.println(companyShouldThrowABigParty(age) ? "Super special party, this year!" : "One year older. Again.");
}
</code>```

The logic about deciding when to throw the party is separate from the System.out, can be tested ,and it is easy to understand. More importantly, though, somebody reading the code can understand the reason it was written that way ("company wants to throw a big party for some of the people").

Body:
I think it's more important to focus on clean, auto-documented code, than LOC. I don't really like your example, though, because it explains what the code is doing, without saying why. For example, this:

boolean sweet_sixteen = (age == 16);

is pretty redundant. Anybody reading "age == 16" knows that. I would rather write the code like this:

public static boolean companyShouldThrowABigParty(int age) {
    return (age == 16) || (age == 21) || ((age > 21) && (((age % 10) == 0) || ((age % 25) == 0)));
}

public static void happyBirthday(int age)
{
    System.out.println(companyShouldThrowABigParty(age) ? "Super special party, this year!" : "One year older. Again.");
}

The logic about deciding when to throw the party is separate from the System.out, can be tested ,and it is easy to understand. More importantly, though, somebody reading the code can understand the reason it was written that way ("company wants to throw a big party for some of the people").


问:
Term for accidental features
Despite the best intentions of programmers; oftentimes, in the real world, software systems contain "accidental features" that are accepted as part of a working system.

For example, there may be some process that runs out of memory and crashes before the process exceeds its quota for calls to an external system (which will cost the company money). Though the software team acknowledges that this is an issue, there is simply not enough perceived business value to fix the problem.

Advantageous accidental behavior like this is often lost in any type of significant technical migration.

My question: Is there a term for this type of "feature" that can serve to differentiate it from a run-of-the-mill bug?

答:
I'd call them "emergent features".

In philosophy, systems theory, science, and art, emergence is the way complex systems and patterns arise out of a multiplicity of relatively simple interactions. Emergence is central to the theories of integrative levels and of complex systems...

The term "emergent" was coined by philosopher G. H. Lewes, who wrote:

"Every resultant is either a sum or a difference of the co-operant forces; their sum, when their directions are the same -- their difference, when their directions are contrary. Further, every resultant is clearly traceable in its components, because these are homogeneous and commensurable. It is otherwise with emergents, when, instead of adding measurable motion to measurable motion, or things of one kind to other individuals of their kind, there is a co-operation of things of unlike kinds. The emergent is unlike its components insofar as these are incommensurable, and it cannot be reduced to their sum or their difference."

Title: Term for accidental features


答:
I call them "undocumented features".

It's a little tongue-in-cheek when such feature is obviously a bug, but it's broad enough that you can use it for experimental features or features included for backwards compatibility.

It's generally not a good idea to let your customers know that the feature was an accident. If customers like it, document it for the next release.

Title: Term for accidental features

Body:
Despite the best intentions of programmers; oftentimes, in the real world, software systems contain "accidental features" that are accepted as part of a working system.

For example, there may be some process that runs out of memory and crashes before the process exceeds its quota for calls to an external system (which will cost the company money). Though the software team acknowledges that this is an issue, there is simply not enough perceived business value to fix the problem.

Advantageous accidental behavior like this is often lost in any type of significant technical migration.

My question: Is there a term for this type of "feature" that can serve to differentiate it from a run-of-the-mill bug?


答:
I just spent some time using DTO between the Controller/Service layer it was fairly easy and pretty efficient ( especially with Automapper ).

Now I have another question regarding the usage of DTO between Service > Date layer.
I'm using a UOW pattern with generic repositories that return POCOs. Is there any best pratices here ? I realize that basically my data layer bleed on the business layer.

I can see that ideally my repository can return DTOS to have a perfect separation between layers but i'm looking at a practical example. I just wonder I can keep a generic repository approach that return DTOs.

Thanks for the help !

Title: MVC4 Service > Controller Models


答: I would keep this tables as is and have a separate log table (with dates). reason being that its just a a matter of time that you want to track Friend-unFriend-FriendAgain event chains

Title: How to maintain user relationship when user un-follows another user

Body:
I have a table of user relationship which stores who follows whom, the table structure is as follows

```<code>-id
-follower
-following
</code>```

when someone follows any other user, I add a record with follower user id and id of user he is following, now my question:

When user wants to un-follow that user, I have decided rather than deleting the record I can add another column break at the end of this table, which I will set to true when user wants to un-follow, this way I can maintain consistency in the records, that is there won't be any gap like 1,2,4,7,8,9,15 if I delete records. If I don't delete the record, I can use it if that user want to follow that user again in future I can set break column of that record to false and the relationship will exist again. What do you think; should I use this approach or I should delete the record?

Tell me if the approach is good or there could be any  issues associated with it and also tell me if there is any better way you know.


答:
What you're considering by having an unfriend field (I prefer the idea of it being a date) which is like a soft delete. It would allow you to maintain other tables that rely on the ID of this relationship table.

A functional approach could be used where another record is added for the same two user relationship, but a field indicating it was broken. This way you never update nor delete a record, just keep adding new ones like a log.

Do whatever causes the fewer problems for the rest of your data if possible. Only you can tell which will have better performance or create any type of replication problems.

I don't understand the whole idea behind keeping the sequence numbering. So what if there are gaps; there shouldn't be any logic/meaning applied to this field other than uniqueness and it could be the foreign-key in another table. Relying on the number for any other reason, is going to cause trouble.


答:
It sounds like the developers are completely removed from the creation of the user stories. Do you expect just to be able to read them like a detailed spec and build it right the first time? If you could do that, you wouldn't need XP or any other agile methodology.

Someone should be asking questions if the story is too vague. Where does Acceptance Testing occur?

User stories are meant to change. You need to deal with it.


问:
In what programming language did "let" first appear?
I was wondering about the origins of the "let" used in Lisp, Clojure, and Haskell.  Does anyone know which language it appeared in first?</p>

答:
Well, between those three, Lisp definitely had it first. Haskell came about in the 80s, and Clojure in the 00s, and let had been around long before either of those dates. :-)

As to whether Lisp was the language to have invented it, I can't vouch for that yet, but I'll do some research and see. :-)

Update: According to Evolution of Lisp (see page 46), it mentioned that let was invented in the 70s:

LET—itself a macro first invented and reinvented locally at each site—was a late-comer to the MacLisp world; according to Lisp Archive, it was retroactively absorbed into PDP-10 MacLisp from Lisp-Machine Lisp in 1979 at the same time as DEFMACRO and the complex Lisp Machine DEFUN argument syntax.

Still doesn't quite answer whether it was invented in another language earlier, of course, but still another data point. :-)


答:
Well, BASIC had LET for assignment as part of the syntax from the start in 1964, so that would predate the use of let in Lisp, which as Chris Jester-Young points out didn't appear until the 1970s according to Evolution of Lisp.

I don't believe COBOL, Fortran, or ALGOL have LET in their syntax either. So I'm going to go with BASIC.

Title: In what programming language did "let" first appear?

Body: I was wondering about the origins of the "let" used in Lisp, Clojure, and Haskell.  Does anyone know which language it appeared in first?</p>


问:
Closest Point of Approach (CPA) mathematical formula in ship radar
I was recently searching for the mathematical formula to find closest point of approach (CPA) between one ship and another ship.  I need to apply the formula in my radar ship program and I can't find the correct way to calculates it.

Does anybody know what the correct formula (or pseudo-code) is instead of plotting it manually?

答:
If both vessels are moving I would probably just calculate both their positions (based on current heading and speed) for every minute in the next N minutes - and then the Euclidean distance between the two points at each time interval

If one ship is stationary you could do a line-to-point closest distance


答:
I've heard this referred to as "Design by Coincidence".

Short example: One project I worked on managed MS Office documents on a network drive. It allowed users to open up the documents directly - a bug, it was supposed to copy the file to the local machine. but that meant users would be alerted if another user had the document already open. This was a basic feature of MS Office, and had nothing to do with our software, but our salesforce and CEO started referring to it as a feature. When I was asked to replicate this feature for the web version of the application, the managers were shocked to learn that the 'feature' didn't actually exist.

Title: Term for accidental features


答:
Given a function defined like:

```<code>int f(int y) { /* ... */ }
</code>```

and a call like:

```<code>int a = 3;
f(a);
</code>```

y is the parameter (aka "formal parameter"), and a is the argument.

Body:
Given a function defined like:

int f(int y) { /* ... */ }

and a call like:

int a = 3;
f(a);

y is the parameter (aka "formal parameter"), and a is the argument.


问:
What is meant by "Now you have two problems"?
There is a popular quote by Jamie Zawinski:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

How is this quote supposed to be understood?

答:
My favourite, in-depth answer to this is given by the famous Rob Pike in a blog post reproduced from an internal Google code comment:
http://commandcenter.blogspot.ch/2011/08/regular-expressions-in-lexing-and.html

The summary is that it's not that they are bad, but they are frequently used for tasks for whcih they are not necessarily suited, especially when it comes to lexing and parsing some input.

Regular expressions are hard to write, hard to write well, and can be expensive relative to other technologies... Lexers, on the other hand, are fairly easy to write correctly (if not as compactly), and very easy to test. Consider finding alphanumeric  identifiers. It's not too hard to write the regexp (something like "[a-ZA-Z_][a-ZA-Z_0-9]*"), but really not much harder to write as a simple loop. The performance of the loop, though, will be much higher  and will involve much less code under the covers. A regular expression library is a big thing. Using one to parse identifiers is like using a  Ferrari to go to the store for milk.

He says a lot more than that, arguing that regular expressions are useful in, e.g. disposable matching of patterns in text editors but should rarely be used in compiled code, and so on. It's worth a read.


答:
This is related to Alan Perlis' epigram #34:

The string is a stark data structure and everywhere it is passed there is much duplication of process. It is a perfect vehicle for hiding information.

So if your choose the character string as your data structure (and, naturally, regex-based code as the algorithms to manipulate it), you have a problem, even if it works: bad design around an inappropriate representation of data which is hard to extend, and inefficient.

However, often it doesn't work: the original problem isn't solved, and so in that case you have two problems.

Title: What is meant by "Now you have two problems"?

Body:
There is a popular quote by Jamie Zawinski:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

How is this quote supposed to be understood?


问:
What language is most similar to JavaScript?
I am looking for a language that

has First class functions

is dynamic

has prototypical inheritance

does not have too many features (i.e is easy to get into and write first program).

I have been programming in JavaScript for quite some time and have gotten quite fond of it. Are there any other languages that have similar design?

Edit (just some clarification)

I know a bit of c#.After doing some programming in node js I really started to appreciate javascript and ease of its use.However outside of web development javascript falls short.Sure there are libraries like app.js that allows desktop programming but that's about it.Which is why I was looking for a more general purpose sripting language that has the above mentioned features.I listed those features to make the question more in tune with stack exchange policies other wise it would probably have been closed.

答:
Self has all those features.

It's actually a major inspiration for JavaScript (some say it's the predecessor).

Unfortunately I don't know how much actual use it gets these days (outside of teaching).


问:
Exercise for implementing design patterns
I have started to study design patterns using some course in pluralsight and the gang of four book.
While I feel I understand what I have studied so far, I think it would be very helpful if I would have some way of practicing them.
I know that I will get the chance in time but I feel I would get a better understanding of each design pattern if I would do some exercises for each of them.

What I would like is if someone knows any websites or documents that provide exercises for implementing design patterns. I am particularly interested in ones where the author provides some source code and the problem that has to be solved and I have to implement a design pattern to solve it.

I am not interested in examples and theory; I already got that covered from what I am reading.

答:
I'm going to try and un-ask the question a bit.

When I was studying design patterns, I got my practical experience by trying to identify where I was using the patterns already in my own code and where I might usefully adopt a pattern to improve it. Using programs/problems supplied by someone else would just not be anything like as engaging.

On the other hand, the tricky parts about patterns are actually learning when to not use them. It is this understanding of the forces and consequences that is the key to being good at using patterns, and it is genuinely hard. (The other bits of a pattern are usually pretty simple.) Patterns are meant to be a way of thinking about good road-tested software engineering approaches, and for communicating this to other people, but too many use them as a crutch or straitjacket, believing that they must use as many patterns as possible and that everything has to be done with patterns. That's utterly foolish.

I still recommend writing your own code, not using someone else's. You need some actual ownership of the problem in order to really grasp the forces and consequences, and those are the part that you need to really learn to think in terms of.


答:
To summarize you are in the following situation:

You are new.

The project (I assume your are talking about a running project) has pressing time constraints.

The developer is expected to fill in the blanks at his own discretion.

The company you are working in is intending to practice XP. However
user stories seem not to be applied in a way which fits into the XP
methodology. On the other hand "The developer is expected to fill in the blanks at his own discretion".

Think about point 4: My opinion is that agile practices should be adapted to the needs and the culture of a company/team (not the other way around). Identify where the company sticks to the XP methodology and where it deviates. This is the groundwork for a constructive approach to your concerns.

Due to 1 and 2 you are currently not in a good position to question if the company applies XP in a reasonable way. Starting a discussion with the management will very likely pose you as someone who "complicates things". However you can start to discuss your concerns with your fellow developers. Maybe you will find some developers who think the way you do. Maybe there is a senior developer who will then convey your concerns to the management. But do not expect that things will change fast, especially not in the current project. However the project will give you a good opportunity to gather more data which adds more substance to a constructive approach.

Now to point 3: I think that good user stories are collaboratively written by customers/end users/product owners and developers. Show some initiative: Look for some opportunity to directly ask the authors of the user stories. If this is not possible ask some senior developer or the management how to deal with open questions which must be answered by the authors of the user stories. Maybe you can at least have some written correspondence. Since you need to fill out the blanks on your own discretion, then your choice should be to actively involve the customers/end users/product owners.

At some point you have made enough thoughts and observeration about how your company applies XP (or agile practices in general). Maybe some time has already passed and you are not perceived as a greenhorn anymore. Maybe your active involvement with the customer has shown some positive effects. Maybe the next project is already starting. Maybe your also have already some backup from other develeopers. Maybe you find out that the way it works is not bad at all. The point is that then you will then have enough ideas to convey your concerns to the management, based on real experience and data within your company.


答: You might want to check out Io which is a dynamic prototype-based programming language. The author describes it as conceptually simple, consistent and easily embedded and extended. It's highly dynamic and highly concurrent. The book Seven Languages in Seven Weeks has a chapter about it as well.</p>

Title: What language is most similar to JavaScript?

Body:
I am looking for a language that

has First class functions

is dynamic

has prototypical inheritance

does not have too many features (i.e is easy to get into and write first program).

I have been programming in JavaScript for quite some time and have gotten quite fond of it. Are there any other languages that have similar design?

Edit (just some clarification)

I know a bit of c#.After doing some programming in node js I really started to appreciate javascript and ease of its use.However outside of web development javascript falls short.Sure there are libraries like app.js that allows desktop programming but that's about it.Which is why I was looking for a more general purpose sripting language that has the above mentioned features.I listed those features to make the question more in tune with stack exchange policies other wise it would probably have been closed.


答:
As a developer,

I need to fully understand the specifics of a user story,

so that I can confidently estimate and implement it.

On other words, you must ask questions until you understand the specifics of the story. This is done in iteration planning and acts as decision point: if you cannot estimate it, you cannot build it.