问:
Does it make sense to split up an existing multi-method interface into several single method interfaces just to take advantage of lambdas?
Say I have an existing callback interface that has multiple methods. To illustrate my point I use a callback the likes that you would see in code that performs some HTTP client operations:

```<code>public interface GetCallback<T> {
    public void onSuccess(T data);
    public void onAuthFailure();
    public void onError(RequestError error);

    //Potentially more methods like onPreGet etc...
}
</code>```

And a method that makes a request would take an instance of this callback as an argument:

```<code>public void issueRequest(String url, GetCallback<T> callback) {
    // Implementation ...
}
</code>```

As is obvious, this suffers with verbosity at the call site:

```<code>public void getData(){
    issueRequest("http://programmers.stackexchange.com", new GetCallback<String>(){
        public void onSuccess(String data) {/*Do Something*/}
        public void onAuthFailure(){/*Ask for credentials*/}
        public void onError(RequestError error){/*Show error message*/}

    });
}
</code>```

I have something similar in my code and it has been working well. I use a DefaultGetCallback class that provides default implementation of the onAuthFailure and onError methods since the action I want to take in those cases is pretty much the same regardless of what resource I'm requesting.

The question is, does it make sense to refactor this into a class composed of a set of single-method interfaces in order to take advantage of the lambda syntax?

```<code>public class GetCallback<T>{
    public interface OnSuccessListener<T> {
        public void onSuccess(T data);
    }

    public interface OnAuthFailureListener {
        public void onAuthFailure();
    }

    public interface OnErrorListener {
        public void onError(RequestError error);
    }

    private OnSuccessListener mSuccess;
    private OnAuthFailureListener mAuthFailure;
    private OnErrorListener mError;

    public GetCallback<T>(OnSuccessListener<T> success) {
        this.mSuccess = success;
    }

    public GetCallback<T> withAuthFailure(OnAuthFailureListener authFailure){
        this.mAuthFailure = authFailure;
        return this;
    }

    public GetCallback<T> withError(OnErrorListener error){
        this.mError = error;
        return this;
    }

}
</code>```

I might use a Builder pattern to construct the GetCallback here but that's besides the point. The call site now becomes:

```<code>public void getData(){
    issueRequest(
        "http://programmers.stackexchange.com",
        new GetCallback<String>(s -> doSomething(s))
            .withAuthFailure(() -> askForCredentials())
            .withError(error -> showErrorMessage(error))
    );
}
</code>```

One advantage is I can customize the behavior of individual "events" (success, error etc) in isolation, at the call site, rather than having to sub-class or to create an anonymous inner class.

But then, how much is too much? Especially given the fact that my current design already served me well?

答:
I would say, if there's a cost for your clients (the Users of your interface) to migrate to this another API, don't do it, it's not that ugly at all. If it's something new, or the cost of change is very low (few clients), go for it, as it would be much better for readability.

Another point is: like writing fluent interfaces, it's extremely verbose to write those functional interfaces for being able to use the lambdas, so if this an internal API I would go with the simplier straight forward implementation (without lambdas). In other hand, If this is a library that will be used for another systems, I would go with the lambda path. :)


答:
You should not design interfaces based on the features of the implementation language but rather on the business model and on the OOP design principles.

A reason for splitting your interface would be a violation of Interface segregation principle (I from SOLID). This means it makes sense splitting if your GetCallback implementations usually don't need to implement all the methods.

ContentLicense: CC BY-SA 3.0

Title: Does it make sense to split up an existing multi-method interface into several single method interfaces just to take advantage of lambdas?

Body:
Say I have an existing callback interface that has multiple methods. To illustrate my point I use a callback the likes that you would see in code that performs some HTTP client operations:

```<code>public interface GetCallback<T> {
    public void onSuccess(T data);
    public void onAuthFailure();
    public void onError(RequestError error);

    //Potentially more methods like onPreGet etc...
}
</code>```

And a method that makes a request would take an instance of this callback as an argument:

```<code>public void issueRequest(String url, GetCallback<T> callback) {
    // Implementation ...
}
</code>```

As is obvious, this suffers with verbosity at the call site:

```<code>public void getData(){
    issueRequest("http://programmers.stackexchange.com", new GetCallback<String>(){
        public void onSuccess(String data) {/*Do Something*/}
        public void onAuthFailure(){/*Ask for credentials*/}
        public void onError(RequestError error){/*Show error message*/}

    });
}
</code>```

I have something similar in my code and it has been working well. I use a DefaultGetCallback class that provides default implementation of the onAuthFailure and onError methods since the action I want to take in those cases is pretty much the same regardless of what resource I'm requesting.

The question is, does it make sense to refactor this into a class composed of a set of single-method interfaces in order to take advantage of the lambda syntax?

```<code>public class GetCallback<T>{
    public interface OnSuccessListener<T> {
        public void onSuccess(T data);
    }

    public interface OnAuthFailureListener {
        public void onAuthFailure();
    }

    public interface OnErrorListener {
        public void onError(RequestError error);
    }

    private OnSuccessListener mSuccess;
    private OnAuthFailureListener mAuthFailure;
    private OnErrorListener mError;

    public GetCallback<T>(OnSuccessListener<T> success) {
        this.mSuccess = success;
    }

    public GetCallback<T> withAuthFailure(OnAuthFailureListener authFailure){
        this.mAuthFailure = authFailure;
        return this;
    }

    public GetCallback<T> withError(OnErrorListener error){
        this.mError = error;
        return this;
    }

}
</code>```

I might use a Builder pattern to construct the GetCallback here but that's besides the point. The call site now becomes:

```<code>public void getData(){
    issueRequest(
        "http://programmers.stackexchange.com",
        new GetCallback<String>(s -> doSomething(s))
            .withAuthFailure(() -> askForCredentials())
            .withError(error -> showErrorMessage(error))
    );
}
</code>```

One advantage is I can customize the behavior of individual "events" (success, error etc) in isolation, at the call site, rather than having to sub-class or to create an anonymous inner class.

But then, how much is too much? Especially given the fact that my current design already served me well?


问:
Is there a technical reason why you can't develop iOS apps on a Linux computer?
I understand why you can't develop OS X apps on a Linux computer, but is there a good technical reason why you can't develop iPhone and iPad apps on Linux?  Why isn't it possible to compile iOS source code into an iOS executable and run it in an iOS simulator on Linux or install it on a development iOS device?

Is it just because the XCode IDE is a Cocoa application?

You can develop Android apps on any kind of platform, it seems. I don't see why the same can't be true of iOS.

答:
There is a technical reason that Xcode will not allow development of iOS apps on other systems.

iOS is similar in many ways to OS X. Many of the frameworks are identical or very close. The iOS Simulator makes use of that to provide a very fast testing environment. When Xcode compiles an app to run in the simulator, it creates x86 binaries which link against frameworks that mostly thunk down to OS X frameworks. You end up with a debug build that runs natively on your Mac, which has great performance.

If you look at Android, it creates platform independent apks which are then emulated in one Android emulator or another. This runs a virtual machine which runs the whole Android stack for you to debug.  There are emulators which are faster than others, but all of them are much slower than the simulator. The benefit, though, is that they are cross-platform.

For Apple to allow iOS apps to be built on other systems, they would either need to port the frameworks to those OSes so they could write a simulator, or they would have to build an emulator. Either of those would be a chunk of work that would take time away from building new features.


答:
Instead of building a facade wouldn't it make sense to do something more like this?

```<code>public interface SuccessListener<T> {

    default void onSuccess(T data) {
        // Completely ignore it.
    }

}

public interface AuthFailureListener {

    default void onAuthFailure() {
        // Completely ignore it.
    }

}

public interface ErrorListener {

    default void onError() {
        // Completely ignore it.
    }

}

// Retain the old API
public interface GetCallback<T> extends SuccessListener<T>, AuthFailureListener, ErrorListener {
    // Now empty - we are a conglmerate.
}

public static <T> void issueRequest(String url, SuccessListener<T> successListener, AuthFailureListener failureListener, ErrorListener errorListener) {
    // Implementation ...
}

public static <T> void issueRequest(String url, GetCallback<T> callback) {
    // Ensures backwards compatability.
    issueRequest(url, callback, callback, callback);
}

public void getData() {
    issueRequest("http://programmers.stackexchange.com", new GetCallback<String>() {

        @Override
        public void onSuccess(String data) {
        }

        @Override
        public void onAuthFailure() {
        }

        //@Override
        //public void onError() {
        // Can now leave out the ones you don't want.
        //}
    });
}
</code>```

It is still compatible with your earlier API and internally who cares that the same object is a listener for all three events. It also opens up the possibilities of adding default implementations and allowing the chance to issue a request with only a SuccessListener.

Note: I tweaked the code to use default for even more niceness.

Body:
Instead of building a facade wouldn't it make sense to do something more like this?

public interface SuccessListener<T> {

    default void onSuccess(T data) {
        // Completely ignore it.
    }

}

public interface AuthFailureListener {

    default void onAuthFailure() {
        // Completely ignore it.
    }

}

public interface ErrorListener {

    default void onError() {
        // Completely ignore it.
    }

}

// Retain the old API
public interface GetCallback<T> extends SuccessListener<T>, AuthFailureListener, ErrorListener {
    // Now empty - we are a conglmerate.
}

