答:
As a picture is worth a thousand words, let's write an interpreter together! Of course, a very simple one. We use OCaml for this, but if you do not know OCaml, this is fine, because we will write very little code and comment it anyway.

We first define what is a program for us. We consider a very simple language, allowing to print text, add numbers, and test if a number is zero with an if-statement:

```<code>type statement =
| Print of string
| If of expr * statement * statement
| Sequence of statement list
and expr =
| Constant of int
| Plus of expr * expr
</code>```

The code above is a type declaration and defines what our idea of a program is. It defines an abstract symbolic form for programs – as opposed to the concrete tetual form – which is easy to manipulate in OCaml. This type definition is a plain translation of the english description of what a program is, with the addition of a sequence, to execute more operations.  (If we remove the Plus and the Sequence operations we pretty much obtain the smallest possible language demonstrating an If statement, but I felt it could be a bit too boring!)

Real life note In real life, a program contains a lot of annotations. An  important one is that program elements are typically annotated with their location in termes of file, line, column, which is useful to report errors.

We can already write an entertaining program in our language:

```<code>let program = Sequence([
  Print("Hello, world!");
  If(Plus(Constant(1),Constant(0)),
    Print("One is the truth"),
    Print("One is a lie"));
  Print("Oh, that was a tough one!");
])
</code>```

This should print the text Hello, world! to please Dennis, then compute 1 + 0 and compare the result to 0 – as for the definition of If in our language - if the result is distinct from 0, then the first branch is executed and the perlish message One is the truth is printed, otherwise the also perlish message One is a lie is printed. After such a tough challenge, our strained computer will share its feelings Oh, that was a tough one!.

Real life note In the real world, one needs to write a parser to translate plain text into an abstract program as the one held by the variable program. We can use lex and yacc for this, and their various derivatives.

Now let us write an interpreter for our language. (If you felt asleep, wake up now, the actual answer to the question will soon be presented!)

```<code>let rec interpreter = function
| Sequence(hd::tl) -> interpreter hd; interpreter(Sequence(tl))
| Sequence([]) -> ()
| Print(message) -> print_endline message
| If(condition, truebranch, falsebranch) ->
    (* The answer to the question is here! *)
    if (eval condition) <> 0 then
      interpreter truebranch
    else
      interpreter falsebranch
and eval = function
| Constant(c) -> c
| Plus(a,b) -> (eval a) + (eval b)
</code>```

Most of us are likely not familiar with OCaml, so let us walk gently through this piece of code:

```<code>let rec interpreter = function
| Sequence(head::tail) -> interpreter head; interpreter(Sequence(tail))
   (* To interpret a list of statements, we interpret the first
      and then interpret the tail of the list. *)

| Sequence([]) -> ()
   (* To interpret an empty list of statements, we just do nothing.
      Fair enough, right? *)

| Print(message) -> print_endline message
    (* To print a message, we use the host-language printing facility. *)

| If(condition, truebranch, falsebranch) ->
    (* The answer to the question is here!

       We first evaluate the condition, with the eval function below
       and use the host-language if facility to take the decision
       of recursively calling the interpreter on the truebranch or
       the falsebranch. *)

    if (eval condition) <> 0 then
      interpreter truebranch
    else
      interpreter falsebranch

and eval = function
| Constant(c) -> c
    (* Constants evaluate to themselves *)
| Plus(a,b) -> (eval a) + (eval b)
    (* A Plus statement evaluates to the sum of its parts. *)
</code>```

Now let's execute the program:

```<code>let () = interpreter program
</code>```

which causes the output

```<code>Hello, world!
One is the truth
Oh, that was a tough one!
</code>```

It you want to try it, just copy the program snippets in a file interpreter.ml and run with ocaml from your shell prompt:

```<code>% ocaml imterpreter.ml
</code>```

Conclusion When we write an interpreter using an intermediate abstract representation of the program like in this small example. The If statement is easily implemented in terms of conditionals in the host language. Other strategies are possible, it is perfectly imaginable to compile the program “on the fly” and to feed it to a virtual machine. (Some people will argue that there is essentially no difference between the two approaches.)

Body:
As a picture is worth a thousand words, let's write an interpreter together! Of course, a very simple one. We use OCaml for this, but if you do not know OCaml, this is fine, because we will write very little code and comment it anyway.

We first define what is a program for us. We consider a very simple language, allowing to print text, add numbers, and test if a number is zero with an if-statement:

type statement =
| Print of string
| If of expr * statement * statement
| Sequence of statement list
and expr =
| Constant of int
| Plus of expr * expr

The code above is a type declaration and defines what our idea of a program is. It defines an abstract symbolic form for programs – as opposed to the concrete tetual form – which is easy to manipulate in OCaml. This type definition is a plain translation of the english description of what a program is, with the addition of a sequence, to execute more operations.  (If we remove the Plus and the Sequence operations we pretty much obtain the smallest possible language demonstrating an If statement, but I felt it could be a bit too boring!)

Real life note In real life, a program contains a lot of annotations. An  important one is that program elements are typically annotated with their location in termes of file, line, column, which is useful to report errors.

We can already write an entertaining program in our language:

let program = Sequence([
  Print("Hello, world!");
  If(Plus(Constant(1),Constant(0)),
    Print("One is the truth"),
    Print("One is a lie"));
  Print("Oh, that was a tough one!");
])

This should print the text Hello, world! to please Dennis, then compute 1 + 0 and compare the result to 0 – as for the definition of If in our language - if the result is distinct from 0, then the first branch is executed and the perlish message One is the truth is printed, otherwise the also perlish message One is a lie is printed. After such a tough challenge, our strained computer will share its feelings Oh, that was a tough one!.

Real life note In the real world, one needs to write a parser to translate plain text into an abstract program as the one held by the variable program. We can use lex and yacc for this, and their various derivatives.

Now let us write an interpreter for our language. (If you felt asleep, wake up now, the actual answer to the question will soon be presented!)

let rec interpreter = function
| Sequence(hd::tl) -> interpreter hd; interpreter(Sequence(tl))
| Sequence([]) -> ()
| Print(message) -> print_endline message
| If(condition, truebranch, falsebranch) ->
    (* The answer to the question is here! *)
    if (eval condition) <> 0 then
      interpreter truebranch
    else
      interpreter falsebranch
and eval = function
| Constant(c) -> c
| Plus(a,b) -> (eval a) + (eval b)

Most of us are likely not familiar with OCaml, so let us walk gently through this piece of code:

let rec interpreter = function
| Sequence(head::tail) -> interpreter head; interpreter(Sequence(tail))
   (* To interpret a list of statements, we interpret the first
      and then interpret the tail of the list. *)

| Sequence([]) -> ()
   (* To interpret an empty list of statements, we just do nothing.
      Fair enough, right? *)

| Print(message) -> print_endline message
    (* To print a message, we use the host-language printing facility. *)

| If(condition, truebranch, falsebranch) ->
    (* The answer to the question is here!

       We first evaluate the condition, with the eval function below
       and use the host-language if facility to take the decision
       of recursively calling the interpreter on the truebranch or
       the falsebranch. *)

    if (eval condition) <> 0 then
      interpreter truebranch
    else
      interpreter falsebranch

and eval = function
| Constant(c) -> c
    (* Constants evaluate to themselves *)
| Plus(a,b) -> (eval a) + (eval b)
    (* A Plus statement evaluates to the sum of its parts. *)

Now let's execute the program:

let () = interpreter program

which causes the output

Hello, world!
One is the truth
Oh, that was a tough one!

It you want to try it, just copy the program snippets in a file interpreter.ml and run with ocaml from your shell prompt:

% ocaml imterpreter.ml

Conclusion When we write an interpreter using an intermediate abstract representation of the program like in this small example. The If statement is easily implemented in terms of conditionals in the host language. Other strategies are possible, it is perfectly imaginable to compile the program “on the fly” and to feed it to a virtual machine. (Some people will argue that there is essentially no difference between the two approaches.)


问:
Why create a Global-ish Object.create function?
I'm a fairly experienced programmer in the .NET and Java realms, and I've started reading up on JavaScript. I bought Douglas Crockford's "The Good Parts" book, and I'm immediately put off by a few things.

One is modifying the fundamental types without need:

```<code>if (typeof Object.create !== 'function') {
    Object.create = function (o) { //Really... 'o'? For a parameter you're only using twice?
        function F() {}
        F.prototype = o;
        return new F();
    };
}
newObject = Object.create(oldObject);
</code>```

Obviously creating a function with this purpose is useful and saves time, but WHY ON EARTH is he recommending creating it on Object? Three breaths ago he espoused that globals are evil, and then he proceeded to monkey patch Object. He even tests if it already exists, and just assumes that if some other library did it for him the implementation is the same.

Is there some reason not to create this in the JS equivalent of a namespace? ie

```<code>MY_UNIQUE_UTIL_LIBRARY.create = function(obj){...}; //The name would be shorter in reality.
</code>```

Don't get me wrong, I think monkey patching is useful, but it's something you do when there's an inherent benefit. I don't see one here? Is there one?

