问:
Dynamically change of UI on value changes in list box
I have a list box with several elements, let it be web servers (tomcat, iis etc). For each list box value, UI must have different views. For example, if we choose IIS, user name and password fields appear. If we choose tomcat, some additional fields appear depending on user OS - IP and port for linux and path for windows.

My current approach is the following:
- I created two enums. The first one for different OS (windows, linux, mac os x. The second one for servers: iis, nginx, tomcat etc.
- I have a method that returns the OS enum value.
- When user makes a choice, I determine it and basing on this choice I check user's OS. And after it I determine what UI elements to hide/add.

Here's some sort of pseudo-code for what I have:

```<code>//OS enum
public enum OS {
    WINDOWS, LINUX, MAC_OS_X;
}

//Servers enum
public enum SERVERS {
    TOMCAT, IIS, NGINX;
}

//Server Listbox Handler
private void chooseServer() {
        //...get value from list box
        switch(server) {
            case TOMCAT:
                changeUI(getOS()); //getOS() returns OS enum value
                break;
            case IIS:
                //IIS is for windows only
                changeUI(OS.WINDOWS);
                break;
            case NGNIX:
                //Temporary support only linux
                changeUI(OS.LINUX);
                break;
        }
    }

//UI changes here
private void changeUI(OS os) {
        switch (os) {
            case WINDOWS:
                userNameField.setEnabled(true);
                userPasswordField.setEnabled(true);
                ipField.setVisible(false);
                portField.setVisible(false);
                serverPathField.setVisible(true);
                break;
            case LINUX:
                userNameField.setEnabled(true);
                userPasswordField.setEnabled(true);
                ipField.setVisible(true);
                portField.setVisible(true);
                serverPathField.setVisible(false);
                break;
            case MAC_OS_X:
                userNameField.setEnabled(false);
                userPasswordField.setEnabled(false);
                ipField.setVisible(false);
                portField.setVisible(false);
                serverPathField.setVisible(false);
                break;
        }
    }
</code>```

I don't like the moment when other OS or new servers will be added. These switch operators will grow more and become more complicated, I don't speak about maintainability of this code. Are there any standard approaches (patterns) for such tasks that help to avoid switch/if...else grow and to make code more generic, expandable, readable and supportable?

I tried to implement Adapter pattern suggested by Neil and ran at some obscure moment. Here's some pseudo-code:

```<code>public abstract class EditorAdapter {
    protected boolean firstInit = true;
    public abstract void adapt(Panel panel);
}

//--------

public class IISWindowsEditorAdapter extends EditorAdapter {
    @Override
    public void adapt(Panel panel) {
        if(firstInit) {
            firstInit = false;

            panel.add(userNameField);
            //add other elements
        }
    }
}

//--------

public class TomcatEditorAdapter extends EditorAdapter {
    private OS os = getOS();

    @Override
    public void adapt(Panel panel) {
        if(firstInit) {
            firstInit = false;

            if(OS == OS.LINUX) {
                panel.add(userNameField);
                //add other elements
            } else if (OS == OS.WINDOWS) {
                //add elements
            } //... else if
        }
    }
}

//--------

public class Editor extends DialogEditor { //extends Dialog with protected Panel field (subPanel)
    public Editor() {
        initialize();
    }

    public void initialize() {
        //...
        main.add(createPanel()); //protected VerticalPanel main;
        //...
    }

    public void createPanel() {
        //listBox initialization
        commonPanel.add(listBox); //panel with common elements
        listBox.addClickHandler(new ChangeHandler() {
            @Override
            public void onChange(ChangeEvent event) {
                selectServer();
            });
        }
        //... add other common elements
    }

    private void selectServer() {
        //... get selection
        switch(server) {
            //Here something should be done in order to control different layouts.
            //At the moment, each choice adds more elements in addition to existing ones
            //As a variant, one can create class fields for each adapter and manipulate with them using lazy initialization
            case IIS:
                new WindowsEditorAdapter().adapt(subpanel);
                break;
            case TOMCAT:
                new TomcatEditorAdapter().adapt(subpanel);
                break;
        }
    }
}
</code>```

The problem is that I have several tables/panels in my Editor that at the end are added to main panel. In general, it looks like:

we open a dialog

choose web-server

some elements change inside the dialog according to our choice (and some choices are affected with OS user is using).

That's why first UI initialization with adapter doesn't work here. At least I didn't catch how to implement this adapter for logic above.

答:
Note:  Edited to reflect Dragon's modified requirement to make it work upon selection.

A common pattern to generalize this sort of thing is an adapter.  Have an abstract class called GUIAdapter which can tinker with the individual gui aspects of your program according to the settings:

```<code>public abstract class GUIAdapter {
    public abstract void adapt(GUIFrame frame);
    public abstract void remove(GUIFrame frame);
}
</code>```

Then override GUIAdapter with adapters suitable for each type of situation:

```<code>public class WindowsGUIAdapter extends GUIAdapter {
    public void adapt(GUIFrame frame) {
        // Things to do when windows operating system
    }
    public void remove(GUIFrame frame) {
        // Remove trace of WindowsGUIAdapter
    }
}

public class LinuxGUIAdapter extends GUIAdapter {
    public void adapt(GUIFrame frame) {
        // Things to do when linux operating system
    }
    public void remove(GUIFrame frame) {
        // Remove trace of LinuxGUIAdapter
    }
}

public class TomcatGUIAdapter extends GUIAdapter {
    public void adapt(GUIFrame frame) {
        // Things to do when using tomcat server engine
    }
    public void remove(GUIFrame frame) {
        // Remove trace of TomcatGUIAdapter
    }
}

// et cetera ...
</code>```

These adapters have as much or as little control as you let them have over your frame.  When the operating system or server is known, you call "remove" on all existing adapters, add the appropriate adapter for the current selection, and then call "adapt" to apply the configuration for current selection.  I would recommend that you would add a panel to the frame and remove it when "remove" is called.  Keep a reference to JPanel as a private member of your extended class of GUIAdapter in order to be able to remove it easily afterwards.

Notice that I didn't make a WindowsTomcatGUIAdapter.  The idea is that your GUIFrame class (I'll assume that's what it's called) houses a list of adapters which get called to modify the state of the frame according to the selection without knowing how they work.

```<code>public class GUIFrame extends JFrame {
    // Other protected variables here
    private List<GUIAdapter> adapters = new ArrayList<GUIAdapter>();

    private JList serverList, osList;

    private SERVERS selectedServer = null;
    private OS selectedOS = null;

    public GUIFrame() {
        initialize();
    }

    private void initialize() {
        // Do things common to all here

        // Operating system select event
        ListSelectionListener refreshOptionsListener = new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent listSelectionEvent) {
                selectedOS = (OS)osList.getSelectedValue();
                selectedServer = (SERVERS)serverList.getSelectedValue();

                refreshAdapters();
            }
        };

        // Instantiate osList
        osList = new JList();
        // ...
        osList.addListSelectionListener(refreshOptionsListener);

        // Instantiate serverList
        serverList = new JList();
        // ...
        serverList.addListSelectionListener(refreshOptionsListener);
    }

    private void refreshAdapters() {
        for(GUIAdapter adapter : adapters) {
            adapter.remove(this);
        }
        adapters.clear();

        if(os == OS.WINDOWS) {
            adapters.add(new WindowsGUIAdapter());
        } else if (os == OS.LINUX) {
            adapters.add(new LinuxGUIAdapter());
        } // else if () ...

        if(server == SERVERS.TOMCAT) {
            adapters.add(new TomcatGUIAdapter());
        } // else if () ...

        for(GUIAdapter adapter : adapters) {
            adapter.adapt(this);
        }
    }

    // Other class logic here
}
</code>```

Now you've decoupled all logic pertaining to operating system or engine with the classes which perform this logic.  Whenever a new operating system or a new server is selected, current adapters are removed and new adapters are added.  If no operating system or server is selected, then no adapter is added (no condition is met in if/else chain since selectedOS or selectedServer would be null), which is fine.  The frame is not adapted since no adaptation is required as you would expect.

This pattern works well only if server adapters do not really need to know what operating system is being used or inversely, if operating system adapters do not really need to know what server is being used.  However, if you find yourself in that situation, you should create a WindowsTomcatGUIAdapter which deals with just that particular case rather than attempt to make WindowsGUIAdapter and TomcatGUIAdapter work well together (as that would create coupling once again).  Future additions are literally as simple as adding a new class and plugging them in on initialization.

Presumably, you could extend this logic to include validation or whatever other type of logic particular to that particular adapter.

Body:
Note:  Edited to reflect Dragon's modified requirement to make it work upon selection.

A common pattern to generalize this sort of thing is an adapter.  Have an abstract class called GUIAdapter which can tinker with the individual gui aspects of your program according to the settings:

public abstract class GUIAdapter {
    public abstract void adapt(GUIFrame frame);
    public abstract void remove(GUIFrame frame);
}

Then override GUIAdapter with adapters suitable for each type of situation:

public class WindowsGUIAdapter extends GUIAdapter {
    public void adapt(GUIFrame frame) {
        // Things to do when windows operating system
    }
    public void remove(GUIFrame frame) {
        // Remove trace of WindowsGUIAdapter
    }
}

public class LinuxGUIAdapter extends GUIAdapter {
    public void adapt(GUIFrame frame) {
        // Things to do when linux operating system
    }
    public void remove(GUIFrame frame) {
        // Remove trace of LinuxGUIAdapter
    }
}

public class TomcatGUIAdapter extends GUIAdapter {
    public void adapt(GUIFrame frame) {
        // Things to do when using tomcat server engine
    }
    public void remove(GUIFrame frame) {
        // Remove trace of TomcatGUIAdapter
    }
}