public static <T> void issueRequest(String url, SuccessListener<T> successListener, AuthFailureListener failureListener, ErrorListener errorListener) {
    // Implementation ...
}

public static <T> void issueRequest(String url, GetCallback<T> callback) {
    // Ensures backwards compatability.
    issueRequest(url, callback, callback, callback);
}

public void getData() {
    issueRequest("http://programmers.stackexchange.com", new GetCallback<String>() {

        @Override
        public void onSuccess(String data) {
        }

        @Override
        public void onAuthFailure() {
        }

        //@Override
        //public void onError() {
        // Can now leave out the ones you don't want.
        //}
    });
}

It is still compatible with your earlier API and internally who cares that the same object is a listener for all three events. It also opens up the possibilities of adding default implementations and allowing the chance to issue a request with only a SuccessListener.

Note: I tweaked the code to use default for even more niceness.


问:
How to express what do do when error occurs in a user story?
How do you express what to do when error occurs in a user story? Should the response to what happen on errors be in a task of the original user story, or should I create another user story that is concerned with what happens on errors?

E.g.

This says nothing about what to do on errors such as credit card is invalid, not enough money, …

As a buyer I want to pay for the order with a credit card to get immediately access to the services.

I could add another user story like this:

As a buyer I want to get information about errors during payment immediately so that I can fix the errors and try again.

Which of these is common/correct? Should the error handling be part of the original user story?

答:
The handling of errors should be spelled out in the acceptance criteria, not in the story. The user story is all about functionality delivered to the end user, and presumably you aren't delivering errors to the end user.

I can see a case for making error handling part of the story for a product that is targeted toward other developers, where error codes and error handling are actual features that you're delivering.


问:
Where to audit a codebase for dangerous code use
Not sure Programmers Stack Exchange is the place to ask this question, but thought I'd give it a go.