答:
Object.create is defined in newer versions of browsers (can't say exactly since when). You can see its description on the Mozilla developer network.

This is just a polyfill (quite similar to the one on that page, with a few less checks) to be able to use the same function on older browsers. On newer browser it is already defined as a function and will thus use the browser optimized version, while on older browsers it is by default undefined and will use this version.

ContentLicense: CC BY-SA 3.0


问:
Are mocks in unit tests dangerous in dynamic languages?
I've started relying heavily on a mocking framework in php for my unit tests.

My concern is that with a dynamic language, there is no way of enforcing a return type. When mocking, you have to ensure that the return type of your mocked method is correct.

Take for example the following interface

```<code>interface MyInterface {

  /**
   * @return SomeObject
   */
   public function myMethod();

}
</code>```

If we are unit testing a class which requires an instance of MyInterface, we would mock the myMethod function to return a known SomeObject.

My concern is what happens if we accidentally have our mocked method return a different type of object, e.g. SomeOtherObject, and SomeOtherObject and SomeObject are not the same duck type (don't have the same methods). We'll now have code that is relying on havingSomeOtherObject, when all implementations ofMyInterfacemyMethodwill returnSomeObject`.

For example, we could write the following production code;

```<code>$someOtherObject = $myInterfaceImp->myMethod();
$newObj = new NewObject($someOtherObject);
</code>```

Hopefully the issue is obvious. We are passing what we think is SomeOtherObject into a constructor. Our tests will pass, but its very likely that in production we will get failures as myMethod() will actually be returning SomeObject. We then try passing this into the constructor, and get an error if there is a type check, or a non existent method is called.

Unless we write very detailed integration and acceptance tests using the real implementations (basically we'd have to ensure they covered all the testing we do an the unit level) we may not ever realise that we have an issue until we receive some runtime error in production.

Other than developer discipline, is there any way to mitigate the risk of incorrect mocks and implementations?

答:
is there any way to mitigate the risk of incorrect mocks and implementations?

In python-mock, you can specify a mock spec. A spec constraints what methods and attributes are available in the mocked object, thus you'll get an error if the system under test (SUT) try to call or access something unexpected.

My concern is what happens if we accidentally have our mocked method return a different type of object e.g. SomeOtherObject? We'll now have code that is relying on having SomeOtherObject, when all implementations of MyInterface myMethod will return SomeObject.

You shouldn't worry about actual types. Actual types should be considered implementation details; it's the duck type that you should be the more concerned about. Test that the correct methods are called with the correct arguments, you usually shouldn't need to test the actual type of the return value. Instead of asserting the actual type, assert the state that you expect for the object to be in, after the SUT.

Unless we write very detailed integration and acceptance tests (basically we'd have to ensure they covered all the testing we do an the unit level) we may not ever realise that we have an issue until we receive some runtime error in production.

Mocks are for unit tests, you should not be using mocks for integration and acceptance tests. Integration and acceptance tests should use the real objects as much as possible, and only use very minimal mock to replace external systems.that may not be fully under your control.


问:
Handling my antiquated coworker
I'm a fairly young programmer, and I work at a medium sized company's IT department. I have a coworker, and he is a really good Visual Basic 6 programmer. And I mean really good. Honestly. He can deliver working applications, containing very few bugs, in the time I need to get my first cup of coffee, and boot my machine. He is just that good.

Thing is, we are working with a team, and his working style is completely antiquated. He doesn't believe in versioning software (if you just make sure your code is correct, you don't need all that nonsense). Doesn't believe in deployment (I can deliver a working executable. How that is deployed is for the sysadmins to figure out). Doesn't believe in abstraction. ('if you want to create a subroutine, go ahead, but don't call any subroutines from that subroutine. It gets messy that way, and the code is hard to follow. This way every one can follow every step on the way.' or 'yeah, sure you can use that library to do that for you, but that way you don't really understand what's going on') and certainly doesn't believe in OOP. (we work in VB.net)

He is so good in what he does, he can deliver applications way faster than I can. But it just doesn't work in a team. Our other team member is quiet, and doesn't like to speak out, though he tends to agree. Our manager thinks I make valid points, but is not a programmer.

I have a really hard time maintaining programs he has written, and it doesn't make for a good team atmosphere. What do you think is the best thing for me to do?

答:
If I were you I would set up my own source control system right now.  Start using it for everything you code, and administer it so that your other team members have accounts and can access it.  Your other coworkers will likely be enthusiastic about using it.

Your colleague who does not believe in such practices may not be easy to persuade.  However, any code that you are forced to work with that was written by him should go into version control so that you can work with it.  When he needs access to your changes, send him a simple step by step set of instructions on how to pull your code from the repository.

You don't have to be combative or go above him to get him involved in more modern processes.  Sometimes just going your own way and being a leader with action is more effective than trying to convince somebody with words.  Baby-steps.  If he starts being more responsive to the version control, start refactoring subroutines and adding unit tests to protect against the changes.  Automate the tests and show him how he can access the results as soon as he makes checkins.

A lot of times people are just resistant because they don't like change.  But if the changes are presented to them in a gradual manner and in a way that makes it easy for them to follow, often they will see the benefits very quickly.

Above all, make it all as simple as possible for him (Keep It Simple Stupid).  Allow him to start following these practices on his own terms.  But don't let it drag you down.

Title: Handling my antiquated coworker

ContentLicense: CC BY-SA 2.5


问:
Compiling and deploying a C program to an MCU running an RTOS
Please note: Even though I'm specifically talking about an RTOS called Embox here, and even though I'm talking about AVR/ARm, I think this question can be answered by anybody whose ever done a fair amount of C-based MCU programming.

Say I have an MCU running Embox on it. Now, I'd like to write 2 executables, and 1 static library (used by both programs) in C and deploy all three artifacts to the MCU/RTOS. I have a few very-similarly-related questions/concerns (hence my choice to make this one question instead of 4):

What formats of executables and libraries does Embox require, and how can I tell? EXE/SO?

How does one compile a C program into an executable/library format (again, perhaps EXE/SO) that is compatible with Embox? For instance, I'm on a Windows machine with GCC provided by MinGW. I don't think I'd be able to write a program for Linux and then deploy it to a Linux machine. I'd need a Linux machine for that. But if the machine I'm deploying to is a simple RTOS/MCU, how do I develop on one platform/architecture (Windows) and make binaries that are compatible on another?

How does one deploy the executables to the MCU such that the RTOS can run the 2 apps at startup?

How does a user interact with the RTOS? Shell/SSH/console?

答:
What formats of executables and libraries does Embox require, and how can I tell?

Embox is a configurable OS and one can create separate kernel image and user application. But since MCU has rather small memory size, most embedded RTOSes including Embox link all software (kernel, apps etc.) to a single image by default.

How does one compile a C program into an executable/library format (again, perhaps EXE/SO) that is compatible with Embox?

You should setup make and a cross-compiler. Then you have to configure Embox (choose a desired template) with make confload-xxx. And finally build the image with a command make.
After that you can find the image in a file ./build/base/bin/embox. Here is a short [getting started][1] page.

How does one deploy the executables to the MCU such that the RTOS can run the 2 apps at startup?

Although Embox creates a single image you can have several apps in it. Unlike most RTOSes in Embox you can have several main routines. This feature is enabled by using a special build system. Embox consists of set of modules and each module is described using a DSL language. There is an 'application' type of module. If a module is marked as an 'application' the build system strips main symbol away and replaces it with <package-name>_<module-name>_main. Also the build system adds the new symbol and the application name to a special applications registry, so that you can run your application from the Embox shell or in some other way.

How does a user interact with the RTOS? Shell/SSH/console?

Embox has a built-in shell and you can access it through UART (COM port), for example. Embox also has telnet and httpd apps which you can interact through. Also Embox has a port of sshd (with dropbear project),  but I think it's not the easiest way to communicate with MCU.


问:
Are there constraints for functions in structured programming?
I just talking with a colleague (University instructor) who teaches C (Fundamental of programming Course). He said I won't give score to a student, if he uses I/O (scanf or printf or cin count) in a function (it shows he hasn't understood it well) or if he writes a function which does two things (for example to return the maximum of an array, he shouldn't sort the array and return the first element, however he can use two functions, one for sorting and another for returning the first element ...)...

I thought these are related to his teaching method but he claimed they are the principles of functions in structured programming.

Are there really such constraints and definitions for functions? What are those?
If yes, in which topic are they discussed?  Should they be discussed in a C or C++ teaching course?

答:
There are 2 things he's probably referring to: side effects and composability.

scanf and printf do IO, which is a side effect.  Side effects (input, output, and mutation of variables) don't really fit well with the mathematical definition of a function, and can make programs harder to reason about, so there's a paradigm of programming called 'functional' that tries to avoid such things as much as possible.  C++ isn't really a functional language, though, so if he's strict about it, that probably doesn't quite make sense.

If a function does 2 things, then it can be broken into 2 functions which do the separate things separately and then be combined.  This is good for a number of reasons: each individual function is smaller (making it easier to reason about), can be understood separately, and, most importantly, can be more easily combined with other functions to do new things.


答:
scanf and printf use stdin and stdout, which means several things:

They have side effects. This means that they are not appropriate for functional programming and for parallel computing. Imagine two threads which read stdin. What could be the possible consequences of running those threads side by side? How easy or difficult would it be to debug the issues which will appear only sometimes and so are difficult to reproduce?

They create dependencies. If a library relies on stdin and stdout, is it straightforward to use in a desktop application where the user expects the data to be shown through GUI instead of a console? What about web applications? To remedy to this problem, dependency injection can be used, determining how the library is interacting with the outside world instead of relying on stdin and stdout.

What if the program is running unattended (outside interactive command prompt)? This is often an issue with some Linux command-line scripts which assume that there would always be a user who can type Y or N to answer specific questions. It works well for very basic scenarios, and then miserably fail when someone needs to use them in an automated fashion (it remains technically possible, just unnecessarily complicated).

They make unit testing more difficult than it should be.

They assume that input and output forms should and will never be configured. For instance, a method can printf information about its execution in order to be monitored, which may be what you need for a basic scenario. Now, what if application grows and the same information should be sent to syslog? What if it needs to be filtered?

As for the function which does two things, this is just plainly wrong. A function should do one and one thing, in the same way as the class should have responsibility over a single part of the functionality only (SRP).

Letting the method to do multiple things leads has several effects:

It's very difficult to find a concise, clear name for the function. CreateProductAndRefreshCache is an ugly name.

It usually leads to long methods. Splitting such method into two short ones often leads to a better readability and maintainability.

Unit testing is not straightforward.

Title: Are there constraints for functions in structured programming?

Body:
I just talking with a colleague (University instructor) who teaches C (Fundamental of programming Course). He said I won't give score to a student, if he uses I/O (scanf or printf or cin count) in a function (it shows he hasn't understood it well) or if he writes a function which does two things (for example to return the maximum of an array, he shouldn't sort the array and return the first element, however he can use two functions, one for sorting and another for returning the first element ...)...

I thought these are related to his teaching method but he claimed they are the principles of functions in structured programming.

Are there really such constraints and definitions for functions? What are those?
If yes, in which topic are they discussed?  Should they be discussed in a C or C++ teaching course?


问:
What is the difference between Callable<T> and Java 8's Supplier<T>?
I've been switching over to Java from C# after some recommendations from some over at CodeReview. So, when I was looking into LWJGL, one thing I remembered was that every call to Display must be executed on the same thread that the Display.create() method was invoked on. Remembering this, I whipped up a class that looks a bit like this.

```<code>public class LwjglDisplayWindow implements DisplayWindow {
    private final static int TargetFramesPerSecond = 60;
    private final Scheduler _scheduler;

    public LwjglDisplayWindow(Scheduler displayScheduler, DisplayMode displayMode) throws LWJGLException {
        _scheduler = displayScheduler;
        Display.setDisplayMode(displayMode);
        Display.create();
    }

    public void dispose() {
        Display.destroy();
    }

    @Override
    public int getTargetFramesPerSecond() { return TargetFramesPerSecond; }

    @Override
    public Future<Boolean> isClosed() {
        return _scheduler.schedule(() -> Display.isCloseRequested());
    }
}
</code>```

While writing this class you'll notice that I created a method called isClosed() that returns a Future<Boolean>. This dispatches a function to my Scheduler interface (which is nothing more than a wrapper around an ScheduledExecutorService. While writing the schedule method on the Scheduler I noticed that I could either use a Supplier<T> argument or a Callable<T> argument to represent the function that is passed in. ScheduledExecutorService didn't contain an override for Supplier<T> but I noticed that the lambda expression () -> Display.isCloseRequested() is actually type compatible with both Callable<bool> and Supplier<bool>.

My question is, is there a difference between those two, semantically or otherwise - and if so, what is it, so I can adhere to it?

答:
The short answer is that both are using functional interfaces, but it's also worthy to note that not all functional interfaces must have the @FunctionalInterface annotation. The critical part of the JavaDoc reads:

However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.

And the simplest definition of a functional interface is (simply, without other exclusions) just:

Conceptually, a functional interface has exactly one abstract method.

Therefore, in @Maciej Chalapuk's answer, it is also possible to drop the annotation and specify the desired lambda:

```<code>// interface
public interface MyInterface {
    boolean myCall(int arg);
}

// method call
public boolean invokeMyCall(MyInterface arg) {
    return arg.myCall(0);
}

// usage
instance.invokeMyCall(a -> a != 0); // returns true if the argument supplied is not 0
</code>```

Now, what makes both Callable and Supplier functional interfaces is because they do contain exactly one abstract method:

Callable.call()

Supplier.get()

Since both methods do not take in an argument (as opposed to the MyInterface.myCall(int) example), the formal parameters are empty (()).

I noticed that the lambda expression () -> Display.isCloseRequested() is actually type compatible with both Callable<Boolean> and Supplier<Boolean>.

As you should be able to infer by now, that is just because both abstract methods will return the type of the expression you use. You should definitely be using a Callable given your usage of a ScheduledExecutorService.

Further exploration (beyond the scope of the question)

Both interfaces comes from entirely different packages, hence they are used differently too. In your case, I don't see how an implementation of Supplier<T> will be used, unless it is supplying a Callable:

```<code>public static <T> Supplier<Callable<T>> getCallable(T value) {
    return () -> () -> {
        return value;
    };
}
</code>```

The first () -> can be loosely interpreted as "a Supplier gives..." and the second as "a Callable gives...". return value; is the body of the Callable lambda, which itself is the body of the Supplier lambda.

However, usage in this contrived example gets slightly complicated, as you now need to get() from the Supplier first before get()-ting your result from the Future, which will in turn call() your Callable asynchronously.

```<code>public static <T> T doWork(Supplier<Callable<T>> callableSupplier) {
    // service being an instance of ExecutorService
    return service.submit(callableSupplier.get()).get();
}
</code>```

Body:
The short answer is that both are using functional interfaces, but it's also worthy to note that not all functional interfaces must have the @FunctionalInterface annotation. The critical part of the JavaDoc reads:

However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.

And the simplest definition of a functional interface is (simply, without other exclusions) just:

Conceptually, a functional interface has exactly one abstract method.

Therefore, in @Maciej Chalapuk's answer, it is also possible to drop the annotation and specify the desired lambda:

// interface
public interface MyInterface {
    boolean myCall(int arg);
}

// method call
public boolean invokeMyCall(MyInterface arg) {
    return arg.myCall(0);
}

// usage
instance.invokeMyCall(a -> a != 0); // returns true if the argument supplied is not 0

Now, what makes both Callable and Supplier functional interfaces is because they do contain exactly one abstract method:

Callable.call()

Supplier.get()

Since both methods do not take in an argument (as opposed to the MyInterface.myCall(int) example), the formal parameters are empty (()).

I noticed that the lambda expression () -> Display.isCloseRequested() is actually type compatible with both Callable<Boolean> and Supplier<Boolean>.

As you should be able to infer by now, that is just because both abstract methods will return the type of the expression you use. You should definitely be using a Callable given your usage of a ScheduledExecutorService.

Further exploration (beyond the scope of the question)

Both interfaces comes from entirely different packages, hence they are used differently too. In your case, I don't see how an implementation of Supplier<T> will be used, unless it is supplying a Callable:

public static <T> Supplier<Callable<T>> getCallable(T value) {
    return () -> () -> {
        return value;
    };
}

The first () -> can be loosely interpreted as "a Supplier gives..." and the second as "a Callable gives...". return value; is the body of the Callable lambda, which itself is the body of the Supplier lambda.

However, usage in this contrived example gets slightly complicated, as you now need to get() from the Supplier first before get()-ting your result from the Future, which will in turn call() your Callable asynchronously.

public static <T> T doWork(Supplier<Callable<T>> callableSupplier) {
    // service being an instance of ExecutorService
    return service.submit(callableSupplier.get()).get();
}


问:
Ternary operator considered harmful?
For example, would you prefer this one-liner

```<code>int median(int a, int b, int c) {
    return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b;
}
</code>```

or an if/else solution involving multiple return statements?

When is ?: appropriate, and when is it not? Should it be taught to or hidden from beginners?

答:
I do not think that the ternary operator is evil.

Here is a gotcha that had me stumped, though.  I was a C programmer for many (10+) and in the late 1990s I moved into web based application programming.  As a web programmer, I soon ran across PHP which also has a ternary operator.  I had a bug in a PHP program which I finally traced to a line of code with a nested ternary operator.  It turns out that the PHP ternary operator associated left to right but the C ternary operator (which I was used to) associates right to left.

Title: Ternary operator considered harmful?


问:
Best practices for programmatic describing of behavior of complex input forms
We have a complex web form (we use GWT/GXT stack) with lots of input elements of different types (text fields, selects, checkboxes, buttons), and behavior of these elements depends on each other.

Now it means, to set form element state correctly, it's necessary to know what happened to it (user input occurred or an event came from server) and state of other elements of that form.

So, the question is what best practices to maintain code for such a complex web form in clean and comprehensible state? Now it seems that ideal solution would employ some form of declarative DSL to describe said behavior.

Initial brain storming produced following kind of Java DSL (this is just to give an idea what I mean, no any real DSL exists right now):

```<code>private Event whenStopOrderChanged;
private Predicate parentPriceValid;
private Command calculateStopPrice;

public void initRules() {
    whenStopOrderChanged.and(parentPriceValid).then(calculateStopPrice);
}
</code>```

So, could you please share your ideas/experience solving such kind of task?

答:
Those form fields are part of the presentation layer.
You should have a view model, basically a model for that presentation.
That viewModel has to have the entire state for that form fields.
The state should be: their value, their enabled/disabled, etc...

So, when you present those fields in the screen you'll have to load the state from your viewModel. And after user interacts, there will a new state for these fields: you will sync the viewmodel with the new state.

What for? Because then if you open a new tab in the web browser you'll see an updated scene with your last changes.

Where does the viewModel live? In the session.


问:
What's the correct approach to DAO layer in presence of ORM framework
I'm using JPA/Hibernate but probably it doesn't limit question.

Currently I'm writing my data access code in my web controller classes. Thanks to JPA, in most cases this code is very simple, basically simple query with trivial setup.

I tried to move those methods into separate classes to improve code reuse. But I've encountered an important problem. Although there are similar methods, they are not the same. This especially applies to fetching joined classes (tables). In some controllers I don't need fetching those classes. But in some controllers I do need that. So I have the following variants:

Move all methods, even slightly different, as a separate methods into DAO class. This makes DAO complex, their method names will be very long, it would be hard to find correct one.

Forget about fetch joins. Setup application to perform loading when needed (lazy loading). This will reduce number of methods, but database access will be much less effective and transaction must span across entire request, not just controller code.

Put complex logic into method when needed. E.g. supply boolean parameters fetchSomething. And method will tweak query according to those parameters. Method implementation will be very complex as I would have to either build query string from pieces or use very cumbersome Criteria API. Method will be hard to read and understand.

Leave as is. I generally like this approach. It leads to some code duplication, but not very much and queries are declarative so I don't see much problems with that. The main problem is lack of testability. To test controller I would need to prepare a database, because there's no (or I didn't found) complex JPA mock implementation with supplied in-memory data.

I wonder what approach used in complex projects? I saw 4-th approach and I saw once very complex in-house ORM based on Hibernate.

I'm talking now about so-called "repository pattern". I don't really understand what people mean by "service layer" and never saw any need with that, so currently the question is about data repository classes.

答:
I prefer the Table Data Gateway pattern, i.e. a stateless object for roughly each entity type, containg methods such as

```<code>void CustomerRepository.createCustomer(Customer c)

List<Customer> CustomerRepository.getCustomersByCountry(String country)
</code>```

Easy to add additional handling such as serialization, error handling, logging, validation, caching.

Easy to find the correct function

Less likely to have duplicate code

Easy to migrate to a different database technology

Easy to mock for testing

Easy to instrument for performance monitoring

Body:
I prefer the Table Data Gateway pattern, i.e. a stateless object for roughly each entity type, containg methods such as

void CustomerRepository.createCustomer(Customer c)

List<Customer> CustomerRepository.getCustomersByCountry(String country)

Easy to add additional handling such as serialization, error handling, logging, validation, caching.

Easy to find the correct function

Less likely to have duplicate code

Easy to migrate to a different database technology

Easy to mock for testing

Easy to instrument for performance monitoring


问:
Design interface for WebService to access several MySQL databases
I am currently trying to design an interface for a WebService that can access several MySQL databases. There will be 4 operations available, Add(), Read(), Update() and Delete().

The WebService just needs to assemble an SQL statement based on the called method and execute it on the target database. But now I am struggling to find a good method signature that provides all needed information to the WebService and is simple to use. So if I want to assemble an INSERT statement when the Add() method was called, I don't know how I can pass all the column information with the corresponding values and types. For example a .NET DateTime should be stored with the MySQL data type for date/time. So I'd need some kind of wrapper object that check the properties via reflection to get the type.

Here are some thoughts:

```<code>Add(String db, String table, Dictionary<String, object> dataSet);
Read(String db, String table, String column, filter?);
Update(String db, String table, String idToReplace, Dictionary<String, object> dataSet);
Delete(String db, String table, String idToDelete);
</code>```

I am not sure how to specify a filter possibility for the SELECT statement in the Read() method. In addition I don't know how to pass parameter information in the Add() and Update() methods. I don't want to save only string values in the db, I'd like to have passed some type information so that the WebService can match them to the corresponding MySQL data types.

答:
I believe you are making fundamental mistake. WebService is created to fulfill some clear purpose, not just operate on very generic data.

Now you have some kind of simple methods and are trying to abstract them so that they would be able to do all the work. This will not scale well. Tomorrow you will want them (since they are really VERY abstracted) to do some more work and will face a real challenge to incorporate that work into your abstracted abstraction.

Believe me, adding more methods here does not complicate matters. By making some generic generics, you are violating SRP principle.

Well, if you insist... Then look into ADO.NET method signatures. I believe they qualify for your task.


问:
How to implement rounding in an all-purpose stack language using different types?
Disclaimer: If you are not terribly interested in numerics and mathematical processes, this is most likely nothing for you.

I am currently a bit stuck in a development process of a private project I followed for a long time and I think I need some input because I cannot decide how to do it best.
Unfortunately I must explain the problem a bit.

EDIT: This is NOT about rounding implementation. This is already done, both for float/doubles and arbitrary precision. You can assume I have enough knowledge about
numerics, rounding modes and floating-point problems, the problem is how to design rounding operators in a stack-based program.

I am interested in the reproducibility problem in numerical computations. Due to the immense power (billions of operations per second) and certain problems by the languages used for number crunching (C and FORTRAN), people cannot check what the machine is actually doing in contrast what the machine is supposedly doing (Deteoriation of language standards like indifference to qNaNs and sNaNs, allow to "optimize" a+(b+c) == (a+b)+c, x86 vs MME floating-point, silent FMA support etc. etc.). This view is shared by William Kahan, the designer of the x86 floating-point architecture.

So I worked on a stack-based language like FORTH which allows reproducible results. You have types: aggregates (Vector,Matrix,Tensor) and numbers (complex, reals). You put two space instances on the stack, execute an ADD, and you get the resulting sum. If the spaces were two floats, you get a float. If the spaces were two doubles, you get a double. If the two spaces were arbitrary precision numbers, you get an arbitrary precision number. The same with vectors and matrices.

My aching problem is rounding. If we exclude exact rationals, after division every higher operation (algebraic and transcendental operations) requires rounding. There are two rounding operations which are already implemented: place rounding, setting the exact position of the rounding (rounding down: 2.345 using 0 => 2 / 2.345 using -1 => 2.3) and significant digits rounding by setting the length of the result (rounding down: 2.345 using 1 = 2 / 2.345 using 2 = 2.3).

The approaches:

One ring to rule them all: Only one rounding setting for all available types. Problem: Some operations are exact and should be executed as such; arbitrary precision numbers offer exact addition and exact multiplication. If I define e.g. ADD_EXACT I include a keyword which is not implemented by most datatypes and will be therefore a normal ADD and the danger is that I (or others) forget to use ADD_EXACT when necessary. Another problem is that it is makes sense to use different rounding modes for some operations: place rounding for addition and significant digit rounding for multiplication. I fear to swamp the program with unnecessary switches to set the rounding mode.

Perhaps some more rings....: Several settable rounding modes. Allows adding and multiplication independently. Problem: Much more possibilities (set and retrieve rounding mode, rounding operation and rounding parameter). How many choices do I offer ? Only two and risking that if e.g. FMA cannot be supported or many more and risking to overwhelm the program with much too much rounding bureaucracy ?

Rounding is a crucial operation and once implemented, it cannot be changed easily. This must be solved as good as possible.

What I need is a simple and elegant model and I fear that I have worked so long on it that I simply do not see it and/or need a plan to find out the right solution. Help is very appreciated and I will update this post to clarify some aspects I may have forgotten.

EDIT:
Performance: Is not the design goal. It does not help you to get an incredibly fast wrong answer. It does not help you if two programmers on different machines get a different or (even similar) result if noone knows what is the right answer (or that even both are wrong). The goal of the program is exactly that: Find out when IEEE 754R precision will fail and find indicators and methods to validate numeric results. If you know that double precision and the tool will get you to the solution, by all means use C and FORTRAN.

答:
Due to the inexplicable power of rubber duck debugging I have now a solution I find better than all the other approaches I thought of.

I will implement a rounding stack. When a subroutine is entered, the last entry will be duplicated and pushed as first element on the stack (It will also be used entry if the stack is completely cleared). The stack is strictly local, access to rounding values of superroutines is not possible. When the subroutine is left, the stack will be cleared; no survivors.

The stack has the following operations: ROUND_DUP (to save the original state if necessary), ROUND_PUSH , ROUND_POP, ROUND_CYCLE (see later) and accessor functions for the current rounding.

ROUND_CYCLE cycles through the rounding modes. If we have 3 rounding modes on the stack, this means rounding mode 1,2,3,1,2,3...If we have only one rounding mode on the stack, the instruction does nothing.

Augmented are test functions:
EXACT_ADD_SUPPORTED
EXACT_MUL_SUPPORTED
(It is not advisable to use only IS_ARBITRARY_PRECISION because it is possible that
 the system may have an long accumulator for adding (even in hardware) and does not
 support exact multiplication).

So I can write general functions for both arbitrary precision and fixed precision.

```<code>EXACT_ADD_SUPPORTED
IF
  ROUND_PUSH EXACT
ENDIF

DO
 ....
 ROUND_CYCLE
 ADD
 ROUND_CYCLE
LOOP
</code>```

If this is arbitrary precision, the two rounding values are switched and I have exact addition. If this is fixed precision, only one rounding value remains and is used; ROUND_CYCLE does nothing.
So I can set the necessary roundings at the beginning of the program, making it easy to find and understand. Given that CYCLE does only switches, I must think before how the rounding modes must be set during the execution, avoiding superfluous and unstructured approaches. I have only one current rounding mode, avoiding overhead.

If you have improvements and criticism, be invited to share.

Body:
Due to the inexplicable power of rubber duck debugging I have now a solution I find better than all the other approaches I thought of.

I will implement a rounding stack. When a subroutine is entered, the last entry will be duplicated and pushed as first element on the stack (It will also be used entry if the stack is completely cleared). The stack is strictly local, access to rounding values of superroutines is not possible. When the subroutine is left, the stack will be cleared; no survivors.

The stack has the following operations: ROUND_DUP (to save the original state if necessary), ROUND_PUSH , ROUND_POP, ROUND_CYCLE (see later) and accessor functions for the current rounding.

ROUND_CYCLE cycles through the rounding modes. If we have 3 rounding modes on the stack, this means rounding mode 1,2,3,1,2,3...If we have only one rounding mode on the stack, the instruction does nothing.

Augmented are test functions:
EXACT_ADD_SUPPORTED
EXACT_MUL_SUPPORTED
(It is not advisable to use only IS_ARBITRARY_PRECISION because it is possible that
 the system may have an long accumulator for adding (even in hardware) and does not
 support exact multiplication).

So I can write general functions for both arbitrary precision and fixed precision.

EXACT_ADD_SUPPORTED
IF
  ROUND_PUSH EXACT
ENDIF

DO
 ....
 ROUND_CYCLE
 ADD
 ROUND_CYCLE
LOOP

If this is arbitrary precision, the two rounding values are switched and I have exact addition. If this is fixed precision, only one rounding value remains and is used; ROUND_CYCLE does nothing.
So I can set the necessary roundings at the beginning of the program, making it easy to find and understand. Given that CYCLE does only switches, I must think before how the rounding modes must be set during the execution, avoiding superfluous and unstructured approaches. I have only one current rounding mode, avoiding overhead.

If you have improvements and criticism, be invited to share.


问:
What should my "code sample" look like?
I've just had quite a good phone interview (for a CakePHP-related position, not that it's especially important to the question).  The interviewer seemed to be impressed with my resume and personality.  At the end, though, he asked me to email him a code sample from my existing work project, "to check you're not secretly a terrible programmer, ha ha!"

I'm not too worried that my code can't stand on its own two feet, but I'm very much an intermediate programmer rather than an expert.  What obvious pitfalls should I make sure my code sample doesn't fall into, in case they rule me out on the spot?  Secondly, and this is probably the harder part of the question to answer, what features in a code sample would be so impressive that they would instantly make you much more favourably inclined towards the programmer?

All ideas or suggestions welcomed!

答:
As one opinion from someone who does request code samples when evaluating candidates, there are a few high-level features (content of the code) and a few low-level features (structure of the code).  High level features:

Identity: The flavor of the code. If you're billing yourself as a UI/HCI coder, I want to see a good look/feel for something visual when I run it.  If you're a DB builder, I want to see something interesting with data representation or analysis.  The sample should be something you're proud of.  If you don't have at least one of those, you have no identity.

Maturity: Do you shift strategies for different problems?  Are you solving interesting problems? Would the code or approach be easy to extend to a similar problem? On the converse, do I feel like I am looking at a member of a cargo cult commune?

Communication: Does the code easily explain what it is doing and why?  This does not mean the code needs to be simple.  In fact, it is a bonus to make complex code easy to understand.

The low-level aspects are simpler:

Style: The code should be clean, consistent (follows some established guidelines), and well-documented.

Packaging: There should be at a minimum a short readme, a runnable version, and runnable tests.  The readme should tell me how to run the latter two, as well as why you are demonstrating this particular code sample.

Language(s): I typically ask someone for a sample in the language for the position, as well as the one they feel strongest in.  Gives a good idea of a person's current ceilings.

For a good candidate, I expect a sample to be either: A) A bulletproof small sample or B) A good part of a larger interesting project (e.g., a module from a Github personal repo).  I expect them to be personal projects or academic projects.  If they send one from a paid project, I expect a note that they were given permission to use it.  If I don't get that note, I will cut them from the candidates (weak candidate) or ask them about it during the interview (strong candidate). Not having permission would be a big red flag (probably insurmountable). For an advanced candidate, I expect a disclaimer noting that some of their best source samples cannot be shown because it was done as part of their job.  However, I then expect a gushing testimonial of why they are proud of that unshowable design and how they love it like a child.

Finally, as much as some people chide that "Oh, someone could just get a code sample from the internet," the counter-argument is that most people who do not understand good production-quality code also do not understand it when they see it.  Besides, one can always Google a distinctive line for the code to check.  Also, at best, stealing code will get a candidate to an interview where they embarrass themselves ("So why did you do it this way...?").

As a last note on code from prior employment: Just don't. From an HR standpoint, asking for code from previous employment is inappropriate and a red flag about the company.  You would both have legal liability (i.e., you could both be sued) and it shows that they have no idea what they are doing. Code done for a prior employer should never be given unless the code is already publicly-available or you have explicit permission from that employer. Worse, in a big company, your direct boss may not have the power to give you permission, so have fun with the legal department in that case? I'm sure they'll be overjoyed to expose their IP for an exiting employee.

Title: What should my "code sample" look like?


答:
As you see, the solution might not be very satisfying. The problem of data access at all is, that we have to consider many different aspects which make code not 100% reusable. It's about transactions and locking, and the way e.g. ORM maps a relational database to objects and vice versa.

Mostly if you try to write architecture components, trying to solve the problem you'll soon notice, that you just move the problem to another place. The reason is simply that a bottom-top approach as your question is, is a bad idea.

What we want is an agile top-down strategy. You will see, that most of the accesses are read-only, which (nearly) means no locking and no transactions. Some writes are field updates which must not be synchronized and a few inserts into different tables might need locking and should be in a transaction.

Now to your variants:

Move all methods, even slightly different, as a separate methods into DAO class. This makes DAO complex, their method names will be very long, it would be hard to find correct one.

violates OCP. there should be one entity/table-definition and querybuilding components around it but only depending on the entity itself. That means no large accessor classes.

Forget about fetch joins. Setup application to perform loading when needed (lazy loading). This will reduce number of methods, but database access will be much less effective and transaction must span across entire request, not just controller code.

lazy loading is cool for code which should be more readable focused than performant, e.g. backends with small lists and a few administrators. Not a good idea for uncached permanently accessed frontend pages.

Put complex logic into method when needed. E.g. supply boolean parameters fetchSomething. And method will tweak query according to those parameters. Method implementation will be very complex as I would have to either build query string from pieces or use very cumbersome Criteria API. Method will be hard to read and understand.

parameters like offset and limit are okay, but boolean parameters whether to load sparse or full is too much overhead in code, which might leads to magic behavior.

Leave as is. I generally like this approach. It leads to some code duplication, but not very much and queries are declarative so I don't see much problems with that. The main problem is lack of testability. To test controller I would need to prepare a database, because there's no (or I didn't found) complex JPA mock implementation with supplied in-memory data.

For integration tests yes, you need to save some data to your database (you can use e.g. sqlite). For unit tests no, you mock the service layer according to your controller input and test how controllers behave.

I wonder what approach used in complex projects? I saw 4-th approach and I saw once very complex in-house ORM based on Hibernate.

Big projects actually use service orientated setups on the highest level and use ORM or plain queries according to their needs. There is no one and only solution.

I'm talking now about so-called "repository pattern". I don't really understand what people mean by "service layer" and never saw any need with that, so currently the question is about data repository classes.

IO-Applications are nearly equal. There is a request and a response. The controller is responsible for collecting data from the request to call a service which produces data which will be collected and returned. E.g. business logic and all the use-cases of the software are 100% part of the service layer. Unit-testing the controller by mocking the services is much easier.

"Repository pattern":

I've spent a lot of time on Doctrine and PHP and over the last years I dropped the repositories, because 1% are simply repository operations like a list of countries ordered by name, 80% are more complex DQL or querybuilder queries, also with flat results and the rest are SQL queries I cannot write with DQL.

Result of most of the queries are table with columns from different joined tables. ORM would not makes sense at all, thus I don't use repositories anymore, but a clean service layer and a couple of data access services.

Title: What's the correct approach to DAO layer in presence of ORM framework

Body:
I'm using JPA/Hibernate but probably it doesn't limit question.

Currently I'm writing my data access code in my web controller classes. Thanks to JPA, in most cases this code is very simple, basically simple query with trivial setup.

I tried to move those methods into separate classes to improve code reuse. But I've encountered an important problem. Although there are similar methods, they are not the same. This especially applies to fetching joined classes (tables). In some controllers I don't need fetching those classes. But in some controllers I do need that. So I have the following variants:

Move all methods, even slightly different, as a separate methods into DAO class. This makes DAO complex, their method names will be very long, it would be hard to find correct one.

Forget about fetch joins. Setup application to perform loading when needed (lazy loading). This will reduce number of methods, but database access will be much less effective and transaction must span across entire request, not just controller code.

Put complex logic into method when needed. E.g. supply boolean parameters fetchSomething. And method will tweak query according to those parameters. Method implementation will be very complex as I would have to either build query string from pieces or use very cumbersome Criteria API. Method will be hard to read and understand.

Leave as is. I generally like this approach. It leads to some code duplication, but not very much and queries are declarative so I don't see much problems with that. The main problem is lack of testability. To test controller I would need to prepare a database, because there's no (or I didn't found) complex JPA mock implementation with supplied in-memory data.

I wonder what approach used in complex projects? I saw 4-th approach and I saw once very complex in-house ORM based on Hibernate.

I'm talking now about so-called "repository pattern". I don't really understand what people mean by "service layer" and never saw any need with that, so currently the question is about data repository classes.


答:
Filter:

In order to implement a filter, you could pass a simple string that is equivalent to the "WHERE " part of the select statement that gets executed, but you wouldn't want to just directly append what gets passed in to the actual query that gets executed since it creates an exploit that can be used against the DB.  So instead of using the string directly, you could have some process that builds up the filter string, based on the input string.

For example: Parse and tokenize the string.  Group over each AND/OR token. Match the values and comparison operators to a predefined list, then build up the filter string using the elements from the predefined list that you matched.  Finally concatenate the AND/OR groups.  This could get complicated if you want to implement all possible filter expressions.

For a list of what to implement, see http://dev.mysql.com/doc/refman/5.6/en/expressions.html and http://dev.mysql.com/doc/refman/5.6/en/functions.html.

Data Types:

As for typing the objects in Add and Update, the types are already predefined by the MySQL table.  Therefore, you may compile a list of tables beforehand with their associated column types, then use that mapping to cast the Dictionary of objects once the WebService receives the request.  The client side would be completely unaware of this process, and would continue to pass data as Dictionary<String, object> dataSet.  If you encounter a new table, you can also create a new mapping entry on the fly by executing "DESCRIBE table" and storing the table information along with the other ones you have already defined.

Title: Design interface for WebService to access several MySQL databases

Body:
I am currently trying to design an interface for a WebService that can access several MySQL databases. There will be 4 operations available, Add(), Read(), Update() and Delete().

The WebService just needs to assemble an SQL statement based on the called method and execute it on the target database. But now I am struggling to find a good method signature that provides all needed information to the WebService and is simple to use. So if I want to assemble an INSERT statement when the Add() method was called, I don't know how I can pass all the column information with the corresponding values and types. For example a .NET DateTime should be stored with the MySQL data type for date/time. So I'd need some kind of wrapper object that check the properties via reflection to get the type.

Here are some thoughts:

```<code>Add(String db, String table, Dictionary<String, object> dataSet);
Read(String db, String table, String column, filter?);
Update(String db, String table, String idToReplace, Dictionary<String, object> dataSet);
Delete(String db, String table, String idToDelete);
</code>```

I am not sure how to specify a filter possibility for the SELECT statement in the Read() method. In addition I don't know how to pass parameter information in the Add() and Update() methods. I don't want to save only string values in the db, I'd like to have passed some type information so that the WebService can match them to the corresponding MySQL data types.


问:
Is physical Agile board "always" better than electronic tool?
Whenever the question comes up on which Agile tool to use use there always some people that answer "don't use an electronic tool because you will lose the big-visible-board advantage which better generate team conversation".

Is this always the case or are there any contexts where an electronic tool is a better choice?  What are some of the pros and cons of each approach?

答:
I don't think an electronic board is a necessity for distributed teams.   There are techniques like having pairing people up into buddys across locations which can help the teams feel more connected.

That is not to say that a virtual story board is never the correct solution.  Having both is sometimes valid as well.   As always, it depends...

If you do end up with both, tools like http://www.wallsync.net can help you keep them both in sync.

There are some advantages of physical boards that are hard (if not impossible) to replicate with a virtual one, http://www.wallsync.net/blog/physical-cards-are-better-1/


问:
How do you find out what resources are unmanaged?
Looking through the .NET documentation, specifically the WebRequest class, I don't see any information indicating that I should wrap an instantiation of it in a using statement. Even the provided example does not do this. In most examples online however, this is exactly what's done.

My question is then, how do I know specifically which classes need to be disposed? Is there a general rule of thumb or do you inspect class definitions to see if they somehow handle unmanaged resources?

答:
My question is then, how do I know specifically which classes need to be disposed?

You could look into the MSDN documentation for each class. That would be boring and cumbersome, but work.

If you are using a Visual Studio version that supports it, you should turn on Static Code Analysis in the options of your project. It will give you a warning for each object that you did not properly dispose, either through a using block or implementing a proper dispose pattern yourself in case of class members.


问:
Software License Web Application
We are in the process of building a web application for a client and they have inquired about owning the code for the site. We would like to issue a license agreement to the client for use of the code if we for any reason we are no longer working on the project.   We would like to have ownership of the code but allow them use wherever they see fit, the only limitation we would like to have is the sale of the code. The are a company with several employees and will only be using the application within their company.

What would such a license agreement look like?

答:
They don't really want ownership of your code.  What they really want is the peace of mind they get by having the code in-house, just in case you go belly-up.

License the source code to them as a company.  They don't get resell rights, and they're not allowed to give or sell the code or any parts of it to anyone else.

Make sure there is an additional charge for this.  It is an additional benefit, after all.

Title: Software License Web Application


问:
How to determine if a class meets the single responsibility principle?
The Single Responsibility Principle is based on the high cohesion principle. The difference between the two is that a highly cohesive classes features a set of responsibilities that are strongly related, while classes adhering to SRP have just one responsibility. </p>

<p>But how do we determine whether a particular class features a set of responsibilities and is thus just highly cohesive, or whether it has only one responsibility and thus adheres to SRP? In other words, isn't it more or less subjective, since some may consider a class very granular (and as such will believe the class adheres to SRP), while others may consider it not granular enough? </p>

答:
Single Responsibility Principles says that each software module should have only one reason to change. On a recent article Uncle Bob explained "reason to change",

However, as you think about this principle, remember that the reasons for change are people. It is people who request changes. And you don't want to confuse those people, or yourself, by mixing together the code that many different people care about for different reasons.

He further explained the concept with an example HERE.


问:
Programmatically extending Hibernate table/entity definitions in Spring, how?
I would like to know if there is a way —maybe with AOP— to extend table/entity definitions so that I can add functionality across the board that requires persistence.

Let me explain what I want to do with a concrete example. Let's suppose we have a simple ecommerce system:

User

id

name

password

Item

id

name

price

stock

ShoppingCart

id

user_id

ShoppingCartItems

id

shopping_cart_id

item_id

Order

id

shopping_cart_id

Purchase

id

order_id

invoice_number

Now, let's suppose that we think:

hey, wouldn't it be great if we could add a field to timestamp all entities?

You would now know things like:

When a User registered

When an item was created

When a shopping cart was created

When an item was added to a shopping cart

When an order was placed

When was the order was processed and paid

Now you have another great idea:

What if there was a status field for all entities so I could soft-delete or archive items, etc.

And yet another idea:

What if there was a text field called meta to serialize unimportant data, but that could help adding functionality without painful database modifications.

There are solutions I can think of (meeting relational integrity requirement):

Of course, you would need to go back, change your tables, modify your implementations so that when creating/updated you save the timestamp of then operation, same for status, same for meta.

And a somewhat convoluted but very modular way. Create some sort of plugin, that creates a table that handles the field, and 1 pivot for each entity. And through events, associate the extended data to the existing entities accordingly.

But what if... you could just tell Hibernate to extend the table definitions programmatically at run time, and add the persistence behaviors through something like AOP to inject functionality.

I actually did the first thing (programmatically extending table definitions outside existing implementation) in Doctrine successfully once, but I'm just starting to learn Hibernate. OTOH, I'm just starting to learn Spring and know the basics on AOP, so at least in my mind it is feasible to intercept Hibernate's configuration process where it understands table definitions.

So, is this possible with Spring and Hibernate?, how?, can you provide an example?

Addendum: The problem is that I need to do this more than once, and it could come from anywhere. AOP was my answer to the multiple inheritance problem since extending classes would be too constrained, however, in the past I did it with Events and worked just as fine... IIRC the problem is that I had to hack Doctrine in order to do this to fire an event at the time between when the model description was being converted from configuration files into actual models.

AOP is not a must, just an idea for an approach if such an event or dependency injection mechanism is not already in place. Another approach could be mixins, but I come back to AOP as probably the most elegant solution.

The main requirement here is to not modify the original model's code.

Disclaimer: I'm not an expert on AOP but I'm fairly familiar to the concepts.

答:
Hibernate has events to which you can react using interceptors. Here's an incomplete list of events:

onDelete

onSave

instantiate

afterTransactionCompletion

Take a look at org.hibernate.Interceptor to see complete list of events to which you can react using Interceptor.

Simplified example of classical usage is auditting interceptor which sets "lastmodified":

```<code>public class AuditInterceptor extends EmptyInterceptor {
    @Override public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
        if (entity instanceof AuditedEntity) {
            int index = findElementIndex(propertyNames, "dateModified");

            if (index >= 0) {
                state[index] = new Date();

                return true; // entity has been modified
            }
        }

        return false; // entity was not modified
    }

    private int findElementIndex(String[] propertyNames, String element) {
        for (int i = 0; i < propertyNames.length; i++) {
            if (element.equals(propertyNames[i])) {
                return i;
            }
        }

        return -1;
    }
}
</code>```

Interceptors might not be enough for your needs. Luckily Hibernate's architecture is quite pluggable - most of the functionality consists of "Services", resp. service implementations which implement service roles (interfaces). You can override default implementations with your custom ones, or even add totally new services. But this might be more involved and might break in future versions of Hibernate. I'd recommend to stick with interceptors as much as possible.

Body:
Hibernate has events to which you can react using interceptors. Here's an incomplete list of events:

onDelete

onSave

instantiate

afterTransactionCompletion

Take a look at org.hibernate.Interceptor to see complete list of events to which you can react using Interceptor.

Simplified example of classical usage is auditting interceptor which sets "lastmodified":

public class AuditInterceptor extends EmptyInterceptor {
    @Override public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException {
        if (entity instanceof AuditedEntity) {
            int index = findElementIndex(propertyNames, "dateModified");

            if (index >= 0) {
                state[index] = new Date();

                return true; // entity has been modified
            }
        }

        return false; // entity was not modified
    }

    private int findElementIndex(String[] propertyNames, String element) {
        for (int i = 0; i < propertyNames.length; i++) {
            if (element.equals(propertyNames[i])) {
                return i;
            }
        }

        return -1;
    }
}

Interceptors might not be enough for your needs. Luckily Hibernate's architecture is quite pluggable - most of the functionality consists of "Services", resp. service implementations which implement service roles (interfaces). You can override default implementations with your custom ones, or even add totally new services. But this might be more involved and might break in future versions of Hibernate. I'd recommend to stick with interceptors as much as possible.


问:
Including standard library headers only once across multiple program headers
I am writing a program with multiple headers and code files, as so:

message.h

message.cpp

option.h

option.cpp

main.cpp

message.h includes option.h as message.cpp requires the definition of the class defined therein.

There are quite a few other files, however just to keep it brief...

If I want to call a function such as memcpy, I include string.h. I include string.h in message.h - so it works fine in message.cpp, but if I want to use it in option.cpp it gives me an error.

So I see two options:

In option.h, I include message.h again. This should not be an issue as I have include guards in both header files, however I feel it's rather messy.

I include string.h in option.h. Now I am including string.h in both of my header files.

This gives me the declaration for memcpy and so I can get on with my programming. However when I'm including 10 different headers for many different functions, it's going to be messy again.

What is a good way for me to structure my code to get around this issue, to keep my code as neat as possible? It has crossed my mind to make all my includes in one separate file and include that in all my header files, could this be a problem in the future, and is there a better way I can go about this to ensure my code is maintainable?

答:
It's perfectly fine to #include additional headers in .cpp files that are not included in the corresponding .h. In fact, you should always do so if the header is not required in the .h, because that potentially speeds up compilation of anything that depends on your .h but not on your .cpp. See this classic Guru of the Week for some tips on minimizing unnecessary #includes in your header files (I don't think any of them have gone out of date yet).

In general, you should avoid relying on what other files do or don't include as much as possible, since that makes your code more modular (and more portable to other standard libraries). That means every file should explicitly and directly #include every header that it needs to know about (I'm assuming every header file has #include guards or an equivalent like #pragma once, since not having those is a far bigger problem). If the message.h author decides to follow that GotW I linked and cut down their superfluous #includes, it would be awfully frustrating if he unknowingly broke option.h/.cpp in the process. At work we once discovered some of our code would compile under GCC but not Clang solely because we were missing a few standard library #includes, and thus unknowingly depended on the fact that certain GCC headers #included each other.

So the direct answer to your original question is: You should directly include string.h in every file you plan on using it, and no others. Assuming you aren't using memcpy() inside option.h (that seems unlikely), that means the #include  belongs in option.cpp.


问:
Is the 80 character limit still relevant in times of widescreen monitors?
on a widescreen monitor one can easily see more than 80 characters at a time, without scrollbars. even linus torvalds sees the 80 character limit as outdated.

so, is the 80 character limit still relevant in times of widescreen monitors?

答: If you use an editor in a GUI, then the 80 characters per line is irrelevant, since most decent editors - for example Notepad++ - have a button to toggle line wrap. With that, it should not be a problem, even when viewing the code in a thin window.</p>


问:
Should I use: One event multiple subscribers or multiple events multiple subscribers
I am writing a data acquisition application. I wondering whether I should use one event multiple subscribers or multiple events multiple subscribers. I am worried about performance. Also could I improve performance by offloading the subscribers to a different thread?

Here is an example of what I mean by multiple events Multiple subscribers.

```<code>public delegate void EventChannelUpdated(object sender, EventArgsChannelUpdated e);

public class EventArgsChannelUpdated : EventArgs
{
    public chCell chCell;
}

public delegate void EventLimitExceeded(object sender, EventArgsLimitExceeded args);

public class EventArgsLimitExceeded : EventArgs
{
}

class Example
{
    public List<Channel> AllChannels;
}

public class Saver_allChannels
{
    private Example example;

    public event EventChannelUpdated eventChannelUpdated;

    public void DataAdded()
    {

        //** this part is pseudo code as I have simplified some of the hwObjs structure
        for (int i = 0; i < hwObjs.Count; i++)
        {
            example.ListOfchannels[i].addSamples(hwObjs[i].Reading);
        }
    }
}

public class Channel
{
    public List<chCell> column { get; set; }

    public string label { get; set; }

    public event EventChannelUpdated eventChannelUpdated;

    public double multipler { get; set; }

    public void addSamples(double unScaledValue)
    {
        chCell temp = new chCell() {channel = this, scaledValue = unScaledValue*multipler};
        column.Add(temp);
        eventChannelUpdated(this,new EventArgsChannelUpdated(){chCell = temp});
    }
}

public class chCell
{
    public double scaledValue { get; set; }

    public Channel channel { get; set; } //** parent Channel List
}

public class Monitor
{
    public double Limit;

    public event EventLimitExceeded eventLimitExceed;

    public void Handle_EventChannelUpdated(object sender, EventArgsChannelUpdated args)
    {
        if (args.chCell.scaledValue > Limit)
        {
            eventLimitExceed(this, new EventArgsLimitExceeded());
        }
    }
}
</code>```

Here is an example of what I mean by one event multiple subscribers

```<code>public delegate void EventChannelUpdated(object sender, EventArgsChannelsUpdated e);

public class EventArgsChannelsUpdated : EventArgs
{
    public List<chCell> RowOfchCells;
}

public delegate void EventLimitExceeded(object sender, EventArgsLimitExceeded args);

public class EventArgsLimitExceeded : EventArgs
{
}

class Example
{
    public List<Channel> ListOfchannels;
}

public class Saver_allChannels
{
    Example example;

    public event EventChannelUpdated eventChannelUpdated;

    public void DataAdded()
    {

        List<chCell> LastRow = new List<chCell>();

        //** this part is pseudo code as I have simplified some of the hwObjs structure
        for (int i = 0; i < hwObjs.Count; i++)
        {
            example.ListOfchannels[i].addSamples(hwObjs[i].Reading);
            LastRow.Add(new chCell() {channel = example.ListOfchannels[i], Value = hwObjs[i].Reading});
        }

        eventChannelUpdated(this, new EventArgsChannelsUpdated() { RowOfchCells = LastRow });

    }
}

public class Channel
{
    public List<chCell> column { get; set; }

    public string label { get; set; }

    public double multipler { get; set; }

    public void addSamples(double unScaledValue)
    {
        chCell temp = new chCell() {channel = this, scaledValue = unScaledValue*multipler};
        column.Add(temp);
    }
}

public class chCell
{
    public double scaledValue { get; set; }

    public Channel channel { get; set; } //** parent Channel List
}

public class Monitor
{
    public double Limit;

    public Channel subbedChannel;

    public event EventLimitExceeded eventLimitExceed;

    public void Handle_EventChannelUpdated(object sender, EventArgsChannelsUpdated args)
    {
        double value = (args.RowOfchCells.FirstOrDefault(x => x.channel == subbedChannel)).scaledValue;
        //** do something with value
    }
}
</code>```

答:
If you get these items in batches, then it obviously makes sense to use events that notify  about changes once per batch:

```<code>public class AllChannelsSaver
{
    public void Add(IEnumerable<ChCell> cells)
    {
        this.m_cells.Add(cells);

        this.OnCellsAdded(cells);
    }

    public event EventHandler<MultipleCellsAddedEventArgs> CellsAdded;

    private void OnCellsAdded(IEnumerable<ChCell> cells)
    {
        var cellsAddedDelegate = this.CellsAdded;

        if (cellsAddedDelegate == null)
            return;

        cellsAddedDelegate(this, new MultipleCellsAddedEventArgs(cells));
    }
}
</code>```

Taking into account that you operate over collections it even makes sense to consider standard INotifyCollectionChanged interface with its CollectionChanged event, depending on whether it suits the domain logic or a more appropriately named event will fit better.

But it is also important to think about two things:

Who is (or should be) responsible for adding items and notifying? Is it all channels object, or is it an individual Channel who is responsible? Do all channels get all cells, or each individual channel gets specific cell?

Ease of use. Your second example's Handle_EventChannelUpdated uses search over the items to get the required item by some condition. If it is not just some example, but a usual usage scenario, then it is obviously something that needs to be reconsidered. Searching each time for a single item, that can be obtained directly is not the best architecture.

If you are not sure what is better from these two points of view, then you can just try to cater to both scenarios - use events on both the global AllChannels aggregator and the individual channels. Just try not to handle the same item twice (perhaps, use some additional Handled flag in EventArgs if it is possible).

Offloading subscribers to different threads

You can do it. The most simple and less error-prone way is to use TPL with Parallel.ForEach over the delegates you get from Delegate.GetInvocationList call:

```<code>public static void Execute(object sender, EventArgs args, Int32 number, Int32 delayMs)
{
    Console.WriteLine("Entering {0}", number);

    Console.WriteLine("Sender = {0}; EventArgs = {1}",
        sender,
        args);

    Thread.Sleep(delayMs);

    Console.WriteLine("Exiting {0}", number);
}

public static void Main()
{
    var eventHandler = new EventHandler((sender, args) =>
        Execute(sender, args, 0, 1000));

    eventHandler += (sender, args) =>
        Execute(sender, args, 1, 1000);

    eventHandler += (sender, args) =>
        Execute(sender, args, 2, 2000);

    var senderArg = typeof(Program);
    var eventArgs = new EventArgs();

    Parallel
        .ForEach(
            eventHandler
                .GetInvocationList()
                .Cast<EventHandler>(),
            (handler) =>
                handler(senderArg, eventArgs));

    Console.WriteLine("All is done. Press any key.");
    Console.ReadKey(false);
}
</code>```

Just make sure that your handlers are not(or make them so) dependent on being raised on the same thread (like handlers modifying UI).

It is also a possible idea to reconsider responsibilies once more - make handlers responsible for offloading. So the handlers themselves offload long-performing job to other threads. But you will have to be very careful, because it will probably violate the invariant that after raising the event all changes have been already handled(because some thread may still continue to process them even after OnEvent returns).

P.S.: While it is not directly related to your question, I'd like to add some points:

Try not to create your specific new delegate classes. While they may add some degree of type-safety, in most cases it is better to use some of the standard generic delegate classes like EventHandler or Action<...> with Func<...>.

I do not want to look like someone who forces you to use a preferred naming convention, but it is still a good idea for you to look into C# naming guidelines on MSDN. Most languages have some more or less widespread, or even standardized way of naming. And such conventions(when you become accustomed to them) can make reading and sharing of programs much easier.

Body:
If you get these items in batches, then it obviously makes sense to use events that notify  about changes once per batch:

public class AllChannelsSaver
{
    public void Add(IEnumerable<ChCell> cells)
    {
        this.m_cells.Add(cells);

        this.OnCellsAdded(cells);
    }

    public event EventHandler<MultipleCellsAddedEventArgs> CellsAdded;

    private void OnCellsAdded(IEnumerable<ChCell> cells)
    {
        var cellsAddedDelegate = this.CellsAdded;

        if (cellsAddedDelegate == null)
            return;

        cellsAddedDelegate(this, new MultipleCellsAddedEventArgs(cells));
    }
}

Taking into account that you operate over collections it even makes sense to consider standard INotifyCollectionChanged interface with its CollectionChanged event, depending on whether it suits the domain logic or a more appropriately named event will fit better.

But it is also important to think about two things:

Who is (or should be) responsible for adding items and notifying? Is it all channels object, or is it an individual Channel who is responsible? Do all channels get all cells, or each individual channel gets specific cell?

Ease of use. Your second example's Handle_EventChannelUpdated uses search over the items to get the required item by some condition. If it is not just some example, but a usual usage scenario, then it is obviously something that needs to be reconsidered. Searching each time for a single item, that can be obtained directly is not the best architecture.

If you are not sure what is better from these two points of view, then you can just try to cater to both scenarios - use events on both the global AllChannels aggregator and the individual channels. Just try not to handle the same item twice (perhaps, use some additional Handled flag in EventArgs if it is possible).

Offloading subscribers to different threads

You can do it. The most simple and less error-prone way is to use TPL with Parallel.ForEach over the delegates you get from Delegate.GetInvocationList call:

public static void Execute(object sender, EventArgs args, Int32 number, Int32 delayMs)
{
    Console.WriteLine("Entering {0}", number);

    Console.WriteLine("Sender = {0}; EventArgs = {1}",
        sender,
        args);

    Thread.Sleep(delayMs);

    Console.WriteLine("Exiting {0}", number);
}

public static void Main()
{
    var eventHandler = new EventHandler((sender, args) =>
        Execute(sender, args, 0, 1000));

    eventHandler += (sender, args) =>
        Execute(sender, args, 1, 1000);

    eventHandler += (sender, args) =>
        Execute(sender, args, 2, 2000);

    var senderArg = typeof(Program);
    var eventArgs = new EventArgs();

    Parallel
        .ForEach(
            eventHandler
                .GetInvocationList()
                .Cast<EventHandler>(),
            (handler) =>
                handler(senderArg, eventArgs));

    Console.WriteLine("All is done. Press any key.");
    Console.ReadKey(false);
}

Just make sure that your handlers are not(or make them so) dependent on being raised on the same thread (like handlers modifying UI).

It is also a possible idea to reconsider responsibilies once more - make handlers responsible for offloading. So the handlers themselves offload long-performing job to other threads. But you will have to be very careful, because it will probably violate the invariant that after raising the event all changes have been already handled(because some thread may still continue to process them even after OnEvent returns).

P.S.: While it is not directly related to your question, I'd like to add some points:

Try not to create your specific new delegate classes. While they may add some degree of type-safety, in most cases it is better to use some of the standard generic delegate classes like EventHandler or Action<...> with Func<...>.

I do not want to look like someone who forces you to use a preferred naming convention, but it is still a good idea for you to look into C# naming guidelines on MSDN. Most languages have some more or less widespread, or even standardized way of naming. And such conventions(when you become accustomed to them) can make reading and sharing of programs much easier.


问:
Documenting MVC JSON API
I've got an MVC5 application that we're using an a JSON API for various clients (mobile apps, other web applications, etc.) as well as a traditional web application. Controller actions that return JSON data are the ones that are part of the API.

My question is - what's the best way to document what functions are exposed? I'm new to this API thing, but it seems like people should be able to access and use the API without having to dig into the codebase.

Options:

Internal Wiki - We have one. I make an article that contains all the functions that are exposed, and ideally keep it updated. This is the easiest, but least maintainable approach in my opinion. Anybody who adds or changes any of the API functions will have to go back and make sure this article is updated.

Discovery endpoint - A well-known API path that provides a self-documenting (auto-generated?) application description that describes the paths and functions of the API.

Some other framework I don't know about?

答:
We use RAML which is a formalized format to describe your REST services using YAML. Example:

```<code>title: World Music API
baseUri: http://example.api.com/{version}
version: v1
traits:
  - paged:
      queryParameters:
        pages:
          description: The number of pages to return
          type: number
  - secured: !include http://raml-example.com/secured.yml
/songs:
  is: [ paged, secured ]
  get:
    queryParameters:
      genre:
        description: filter the songs by genre
  post:
  /{songId}:
    get:
      responses:
        200:
          body:
            application/json:
              schema: |
                { "$schema": "http://json-schema.org/schema",
                  "type": "object",
                  "description": "A canonical song",
                  "properties": {
                    "title":  { "type": "string" },
                    "artist": { "type": "string" }
                  },
                  "required": [ "title", "artist" ]
                }
            application/xml:
    delete:
      description: |
        This method will *delete* an **individual song**
</code>```

Its formalized nature has several advantages:

it is not ambiguous (which is often a problem with normal non-format wiki docs)

it can be validated

it can be used to create a skeleton of automated tests (there's a SoapUI plugin for that)

it can be used to generate (beautiful) documentation - see e.g. https://anypoint.mulesoft.com/apiplatform/popular/#/portals/apis/5502/versions/5487/pages/30295

it can be used to generate clients/server code (in a similar way how this is done in SOAP) - see http://raml.org/projects.html

you can define "trait" - e.g. pagination with defined parameters which can then be included in multiple web services. You don't have to duplicate your documentation and you get more consistent APIs.

Title: Documenting MVC JSON API

Body:
We use RAML which is a formalized format to describe your REST services using YAML. Example:

title: World Music API
baseUri: http://example.api.com/{version}
version: v1
traits:
  - paged:
      queryParameters:
        pages:
          description: The number of pages to return
          type: number
  - secured: !include http://raml-example.com/secured.yml
/songs:
  is: [ paged, secured ]
  get:
    queryParameters:
      genre:
        description: filter the songs by genre
  post:
  /{songId}:
    get:
      responses:
        200:
          body:
            application/json:
              schema: |
                { "$schema": "http://json-schema.org/schema",
                  "type": "object",
                  "description": "A canonical song",
                  "properties": {
                    "title":  { "type": "string" },
                    "artist": { "type": "string" }
                  },
                  "required": [ "title", "artist" ]
                }
            application/xml:
    delete:
      description: |
        This method will *delete* an **individual song**

Its formalized nature has several advantages:

it is not ambiguous (which is often a problem with normal non-format wiki docs)

it can be validated

it can be used to create a skeleton of automated tests (there's a SoapUI plugin for that)

it can be used to generate (beautiful) documentation - see e.g. https://anypoint.mulesoft.com/apiplatform/popular/#/portals/apis/5502/versions/5487/pages/30295

it can be used to generate clients/server code (in a similar way how this is done in SOAP) - see http://raml.org/projects.html

you can define "trait" - e.g. pagination with defined parameters which can then be included in multiple web services. You don't have to duplicate your documentation and you get more consistent APIs.


答:
Use both.

But you need the physical board first. The electronic system should be for detailed docs and attachments you want to associate with a task. Not managing the process.

I would say the physical board is best for running the scrum, the electronic board is best for running the backlog

Title: Is physical Agile board "always" better than electronic tool?

Body:
Whenever the question comes up on which Agile tool to use use there always some people that answer "don't use an electronic tool because you will lose the big-visible-board advantage which better generate team conversation".

Is this always the case or are there any contexts where an electronic tool is a better choice?  What are some of the pros and cons of each approach?


问:
Is there any point in preventing developers from having a local copy of the database in their machine?
Is there any point to having a dedicated development database server(s) that all developers can use, i.e. they don't have a local copy of the db in their machines. Quite clearly, this will slow down development but I'm curious whether anyone actually does this in the enterprise level. I know I should trust the devs we hire and I'm guessing this will mostly be the kind of answers that I will be getting but if anyone actually does this I would want to know if it's even worth doing.

UPDATE:

Great answers. My question arises from this question from quora regarding source code protection: http://www.quora.com/How-does-Facebook-protect-their-source-code

Here's the pertinent answer that got me thinking:

Facebook (and Google and probably many others) don't have employees check out code on their laptops. Code is checked out on developer servers or workstations and employees connect to these to work. These are only accessible on the corporate network, and connecting  from outside the network requires VPN, which itself requires multi-factor authentication.

Now that I think about this, if developer have terminal access to the development servers then they must have access to mostly whatever is in there which most likely includes the db.

答:
If you have Devs and DBAs rather than just Devs then you should probably only allow devs to access the DB via SProcs. and thus knowledge of the underling schema is not needed. A test DB could be created which always returned static data in response to sproc calls and Dev velocity would be unaffected (possibly even improved!)

However, in my experience, even if a company does have a separated DBA team, its usually the Devs who write the sprocs and table schemas etc which are then handed off to DBAs who look after the DB infrastructure/backups/indexing etc

In this case its ridiculous to hide the schema from the devs who are writing it.

Also, I'm not sure any security benefit is gained by hiding the schema. Or even the source code! Unless you have a very technical cutting edge product (in which case you should patent the algorithms) Anyone can code up a better version in a few months.

In fact, if your product is any good, you can probably already download an open source version for free.

The value of a software company is it user base and copyrighted names. Not its code.

Answer to rewritten question : Should Devs be allowed local Databases

OK, Assuming your Devs create the database schema there is no difference (security wise) between code and DB schema.

ie. You should have a DB project and maintain the schema in a source control system. Having a local DB is just an implementation of the schema and increases no risk.

Now you can argue that not having source code locally on a laptop which is taken out of the building is a  security benefit. Even if you trust your devs laptops are lost/stolen all the time.

But this isn't really an argument for or against local vs development DBs its an argument for not taking development computers home. Which, unless you have people working from home why would you?

If you have remote workers, then yes you can address security issues about stolen computers releasing confidential info. but I would be far more worried about confidential customer data/emails etc rather than sourcecode/db schema