// et cetera ...

These adapters have as much or as little control as you let them have over your frame.  When the operating system or server is known, you call "remove" on all existing adapters, add the appropriate adapter for the current selection, and then call "adapt" to apply the configuration for current selection.  I would recommend that you would add a panel to the frame and remove it when "remove" is called.  Keep a reference to JPanel as a private member of your extended class of GUIAdapter in order to be able to remove it easily afterwards.

Notice that I didn't make a WindowsTomcatGUIAdapter.  The idea is that your GUIFrame class (I'll assume that's what it's called) houses a list of adapters which get called to modify the state of the frame according to the selection without knowing how they work.

public class GUIFrame extends JFrame {
    // Other protected variables here
    private List<GUIAdapter> adapters = new ArrayList<GUIAdapter>();

    private JList serverList, osList;

    private SERVERS selectedServer = null;
    private OS selectedOS = null;

    public GUIFrame() {
        initialize();
    }

    private void initialize() {
        // Do things common to all here

        // Operating system select event
        ListSelectionListener refreshOptionsListener = new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent listSelectionEvent) {
                selectedOS = (OS)osList.getSelectedValue();
                selectedServer = (SERVERS)serverList.getSelectedValue();

                refreshAdapters();
            }
        };

        // Instantiate osList
        osList = new JList();
        // ...
        osList.addListSelectionListener(refreshOptionsListener);

        // Instantiate serverList
        serverList = new JList();
        // ...
        serverList.addListSelectionListener(refreshOptionsListener);
    }

    private void refreshAdapters() {
        for(GUIAdapter adapter : adapters) {
            adapter.remove(this);
        }
        adapters.clear();

        if(os == OS.WINDOWS) {
            adapters.add(new WindowsGUIAdapter());
        } else if (os == OS.LINUX) {
            adapters.add(new LinuxGUIAdapter());
        } // else if () ...

        if(server == SERVERS.TOMCAT) {
            adapters.add(new TomcatGUIAdapter());
        } // else if () ...

        for(GUIAdapter adapter : adapters) {
            adapter.adapt(this);
        }
    }

    // Other class logic here
}

Now you've decoupled all logic pertaining to operating system or engine with the classes which perform this logic.  Whenever a new operating system or a new server is selected, current adapters are removed and new adapters are added.  If no operating system or server is selected, then no adapter is added (no condition is met in if/else chain since selectedOS or selectedServer would be null), which is fine.  The frame is not adapted since no adaptation is required as you would expect.

This pattern works well only if server adapters do not really need to know what operating system is being used or inversely, if operating system adapters do not really need to know what server is being used.  However, if you find yourself in that situation, you should create a WindowsTomcatGUIAdapter which deals with just that particular case rather than attempt to make WindowsGUIAdapter and TomcatGUIAdapter work well together (as that would create coupling once again).  Future additions are literally as simple as adding a new class and plugging them in on initialization.

Presumably, you could extend this logic to include validation or whatever other type of logic particular to that particular adapter.


答:
I guess what you are looking for is some kind of decision table. For each possible combination of OS, server and GUI element store a boolean flag indicating the visibility. You could simply utilize a 3 dimensional boolean array (bool[][][] uiVisibility) for that task, indexed by enums indicating the OS, the server and the particular UI element. And you GUI initialization code then will just look like this:

```<code>    userNameField.setEnabled(uiVisibility[osIndex][serverIndex][UIelem.userNameField.getValue()]);
    userPasswordField.setEnabled(uiVisibility[osIndex][serverIndex][UIelem.userPasswordField.getValue()]);
</code>```

As you see - no switch/case any more, and the visibility setting code is in just one place.

Note that it is much more likely that your list of GUI elements will grow than the list of OSs or servers - at least as long as you don't have to distinguish between different OS versions or server versions.