Our team had a near miss recently with a nasty error where a method call had been added to the wrong area of code,such that it deleted the an order immediately after the user had been through the checkout.  There was no warning to the customer or us due to the nature of the API we were using (and can't modify).

It occurred to me that what we wanted was some sort of Audit tool, a bit like a linter, that we could configure to check each new Github commit for use of certain key method calls.  If someone made that method call, it would flag it for extra scrutiny.
Maybe a Jenkins plug-in would be the best place for this, as our code runs through Jenkins CI every time we push to our main pre-release branch?

For clarity, this code had been fully tested and code reviewed.  While there are lessons to learn in both these areas, this feels like something an automated process could help with.
Ultimately finding the bug was something of good fortune, as one of the developers was tidying something else up in that area of the code.

Some of the questions I have:

Do such tools exist?

Where would they typically be best applied; in the IDE, during the source control check in process or in something like Jenkins during CI?

Are they all programming language specific?  Or really,are we limited to simply as running a grep over our code-base?

Any thoughts or ideas really appreciated.

答:
For clarity, this code had been fully tested and code reviewed

tested and reviewed, but not fully, obviously. I think that's the area you should be looking at.

As for a tool - surely a simply regex running over every file in the build is what you want. Alternatively get a open-source static analyis tool and modify it to handle cases where your method is called. These tools will already have checks for other, dangerous methods (eg memcpy in C) so it should be an easy task to modify to handle your own methods.


问:
Distinct Log and Trace for each object in .NET
I am dealing with very complex objects in .NET (in my case a finite element model that can consist of thousands of other objects say a Model instance have a large list of Element instance). I would like to add log feature per Model and its only for showing the log to user, not storing it. A very simple way is to add a Status property of type string to model and write status into it. Also can create a more complex type Status but the thing i want to know what is prettier way to this? is there any built in feature in .NET for this purpose?</p>

答:
You are probably looking for TraceSource, as opposed to its older sibling, Trace.

It works very similarly, except you create instances of TraceSource with different identifiers.

```<code>var source = new TraceSource("foo");
source.Listeners.Add(new ConsoleTraceListener());
source.TraceEvent(TraceEventType.Error, 1, "here be dragons");
</code>```

The instances can be configured in code or through (app/web/machine).config files, though most of that is explained in the MSDN link.

As far as showing it to the user rather than storing it - that is just a matter of attaching the right listener.  If a built-in listener type which does what you want does not exist, it is pretty easy to extend TraceListener.  For example, in a small test utility, I created one that raised events when messages were written and then wired the events to display them in the system tray.

Body:
You are probably looking for TraceSource, as opposed to its older sibling, Trace.

It works very similarly, except you create instances of TraceSource with different identifiers.

var source = new TraceSource("foo");
source.Listeners.Add(new ConsoleTraceListener());
source.TraceEvent(TraceEventType.Error, 1, "here be dragons");

The instances can be configured in code or through (app/web/machine).config files, though most of that is explained in the MSDN link.

As far as showing it to the user rather than storing it - that is just a matter of attaching the right listener.  If a built-in listener type which does what you want does not exist, it is pretty easy to extend TraceListener.  For example, in a small test utility, I created one that raised events when messages were written and then wired the events to display them in the system tray.


问:
Would it be a wise decision to opt for just Javascript to create a single page application, instead of HTML and CSS?
I've mainly done application development, but have also worked on simple web projects (where the HTML and CSS were created by the web dev guys).

Recently I tried creating a website for myself, and found it extremely annoying trying to get the placement of div's and other elements on the page right. Totally unpredictable. I've tried reading through this, but I'd like to have an environment where it's easier to position an element on the screen

I see that processing.js, paper.js and raphael.js are available, but would it be wise to use just these to create a single-page-web-app?

Would it be possible to create a web-app to be able to have

A homepage, with a menu which when clicked would clear the old
content from the screen and load new content onto the screen

Be able to interact with a database like Neo4j or MongoDB

Have a UI which is useable on a PC browser and mobile phones

ps: I don't mind not being able to support old browsers.

答:
To some extent, there are web sites that do just that, where the HTML elements are created and placed on the page and styled using CSS. But it must be kept in mind that you still need to use HTML elements and style them with CSS.

One disadvantage of doing it that way is search engines only read the content provided by the original HTML. More and more Google is able to read javascript but it's not gotten very far and it's unknown when and what that will affect as far as search results are concerned.

Which comes back to my original point, you must use HTML and CSS when you create a page, statically or dynamically, and there is no way around that.


问:
How to work around Java's lack of pointers to pointers when working with linked data structures?
I've learned from a textbook how to implement binary search trees recursively in Java, and am working on implementing them nonrecursively. I've found a simple and elegant way to implement an insert method in C/C++ by traversing the tree using a pointer of type Node**, but can't find an elegant way to do this in Java.

My C++ code is as follows:

```<code>class BST {
    class Node {
    public:
        int key;
        int val;
        Node *left = nullptr;
        Node *right = nullptr;
        Node(int k, int v) : key(k), val(v) {}
    };
    Node *root = nullptr;

public:
    void insert(int key, int val);
};

void BST::insert(int k, int v) {
    Node **link = &root;

    while (*link != nullptr && (*link)->key != k) {
        if (k < (*link)->key)
            link = &(*link)->left;
        else if (k > (*link)->key)
            link = &(*link)->right;
    }

    if (*link == nullptr)
        *link = new Node(k, v);
    else
        (*link)->val = v;
}
</code>```

Which I think expresses the idea pretty directly. My first attempt in Java was the following.

```<code>public class BST {

    private class Node {
        int key;
        int val;
        Node left = null;
        Node right = null;
        Node (int k, int v) {
            key = k; val = v;
        }
    }
    Node root = null;

    void insert(int k, int v) {
        if (root == null) {
            root = new Node(k, v);
            return;
        }

        Node node = root;
        while (node.key != k) {
            if (k < node.key) {
                if (node.left == null) {
                    node.left = new Node(k, v);
                    return;
                } else {
                    node = node.left;
                }
            } else {
                if (node.right == null) {
                    node.right = new Node(k, v);
                    return;
                } else {
                    node = node.right;
                }
            }
        }

        node.val = v;
    }
}
</code>```

This seems much less clear to me - it has to deal with lots of different cases separately, and the code for creating new nodes is mingled with the code for traversing the tree, whereas the C++ version goes through two clear stages. Then it occurred to me that I could replicate the C++ version by storing the Node pointers in objects of a Link class:

```<code>public class BST {

    private class Link {
        Node node = null;
    }

    private class Node {
        int key;
        int val;
        Link left = new Link();
        Link right = new Link();
        Node (int k, int v) {
            key = k; val = v;
        }
    }
    Link root = new Link();

    void insert(int k, int v) {
        Link link = root;
        while (link.node != null && link.node.key != k) {
            if (k < link.node.key)
                link = link.node.left;
            else if (k > link.node.key)
                link = link.node.right;
        }

        if (link.node == null)
            link.node = new Node(k, v);
        else
            link.node.val = v;
    }
}
</code>```

This allows the algorithm to be expressed elegantly, but the overhead of adding an extra layer of indirection to every node of the data structure seems rather a heavy price to pay. Is there a better way of doing this?

答:
Part of the problem is that you're not following good OO principles.

In this case, the one that's probably most applicable is "Tell, don't ask": If you want a Node to add a child, you should tell it to add a child, you shouldn't ask it to expose all the relevant information you need then go ahead and add the child for it. Likewise, if (because you're doing an iterative solution), you need to traverse a level down the tree, tell the Node you want to traverse to the appropriate child, don't ask it for everything you need to know to do the calculation yourself.

Consider:

```<code>private class Node {
    int key;
    int val;
    Node left = null;
    Node right = null;
    Node (int k, int v) {
        key = k; val = v;
    }

   public Node traverseNext(int targetKey) {
       if (key==target) {
           return null;
       }
       return key < target ? left : right;
   }

   public void setChild(int key, int value) {
       if (key == this.key) {
           return;
       }
       if (key < this.key) {
           left = new Node(key, value);
       }
       else {
           right = new Node(key, value);
       }
   }
</code>```

Then a caller wanting to add a child would just have to do:

```<code>Node node;
Node nextNode = root;

while(nextNode != null) {
    node = next;
    nextNode = node.traverseNext(key);
}

node.setChild(key, value);
</code>```

(Excuse any mistakes, Java isn't my native language)

That's not exactly stellar code because I had to go out of my way to work around the obvious recursive solution. For example, you wouldn't realistically want to expose a method that cheerfully replaces one child with another if asked. But it should give the basic idea.

Note: I realise that this doesn't very directly address the issue which caused the difference between those two code samples- the capability that a pointer has which a reference doesn't. But I'm also of the opinion that it's no coincidence that as soon as you solve this problem in a Java-idiomatic way, that difference ceases to be relevant.

Body:
Part of the problem is that you're not following good OO principles.

In this case, the one that's probably most applicable is "Tell, don't ask": If you want a Node to add a child, you should tell it to add a child, you shouldn't ask it to expose all the relevant information you need then go ahead and add the child for it. Likewise, if (because you're doing an iterative solution), you need to traverse a level down the tree, tell the Node you want to traverse to the appropriate child, don't ask it for everything you need to know to do the calculation yourself.

Consider:

private class Node {
    int key;
    int val;
    Node left = null;
    Node right = null;
    Node (int k, int v) {
        key = k; val = v;
    }

   public Node traverseNext(int targetKey) {
       if (key==target) {
           return null;
       }
       return key < target ? left : right;
   }

   public void setChild(int key, int value) {
       if (key == this.key) {
           return;
       }
       if (key < this.key) {
           left = new Node(key, value);
       }
       else {
           right = new Node(key, value);
       }
   }

Then a caller wanting to add a child would just have to do:

Node node;
Node nextNode = root;

while(nextNode != null) {
    node = next;
    nextNode = node.traverseNext(key);
}

node.setChild(key, value);

(Excuse any mistakes, Java isn't my native language)

That's not exactly stellar code because I had to go out of my way to work around the obvious recursive solution. For example, you wouldn't realistically want to expose a method that cheerfully replaces one child with another if asked. But it should give the basic idea.

Note: I realise that this doesn't very directly address the issue which caused the difference between those two code samples- the capability that a pointer has which a reference doesn't. But I'm also of the opinion that it's no coincidence that as soon as you solve this problem in a Java-idiomatic way, that difference ceases to be relevant.


问:
Should I keep my GitHub forked repositories around forever?
So I've forked someone else's repository, made a few changes, submitted a pull request, and my changes made it into the product. Great!

But...what should I do with my forked repository? Is there a compelling reason for me to keep my repository around, or should I go ahead and delete it? I don't plan on making any additional contributions, but if I change my mind I assume I can always just re-fork it.

I'm not really concerned about keeping a backup. I'm more worried about breaking links, losing commit messages, etc.

答:
You can delete your fork as soon as you submit a Pull Request, regardless if it's merged or not. GitHub stores all PRs in the upstream repository, meaning proposed changes are tracked even if the fork is deleted.

That simplifies the decision.

You may still want to keep the fork if:

You'll be contributing more right away (e.g. extend existing PR or open new PRs)

You may want to delete the fork if:

You want a clean portfolio of projects under your name

ContentLicense: CC BY-SA 2.5


答:
You can avoid the repetition by creating the new child Nodes earlier and defaulting them to empty, rather than using null to represent an empty Node.  The body of your while loop might look something like:

```<code>Node child = node.right;
if (k < node.key)
    child = node.left;
if (child.isEmpty()) {
    child.set(k, v);
    child.left  = new Node();  //Could be done inside set
    child.right = new Node();
    return;
} else {
    node = child;
}
</code>```

This basically preallocates the next level of leaves, but shouldn't be too much overhead.  Another option could be replacing left and right with a children[2], then you can use the array index to avoid the repetition.

Title: How to work around Java's lack of pointers to pointers when working with linked data structures?

Body:
I've learned from a textbook how to implement binary search trees recursively in Java, and am working on implementing them nonrecursively. I've found a simple and elegant way to implement an insert method in C/C++ by traversing the tree using a pointer of type Node**, but can't find an elegant way to do this in Java.

My C++ code is as follows:

```<code>class BST {
    class Node {
    public:
        int key;
        int val;
        Node *left = nullptr;
        Node *right = nullptr;
        Node(int k, int v) : key(k), val(v) {}
    };
    Node *root = nullptr;

public:
    void insert(int key, int val);
};

void BST::insert(int k, int v) {
    Node **link = &root;

    while (*link != nullptr && (*link)->key != k) {
        if (k < (*link)->key)
            link = &(*link)->left;
        else if (k > (*link)->key)
            link = &(*link)->right;
    }

    if (*link == nullptr)
        *link = new Node(k, v);
    else
        (*link)->val = v;
}
</code>```

Which I think expresses the idea pretty directly. My first attempt in Java was the following.

```<code>public class BST {

    private class Node {
        int key;
        int val;
        Node left = null;
        Node right = null;
        Node (int k, int v) {
            key = k; val = v;
        }
    }
    Node root = null;

    void insert(int k, int v) {
        if (root == null) {
            root = new Node(k, v);
            return;
        }

        Node node = root;
        while (node.key != k) {
            if (k < node.key) {
                if (node.left == null) {
                    node.left = new Node(k, v);
                    return;
                } else {
                    node = node.left;
                }
            } else {
                if (node.right == null) {
                    node.right = new Node(k, v);
                    return;
                } else {
                    node = node.right;
                }
            }
        }

        node.val = v;
    }
}
</code>```

This seems much less clear to me - it has to deal with lots of different cases separately, and the code for creating new nodes is mingled with the code for traversing the tree, whereas the C++ version goes through two clear stages. Then it occurred to me that I could replicate the C++ version by storing the Node pointers in objects of a Link class:

```<code>public class BST {

    private class Link {
        Node node = null;
    }

    private class Node {
        int key;
        int val;
        Link left = new Link();
        Link right = new Link();
        Node (int k, int v) {
            key = k; val = v;
        }
    }
    Link root = new Link();

    void insert(int k, int v) {
        Link link = root;
        while (link.node != null && link.node.key != k) {
            if (k < link.node.key)
                link = link.node.left;
            else if (k > link.node.key)
                link = link.node.right;
        }

        if (link.node == null)
            link.node = new Node(k, v);
        else
            link.node.val = v;
    }
}
</code>```

This allows the algorithm to be expressed elegantly, but the overhead of adding an extra layer of indirection to every node of the data structure seems rather a heavy price to pay. Is there a better way of doing this?

Body:
You can avoid the repetition by creating the new child Nodes earlier and defaulting them to empty, rather than using null to represent an empty Node.  The body of your while loop might look something like:

Node child = node.right;
if (k < node.key)
    child = node.left;
if (child.isEmpty()) {
    child.set(k, v);
    child.left  = new Node();  //Could be done inside set
    child.right = new Node();
    return;
} else {
    node = child;
}

This basically preallocates the next level of leaves, but shouldn't be too much overhead.  Another option could be replacing left and right with a children[2], then you can use the array index to avoid the repetition.


答:
There is no way to do what you want to do in Java.  Java doesn't offer the freedom of C when dealing with pointers.  The only pointers Java has are object references.

Your first attempt is therefore as good as you can do in Java.  You have to distinguish the case of left, right and root insertion.  If creating and initializing the node is complex, you can move the node creation code to a procedure.

Adding a Link object is a clever idea but it complexifies the data structure as you noted.  It also affects all other methods that manipulate or traverse the tree, and that just to make your insert method more elegant.  A bit silly if you think of it.

So the answer is you can't.  This being said, I am sure it is just an exercise, so experiment as you like.  But in real life, before writing your own binary sort tree, make sure no Java collection fills your needs.  And if they don't, check out open source frameworks like Google guava.


问:
When do you use float and when do you use double
Frequently, in my programming experience, I need to make a decision whether I should use float or double for my real numbers. Sometimes I go for float, sometimes I go for double, but really this feels more subjective. If I would be confronted to defend my decision, I would probably not give sound reasons.

When do you use float and when do you use double? Do you always use double, only when memory constraints are present you go for float? Or you always use float unless the precision requirement requires you to use double? Are there some substantial differences regarding the computational complexity of basic arithmetics between float and double? What are the pros and cons of using float or double? And have you even used long double?

答:
Some platforms (ARM Cortex-M2, Cortex-M4 etc) don't support double (It can always be checked in the reference manual to your processor. If there is no compilation warnings or errors, it does not mean that code is optimal. double can be emulated.). That is why you may need to stick to int or float.

If that is not the case, I would use double.

You can check the famous article by D. Goldberg ("What Every Computer Scientist Should Know About Floating-Point Arithmetic"). You should think twice before using floating-point arithmetic. There is a pretty big chance they are not needed at all in your particular situation.

http://perso.ens-lyon.fr/jean-michel.muller/goldberg.pdf

ContentLicense: CC BY-SA 4.0


问:
Should I mark what blocks mean in data-* attributes?
I was writing a webpage today with a comment after the start of every major section. Instead of using a comment, which comes with the bulgy  syntax, could I instead put this in a data-* attribute? This would be more for me than anything else, so I don't want to put it in an id or class, but it would also leave it open for userscripts to more easily parse the page.

Examples

My current method:

How To Fix Everything

This is the best magic there is:

Find a problem

FIX IT

Back to step 1

        Share on Example.com!

```

<p>My proposed method:</p>

<pre class="lang-html prettyprint-override"><code><article data-news>
    <header data-headline>
        <h1>How To Fix Everything</h1>
    </header>

    <section data-news-body>
        <p>This is the best magic there is:</p>
        <ol>
            <li>Find a problem</li>
            <li>FIX IT</li>
            <li>Back to step 1</li>
        </ol>
    </section>

    <footer data-social>
        Share on Example.com!
    </footer>
</article>
</code>```

答:
I would use classes as what your doing is adding contextual classification:

```<code><footer class="social">
  <a href="//example.com/share">Share on Example.com!</a>
</footer>
</code>```

Can be read as its a footer containing social media functions, which has a more specific semantical meaning than just .

This together with role attributes can be used to make html better describe subject matter.

Body:
I would use classes as what your doing is adding contextual classification:

<footer class="social">
  <a href="//example.com/share">Share on Example.com!</a>
</footer>

Can be read as its a footer containing social media functions, which has a more specific semantical meaning than just <header>.

This together with role attributes can be used to make html better describe subject matter.


问:
Why don't developers make installation automatic on windows?
This is the inverse to "Why don't developers make installation wizards on linux?", which is interesting, but made me think "Automatic installation is the natural way. Why do they use wizards?".

So here is the inverse question:

I'm sure it's not about laziness, or anything like that, but I fail to understand why developers, of even mainly consumer facing apps, don't make a fully automatic sort of installation where you are not bothered at all. The same apps usually have automatic installation on Linux, so why not Windows and Mac OS?

Is there any technical reason for this trend, or is it just convention?

答:
On the technical side, Windows tends towards greater integration between programs (via the registry) than Linux.  That requires an official 'installation' process rather than just copy the program to your hard drive (for example, to enable context menus).  Some OSs (Mac OS for example) will do some of that behind the scenes or on first run, but Windows prefers to make it an explicit part of installation.

On the non-technical side, Windows prefers the model of set it and forget it.  Linux, for example, tends not to have as much set up (installation options), but often you use flags when you run a program - because you're used to doing so; or you change options once you're in a program.  Windows prefers the experience of set options during a designated time (installation), and not expect a user to use command line flags or otherwise set options each time a program is run. This decreases flexibility (as you can use different flags each time), although often this is exposed for power users (options in a shortcut for example); but provides a simpler interface for most users, and allows the developer to present to users a clean interface for setting the necessary options and defaults.


答:
Use a class.

A class labels the contents on it if you work semantically. That you can use a CSS selector on it is, of course, also good and useful, but in general it describes the role of the element, and that's exactly what you are looking for.

Next to that, people are used to reading class names as semantic data describing the element.

It also reduces duplicate code because you would use a class also for the CSS anyway. Even if you don't need the class in CSS at this moment, it can be good to attach it. That said, it has a real meaning. That will make it possible to change the styles easier without changing classes in the HTML, which is important in bigger teams.

And finally, it makes code more readable in general, because you can simply match the class. That seems (but that's never stable)  to be, performance-wise, a good solution. In terms of code organisation, it makes things much easier to deal with.

Title: Should I mark what blocks mean in data-* attributes?

Body:
I was writing a webpage today with a comment after the start of every major section. Instead of using a comment, which comes with the bulgy  syntax, could I instead put this in a data-* attribute? This would be more for me than anything else, so I don't want to put it in an id or class, but it would also leave it open for userscripts to more easily parse the page.

Examples

My current method:

How To Fix Everything

This is the best magic there is:

Find a problem

FIX IT

Back to step 1

        Share on Example.com!

```

<p>My proposed method:</p>

<pre class="lang-html prettyprint-override"><code><article data-news>
    <header data-headline>
        <h1>How To Fix Everything</h1>
    </header>

    <section data-news-body>
        <p>This is the best magic there is:</p>
        <ol>
            <li>Find a problem</li>
            <li>FIX IT</li>
            <li>Back to step 1</li>
        </ol>
    </section>

    <footer data-social>
        Share on Example.com!
    </footer>
</article>
</code>```


问:
Do compilers un-inline recurrent expressions?
Does a compiler look for recurrent expressions to convert it into 'function' to reduce binary size and improve performance?

Of course, the obvious answer might be "some do it, some don't", so I ask for compiler of mainstream language, let's take for example : Java SDK compiler, GCC compiler and Clang.

If "yes, they do it", is it frequent or in very specific case? (A code example where it actually happens might be very instructive)

答:
They don‘t do it.

What you are looking for is clone detection and automatic code deduplication. There are many tools to discover duplicate code (some quite advanced, see AST based clone detectors) and a good literature about this topic but usually only two cases of duplication are managed by the compiler:

common subexpression elimination

code vectorization

Anyway consider that code duplication is bad for readability/maintainability of source code not necessarily for performance of compiled code.

Some related questions are:

can C compilers deduplicate code?

can C++ compilers automatically eliminate duplicate code?

EDIT

Some linkers can perform the Identical Code Folding (ICF): at link time, ICF detects functions with identical object code and merges them into a single copy.

But

ICF can be unsafe as it can change the run-time behaviour of code that relies on each function having a unique address (C99 guarantees that the addresses of two different functions are not equal; for C++11 it isn't so clear). ICF can be used in a safe mode where it identifies and folds functions whose addresses are guaranteed not to have been used in comparison operations. Further, profiling and debugging binaries with merged functions can be confusing, as the PC values of merged functions cannot be always disambiguated to point to the correct function

this is a somewhat "passive" optimization with a limited scope: mainly useful for C++ templates.


问:
When creating a library, is there a way to make certain classes entirely internal to the library, and not exposed to the user of the library?
Suppose you were designing a Java library for other people to use. You compile the library into a JAR that they can import into their projects and use.

Needless to say, you intend for the library to be used in certain ways and through certain interfaces. For example, you might create several Facade classes to control the library, and in the documentation you state how the library should be used, what every class and method is used for, etc.

But is there a way to hide completely a certain class from the user? In every library there are certain classes (I suppose usually the majority of the classes), that are used internally by the library and are not supposed to be used directly by the code using the library.

Is there a way for me to state "this class is for internal use by this library inside this JAR or inside this package, it cannot be used outside of the boundaries of this library"? Is this technically possible? Or should I just state in the docs that certain libraries shouldn't be used by the user, and that's it?

答:
Use package-private, which is what you get when you specify no access modifier at all. It limits a class or method to only be visible to the package it's in.

```<code>package animals;

public class Animal { ... };

public class Giraffe extends Animal {
    void run() { ... }
    public void jump() { ... }
}

class Platypus extends Animal { ... }
</code>```

Any code that imports the animals package will be able to see the Animal class and the Giraffe class, but not the Platypus class. Additionally, that code will be able to call the Giraffe.jump() method, but not the Giraffe.run() method. However, inside the package, both of Giraffe's methods as well as the Platypus class are visible.

Note that this does not work for nested packages, so you can't have a package-private class in package A be visible to classes in package A.B. This is because nested packages aren't really nested, they're treated by java as two distinct packages and have no special relationship with each other. Packages A and A.B interact no differently than any other two packages would.

Body:
Use package-private, which is what you get when you specify no access modifier at all. It limits a class or method to only be visible to the package it's in.

package animals;

public class Animal { ... };

public class Giraffe extends Animal {
    void run() { ... }
    public void jump() { ... }
}

class Platypus extends Animal { ... }

Any code that imports the animals package will be able to see the Animal class and the Giraffe class, but not the Platypus class. Additionally, that code will be able to call the Giraffe.jump() method, but not the Giraffe.run() method. However, inside the package, both of Giraffe's methods as well as the Platypus class are visible.

Note that this does not work for nested packages, so you can't have a package-private class in package A be visible to classes in package A.B. This is because nested packages aren't really nested, they're treated by java as two distinct packages and have no special relationship with each other. Packages A and A.B interact no differently than any other two packages would.


问:
In the BDD paradigm why should the "ubiquitous language" be merely semi-formal and not completely formal?
Here's the relevant quote:

A common risk with software development includes communication breakdowns between Developers and Business Stakeholders. BDD uses the specification of desired behavior as a ubiquitous language for the project team members. This is the reason that BDD insists on a semi-formal language for behavioral specification: some formality is a requirement for being a ubiquitous language.  In addition, having such a ubiquitous language creates a domain model of specifications, so that specifications may be reasoned about formally.

I'm thinking an actual formal rigorous "language" that has a grammar and compiler could be useful for, say, auto-generating test stubs from specs or for guaranteeing that specs have certain properties (consistently named nouns and verbs, etc.).

In the BDD paradigm, then, why should the "ubiquitous language" be merely semi-formal and not completely formal/rigorous?

答:
The "ubiquitous language" should be semi-formal because you want to have conversations about how the code should behave.

If you make the language formal, you'll end up having more conversations about adhering to the formal language than you will about the behaviour of the code.

I wrote a blog post that illustrates what happens when the concept of formal examples is taken a bit too far. The ability to simply have a conversation, be forgiving about the language used, and sort the rest out later, is key to successful BDD. Here's another blog post on deriving Gherkin from conversations which might also help.


答:
Ben Aaronson's answer is much better than either of my attempts, but I think the main reason is the technique he uses to iterate through the tree, using two Node pointers instead of one, rather than the more object-orientated style. The whole thing can be inlined, which allows a direct comparison with my version and shows that it is indeed more elegant, cleanly separating the tree traversal from the node creation (even if it does still take twice as much code as the C++ version):

```<code>void insert(int k, int v) {
    if (root == null) {
        root = new Node(k, v);
        return;
    }

    Node node = root;
    Node next = root;

    while (next != null) {
        node = next;
        if (k == node.key)
            next = null;
        else
            next = k < node.key ? node.left : node.right;
    }

    if (k == node.key)
        node.val = v;
    else if (k < node.key)
        node.left = new Node(k, v);
    else if (k > node.key)
        node.right = new Node(k, v);
}
</code>```

I do take on board Ben's broader points about the value of using OO principles, and clearly the code is improved further by dividing it into separate methods as he has done.

Body:
Ben Aaronson's answer is much better than either of my attempts, but I think the main reason is the technique he uses to iterate through the tree, using two Node pointers instead of one, rather than the more object-orientated style. The whole thing can be inlined, which allows a direct comparison with my version and shows that it is indeed more elegant, cleanly separating the tree traversal from the node creation (even if it does still take twice as much code as the C++ version):

void insert(int k, int v) {
    if (root == null) {
        root = new Node(k, v);
        return;
    }

    Node node = root;
    Node next = root;

    while (next != null) {
        node = next;
        if (k == node.key)
            next = null;
        else
            next = k < node.key ? node.left : node.right;
    }

    if (k == node.key)
        node.val = v;
    else if (k < node.key)
        node.left = new Node(k, v);
    else if (k > node.key)
        node.right = new Node(k, v);
}

I do take on board Ben's broader points about the value of using OO principles, and clearly the code is improved further by dividing it into separate methods as he has done.


答:
go ahead an formalize the ubiquitous language if it helps describe/define/solve the problem in the chosen domain - that's called a Domain Specific Language

But don't expect business users to write DSL; it's enough if they can read it, to facilitate the conversation described by Lunivore

Title: In the BDD paradigm why should the "ubiquitous language" be merely semi-formal and not completely formal?

Body:
Here's the relevant quote:

A common risk with software development includes communication breakdowns between Developers and Business Stakeholders. BDD uses the specification of desired behavior as a ubiquitous language for the project team members. This is the reason that BDD insists on a semi-formal language for behavioral specification: some formality is a requirement for being a ubiquitous language.  In addition, having such a ubiquitous language creates a domain model of specifications, so that specifications may be reasoned about formally.

I'm thinking an actual formal rigorous "language" that has a grammar and compiler could be useful for, say, auto-generating test stubs from specs or for guaranteeing that specs have certain properties (consistently named nouns and verbs, etc.).

In the BDD paradigm, then, why should the "ubiquitous language" be merely semi-formal and not completely formal/rigorous?


问:
Is there a way to sort code properly into regions dividing methods and events?
I'm using ReSharper and CodeMaid, both have their own "organize" code option but the problem is that i have no idea how to tell them what is an event and what is a method/function that i coded.

If i reorganize code (i want regions) it groups every control event and method together.

Is there a way to tell them what is a method and what is an event? or is there another extension that is specifically better for reorganizing code the way i want?

I want something like this:

```<code>private void button1_click(object sender, EventArgs e){}

private void MyMethod1(){}

private void MyMethod2(){}

private void button2_click(object sender, EventArgs e){}
</code>```

to become:

```<code>#region Events
private void button1_click(object sender, EventArgs e){}

private void button2_click(object sender, EventArgs e){}
#endregion Events

#region Methods
private void MyMethod1(){}

private void MyMethod2(){}
#endregion Methods
</code>```

答:
Regions shouldn't be used. Never.

If you want to organize methods, properties, fields, events, etc., you may be interested in following StyleCop rules and in making StyleCop checking mandatory during every commit.

Also, if you're currently writing code in a basic text editor, you may be interested in moving to Visual Studio, where methods, properties, fields, events, etc. have distinctive icons in Intellisense which make it very easy to recognize visually. Note that Visual Studio Express is free.


答:
Is there a way to sort code properly into regions dividing methods and events?

No.

Is there a way to sort code properly divide methods and events?

Yes.  Follow the resharper guidelines, sorting by accessibility and then alphabetically.  You can then use ctrl+e, ctrl+c (code cleanup) to use resharper to sort them for you.

Body:
I'm using ReSharper and CodeMaid, both have their own "organize" code option but the problem is that i have no idea how to tell them what is an event and what is a method/function that i coded.

If i reorganize code (i want regions) it groups every control event and method together.

Is there a way to tell them what is a method and what is an event? or is there another extension that is specifically better for reorganizing code the way i want?

I want something like this:

```<code>private void button1_click(object sender, EventArgs e){}

private void MyMethod1(){}

private void MyMethod2(){}

private void button2_click(object sender, EventArgs e){}
</code>```

to become:

```<code>#region Events
private void button1_click(object sender, EventArgs e){}

private void button2_click(object sender, EventArgs e){}
#endregion Events

#region Methods
private void MyMethod1(){}

private void MyMethod2(){}
#endregion Methods
</code>```


问:
Is there a set of standards for data validation rules?
I'm trying to develop a generic data validation engine for web forms.  Basically, the idea is to write a library that loads a JSON "validation schema", and then generates the appropriate server-side and client-side validation rules for various data validation libraries.

It seems like everyone has their own set of validation rule names.  For example, suppose you need to check that a string has a minimum number of characters.  In the server-side library Valitron, the rule is called lengthMin.  In the client-side library bootstrapvalidator, it's called stringLength.

My question is, is there any kind of standard out there (ANSI, ISO, etc) for the rule names and parameter names of common data validation rules?

答:
There are no standards for naming conventions by any major working group.  The closest you might get would be standards within an organisation or for a particular product so you are effectively free to choose the names that you feel are best.

Maybe pick the best of some already great implementations (e.g. ActiveRecord Validations / Flask WTF etc.).  You can't go wrong borrowing from them.


问:
Who is a tester?
I don't really understand the concept of testers. I just graduated and before I joined into workplace I thought I'd be pair programming with testers and using TDD where they will be writing tests and I will be passing them or something similar. However that's not the case. Apparently none of them that I have seen knows how to code. A few of them knows using basics of scripting languages, but that's pretty much all.

So essentially what happens is, when I am done with my code, I write tests (unit, integration etc.) for that and then push my code in. I tell tester what it is and what it does, then the tester tests the functionality and approves or asks for further discussion. I really don't see any use of this. I wish I could just tell them what I coded and they would just write the tests.

I also have seen some brilliant software developers being testers at tech companies (Google, Microsoft etc.). Why do these developers want to become testers? Are their developer skills actually being used? If so, by how?

I am so sorry, I am really confused about this whole tester concept (and yes, it's not taught at university). I also have read the question Are programmers bad testers? however it mentions programmers getting involved of manual testing. While I have no doubt that a tester is great at testing a project, I found it a bit unnecessary for them to test a little functionality (ie this button submits a post request to xyz end point and sends these values).

答:
I think the problem here is that you are confusing a particular sub-set of testing "unit test" with the much larger set of tests generally accepted as "testing".

Unit testing is generally done by the programming team themselves. It could be manual but most often using an automated testing framework such as Junit.

Generally speaking the testing team does not care about unit testing there sole job is to test whether the system works to spec. They do not need to know how it was built, what languages frameworks were used etc.etc. to establish whether it works or not.

Testing apart from unit testing falls into several categories:

Smoke test -- start the system and see if it can stay up and running for a day so.

Functional testing -- does the program do what the spec says.

Integration Testing -- does the program play well with the other components in the larger environment.

Non Functional Requirements -- does the program meet any NFRs in the spec (response times, throughput, hardware requirments, memory footprints etc.)

User Acceptance Testing -- Get the real users to use it, confirm that the system is usable, and does what the business sponsors really want.

Its almost impossible to write code without introducing bugs. Worse its almost impossible to specify a module correctly.

So unless your name is "Bill Joy" you are going to introduce bugs when you code. Even if you code precisely to spec the finished module can still be wrong.

All good programmers that I know believe there programs to be full of un-spotted bugs, and know in there hearts that know matter how careful they are they will have done something wrong. Edge cases can be a nightmare to code correctly (should a loop execute n times or n - 1 times). Interface specs can be in-complete and ambiguous; you read the docs but you really don't know whats going to happen when you call the API.

Testing is fundamental to the software development process, if 50% of the projects time is not devoted to testing of various sorts then the code will fail soon after deployment. The failures could be trivial, they could be deeply embarrassing, or, they could be disastrous.

So learn to love your testers! Rejoice when they find a bug, they just saved your ass!

Title: Who is a tester?


问:
5 things before starting a project?
What are the first 5 things you do before starting a new project?

Do you always spend a day researching new frameworks? Or, using similar or competing products?

答:
I'm just going to answer this part of the question, because it's the only part I could relate to:

Do you always spend a day researching new frameworks?

No. I seriously doubt that could even work... How could someone research new frameworks in just one day, before each project, and learn something relevant? It just doesn't happen that way. Instead, I spend parts of my day, every day, researching different technology (not only new frameworks). Research it's not something I do when I need to. It's something I do all the time and that's already there when I need it to be there. Programming is fun, that's why I am in this business. You can't keep me from trying out different stuff every day.

Does a writer spend a day collecting ideas before starting a new book?

Title: 5 things before starting a project?


答:
I write the code and they write the tests...

Sure this happens at some of the top tech companies like google and facebook where they have full time, highly qualified quality engineers that have a programming backgfround such as you describe.

Now to the other 99% of the  ('real') programming world:  Most testers are doing most of their testing by running suites of unit tests, doing manual testing and writing some automated testing, however this is still in its infancy and not usually at the 'per ticket' level.  Often more as smoke tests to allow mocking and stubbing in unit tests.

I would caution at the notion that they are not adding value as manual testers.

(btw I moved from dev. to test after decades of dev. myself.)

Manual testing still uncovers a great deal of issues including:

different usage patterns and approaches

integration issues

different devices

different browsers

different browser versions

different window sizes

usability issues

temporal issues

bandwidth issues in real circumstances

responses to invalid inputs

For your example:  "a bit unnecessary for them to test a little functionality (ie this button submits a post request to xyz end point and sends these values)."

What if they put in different values?

How big is the button on a iPhone?

Does the button have visible text on a Samsung 5 running Anndroid?

Does the button and the button text have contrast to help color-blind users?

Have the developer followed the company standards for font and font size?

What if the network is down when they try to do the send?

What if the button is an image from the CDN and the CDN is down, will it still work?

How is the POST formatted, is it using the new PATCH type and is that accepted on the server?

Title: Who is a tester?

Body:
I don't really understand the concept of testers. I just graduated and before I joined into workplace I thought I'd be pair programming with testers and using TDD where they will be writing tests and I will be passing them or something similar. However that's not the case. Apparently none of them that I have seen knows how to code. A few of them knows using basics of scripting languages, but that's pretty much all.

So essentially what happens is, when I am done with my code, I write tests (unit, integration etc.) for that and then push my code in. I tell tester what it is and what it does, then the tester tests the functionality and approves or asks for further discussion. I really don't see any use of this. I wish I could just tell them what I coded and they would just write the tests.

I also have seen some brilliant software developers being testers at tech companies (Google, Microsoft etc.). Why do these developers want to become testers? Are their developer skills actually being used? If so, by how?

I am so sorry, I am really confused about this whole tester concept (and yes, it's not taught at university). I also have read the question Are programmers bad testers? however it mentions programmers getting involved of manual testing. While I have no doubt that a tester is great at testing a project, I found it a bit unnecessary for them to test a little functionality (ie this button submits a post request to xyz end point and sends these values).


问:
Is my work on a developer test being taken advantage of?
I am looking for a job and have applied to a number of positions. One employer responded. I had a pretty lengthy phone interview (perhaps an hour +) and they then set me up with a developer test. I was told that the test was estimated to take between 6 and 8 hours and that, provided the results met with their approval, I would be paid for my work.

That gave me some pause, but I endeavored. The developer test took place on a VM accessed via RDP. The task was to implement a search page in a web project that requests data from the server, displays it on the screen in a table, has a pretty complicated search filtering scheme (there are about 15 statuses and when sending the search to the server you can search by these statuses) in addition to the string/field search. Additionally, they want SVG icons to change color on certain data values, and some data represented differently than how it's structured in the database.

Loooong story short, this took a heck of a lot longer than 6-8 hours. Much of it was due to the very poor VM that I was running on (Visual Studio 2013 took 10 minutes to load, and another 15 minutes to open the 3 GB ginormous solution).

I was told that after completing the test I should commit my changes to source control...  Hmm, OK. I followed directions. And after committing the changes, I was emailed a response. The SVGs weren't colored right, there was a bug in this edge-case, there was an occasional problem with this other thing that I never experienced, etc. So I am 13-14 hours into this thing now, and I have to do bug fixes. I do them, and the employer comes back with more bug fix requests.

All my work is apparently going into a production application. I noticed a few anomalies in the code where it looked like others had coded all of one functionality but hadn't touched anything else.

Am I just being used for cheap labor? Even if they pay me the promised 50 dollars an hour for 6 hours, I have committed about 18 hours to this thing now. If I bug fix all of the stuff they keep coming up with, I will have worked at least 16 hours for free.

I have taken a number of developer tests, but I have never taken one during which I worked on code destined for production. I have never taken a test where I implemented a feature that was in the pipeline for development, and I have never taken one that took 4 rounds and a total of 20+ hours. I get the impression they are using their developer test to field some of the functionality on the cheap.

Do I have the wrong impression? And is this testing protocol appropriate?

答:
Coding tests are unfortunately a fact of life. That said, it bothers me to be asked to blow four hours on a coding test as a condition of getting my first phone screening. It's unfair to ask a candidate to invest so much when the company has invested so little in the relationship.

I'm a senior developer, and I can pass their coding test. But I won't waste a bunch of time on it unless the company has shown some personal interest in me. I generally don't complete an application to any company with a big, poorly-written online application form that asks me to re-enter my resume so their poorly-written robot can botch the keyword lookup. I generally don't agree to complete a coding test unless it is brief or they are watching it live and talking to me.

Even if they're not putting your code into production, a company that wants you to spend a whole bunch of time typing before you find out if you are even a good fit is a company that is comfortable taking advantage of you. They are signalling what they want their relationship to be; you are the code monkey. They call the shots. And their interview process is designed to find people who are comfortable with that relationship.

Don't be a code monkey. Walk away.


问:
What makes for a bad case for quick sort?
I am learning about quicksort and want to illustrate different arrays that quicksort would have a hard time on. The quicksort I have in mind does not have an initial random shuffling, does 2 partition, and does not compute the median.

I thought up of three examples so far:

```<code>[1,2,3,4,5,6,7,8,9,10] - when the array is sorted
[10,9,8,7,6,5,4,3,2,1] - when the array is reversed
[1,1,1,1,1,1,1,1,1,1] - when the array is the same values
[1,1,1,2,2,2,3,3,3,3] - when there are few and unique keys
</code>```

For instance, I'm not too sure about this one:

```<code>[1,3,5,7,9,10,8,6,4,2]
</code>```

So what makes for an array that quicksort has difficulty with compared to one where it is (nearly) ideal?

答:
Every sort algorithm has a worst case, and in many cases the worst case is really bad so it is worth testing for it. The problem is, there is no single worst case just because you know the basic algorithm.

Common worst cases include: already sorted; sorted in reverse; nearly sorted, one out of order element; all values the same; all the same except first (or last) is higher (or lower). We once had a sort where the worst case was a particular sawtooth pattern, which was very hard to predict but quite common in practice.

The worst case for quicksort is one that gets it to always pick the worst possible pivot, so that one of the partitions has only a single element. If the pivot is the first element (bad choice) then already sorted or inverse sorted data is the worst case. For a median-of-three pivot data that is all the same or just the first or last is different does the trick.

For quicksort the average complexity is nlogn and worst case is n^2. The reason it's worth triggering worst case behaviour is because this is also the case that produces the greatest depth of recursion. For a naive implementation the recursion depth could be n, which may trigger stack overflow. Testing other extreme situations (including best case) may be worthwhile for similar reasons.


问:
Is it possible to make a printable 'template' document?
I'm writing a piece of software to generate and print nametags. The issue I'm having is that nametags need to be formatted the same, but have different values (ie. different names, titles), and can be on different sizes of paper.

So I need an efficient way to store a sort of 'template' that has certain formatting info (alignment, size and location relative to document's dimensions) and has placeholders for values to be substituted in. Then, at runtime, I need to be able to provide the dimensions of the nametag and the field values, to return a printable document.

My current approach is to have a bunch of pre-written HTML documents which have tables and different sizes, and then substituting the cell values with the given information. The problem with this is that HTML tables are really limited on positioning and sizing of elements. Plus, I end up needing to write javascript to resize and translate elements to handle different sizes of paper and really long field values, which limits code reusability as everyone needs to have the same JS or the files will produce different nametags.

Is there a better way to do this? Is there a printable document type that uses relative sizing and positioning for elements, such that if the values are edited the formatting will be preserved?

I would write my own file type (probably an XML structure) but then anyone using these files would have to use additional code to read my document and turn it into something printable.

答:
I wouldn't use HTML, because the printing can be a mess.
A better solution is to build up a PDF. Most of the external libraries are good enough to build your nametags. However, a lot of them don't allow the usage of templates.

What I did for projects:
1) (A quite old version) We had an rtf-File with special placeholders. That was the template. We replaced the placeholders with out data and printed the concatinated file via the standard-application for rtf. Why rtf? It was easy to handle.
2) There are some libraries to process ODF. The allowed us to write the templates in an WYSIWYG-Editor and then we told an headless Libreoffice to produce an PDF out of it. The PDF was printed out and stored for later use.


问:
How should I make progress further as a programmer?
I have just left my college after doing graduation in computer engineering,during my college life I tried to do some freelancing in local market.I succeeded in the last year and earned some small amounts based on joomla,wordpress and visual basic based job.I had some small projects on php,mysql also.
After finishing my undergrad life,I sat for an written test for post of python programmer and luckily I got the job and is working there(Its a small software firm do most of the  task in python).Day by day I have gained some experience with core python.

Meanwhile an USA based web service firm called me for the interview and after finishing three steps(oral+mini coding project+final oral)they selected me(i was wondered!).And I am going to join their with in few days.There I have to work in python(based on Django framework,I know only basic of this framework).

My problem is when I started to work with python simultaneously I worked in Odesk as a wordpress,joomla,drupal,php developer.
Now a days I am feeling that I am getting "Jack of all trades master of none".

My current situation is i am familiar with several popular web technologies but not an expert.I want to make myself skilled.
How should I organize myself to be a skilled web programmer?

答:
I have just left my college...Now a days I am feeling that I am getting "Jack of all trades master of none".

You'll feel like that for about the next five years. And then you'll decide you know too much in one area and yearn to branch out into others.

Welcome to the real world!


问:
What is "presentation logic" and how much is acceptable in views?
In my web application I have to provide a form for creating and editing. The forms for creating and for editing have minor differences, so I am thinking of doing something like this in my view:

```<code><form>
// a lot of htnl goes here
@if (editing)
{
  // some more fields shown in edit mode
}
@if(!editing)
{
 // some stuff shown in create mode
}
</code>```

I have always tried to not put any if statements in my views, but this time I don’t see any other option except copying a huge portion of HTML in two places, which I don’t want to do. Is this proper “presentation logic” and are there any other options?

答:
Presentation logic comprises the logic and calculations that are needed to present the business data in the right way for a particular view.

For complex graphical views, this can be quite complex calculations (for example, calculating the size of each pie slice and the positioning of the labels for a pie chart), but the main characteristic is that it only calculates information that is relevant for the current view and that it doesn't modify the business data in any way.

Whether the selection of fields for edit/create mode is a proper use of presentation logic is debatable. In part it depends on the kind and amount of customization.

For example, if the difference is just a title change, or showing one or two fields as read-only in one of the modes, then it can be the right choice to have one view and select the modes dynamically.

On the other hand, my first reaction was that it should really be two different views, where the common parts are imported from a third file (similar to how commonly the header and footer are added to the views).


问:
In plain English, what is recursion?
The idea of recursion is not very common in real world. So, it seems a bit confusing to the novice programmers. Though, I guess, they become used to the concept gradually. So, what can be a nice explanation for them to grasp the idea easily?</p>

答:
The OP said that recursion doesn't exist in the real world, but I beg to differ.

Let's take the real world 'operation' of cutting up a pizza. You've taken the pizza out of the oven and in order to serve it up you have to cut it in half, then cut those halves in half, then again cut those resultant halves in half.

The operation of cutting the pizza you performing again and again until you've got the result you want (the number of slices). And for arguments sake let's say that an uncut pizza is a slice itself.

Here's an example in Ruby:

```
def cut_pizza(existing_slices, desired_slices)
  if existing_slices != desired_slices
    # we don't have enough slices yet to feed everyone, so
    # we're cutting the pizza slices, thus doubling their number
    new_slices = existing_slices * 2
    # and this here is the recursive call
    cut_pizza(new_slices, desired_slices)
  else
    # we have the desired number of slices, so we return
    # here instead of continuing to recurse
    return existing_slices
  end
end

pizza = 1 # a whole pizza, 'one slice'
cut_pizza(pizza, 8) # => we'll get 8
```

So the real world operation is cutting a pizza, and the recursion is doing the same thing over and over until you have what you want.

Operations you'll find that crop up that you can implement with recursive functions are:

Calculating compound interest over a number of months.

Looking for a file on a file system (because file systems are trees because of directories).

Anything that involves working with trees in general, I guess.

I recommend writing a program to look for a file based on it's file name, and try to write a function that calls itself until it's found, the signature would look like this:

find_file_by_name(file_name_we_are_looking_for, path_to_look_in)

So you could call it like this:

find_file_by_name('httpd.conf', '/etc') # damn it i can never find apache's conf

It's simply programming mechanics in my opinion, a way of cleverly removing duplication. You can rewrite this by using variables, but this is a 'nicer' solution. There is nothing mysterious or difficult about it. You'll write a couple of recursive functions, it'll click and huzzah another mechanical trick in your programming tool box.

Extra Credit The cut_pizza example above will give you a stack level too deep error if you ask it for a number of slices that isn't a power of 2 (i.e 2 or 4 or 8 or 16). Can you modify it so that if someone asks for 10 slices it wont run for ever?

Title: In plain English, what is recursion?

Body:
The OP said that recursion doesn't exist in the real world, but I beg to differ.

Let's take the real world 'operation' of cutting up a pizza. You've taken the pizza out of the oven and in order to serve it up you have to cut it in half, then cut those halves in half, then again cut those resultant halves in half.

The operation of cutting the pizza you performing again and again until you've got the result you want (the number of slices). And for arguments sake let's say that an uncut pizza is a slice itself.

Here's an example in Ruby:

def cut_pizza(existing_slices, desired_slices)
  if existing_slices != desired_slices
    # we don't have enough slices yet to feed everyone, so
    # we're cutting the pizza slices, thus doubling their number
    new_slices = existing_slices * 2
    # and this here is the recursive call
    cut_pizza(new_slices, desired_slices)
  else
    # we have the desired number of slices, so we return
    # here instead of continuing to recurse
    return existing_slices
  end
end

pizza = 1 # a whole pizza, 'one slice'
cut_pizza(pizza, 8) # => we'll get 8

So the real world operation is cutting a pizza, and the recursion is doing the same thing over and over until you have what you want.

Operations you'll find that crop up that you can implement with recursive functions are:

Calculating compound interest over a number of months.

Looking for a file on a file system (because file systems are trees because of directories).

Anything that involves working with trees in general, I guess.

I recommend writing a program to look for a file based on it's file name, and try to write a function that calls itself until it's found, the signature would look like this:

find_file_by_name(file_name_we_are_looking_for, path_to_look_in)

So you could call it like this:

find_file_by_name('httpd.conf', '/etc') # damn it i can never find apache's conf

It's simply programming mechanics in my opinion, a way of cleverly removing duplication. You can rewrite this by using variables, but this is a 'nicer' solution. There is nothing mysterious or difficult about it. You'll write a couple of recursive functions, it'll click and huzzah another mechanical trick in your programming tool box.

Extra Credit The cut_pizza example above will give you a stack level too deep error if you ask it for a number of slices that isn't a power of 2 (i.e 2 or 4 or 8 or 16). Can you modify it so that if someone asks for 10 slices it wont run for ever?

OwnerDisplayName: Ryan Allen

LastEditorDisplayName: Ryan Allen


问:
How to express what do do when error occurs in a user story?
How do you express what to do when error occurs in a user story? Should the response to what happen on errors be in a task of the original user story, or should I create another user story that is concerned with what happens on errors?

E.g.

This says nothing about what to do on errors such as credit card is invalid, not enough money, …

As a buyer I want to pay for the order with a credit card to get immediately access to the services.

I could add another user story like this:

As a buyer I want to get information about errors during payment immediately so that I can fix the errors and try again.

Which of these is common/correct? Should the error handling be part of the original user story?

答:
As most other answers i only use the Happy_path or "main success scenario" for the description of the User_story

After that I add Scenarios that describe differences to Happy_path as alternatives and errors

Example

(a) payment with Creditcard (Successfull)

alternatives:

(b) same as (a) but Creditcard is from a foreign country

errors that cancel the transaction:

(c) same as (a) but Creditcard is Expired


答:
It seems perfectly reasonable to use an @if statement or two in a Razor view.

They added @if to Razor - it's meant to be used.

Your code could be shortened to one @if:

```<code>@if (editing)
{
  // some more fields shown in edit mode
}
else
{
 // some stuff shown in create mode
}
</code>```

An alternative is to use three views:

Partial view containing the common HTML

Create view (calls the partial view)

Edit view (also calls the partial view)

You could check out DisplayTemplates and EditorTemplates, which are a good way of splitting read-only and editable views.

http://www.growingwiththeweb.com/2012/12/aspnet-mvc-display-and-editor-templates.html

Title: What is "presentation logic" and how much is acceptable in views?

Body:
In my web application I have to provide a form for creating and editing. The forms for creating and for editing have minor differences, so I am thinking of doing something like this in my view:

```<code><form>
// a lot of htnl goes here
@if (editing)
{
  // some more fields shown in edit mode
}
@if(!editing)
{
 // some stuff shown in create mode
}
</code>```

I have always tried to not put any if statements in my views, but this time I don’t see any other option except copying a huge portion of HTML in two places, which I don’t want to do. Is this proper “presentation logic” and are there any other options?

Body:
It seems perfectly reasonable to use an @if statement or two in a Razor view.

They added @if to Razor - it's meant to be used.

Your code could be shortened to one @if:

@if (editing)
{
  // some more fields shown in edit mode
}
else
{
 // some stuff shown in create mode
}

An alternative is to use three views:

Partial view containing the common HTML

Create view (calls the partial view)

Edit view (also calls the partial view)

You could check out DisplayTemplates and EditorTemplates, which are a good way of splitting read-only and editable views.

http://www.growingwiththeweb.com/2012/12/aspnet-mvc-display-and-editor-templates.html


答:
The current HTML5 spec (PR) says about custom data attributes (emphasis mine):

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

And the definition of the class attribute contains:

[…] representing the various classes that the element belongs to […]

[…] authors are encouraged to use values that describe the nature of the content […]

So it seems that class is more appropriate than data-* for your use case.

However, it would not be wrong to use custom data attributes instead (or in addition). It’s your understanding of your content that matters, and you might argue that something is or is not a class (as only vaguely defined by the spec).

(CSS doesn’t matter for this decision at all, as you can use both attributes as hooks in your CSS.)

(Side note: Your use of section in this example is most likely wrong. Don’t use it for the "text body" of an article. Only use section here if it represents a sub-section of the parent section, i.e., when you are using sub-headings.)


问:
What do Java developers think of Scala?
I've noted that IDE support is nowhere near as good, but the language itself supports functional programming idioms much more cleanly.</p>

答:
I've been programming Scala for more than one year now, so I'll try to set myself back a year to answer this question.

Scala code is more
concise than Java code (no setter or
getter, a lot of the type information
can be inferred)

The built-in support for XML literal is very appealing.

Java library compatibility and interoperability is great

The support for certain functional idioms is refreshing (for comprehension, closure, lambda functions, map, fold, reduce)

There does not seem to be a cool feature that the language creator did not want to include

The points above were more or less what I thought of Scala before I started to learn it.

In the course of a year, here is what I found out:

Buying the staircase book was a great investment and has saved me hours of learning things on my own

The syntax has some quirks and there was sometimes where I was really puzzled why something was not valid. The trade off is once you're familiar, the code has less clutter and is easier to read. Note that this isn't really an issue if you read rather than write code.

The collection library in 2.8 is a pleasure to use. It's hard to come back to the Java one.

XML literal is nice, but beyond some basic things, I had to reach out to the Java library ecosystem. It's convenient though.

Using Java libraries from Scala is super easy and convenient. Using Scala classes from Java is a bit more tricky, but it works.

I've switched to IntelliJ IDEA community edition and although it's not perfect it's more than good enough.

The language creator really thought about the set of feature and all works really nicely together. The object oriented support is better than in Java (with the traits) and you can do functional programming.

It's a language that apparently some Java developers hate with a passion. For me, it has brought back the joy of programming.

Title: What do Java developers think of Scala?


问:
WebAPI authorisation for other apps
I would like to create a WebAPI application that can serve some of my web sites. My goal is to abstract some common task such as email sending, address resolving etc by providing an API to all of my web sites.

I have created a WebAPI application that implements most of the above APIs but without any authorization. I would like to restrict the access only to my applications.

I could implement identity 2.0 or membership provider but all these are meant to be used from users and not from other web sites. My clients are web sites and not just users.

What would be a good and secure approach to this problem?

答:
If what I assume is correct, you need to mimick what facebook/linkedin/twitter have and create something similar to:

OAuth ("The OAuth 2.0 Authorization Framework", RFC 6749)

What this means is that the client applications need to obtain the required keys to be allowed to access users/user-data from the single login.

The issue with this type of scenario is that it can become quite complex (so hopefully you're working with a team).

Some of the reasons it will become complex:

Building out the internal infrastructure to deal with Authorization and the passing of data to client applications

Security of the login feature (your service will be handling all logins and will need to at least have strong encryption, etc.)

Maintaining an API/documentation that provides all the required information for other developers to use the API to access users/user-data

Another suggestion I might consider is to create a "thin" login functionality that lives below all other applications (basically, it is a single application that is structured in a way where all other applications are built on top of it (it sounds similar to what an API is, but it is different in the sense that the login and client application are more strongly coupled).

The main point you should realize from this is that any solution you find will be "somewhat" complex to implement (based on your exp. and how many are in your team, etc.).

Title: WebAPI authorisation for other apps


问:
Java Modal Object Design
This question is not about a specific program. This is about design - the UML phase of the project.

I am supervising a Java project. It will contain a lot of modal popup dialogs. From a C/C++ standpoint, I have a reference to the main window maintained throughout the program so every dialog may, as necessary, block interactivity with the main dialog. In Java, is there a standard way to do this?

This is a scenario: The main executable owns a JFrame that is the main window. The main executable has an object, I will call it a House. The House has some Room objects. The Room object has a Closet object.

If I want the Closet object to pop up a dialog, blocking input to the main window, do I have to send an instance of the main JFrame to the House, pass it along to each Room, then passing it along to each Closet? Is there a way to say "Give me the top level component"? Or... Is this simply not the way that it is done properly in Java?

答:
Sure, if a data sink in your application's world really is unique, i.e. all messages of some kind originating anywhere in your system should end up there, then there's nothing wrong with having a dedicated instance servicing them all (although it might become a bottleneck with respect to performance or even deadlock).

It's just not customary to hold such a reference in a global variable. Much more often you see a singleton with a getInstance() method, a named entity that every component can look up via some sort of service registry, something invisibly weaved into the program by AOP, or similar mechanisms.

Title: Java Modal Object Design


问:
What is svn cat abbreviating in Subversion?
Subversion offers the svn cat command which retrieves a file as it existed in a particular revision number and displays it.

Sample usage:

```<code>$ svn cat -r 3 http://svn.red-bean.com/repos/test/readme.txt
This is a README file.

INSTRUCTIONS
============

Step 1:  Do this.

Step 2:  Do that.
$
</code>```

I understand what it is doing and how to use it, but I have a difficult time recalling it much of the time since I can't figure out what it is representing/ abbreviating.

Is it just paying homage to our furry feline friends? Does it stand for capture?

答:
It comes from the Unix concatenate command - cat

The cat program is a standard Unix utility that will output the contents of a specific file and can be used to concatenate and list files. The name is an abbreviation of catenate, a synonym of concatenate.


问:
Do Agile projects use abbreviated defect reporting?
I'm accustomed to relatively rigid defect reporting, something like this.

```<code>Steps to reproduce:
1. Access customer manager for user Test01
2. Check "User must change password" and click Apply
3. Access login page
4. Enter user name and password
5. Click Login

Expected results:
6. Site displays user profile page (see use case 21.1.2)

Actual results:
6. Site displays error page (see attached screen shot)
</code>```

I recently joined an Agile project where the defect reports look more like this:

```<code>Can't sign on with user Test01, see screenshots
</code>```

In my many years of development experience, I've found that the longer defect reports serve numerous purposes, e.g. it succinctly communicated the precise problem and avoids any sort of judgmental language, and clearly represents the defect as a departure from a required behavior, rather than allowing the QA engineer to make up defects for behaviors that "seem" wrong.

Agile methodology de-emphasizes the importance of documentation.  Instead we're encouraged to pick up the phone and talk to each other.

Is this a valid application of Agile principles?  Or should defect reports be fairly verbose even when we're trying to be agile?

答:
If encouraging people to frequently interrupt each other just because of plain laziness is considered Agile, then I have to admit that my understanding of Agile is seriously broken.

A sufficient problem description is not a (potentially superfluous) product documentation, rather it is a distinct collection of all facts necessary to efficiently reproduce and solve the issue.

If the description in whatever form is sufficient, fine. If that's not the case, close it as "Not reproducible, reopen if new infomation becomes available" - with one exception:  If you feel the need to investigate because of the potential risks uncovered by the issue, you may consider biting the bullet and follow-up. You don't want (e.g.) a security issue left unfixed just because of a poor description.


问:
Pass Event between Systems in a multi-threaded Entity-Component-System
Is there a way to pass Events between Systems in a multi-threaded Entity-Component-System that realizes the benefits of saving on system resources?

I've read a german article about the Entity-Component-System design-pattern. In this article, the author wrote, that it would be good to let the systems communicate via Events with each other. So, if the CollisionSystem fires an CollisionEvent when an Entity has
collided with another one the SoundSystem can play a sound.

I've implemented that with the Observer-pattern: An EventManager receives events from Systems and notifies all Systems. Then the Systems can look themselves if the want to react on that Event.

By using this Event-based system I can save a lot of computer-power. A System just does anything if it has to do. The author from the article also wrote, that because of that encapsulation from Systems you can put every System in it's own thread.

I tried to implement that behavior, but noticed, that if System A fires an Event and System B reacts on this Event because it's update-Method is called from the EventManager, the action gets called in the Thread of System A.

The only solution which comes to my mind is, to have a loop inside each System which looks in a fixed frequency through a Event-Queue and if it finds an interesting Event it fires the action by itself. In that way I would loose my Observer-Pattern and would not save the computer-power.

答: The observer pattern does not fit here. Observers are being called synchronically, and must finish before the caller may proceed. What you want is the Actor Model - which, like you said, uses event queues. You don't have to do busy waiting though - there are more efficient ways to do it, like making threads wait on the event queues.</p>


问:
Which approach is right doing use case first or classes first ? why?
There are people who prefer to do use cases first and then do the classes, but there are also some who prefer to do class diagram first and then use cases. So is it personal choice for convenience? What are the pros and cons of the above ways?</p>

答:
Use-cases are the description of the problem to solve, therefore, they must come before any other step in the process.

I'd argue that it's not possible to make anything meaningful without knowing the problem.

Use-cases will then determine what you design, whether you make class diagrams before writing any code, however, is personal preference.