EDIT: if this is the right tool for the job depends. First, a decision table is definitely much better maintainable then to duplicate the same setEnabled code 12 times, with minor modifications between that blocks (note that Neil's suggestion does not solve that problem, it just hides it because he does not show the // Things to do part in his answer)

The key is how you initialize the table. You have different options for that, for example, using standard array initialization. If you have only minor differences between the 12 combinations, there is also the option to create a default initialization for all blocks in the decision table (or a default initilization for each OS) and add some small code writing only that modifications for specific combinations of server/OS.

ContentLicense: CC BY-SA 3.0

Title: Dynamically change of UI on value changes in list box

Body:
I have a list box with several elements, let it be web servers (tomcat, iis etc). For each list box value, UI must have different views. For example, if we choose IIS, user name and password fields appear. If we choose tomcat, some additional fields appear depending on user OS - IP and port for linux and path for windows.

My current approach is the following:
- I created two enums. The first one for different OS (windows, linux, mac os x. The second one for servers: iis, nginx, tomcat etc.
- I have a method that returns the OS enum value.
- When user makes a choice, I determine it and basing on this choice I check user's OS. And after it I determine what UI elements to hide/add.

Here's some sort of pseudo-code for what I have:

```<code>//OS enum
public enum OS {
    WINDOWS, LINUX, MAC_OS_X;
}

//Servers enum
public enum SERVERS {
    TOMCAT, IIS, NGINX;
}

//Server Listbox Handler
private void chooseServer() {
        //...get value from list box
        switch(server) {
            case TOMCAT:
                changeUI(getOS()); //getOS() returns OS enum value
                break;
            case IIS:
                //IIS is for windows only
                changeUI(OS.WINDOWS);
                break;
            case NGNIX:
                //Temporary support only linux
                changeUI(OS.LINUX);
                break;
        }
    }

//UI changes here
private void changeUI(OS os) {
        switch (os) {
            case WINDOWS:
                userNameField.setEnabled(true);
                userPasswordField.setEnabled(true);
                ipField.setVisible(false);
                portField.setVisible(false);
                serverPathField.setVisible(true);
                break;
            case LINUX:
                userNameField.setEnabled(true);
                userPasswordField.setEnabled(true);
                ipField.setVisible(true);
                portField.setVisible(true);
                serverPathField.setVisible(false);
                break;
            case MAC_OS_X:
                userNameField.setEnabled(false);
                userPasswordField.setEnabled(false);
                ipField.setVisible(false);
                portField.setVisible(false);
                serverPathField.setVisible(false);
                break;
        }
    }
</code>```

I don't like the moment when other OS or new servers will be added. These switch operators will grow more and become more complicated, I don't speak about maintainability of this code. Are there any standard approaches (patterns) for such tasks that help to avoid switch/if...else grow and to make code more generic, expandable, readable and supportable?

I tried to implement Adapter pattern suggested by Neil and ran at some obscure moment. Here's some pseudo-code:

```<code>public abstract class EditorAdapter {
    protected boolean firstInit = true;
    public abstract void adapt(Panel panel);
}

//--------

public class IISWindowsEditorAdapter extends EditorAdapter {
    @Override
    public void adapt(Panel panel) {
        if(firstInit) {
            firstInit = false;

            panel.add(userNameField);
            //add other elements
        }
    }
}

//--------

public class TomcatEditorAdapter extends EditorAdapter {
    private OS os = getOS();

    @Override
    public void adapt(Panel panel) {
        if(firstInit) {
            firstInit = false;

            if(OS == OS.LINUX) {
                panel.add(userNameField);
                //add other elements
            } else if (OS == OS.WINDOWS) {
                //add elements
            } //... else if
        }
    }
}

//--------

public class Editor extends DialogEditor { //extends Dialog with protected Panel field (subPanel)
    public Editor() {
        initialize();
    }

    public void initialize() {
        //...
        main.add(createPanel()); //protected VerticalPanel main;
        //...
    }

    public void createPanel() {
        //listBox initialization
        commonPanel.add(listBox); //panel with common elements
        listBox.addClickHandler(new ChangeHandler() {
            @Override
            public void onChange(ChangeEvent event) {
                selectServer();
            });
        }
        //... add other common elements
    }

    private void selectServer() {
        //... get selection
        switch(server) {
            //Here something should be done in order to control different layouts.
            //At the moment, each choice adds more elements in addition to existing ones
            //As a variant, one can create class fields for each adapter and manipulate with them using lazy initialization
            case IIS:
                new WindowsEditorAdapter().adapt(subpanel);
                break;
            case TOMCAT:
                new TomcatEditorAdapter().adapt(subpanel);
                break;
        }
    }
}
</code>```

The problem is that I have several tables/panels in my Editor that at the end are added to main panel. In general, it looks like:

we open a dialog

choose web-server

some elements change inside the dialog according to our choice (and some choices are affected with OS user is using).

That's why first UI initialization with adapter doesn't work here. At least I didn't catch how to implement this adapter for logic above.

Body:
I guess what you are looking for is some kind of decision table. For each possible combination of OS, server and GUI element store a boolean flag indicating the visibility. You could simply utilize a 3 dimensional boolean array (bool[][][] uiVisibility) for that task, indexed by enums indicating the OS, the server and the particular UI element. And you GUI initialization code then will just look like this:

    userNameField.setEnabled(uiVisibility[osIndex][serverIndex][UIelem.userNameField.getValue()]);
    userPasswordField.setEnabled(uiVisibility[osIndex][serverIndex][UIelem.userPasswordField.getValue()]);

As you see - no switch/case any more, and the visibility setting code is in just one place.

Note that it is much more likely that your list of GUI elements will grow than the list of OSs or servers - at least as long as you don't have to distinguish between different OS versions or server versions.

EDIT: if this is the right tool for the job depends. First, a decision table is definitely much better maintainable then to duplicate the same setEnabled code 12 times, with minor modifications between that blocks (note that Neil's suggestion does not solve that problem, it just hides it because he does not show the // Things to do part in his answer)

The key is how you initialize the table. You have different options for that, for example, using standard array initialization. If you have only minor differences between the 12 combinations, there is also the option to create a default initialization for all blocks in the decision table (or a default initilization for each OS) and add some small code writing only that modifications for specific combinations of server/OS.


问:
Forward declaration vs include

Reduce the number of #include files in header files. It will reduce build times. Instead, put include files in source code files and use forward declarations in header files.

I read the quote above here: http://www.yolinux.com/TUTORIALS/LinuxTutorialC++CodingStyle.html.

So, it says if a class (class A) in a header file does not need to use the actual definition of some class (class B). At that time we can use a forward declaration instead of including the particular (class B) header file.

Question: If the class (class A) in the header doesn't use the actual definition of a particular class (class B), Then how can forward declaration help to reduce the compile time?

答:
Remember, C/C++ preprocessor is a separate, purely textual, processing step. The #include directive pulls in the content of the included header and the compiler has to parse it. Moreover, compilation of each .cpp is completely separate, so the fact that the compiler just parsed B.h when compiling B.cpp does not help it the least when it needs it again when compiling A.cpp. And again when compiling C.cpp. And D.cpp. And so on. And each of those files have to be recompiled if any file included in it has changed.

So say class A uses class B and classes C and D use class A, but don't need to manipulate B. If class A can be declared with just forward-declaration of B, than B.h is compiled twice: when compiling B.cpp and A.cpp (because B is still needed inside A's methods).

But when A.h includes B.h, it is compiled four times—when compiling B.cpp, A.cpp, C.cpp and D.cpp as the later two now indirectly include B.h too.

Also when header is included more than once, the preprocessor still has to read it each time. It will skip processing it's content because of the guarding #ifdefs, but it still reads it and needs to search for the end of the guard, which means it has to parse all preprocessor directives inside.

(As mentioned in the other answer, precompiled headers are attempt to work around this, but they are their own can of worms; basically you can reasonably use them for system headers and only if you are not using too many of them, but not for headers in your project)

ContentLicense: CC BY-SA 4.0

Title: Forward declaration vs include


问:
Why do we need "callback functions"?
I am reading the book programming in Lua. It said that

Closures provide a valuable tool in many contexts. As we have seen, they are
  useful as arguments to higher-order functions such as sort. Closures are valuable for functions that build other functions too, like our newCounter example;
  this mechanism allows Lua programs to incorporate sophisticated programming
  techniques from the functional world. Closures are useful for callback functions,
  too. A typical example here occurs when you create buttons in a conventional
  GUI toolkit. Each button has a callback function to be called when the user
  presses the button; you want different buttons to do slightly different things
  when pressed. For instance, a digital calculator needs ten similar buttons, one
  for each digit. Y ou can create each of them with a function like this:

```<code>function digitButton (digit)
  return Button{label = tostring(digit),
                action = function ()
                  add_to_display(digit)
                  end}
end
</code>```

It seems that if I call the digitButton, it will return the action (this will create a closure), so, I can access the digit passed to digitButton.

My question is that:

```<code>Why we need call back functions? what situations can I apply this to?
</code>```

The author said:

In this example, we assume that Button is a toolkit function that creates new
  buttons; label is the button label; and action is the callback closure to be
  called when the button is pressed. The callback can be called a long time after
  digitButton did its task and after the local variable digit went out of scope, but
  it can still access this variable.

according to the author, I think a similar example is like this:

```<code>function Button(t)
  -- maybe you should set the button here
  return t.action -- so that you can call this later
end

function add_to_display(digit)
  print ("Display the button label: " .. tostring(digit))
end

function digitButton(digit)
  return Button{label = tostring(digit),
                action = function ()
                           add_to_display(digit)
                           end}
end

click_action = digitButton(10)
click_action()
</code>```

thus, the callback can be called a long time after digitButton did its task and after the local variable digit went out of scope.

答: No, it will never return the action. The button will execute it when the user clicks on it. And that is the answer. You need callback functions when you want to define actions that should happen in another component in reaction to an event you don't control (the event loop, which is part of the system, will execute a method of the button which will in turn execute the action).

Title: Why do we need "callback functions"?


问:
How do you manage the testing of your Android software on physical devices?
I'm in charge of managing mobile application development at my company, and I am currently building a mobile device "library" for testing. Essentially, we want to have a representative device in-house for each of the OSes we are developing for, currently iOS (iPhone-only), Blackberry, and Android. Simulators only go so far, but I'm placing into the process a step to test software on the devices themselves.

The problem we're finding is with Android. I don't think any of us here ever really understood just how fragmented the whole platform is until we started looking at devices to acquire. We are going to wait until v2.3 of Android is released, but which products to choose? Do we go by the most popular by market share? Do we get a small range of products by specs from least to most powerful overall?

We're trying to avoid having to manage a dozen different devices to test each app, if not because of cost if only for the repeated time sink.

How do you manage the testing of your Android software on physical devices?

UPDATE: To bring some context to what I am asking, the applications being created are for educational purposes only, and there are no plans to use any of the hardware features of the devices themselves. We are simply displaying content in a variety of ways: eBooks, test questions, flash cards, etc. that may or may not be downloadable content. So, no cameras, GPS, user-driven content management, or anything like that; just as device-agnostic as we can possibly make it.

答:
Well, the good thing about Android's code is that you can implement it in so many ways - from a Tablet to a wrist-watch, thus creating a testing group for it a bit complicated.

The way I see it, excluding the version differences for now, there are a few test groups: Tablets, High-End Handsets, Low-End handsets and finally, like the guy above me said - old handset.

I specifically made the distinction between low-end and old since while both might be considered nowadays to be around the same level, old devices would usually run an earlier version of Android which might cause the code to behave quite differently.

There are specialized online services, like Perfecto Mobile or DA that gives you RDA access to real devices (as opposed to emulators, which like you said - only goes so far) without having to physically own them.

Perfecto offers a free hour-long demo on their website (http://www.perfectomobile.com), and I think this might exactly suit your needs.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Joshua Shooman


问:
How do I Integrate a Former Team Member into the Current Team
Is it possible to re-integrate a former team member into a software project?

We have a  product with a looming customer deadline and we don't have enough hours to get it done!  We have a former employee who left on excellent terms and wants to come back.  They are familiar with the codebase and architecture (which has not changed significantly since they left).

Can we use this situation to avoid Brooks Law?

It seems like an ideal situation, team member up to speed with processes, tools, etc. What do we need to be careful of?  Are there any dragons in the water?  Or should we expect smooth sailing?

答:
If you're worried about other team members resenting the return of this person (you mentioned that in a comment), what alternatives have they offered? Does everyone agree that you are not going to make your deadline unless you do something? At this point, I'm not sure I could tollerate complainers.

How affective this person is depends on how long they were away from the project. Technically they left the company, but leaving for one month is just a lengthy vacation.

Make sure the new person is informed about changes you made since they were there last. Maybe he favored using framework X and you switched to Y. This person needs to understand that you need to meet a deadline, so there is no time for a lot of debate. Like everyone else, he needs to focus on the task at hand and not lament over how much easier this project would be if he could only use X.


问:
Generating random math expression
I have this idea running around in my head, to generate and evaluate random mathematical expressions. So, I decided to give it a shot and elaborate an algorithm, before coding it to test it.

Example:

Here are some example expressions I want to generate randomly:

```<code>4 + 2                           [easy]
3 * 6 - 7 + 2                   [medium]
6 * 2 + (5 - 3) * 3 - 8         [hard]
(3 + 4) + 7 * 2 - 1 - 9         [hard]
5 - 2 + 4 * (8 - (5 + 1)) + 9   [harder]
(8 - 1 + 3) * 6 - ((3 + 7) * 2) [harder]
</code>```

The easy and medium ones are pretty straight-forward. Random ints separated by random operators, nothing crazy here. But I'm having some trouble getting started with something that could create one of the hard and harder examples. I'm not even sure a single algorithm could give me the last two.

What I am considering:

I can't say I tried those ideas, because I didn't really want to waste much time going in a direction that had no chance of working in the first place. But still, I thought of a couple solutions:

Using trees

Using regular expressions

Using a crazy "for-type" loop (surely the worst)

What I'm looking for:

I'd like to know which way you believe is the best to go, between the solutions I considered, and your own ideas.

If you see a good way to start, I'd appreciate a lead in the right direction, e.g. with the beginning of the algorithm, or a general structure of it.

Also note that I will have to evaluate those expressions. This can be done either after the expression is generated, or during its creation. If you take that in consideration in your answer, that's great.

I'm not looking for anything language-related, but for the record, I'm thinking of implementing it in Objective-C, as that's the language I'm most working with recently.

Those examples did not include the : operator, as I only want to manipulate ints, and this operator adds many verifications. If your answer gives a solution handling this one, that's great.

If my question needs any clarification, please ask in the comments. Thanks for your help.

答:
Here's a slightly different take on Blubb's excellent answer:

What you're trying to build here is essentially a parser that operates in reverse.  What your problem and a parser have in common is a context-free grammar, this one in Backus-Naur form:

```<code>digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
number ::= <digit> | <digit> <number>
op ::= '+' | '-' | '*' | '/'
expr ::= <number> <op> <number> | '(' <expr> ')' | '(' <expr> <op> <expr> ')'
</code>```

Parsers start with a stream of terminals (literal tokens like 5 or *) and try to assemble them into nonterminals (things composed of terminals and other nonterminals, such as number or op).  Your problem starts with nonterminals and works in reverse, picking anything between the "or" (pipe) symbols at random when one is encountered and recursively repeating the process until reaching a terminal.

A couple of the other answers have suggested that this is a tree problem, which it is for a certain narrow class of cases where there are no nonterminals that reference themselves directly or indirectly through another nonterminal.  Since grammars allow that, this problem is really a directed graph.  (Indirect references through another nonterminals count toward this as well.)

There was a program called Spew published on Usenet in the late 1980s which was originally designed to generate random tabloid headlines and also happens to be a great vehicle for experimenting with these "reverse grammars."  It operates by reading a template that directs the production of a random stream of terminals.  Beyond its amusement value (headlines, country songs, pronounceable English gibberish), I've written numerous templates that are useful for generating test data that's ranged from plain text to XML to syntactically-correct-but-uncompilable C.  Despite being 26 years old and written in K&R C and having an ugly template format, it compiles just fine and works as advertised.  I whipped up a template that solves your problem and posted it on pastebin since adding that much text here doesn't seem appropriate.

Title: Generating random math expression

Body:
Here's a slightly different take on Blubb's excellent answer:

What you're trying to build here is essentially a parser that operates in reverse.  What your problem and a parser have in common is a context-free grammar, this one in Backus-Naur form:

digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
number ::= <digit> | <digit> <number>
op ::= '+' | '-' | '*' | '/'
expr ::= <number> <op> <number> | '(' <expr> ')' | '(' <expr> <op> <expr> ')'

Parsers start with a stream of terminals (literal tokens like 5 or *) and try to assemble them into nonterminals (things composed of terminals and other nonterminals, such as number or op).  Your problem starts with nonterminals and works in reverse, picking anything between the "or" (pipe) symbols at random when one is encountered and recursively repeating the process until reaching a terminal.

A couple of the other answers have suggested that this is a tree problem, which it is for a certain narrow class of cases where there are no nonterminals that reference themselves directly or indirectly through another nonterminal.  Since grammars allow that, this problem is really a directed graph.  (Indirect references through another nonterminals count toward this as well.)

There was a program called Spew published on Usenet in the late 1980s which was originally designed to generate random tabloid headlines and also happens to be a great vehicle for experimenting with these "reverse grammars."  It operates by reading a template that directs the production of a random stream of terminals.  Beyond its amusement value (headlines, country songs, pronounceable English gibberish), I've written numerous templates that are useful for generating test data that's ranged from plain text to XML to syntactically-correct-but-uncompilable C.  Despite being 26 years old and written in K&R C and having an ugly template format, it compiles just fine and works as advertised.  I whipped up a template that solves your problem and posted it on pastebin since adding that much text here doesn't seem appropriate.


答:
To expand on the tree approach, let's say each node is either a leaf or a binary expression:

```<code>Node := Leaf | Node Operator Node
</code>```

Note that a leaf is just a randomly-generated integer here.

Now, we can randomly generate a tree. Deciding the probability of each node being a leaf allows us to control the expected depth, although you might want an absolute max depth as well:

```<code>Node random_tree(leaf_prob, max_depth)
    if (max_depth == 0 || random() > leaf_prob)
        return random_leaf()

    LHS = random_tree(leaf_prob, max_depth-1)
    RHS = random_tree(leaf_prob, max_depth-1)
    return Node(LHS, RHS, random_operator())
</code>```

Then, the simplest rule for printing the tree is to wrap () around each non-leaf expression and avoid worrying about operator precedence.

For example, if I parenthesize your last sample expression:

```<code>(8 - 1 + 3) * 6 - ((3 + 7) * 2)
((((8 - 1) + 3) * 6) - ((3 + 7) * 2))
</code>```

you can read off the tree that would generate it:

```<code>                    SUB
                  /      \
               MUL        MUL
             /     6     /   2
          ADD          ADD
         /   3        3   7
       SUB
      8   1
</code>```

Title: Generating random math expression

Body:
I have this idea running around in my head, to generate and evaluate random mathematical expressions. So, I decided to give it a shot and elaborate an algorithm, before coding it to test it.

Example:

Here are some example expressions I want to generate randomly:

```<code>4 + 2                           [easy]
3 * 6 - 7 + 2                   [medium]
6 * 2 + (5 - 3) * 3 - 8         [hard]
(3 + 4) + 7 * 2 - 1 - 9         [hard]
5 - 2 + 4 * (8 - (5 + 1)) + 9   [harder]
(8 - 1 + 3) * 6 - ((3 + 7) * 2) [harder]
</code>```

The easy and medium ones are pretty straight-forward. Random ints separated by random operators, nothing crazy here. But I'm having some trouble getting started with something that could create one of the hard and harder examples. I'm not even sure a single algorithm could give me the last two.

What I am considering:

I can't say I tried those ideas, because I didn't really want to waste much time going in a direction that had no chance of working in the first place. But still, I thought of a couple solutions:

Using trees

Using regular expressions

Using a crazy "for-type" loop (surely the worst)

What I'm looking for:

I'd like to know which way you believe is the best to go, between the solutions I considered, and your own ideas.

If you see a good way to start, I'd appreciate a lead in the right direction, e.g. with the beginning of the algorithm, or a general structure of it.

Also note that I will have to evaluate those expressions. This can be done either after the expression is generated, or during its creation. If you take that in consideration in your answer, that's great.

I'm not looking for anything language-related, but for the record, I'm thinking of implementing it in Objective-C, as that's the language I'm most working with recently.

Those examples did not include the : operator, as I only want to manipulate ints, and this operator adds many verifications. If your answer gives a solution handling this one, that's great.

If my question needs any clarification, please ask in the comments. Thanks for your help.

Body:
To expand on the tree approach, let's say each node is either a leaf or a binary expression:

Node := Leaf | Node Operator Node

Note that a leaf is just a randomly-generated integer here.

Now, we can randomly generate a tree. Deciding the probability of each node being a leaf allows us to control the expected depth, although you might want an absolute max depth as well:

Node random_tree(leaf_prob, max_depth)
    if (max_depth == 0 || random() > leaf_prob)
        return random_leaf()

    LHS = random_tree(leaf_prob, max_depth-1)
    RHS = random_tree(leaf_prob, max_depth-1)
    return Node(LHS, RHS, random_operator())

Then, the simplest rule for printing the tree is to wrap () around each non-leaf expression and avoid worrying about operator precedence.

For example, if I parenthesize your last sample expression:

(8 - 1 + 3) * 6 - ((3 + 7) * 2)
((((8 - 1) + 3) * 6) - ((3 + 7) * 2))

you can read off the tree that would generate it:

                    SUB
                  /      \
               MUL        MUL
             /     6     /   2
          ADD          ADD
         /   3        3   7
       SUB
      8   1


答:
You asked the question

Why we need "call back functions"?

I will try to answer it in a concise and clear manner (if I fail at that, please refer to the wiki link at the bottom of this answer).

Callbacks are used to defer the specific implementation of something to the last possible moment.

The button example is a good illustration of this. Say you want to have a button in your application that prints a page to the printer, we could imagine a world where you would have to code an entire new PrinterButton class in order to do this.

Luckily, we have the notion of callbacks (inheritence and the use of the template pattern is also a kind of callback semantic) so we do not need to do that.

Instead of re-implementing every aspect of a button, what we do is to add to the implementation of the button. The Button has the concept of doing something when it's pressed. We simply tell it what that something is.

That mechanism of injecting behavior into frameworks is called callbacks.

Example:

Let's inject some behavior into an HTML button:

```<code><button onclick="print()">Print page through a callback to the print() method</button>
</code>```

In this instance, onclick points to a callback, which for this example is the print() method.

http://en.wikipedia.org/wiki/Callback_(computer_programming)

Title: Why do we need "callback functions"?

Body:
I am reading the book programming in Lua. It said that

Closures provide a valuable tool in many contexts. As we have seen, they are
  useful as arguments to higher-order functions such as sort. Closures are valuable for functions that build other functions too, like our newCounter example;
  this mechanism allows Lua programs to incorporate sophisticated programming
  techniques from the functional world. Closures are useful for callback functions,
  too. A typical example here occurs when you create buttons in a conventional
  GUI toolkit. Each button has a callback function to be called when the user
  presses the button; you want different buttons to do slightly different things
  when pressed. For instance, a digital calculator needs ten similar buttons, one
  for each digit. Y ou can create each of them with a function like this:

```<code>function digitButton (digit)
  return Button{label = tostring(digit),
                action = function ()
                  add_to_display(digit)
                  end}
end
</code>```

It seems that if I call the digitButton, it will return the action (this will create a closure), so, I can access the digit passed to digitButton.

My question is that:

```<code>Why we need call back functions? what situations can I apply this to?
</code>```

The author said:

In this example, we assume that Button is a toolkit function that creates new
  buttons; label is the button label; and action is the callback closure to be
  called when the button is pressed. The callback can be called a long time after
  digitButton did its task and after the local variable digit went out of scope, but
  it can still access this variable.

according to the author, I think a similar example is like this:

```<code>function Button(t)
  -- maybe you should set the button here
  return t.action -- so that you can call this later
end

function add_to_display(digit)
  print ("Display the button label: " .. tostring(digit))
end

function digitButton(digit)
  return Button{label = tostring(digit),
                action = function ()
                           add_to_display(digit)
                           end}
end

click_action = digitButton(10)
click_action()
</code>```

thus, the callback can be called a long time after digitButton did its task and after the local variable digit went out of scope.

Body:
You asked the question

Why we need "call back functions"?

I will try to answer it in a concise and clear manner (if I fail at that, please refer to the wiki link at the bottom of this answer).

Callbacks are used to defer the specific implementation of something to the last possible moment.

The button example is a good illustration of this. Say you want to have a button in your application that prints a page to the printer, we could imagine a world where you would have to code an entire new PrinterButton class in order to do this.

Luckily, we have the notion of callbacks (inheritence and the use of the template pattern is also a kind of callback semantic) so we do not need to do that.

Instead of re-implementing every aspect of a button, what we do is to add to the implementation of the button. The Button has the concept of doing something when it's pressed. We simply tell it what that something is.

That mechanism of injecting behavior into frameworks is called callbacks.

Example:

Let's inject some behavior into an HTML button:

<button onclick="print()">Print page through a callback to the print() method</button>

In this instance, onclick points to a callback, which for this example is the print() method.

http://en.wikipedia.org/wiki/Callback_(computer_programming)


答:
I think a better example for the use of callbacks is in asynchronous functions. I can't speak for Lua, but in JavaScript, one of the most common asynchronous action is contacting a server via AJAX.

The AJAX call is asynchronous, meaning if you do something like this:

```<code>var ajax = ajaxCall();
if(ajax == true) {
  // Do something
}
</code>```

the contents of the if block will not reliably run correctly, and when it does, it's only because the ajaxCall() function happened to finish before the execution reached the if statement.

However, callbacks eliminate this issue, by ensuring the asynchronous call is finished before calling the required function. So, your code would change to something like this:

```<code>function ajaxCallback(response) {
  if(response == true) {
    // Do something
  }
}

ajaxCall(ajaxCallback);
</code>```

The purpose of this is to allow you to do things like gather data, without interfering with other things, such as drawing the interface. If the data gathering was synchronous, then the interface would become unresponsive as the application waited to get the data. An unresponsive interface is very bad for user experience, because most users will think the application has "crashed" and will try to terminate the process.

To see this in action, you just need to look at any website that does any kind of updating without reloading the whole page. Twitter, LinkedIn, and the StackExchange sites are good examples. Twitter's "endless scrolling" of feeds, and SE's notifications (for both user notifications, and notifications that a question has new activity), are powered by asynchronous calls. When you see a spinner somewhere, that means that section has made an asynchronous call, and is waiting for that call to finish, but you can interact with other things on the interface (and even make other asynchronous calls). Once that call finishes, it will react and update the interface accordingly.

Title: Why do we need "callback functions"?

Body:
I think a better example for the use of callbacks is in asynchronous functions. I can't speak for Lua, but in JavaScript, one of the most common asynchronous action is contacting a server via AJAX.

The AJAX call is asynchronous, meaning if you do something like this:

var ajax = ajaxCall();
if(ajax == true) {
  // Do something
}

the contents of the if block will not reliably run correctly, and when it does, it's only because the ajaxCall() function happened to finish before the execution reached the if statement.

However, callbacks eliminate this issue, by ensuring the asynchronous call is finished before calling the required function. So, your code would change to something like this:

function ajaxCallback(response) {
  if(response == true) {
    // Do something
  }
}

ajaxCall(ajaxCallback);

The purpose of this is to allow you to do things like gather data, without interfering with other things, such as drawing the interface. If the data gathering was synchronous, then the interface would become unresponsive as the application waited to get the data. An unresponsive interface is very bad for user experience, because most users will think the application has "crashed" and will try to terminate the process.

To see this in action, you just need to look at any website that does any kind of updating without reloading the whole page. Twitter, LinkedIn, and the StackExchange sites are good examples. Twitter's "endless scrolling" of feeds, and SE's notifications (for both user notifications, and notifications that a question has new activity), are powered by asynchronous calls. When you see a spinner somewhere, that means that section has made an asynchronous call, and is waiting for that call to finish, but you can interact with other things on the interface (and even make other asynchronous calls). Once that call finishes, it will react and update the interface accordingly.


答:
Why we need call back functions? what situations can I apply this to?

Callback functions are very useful in event-driven programming. They allow you to set up your program in such a way that events will trigger the correct code. This is very common in programs with GUIs where users can click on any element on the UI (such as buttons or menu items) and the appropriate code will be run.

Title: Why do we need "callback functions"?


答:
Guy 1 to Guy 2: hey dude I wanna do something when a user clicks in there, call me back when that happens alright?

Guy 2 calls back Guy 1 when a user clicks here.

Title: Why do we need "callback functions"?


问:
Approach to simplifying an algorithm
For completely random reasons*, I wrote some code that calculates and displays the following expression:

P=1*(2+2)(3+3+3)(4+4+4+4)..(n+n...…

Which is equivalent to (n!)^2

The version I wrote (listed below the line) isn't terribly efficient; especially not in how it calculates the inner product.

How should I go about simplifying the algorithm so it will operate faster and be more easily understood?

And yes, I know I should use something other than int for the variables.  That aspect of my code isn't as interesting as re-working the algorithmic approach.

* In the spirit of full disclosure this off-topic question sparked my working on the code

int sequence(int n)
{
  int i, accum, prod, j;

  accum = 1;
  for (i = 2 .. n)
  {
    prod = i;
    for (j = 1 .. i-1)
    {
      prod += i;
    }
    accum *= prod;
  }
  return accum;
}
```

答:
Can't you just square i in the inner loop, rather than multiplying-by-adding?

EDIT: It ain't rocket science.

```<code>(3 + 3 + 3)
</code>```

equals

```<code>3 * 3
</code>```

It's not clear what you mean by "improving the algorithm".

FURTHER EDIT: Since you clarified the question, let me try to answer it. Let me make a distinction between 1) algorithms (1-page programs), and 2) programs (1000 LOC and up).

Algorithms. First get familiar with searching, sorting, and big-O. The way these work is by executing a series of decision points. At each decision point, ask what is the probability of taking each branch of the decision. If those probabilities are very much unequal, cycles are being wasted, big time. So if your inner loop is basically for(i=0; i<n; i++) what's the probability that i<n? Almost always almost 1, right? That's a red flag. So the difference between, say, linear search and binary search, is whether or not the probabilities are very different or almost the same at each decision point.

Programs. This is a very different subject. Here the issue is that due to the way you or I or someone else designed the program, it contains dumb stuff that you would never guess is in there. The bigger the program, the more dumb stuff is hiding in it. The way to clean it out is to expose the biggest stuff first. I do it by random pausing, as in this example. It is a 3rd cousin to profiling. People will tell you "use a profiler", but what they won't tell you is how much speedup they got that way. That example shows a 43-times speedup. The secret is after you find and fix the first problem, find and fix the second, and so on until you truly can't find any more. What happens is after you fix each problem, the remaining ones become larger as a percentage, because the total time has become smaller. In this way, you can keep squeezing it until you've got it down to the absolute bare minimum.

Title: Approach to simplifying an algorithm

Body:
Can't you just square i in the inner loop, rather than multiplying-by-adding?

EDIT: It ain't rocket science.

(3 + 3 + 3)

equals

3 * 3

It's not clear what you mean by "improving the algorithm".

FURTHER EDIT: Since you clarified the question, let me try to answer it. Let me make a distinction between 1) algorithms (1-page programs), and 2) programs (1000 LOC and up).

Algorithms. First get familiar with searching, sorting, and big-O. The way these work is by executing a series of decision points. At each decision point, ask what is the probability of taking each branch of the decision. If those probabilities are very much unequal, cycles are being wasted, big time. So if your inner loop is basically for(i=0; i<n; i++) what's the probability that i<n? Almost always almost 1, right? That's a red flag. So the difference between, say, linear search and binary search, is whether or not the probabilities are very different or almost the same at each decision point.

Programs. This is a very different subject. Here the issue is that due to the way you or I or someone else designed the program, it contains dumb stuff that you would never guess is in there. The bigger the program, the more dumb stuff is hiding in it. The way to clean it out is to expose the biggest stuff first. I do it by random pausing, as in this example. It is a 3rd cousin to profiling. People will tell you "use a profiler", but what they won't tell you is how much speedup they got that way. That example shows a 43-times speedup. The secret is after you find and fix the first problem, find and fix the second, and so on until you truly can't find any more. What happens is after you fix each problem, the remaining ones become larger as a percentage, because the total time has become smaller. In this way, you can keep squeezing it until you've got it down to the absolute bare minimum.


答:
It seems to me you have answered your own question.

n! is an O(n) operation.  n^2 (square) is O(1).

Why not calculate the factorial, and then square it, as implied by your (n!)^2 remark?

Title: Approach to simplifying an algorithm

Body:
For completely random reasons*, I wrote some code that calculates and displays the following expression:

P=1*(2+2)(3+3+3)(4+4+4+4)..(n+n...…

Which is equivalent to (n!)^2

The version I wrote (listed below the line) isn't terribly efficient; especially not in how it calculates the inner product.

How should I go about simplifying the algorithm so it will operate faster and be more easily understood?

And yes, I know I should use something other than int for the variables.  That aspect of my code isn't as interesting as re-working the algorithmic approach.

* In the spirit of full disclosure this off-topic question sparked my working on the code

int sequence(int n)
{
  int i, accum, prod, j;

  accum = 1;
  for (i = 2 .. n)
  {
    prod = i;
    for (j = 1 .. i-1)
    {
      prod += i;
    }
    accum *= prod;
  }
  return accum;
}
```


问:
What differentiates the exceptional programmers from the really good ones?
You know who they are.  They are the rock stars of programming:

They code 10X
faster.

Their code just works.

They not only know their primary
language inside and out, but they
also know how it works under the
hood.

They know the answer to most any
question before you ask it.

A few of them invented the programming
principles we all use.

And they tend to be
uncharacteristically humble, as well.

What is it about these folks?  Is there something about their thought process that is fundamentally different from the above-average programmer?  Or are they simply very talented people that work hard?

To put it another way: How can I be like them?  I know what I think I need to learn to be that good, but it seems like it will take me the next ten years to learn it, and then my knowledge will be obsolete.

答:
Few things differentiate an exceptional with a typical.

Exceptional:

Highly passionate about his work and strive to deliver a master-piece.

Performance and quality is the big picture in their mind even before coding starts.

They think of continuous improvement after each release.

They keep strict vigil on the alternatives and are early adopters.

Their theme in professional life is: "Write less convey more".

They keep thinking about logical perspectives even when not coding.

Typical

Sometimes somewhat passionate but strive to deliver because it is a job after all. If it is not a masterpiece, its OK. At least delivered on time.

Will think of the performance later, anyway PCs are fast enough these days.

Improve only when there is no option left to save a job.

No time to dig into other technologies. Stick to what your job demands now. Will learn other things when the need arises.

Their theme is: "Do what is asked and reach home in time".


答:
blubb's answer is a good start, but his formal grammar creates too many parantheses.

Here's my take on it:

```<code>E -> I
E -> M '*' M
E -> E '+' E
M -> I
M -> M '*' M
M -> '(' E '+' E ')'
</code>```

E is an expression, I an integer and M is an expression that is an argument for a multiplication operation.

Title: Generating random math expression

Body:
blubb's answer is a good start, but his formal grammar creates too many parantheses.

Here's my take on it:

E -> I
E -> M '*' M
E -> E '+' E
M -> I
M -> M '*' M
M -> '(' E '+' E ')'

E is an expression, I an integer and M is an expression that is an argument for a multiplication operation.


问:
Should I re-download my server data after each change?
I have a simple DB editor that sits on the client. When I make changes via the editor, should I re-get all my data, as some of it is changed, or can I just do a check to make sure the procedure ran without error and assume my data is the same as the server?</p>

答:
Your question lacks a bit of detail, but I think the answer is still that you have to re-get your data.  For instance:

Some of your data might be computed columns, which depend on the data you changed, and that formula is on the server, not the client.

There are database triggers you have to take into account, which can modify data on or after an update or insert.

The stored procedure might not actually do an update, or might do something unexpected with the data.

In systems supporting optimistic concurrency, your update might fail if someone else has already updated the data in the mean time.  In that case you would want to show the changed values.


答:
If there were an algorithm that could optimize algorithms, we programmers would all be out of a job.   However, we already perform small optimizations in compilers.  Small optimizations can be made which do not change the intended meaning of the operation, however our limitation is precisely that:  intended meaning.  For instance, if we knew that a number is always positive, we could replace multiplication by 2 with bit shifting.  However, when we are left with signed integers, even if they are used purely for positive numbers, the compiler cannot make these sorts of assumptions.

The real trick is understanding what the algorithm is supposed to do.  If you understand that, then you realize that an algorithm is not about the steps it takes but about the end result.  Without this, there is very little hope to improve on an algorithm.  For example, if you give your friend instructions for getting to your house and you don't see the bigger picture, you may never realize that you made your friend take a longer route to get there.

So how do you define the context of an algorithm?  It boils down to input and output.  If you can make mathematical assumptions on the input and describe the expected assumptions on the output, then an algorithm is simply a mathematical proof in its purest form, describing all the steps you'd need to perform in order to guarantee that for the given input, you receive the expected output.

Each step is transformed into an equivalent mathematical transformation (for instance, performing a loop which accumulates values could be thought of as a sum operation).  Once you have this, you can not only begin to prove soundness and correctness but you can also simplify much like you would combine like terms in a mathematical formula.

Of course this is all very theoretical and ongoing, but the idea is that we can one day write compilers which can not only tell you that your algorithm won't work as expected, but also on what line and how to fix it as well as any optimizations which can be made to improve performance (this would likely be done upon automatically).

Unfortunately we are not yet at this stage, but I hope to see it sometime in my lifetime anyway.  I hope that answers your question.

Title: Approach to simplifying an algorithm


问:
What is a development stack?
I am just now in the process of looking for jobs as I am about to graduate from college. An interviewer asked me what my current 'development stack' is?

I know this is probably a really basic question. but could someone explain to me what a 'development stack' is? It isn't a term that gets used in school.

答:
It simply means the set of languages, libraries, IDEs and tools (including OS, database server and application server) used for application development.

For example, people may refer to the LAMP stack, meaning Linux/Unix + Apache + MySQL + PHP/Perl.

Other stacks are the Microsoft Stack (Windows + IIS + SQL Server + C#/VB.NET).

Title: What is a development stack?


问:
Getting into Guava
So I recently started using Netty for my applications client/server communication and I discovered I loved the idea of listenable Futures. I wondered why I didn't know about Java being able to do this, and, sure enough, it cannot.

After some searching I realized that this is a feature provided by Guava's concurrency tools, which got me skimming through it's user guide. It seems awesome, but I have some concerns:

I already have a decent amount of code that uses JDK concurrency. How hard will it be to migrate over?

What is the risk of starting to become a "Guava programmer" so to speak? How difficult will it be to bounce back and forth between doing things the Guava way and the core Java way?

What potential harm could there be if, in an existing project, I write new classes with Guava classes without migrating the rest of the code over?

Is there a good guide for slowly beginning to use Guava features without having to stop doing my actual job to train myself for a few days/weeks?

Is there anything else I should know in advance that I haven't already thought of?

答:
I think the underlying issue you have is that you're thinking of Guava as if it's an entire framework or DSL (domain-specific language).  Guava is another library like Apache Commons where it provides common abstractions, data structures and convenience methods complementary to the JDK libraries.

Answers to your questions:

If your code is designed well, it shouldn't be difficult to use Guava's concurrency library.

No risk of being a "Guava programmer", as I mentioned, Guava is not a DSL or JVM language (like Scala/Groovy) where you will dramatically write code differently.

Besides the Wiki, JavaDocs and PDFs you find on the site, you will find plenty of blog posts on using Guava.  I don't know of any books or publications that are otherwise available.  It should not take you more than a few days.

No.

The only exception I see to the above is that you want to use Guava's Functional idioms and use it as an introduction to Functional Programming in Java.  Then I could see a paradigm shift occurring where you will write code differently.  In that case:

There is a book called "Functional Programming in Java" by Dean Wampler that talks about FP pre-Java-8.  There is a beta book published by PragProg that talks about FP using Java 8 features.

The Guava wiki itself warns you to use Functional idioms judiciously:

Excessive use of Guava's functional programming idioms can lead to
  verbose, confusing, unreadable, and inefficient code. These are by far
  the most easily (and most commonly) abused parts of Guava, and when
  you go to preposterous lengths to make your code "a one-liner," the
  Guava team weeps.

  You will find from reading the above that FP (pre Java-8) can be very awkward and verbose (due to lack of first-class functions and having to use inner classes).  Believe me, there is some code in our codebase that (ab)uses these idioms and the team complains about it all the time (how it is hard to read and understand), despite having no aversion to FP in general.

Title: Getting into Guava


问:
Requirement gathering in an agile methodology
In the great book User Stories Applied the author specified the following process for trawling requirements in the form of user stories:

Create user roles (personas) --> brainstorm user goals for each role --> Write user stories -->

estimate all user stories --> prioritizes stories --> select some user stories for the first release -->

write acceptance criteria for each story --> divide each story into tasks --> estimate tasks

However, I don't get why ALL stories should be estimated first and if they need to be estimated why leave the acceptance criteria out of the story till it's time to work on it?

Next thing is about the acceptance criteria itself, in the book acceptance criteria where simple statements as:

test with Master Card for payment.

test with Visa for payment.

Isn't the Given... When... Then... format better for writing acceptance tests?

Last thing is about breaking user stories to tasks, why bother re-estimating the tasks when the task itself was estimated in story point?

答:
I think the point of the initial estimate is to get everyone to agree on (at a high-level) the order of complexity involved in implementing the Story.  This should help with Story prioritization.

When our team made the switch to Agile there was a lot of debate around how to write AC.

What we eventually concluded is that both "test with master Card for payment" and "Given... When... Then..." formats had their merits.  The former is obviously easier to write because it is in a natural language.  The latter is more precise because it explicitly sets up prerequisites, actions, and expectations.

We found that, for the sake of speed, AC were initially written in a natural language.  If after this there is still an element of ambiguity then they get translated to the formal format.  Also, if an AC is destined to be coded as an automated test, then it should be in the formal format.

Regarding the breakdown of stories into tasks:  We also followed that advice for a bit, but found it to be needless overhead.


问:
How do you keep logins organized between multiple developers?
I've worked at several places with 2-10 developers and each place has struggled in the area of tracking if the company has an account on a given web site or service.  We're always left wondering...

What's the username

What's the password (Obviously you don't want to store this, I'm not looking for something that does)

What's the account number

Who created this

When was it created

What email is our account registered under

What do you guys use to track this kind of thing between multiple developers?  I've setup at least a dozen accounts for the company I currently work for and I don't have any documentation to show the next guy what's been done.

Ideally I'm looking for a web solution that will be locked down within our VPN.

答: You probably want to look at something like Secret Server -- it was a product originally built by a development shop to solve this sort of problem and it is also a wonderful password safe program on the side. </p>


答:
I would recommend using some kind of personal wiki (like TiddlyWiki) when an issue arises... copy/pasta the question and appropriate answers into the wiki and store on a local server/development box. Then if you have issues and no outside internet access, you'll still have a (sort of) solution for when problems arise. Additionally, you can put accompanying info that might not be releasable to the public as well as links to other intranet locations/sites.

To answer the question though: developers should use their own accounts for the information. Anything relevant to the domain/work area should just be stored locally rather than the "cloud"

Title: How do you keep logins organized between multiple developers?

Body:
I've worked at several places with 2-10 developers and each place has struggled in the area of tracking if the company has an account on a given web site or service.  We're always left wondering...

What's the username

What's the password (Obviously you don't want to store this, I'm not looking for something that does)

What's the account number

Who created this

When was it created

What email is our account registered under

What do you guys use to track this kind of thing between multiple developers?  I've setup at least a dozen accounts for the company I currently work for and I don't have any documentation to show the next guy what's been done.

Ideally I'm looking for a web solution that will be locked down within our VPN.


问:
Why use typedefs for structs?
in C (ANSI, C99, etc.), structs live in their own namespace. A struct for a linked list might look something like this:

```<code>struct my_buffer_type {
   struct my_buffer_type * next;
   struct my_buffer_type * prev;
   void * data;
};
</code>```

It seems quite natural however for most C programmers to automatically typdef those structs like the following

```<code>typedef struct tag_buffer_type {
   struct tag_buffer_type * next;
   struct tag_buffer_type * prev;
   void * data;
} my_buffer_type;
</code>```

And then reference the struct like a normal type, i.e. get_next_element(my_buffer_type * ptr).

Now my question is: Is there a specific reason for this?

Wikipedia says http://en.wikipedia.org/wiki/Typedef#Usage_concerns

Some people are opposed to the extensive use of typedefs. Most arguments center on the idea that typedefs simply hide the actual data type of a variable. For example, Greg Kroah-Hartman, a Linux kernel hacker and documenter, discourages their use for anything except function prototype declarations. He argues that this practice not only unnecessarily obfuscates code, it can also cause programmers to accidentally misuse large structures thinking them to be simple types.[4]

Others argue that the use of typedefs can make code easier to maintain. K&R states that there are two reasons for using a typedef. First, it provides a means to make a program more portable. Instead of having to change a type everywhere it appears throughout the program's source files, only a single typedef statement needs to be changed. Second, a typedef can make a complex declaration easier to understand.

I personally wonder if there is not enough benefit of having the separate struct namespace to sometimes not use typedef'd structs and since there are several C programming cultures around (Windows C programming has different traditions than Linux C programming in my experience) if there are other traditions that I am not aware of.

Then I am interested in historical considerations (predecessors, first versions of C).

答:
Every time instead of typing

```<code>struct my_buffer_type *buffer;
</code>```

if you typedef it you can directly use

```<code>my_buffer_type *buffer;
</code>```

typedef's main usege is to reduce the number of keystrokes required to write code and to enhance readability.

Title: Why use typedefs for structs?

Body:
Every time instead of typing

struct my_buffer_type *buffer;

if you typedef it you can directly use

my_buffer_type *buffer;

typedef's main usege is to reduce the number of keystrokes required to write code and to enhance readability.


答:
I worked on a large project that extensively used typedef'd structs.  We did so for a couple of reasons. Please keep in mind that this was pre-C99 and namespace segregation.

It was easier to type my_buffer_type *buffer instead of struct tag_buffer_type *buffer, and for the size of the codebase (1M+ loc) that made a big difference.

It abstracts the structure into an object.  Rather than focus on every individual variable within the struct, we would focus on the data object that it represented.  This abstraction led to generally more useful and easier to write code.

I think this is in direct contradiction to the quote attributed to Greg Kroah-Hartman that you provided.  FWIW, that project was a client / server application and not a kernel so there's definitely some different considerations to take into account.

Treating the structure as an object also enabled us to better encapsulate the information.  Code review caught quite a few situations where a newer developer would violate the principles of encapsulation we had put in place.  Using typedef'd structs really made those violations obvious.

Portability was a concern as we wrote for a half-dozen platforms with the server and quite a few more with the client.

Title: Why use typedefs for structs?

Body:
in C (ANSI, C99, etc.), structs live in their own namespace. A struct for a linked list might look something like this:

```<code>struct my_buffer_type {
   struct my_buffer_type * next;
   struct my_buffer_type * prev;
   void * data;
};
</code>```

It seems quite natural however for most C programmers to automatically typdef those structs like the following

```<code>typedef struct tag_buffer_type {
   struct tag_buffer_type * next;
   struct tag_buffer_type * prev;
   void * data;
} my_buffer_type;
</code>```

And then reference the struct like a normal type, i.e. get_next_element(my_buffer_type * ptr).

Now my question is: Is there a specific reason for this?

Wikipedia says http://en.wikipedia.org/wiki/Typedef#Usage_concerns

Some people are opposed to the extensive use of typedefs. Most arguments center on the idea that typedefs simply hide the actual data type of a variable. For example, Greg Kroah-Hartman, a Linux kernel hacker and documenter, discourages their use for anything except function prototype declarations. He argues that this practice not only unnecessarily obfuscates code, it can also cause programmers to accidentally misuse large structures thinking them to be simple types.[4]

Others argue that the use of typedefs can make code easier to maintain. K&R states that there are two reasons for using a typedef. First, it provides a means to make a program more portable. Instead of having to change a type everywhere it appears throughout the program's source files, only a single typedef statement needs to be changed. Second, a typedef can make a complex declaration easier to understand.

I personally wonder if there is not enough benefit of having the separate struct namespace to sometimes not use typedef'd structs and since there are several C programming cultures around (Windows C programming has different traditions than Linux C programming in my experience) if there are other traditions that I am not aware of.

Then I am interested in historical considerations (predecessors, first versions of C).


问:
Is deep nesting of control flow in code a studied problem?
I made the case to coworkers that deep levels of control flow was harmful to the readability of code.

Example, taken from the relevant stack overflow question https://softwareengineering.stackexchange.com/questions/52685/if-you-need-more-than-3-levels-of-indentation-youre-screwed:

```<code>for(int i=0; i<10; ++i){
  Object val = repeat(i, someVar);
  if(val.value > 3){
    switch(val.item){
      case DOG:
        if(mProcess){
          outputToUser(val);
          doMoreThings(val, mMoreThingDoer);
          if(mRepurpose){
            addExample(val);
          }
          // and so on, and so on...
</code>```

As with most things, it's trivially easy to find opinions on this topic.

I'm wondering however if someone can contribute more to it than that.

Has there for example been done an actual study relevant to the problem?

Or can other arguments be made that go beyond "I like X better"?

答:
Quick googling shows that some research has been done. For instance, this paper shows that there's a value of cyclomatic complexity of code that minimizes bug rate:

Probably deep nesting may be fine as long as it does not branch at every point. That is, a having many nested conditions on top, as in your example, is probably fine, since it's essentially one condition, just not written as a conjunction.

OTOH if your switch statement below is large and has seriously non-trivial branches, the 'you're screwed' clause may apply.


问:
Efficient Data Structure for holding a graph
Problem Link - http://opc.iarcs.org.in/index.php/problems/NUMTRIPLE

In my opinion, the problem can be solved by a data structure, that shows how each number is connected to another, and via recursion find the smallest possible value. But my question is, what data structure (most efficient) can hold/represent such data? Also, is there a better (faster) way of solving this problem.

Thanks

答:
multidimetional array, we can also call it matrix.

create nxn dimentional array (lets say A) - where n is number of node in graph.
when node i and j is connected set A[i][j] to 1 else set to 0.


问:
Spring - Confusion over configuration?
Somewhere I read Spring offers convenience over configuration. But Spring folks are bringing in so much changes over the configuration , that I am now really getting confused to use the xml configuration or the annotation.

I would like anyone to suggest a surefire methodology or rule of thumb in using xml and annotations.

Examples at SO to show that many beginners like me are getting confused over the configuration.

link-1

I don't seem to grasp the functionality behind <context:annotation-config> and <context:component-scan>.

From what I've read they seem to handle different annotations (@Required, @Autowired etc vs @Component, @Repository, @Service etc) but also from what I've read they register the same bean post processor classes.

To confuse me even more, there is an annotation-config attribute on <context:component-scan>...

link 2

I still have  the component scan tag:

```<code><context:component-scan base-package="com.mycompany.maventestwebapp" />
</code>```

but I have also another tag (that look like have similar task), this one:

```<code><annotation-driven />
</code>```

What is the difference between these two tags?
  An other "strange" thing is that the previous example (that don't use the annotation-driven tag) is very similar to the project create by STS using the Spring MVC Template project but if I delete the annotation-driven tag from its configuration file the project don't run and give me the following error: HTTP Status 404 -...

Spring 3.2 no longer need cglib for proxying , but lower versions uses cglib. A quote from the springsource blog

In order to generate such proxies, Spring uses a third party library
  called cglib. Unfortunately, this project is not active anymore. In
  Spring 3.2, it is very likely that Spring will be using Javassist
  instead by default.

Are these enough to suggest that Spring is Confusion over configuration ?

答:
I have found that annotations based IoC/Bean creation is handy when you have a singleton implementation but may need to swap it out.

In constrast to a situation where you may need to reuse a bean repeatedly with different dependent classes/instances.

In those cases I declare the bean in config and usually do constructor injection of whatever dependency I need. Then, in the class that will use said bean(s) I @Autowire and then @Qualifier("") -- that's how factories are suppose to work.

A singleton is a factory method that only returns 1 result. When this doesn't handily apply that's when you need to mix it up.

As for using component-scan vs. not this really is subject to the above criteria and good judgement. I generally am very explicit about package component-scanning. That way I can create a different application context for testing where I can mock out external dependencies (like a db) while still testing the rest of my IoC setup.

In addition, I don't @Component any library code in my project. You never know when/how you will need to use a bean in there and if you @Component it, you may accidentally pick it up in a scan and you limit it's reusability. For these cases I generally have an application context defined in the library with some handy bean declaration defaults that my main project CAN included with imports into it's application context.

No religion here. Just experiences to pass on

Title: Spring - Confusion over configuration?


答:
Accurately estimating a story is work (not much, but it adds up). An accurate estimate has no direct value for the customer. So estimate only as much (and as accurately) as you need for planning.

Long term, you can get away with 'small/medium/large'. Do that. Taking time to go through acceptance criterial, tests, tasking or spike for accurate estimation is a waste of time if you aren't going to work on the story for two month - by the time you revisit that story chances are that content, context or knowledge has changed.

In a sprint/iteration, you need fairly accurate estimates. Tasking and detail AC (in whatever format the team likes best) is worth the additional effort.

I think the idea to estimate the story (gross estimate) and then the task separately (fine grained estimate) walks you through the process of refining the estimates as you need them.

Also, 'Given...When...Then' has merits, as well as 'As foo, I want to...' and 'just make it work, we all know what we're talking about'. For me, there is not one format - it depends on the story and the context.

Title: Requirement gathering in an agile methodology

Body:
In the great book User Stories Applied the author specified the following process for trawling requirements in the form of user stories:

Create user roles (personas) --> brainstorm user goals for each role --> Write user stories -->

estimate all user stories --> prioritizes stories --> select some user stories for the first release -->

write acceptance criteria for each story --> divide each story into tasks --> estimate tasks

However, I don't get why ALL stories should be estimated first and if they need to be estimated why leave the acceptance criteria out of the story till it's time to work on it?

Next thing is about the acceptance criteria itself, in the book acceptance criteria where simple statements as:

test with Master Card for payment.

test with Visa for payment.

Isn't the Given... When... Then... format better for writing acceptance tests?

Last thing is about breaking user stories to tasks, why bother re-estimating the tasks when the task itself was estimated in story point?


问:
Which is simpler for REST client call to return JSON - JQuery/JavaScript or Spring RestTemplate?
I've been trying to hack up an annotated Spring MVC web app but it's proving pretty hard to call a URL of my web app which fires a request to a remote API (UK Police data) and recieves a reply which I can then return as JSON. I've been trying to use Spring's RestTemplate.

The odd JavaScript example that I've glanced at does seem to be suited to that task a lot better and more simplistic than a full blown servlet. Is that an opinion that you also share and can back up with a good, clear simple example?

JavaScript does seem to provide a good platform for this kind of task

Or, in other words, is it simpler to create a "web-app" with JavaScript that does some REST calls and renders the response than trying to do it with Spring?

答:
Simply declaring @Produces("application/json") and installing the appropriate marshaller should take any compatible DTO and produce JSON

as for "proven"/"not proven" this is a puzzling statement. It's a syntax for representing an Object graph. JSON is natural as rain for integrating with a front-end because a Javascript object can simply assign to a webservice call to get at the results.

It's "proven" to represent the same object graph with approximately 50% less data on the wire than xml. You can prove this anecdotally by simply submitting a curl call to any url as '-H "accept: application/json" and then the same call as "-H "accept: application/xml"' and piping those results to "wc -c"

Does it meet your needs? Who knows. Use your best judgement.

I was a big proponent of XML until I actually did some legitimate analysis between JSON/XML. A whole lot less data for no extra work and natively FE compatible. For me, it works.


问:
What are the worst false economies in software development?
What are the worst false economies (that is ways of saving money that ultimately cost more than they save) prevalent in the software industry and how do you combat them?</p>

答: In many cases offshoring costs more money. In my company it's very hard to get new employee slots, we are pushed heavily to outsource. Its also hard to get on-site contractors; there is ratio of 3:1 offshore to onshore they are supposed to maintain. Consequently, many teams just hire a dozen offshore and barely use them at all, just so they can get 4 onsite contractors.</p>


问:
Why do we need "callback functions"?
I am reading the book programming in Lua. It said that

Closures provide a valuable tool in many contexts. As we have seen, they are
  useful as arguments to higher-order functions such as sort. Closures are valuable for functions that build other functions too, like our newCounter example;
  this mechanism allows Lua programs to incorporate sophisticated programming
  techniques from the functional world. Closures are useful for callback functions,
  too. A typical example here occurs when you create buttons in a conventional
  GUI toolkit. Each button has a callback function to be called when the user
  presses the button; you want different buttons to do slightly different things
  when pressed. For instance, a digital calculator needs ten similar buttons, one
  for each digit. Y ou can create each of them with a function like this:

```<code>function digitButton (digit)
  return Button{label = tostring(digit),
                action = function ()
                  add_to_display(digit)
                  end}
end
</code>```

It seems that if I call the digitButton, it will return the action (this will create a closure), so, I can access the digit passed to digitButton.

My question is that:

```<code>Why we need call back functions? what situations can I apply this to?
</code>```

The author said:

In this example, we assume that Button is a toolkit function that creates new
  buttons; label is the button label; and action is the callback closure to be
  called when the button is pressed. The callback can be called a long time after
  digitButton did its task and after the local variable digit went out of scope, but
  it can still access this variable.

according to the author, I think a similar example is like this:

```<code>function Button(t)
  -- maybe you should set the button here
  return t.action -- so that you can call this later
end

function add_to_display(digit)
  print ("Display the button label: " .. tostring(digit))
end

function digitButton(digit)
  return Button{label = tostring(digit),
                action = function ()
                           add_to_display(digit)
                           end}
end

click_action = digitButton(10)
click_action()
</code>```

thus, the callback can be called a long time after digitButton did its task and after the local variable digit went out of scope.

答:
I don't know lua but in general callback methods some what like multithreading.
For example in mobile application development programming most of the applications are functioning like sending request to the server and playing with UI with the data came as response from the server. When the user sends a request to server, it will take time to get response from server but for best UX UI should not stuck.

Because of this we use multiple thread to do parallel operations. When we get the response from the server we need to update UI. we have to notify from that thread to update. from the functional world. This type of function calls are called callback methods. When you call these methods the controle should have return to the main thread. For example callback methods are blocks in objective-C.

Title: Why do we need "callback functions"?


问:
Unit Test code generation
We have a project that was written over a period of 2 years, but has a poorly designed architecture and not unit tests.

The software works well, but we're at the point where we want to refactor some core modules.

The budget is also limited so we can not hire a sufficient number of developers to write unit tests.

Would generating unit test code automatically to cover (as an example) integration scenarios via some too be a viable strategy? An assumpion is that considering the system works fine right now, and the its output can be converted into XML data for unit testing?

This approach gives us a possibility of quickly starting to refactor existing code and receieve immediate feedback if some core functionality is broken because of those changes.

答:
Well, I've done that with a hierarchical tree data structure I wrote.  The data structure parses an input data set and creates a tree based on that data set and its defined data relationships.

I created trees using various input data sets that I knew would adequately cover the various cases (there are about sixty tests), serialized each tree to XML, and used those serialized strings as expected results for the unit tests, when I was satisfied with the XML output each tree produced.

Did it work?  Yes, pretty well, in fact, and it took a fraction of the time it would have taken painstakingly writing individual tests by hand.

Are there disadvantages?

The tests are fairly brittle (they break when any change is made to the code).

It's not always clear what exactly is being tested in each test, since there is no mapping of tests to individual requirements.

If one test breaks, several others also tend to break.

Diagnosing a failed test requires taking the expected and actual test results, pasting them into a text editor, and running a diff to see what changed.

Title: Unit Test code generation


问:
Should I store UK postcode data in my database
I am building a website for a UK audience that will utilise location data to offer search results based on a desired location or home address.

I have a large list of UK postcodes and geographic locations that I could parse and input to my DB to use in searches

I am wondering if this is the right thing to do?

Would it be better to just rely on an API such as google geolocation?

答: How does the API work? Do you make a call to the API, and the API looks up the data on Google's servers? The risk there, of course, is that if anything happens to your service provider (Google), you won't be able to do the lookup. Since you have lookup data that you can use locally, I'd recommend using it. It makes you less dependent on third-party APIs and will probably be faster (in theory, anyway) since there's no calls to outside systems. How much data is it? A few thousand rows? Most databases can handle that with no problem if you index it properly. You could even have it loaded to an in-memory cache when your application starts, so you don't even have to go to the database to retrieve it.</p>


问:
How common is it for a team to write everything in-house?
In a recent interview I asked the interviewers "how do you go about evaluating new technologies and libraries (such as SignalR) and bringing them in to use?". They said they don't, that instead they write everything themselves so they don't have to rely on anyone else.

The firm doesn't work for the government or defence contractors or on any safety-critical projects or anything like that. They were just your average, medium-size software development firm.

My question is: how common is it for teams to write everything themselves? Should I be concerned by teams that do?

Edit -- Most every response has said this is something to be concerned by. Would a second interview be an appropriate time to ask them to clarify/repeat their position on writing everything in house?

答:
What you've got is a really good opportunity to go into the second interview and ask them some tough questions. I don't know what the company does so it's difficult to say why this seems a strange choice. You could use the comment by @Daniel Pryden with regards to Google's usage of third party libraries.

Any piece of software you use, whether it is in-house or from a third party has advantages and disadvantages. Not to use a tool because it's not in-house, even if it is the best tool for the job shows a certain closed mindset and that's never going to encourage innovation and creativity.

Perhaps though, just perhaps, you're the person to introduce that change. Good luck with everything.


答:
What happens without callbacks:

Guy 1: Okay, I'm waiting for that thing to happen. (whistles, twiddles thumbs)

Guy 2: Dammit! Why is Guy 1 not showing me stuff? I want to see stuff happening!! Where's my stuff? How is anybody supposed to get anything done around here?

Title: Why do we need "callback functions"?