问:
Understanding how variable assignment works
When I started learning C programming a few years ago, my tutor taught me similar to most of the tutors around the world. She said me the very basic things like any int datatype is of 2 bytes memory. If the following is my code,

```<code>#include"stdio.h"
#include"conio.h"
void main()
{
    clrscr();
    int i,n;
    n = 0;
    for(i=0;i<3;i++)
        n = n + i;
    printf("%d",n); //obviously it prints 3
    getch();
}
</code>```

she will explain like what I have written below. Here my teacher starts off her class yet again. . .

Listen students. Here we have two integer values. So let us draw two boxes each of 2 bytes memory.The first box be the memory space of i and the second box be that of n. At n = 0; 0 gets stored into the box n. As the control gets into the loop, 0 gets stored into the box i intially.

0 0

Now the condition is checked. i < 3. Condition gets true. So now the value of n changes from 0 to n+i i.e., 0+0=0. The first iteration then ends after the increment statement. Now i gets incremented to 1. So our picture becomes like this.

1 0

And now i < 3 again. Condtion gets true. n changes from 0 to n + i i.e., 0+1=1. Don't forget the increment my dears. Only then our iteration gets completed. i++ makes our i to 2 now. And the picture will now look like

2 1

She will go on similarly step by step and will complete when both the boxes get 3, 3 values.

So thats it kids. After we get our boxes like this

3 3

the value of n gets printed on the screen.

3

By that time, I was merely like a kid nodding its head when a teacher claims earth as a  circular mass. I never asked her any questions. I felt logically she was perfect. But now I am plentiful of queries. If there is a statement like n = n + i;, won't there be a conflict as both the destination space and the operation space is the same n box? Will the operations be done with the help of any default temporary space for calculations? What will happen if I use a recursive code like the following snippet.

```<code>int factorial(int n)
{
    if(n < 2)
    {
        return n;
    }
    else
    {
        n = n * factorial(n - 1);
        return n;
    }
}
</code>```

How could it be possible to use a single n box as my tutor taught? Won't a new n box be created whenever factorial(n - 1) is called? If I am right, how could the computer know which n box value to be returned? Somebody help me please. I am pulling of hairs from ma head!

答:
How could it be possible to use a single n box as my tutor taught? Won't a new n box be created whenever factorial(n - 1) is called?

Yes, exactly.  Each time you call a function, additional memory is set aside for the function arguments and local variables.

Let's drop a couple of levels below C and talk about how a compiled program is laid out in memory1.  We're going to assume a 32-bit, x86-like system for this discussion.

While the details vary from platform to platform, the general concepts are the same for most systems you're likely to work on.  When a compiled program is loaded into memory, it's usually divided up into several logical segments; one segment contains the machine code, another contains constant (read-only) data items, another contains space for non-constant, global data items, another contains space for the stack, another contains the space for the heap, etc.  The general layout looks something like the following (taken from this page):

```<code>              +------------------------+
high address  | Command line arguments |
              | and environment vars   |
              +------------------------+
              |         stack          |
              | - - - - - - - - - - -  |
              |           |            |
              |           V            |
              |                        |
              |           ^            |
              |           |            |
              | - - - - - - - - - - -  |
              |          heap          |
              +------------------------+
              |    global and read-    |
              |       only data        |
              +------------------------+
 low address  |     program text       |
              |    (machine code)      |
              +------------------------+
</code>```

As your program runs, it uses the stack to store function arguments and local variables, along with some program state (previous frame pointer, address to the next instruction).  On x86-like systems, the stack grows "downwards", towards decreasing addresses.  Among the registers2 provided, there are usually two to keep track of what's on the stack.  There's the stack pointer, which points to the most recent item on the stack, and the frame pointer3, which points to the current stack frame.  A stack frame is a region of the stack that contains the arguments and local variables for the current function, along with any saved program state:

```<code>             + - - - - - - - - -  +
high address |  previous stack    |
             |       frame        |
             + - - - - - - - - -  +
             |  previous stack    |
             |       frame        |
             +--------------------+  ----------------------+
             | function arguments |                        |
             |        ...         |                        |
             +--------------------+                        |
             |   return address   |                        |
             +--------------------+                        +-- current stack frame
             | old frame pointer  | <-- frame pointer      |
             +--------------------+                        |
             |  local variables   |                        |
             |        ...         | <-- stack pointer      |
             +--------------------+ -----------------------+
 low address |  available memory  |
             + - - - - - - - - -  +
</code>```

On the systems I'm familiar with, the function arguments and program state are stored "above" the location stored in the frame pointer, and local variables are stored "below" it.  Within the generated assembly code, arguments and variables are referred to by their offset from the address stored in the frame pointer.  On x86. it would look something like

```<code>cmpl  $1, 8(%ebp)   ;; compare the literal value 1 to the first function argument
movl  $1, -4(%ebp)  ;; write the literal value 1 to the first local variable
</code>```

The first function argument is stored 8 bytes "above" the address value stored in the frame pointer %ebp, while the first local variable would be 4 bytes "below" it (note that this assumes a 32-bit system).

The exact size of the frame depends on how many arguments and local variables need to be stored, although the platform may also require it to be aligned to certain boundary (IOW, the size of the frame must be a multiple of some number of bytes, usually 4 or 8, sometimes 16; for the purposes of this discussion, we're not going to worry about alignment).

Suppose your factorial function is called with an argument value of 3:

```<code>x = factorial( 3 );
</code>```

A new stack frame will be set up that looks something like this:

```<code> +--------------------+
 |         3          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer | <-- frame pointer, stack pointer
 +--------------------+
</code>```

where the "return address" is the address of the instruction immediately following the function call in the caller (in this case, it would be the instruction that assigns the result of factorial(3) to x).

Since there are no local variables, no space is allocated for them in the stack frame.  Now, since n is not less than 2, you execute the line

```<code>n = n * factorial( n - 1 );
</code>```

This means factorial is called again, this time with an argument value of 2.  A new stack frame is created

```<code> +--------------------+
 |         3          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer |
 +--------------------+
 |         2          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer | <-- frame pointer, stack pointer
 +--------------------+
</code>```

n is still not less than 2, so we call factorial again with an argument of 1:

```<code> +--------------------+
 |         3          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer |
 +--------------------+
 |         2          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer |
 +--------------------+
 |         1          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer | <-- frame pointer, stack pointer
 +--------------------+
</code>```

1 is less than 2, so we execute the line

```<code>return n;
</code>```

The common convention for returning values from functions is to write the value to a particular register.  On x86, integer values are returned through register %eax, so the compiled code will do something like

```<code>movl  8(%ebp), %eax
</code>```

Now register %eax will contain the value 1.

When the function returns, the stack and frame pointers are restored to their previous values (the stack contents are left as-is):

```<code>             + - - - - - - - - -  +
high address |  previous stack    |
             |       frame        |
             + - - - - - - - - -  +
             |  previous stack    |
             |       frame        |
             +--------------------+  ----------------------+
             | function arguments |                        |
             |        ...         |                        |
             +--------------------+                        |
             |   return address   |                        |
             +--------------------+                        +-- current stack frame
             | old frame pointer  | <-- frame pointer      |
             +--------------------+                        |
             |  local variables   |                        |
             |        ...         | <-- stack pointer      |
             +--------------------+ -----------------------+
 low address |  available memory  |
             + - - - - - - - - -  +
</code>```0

So now we need to execute the remainder of

```<code>             + - - - - - - - - -  +
high address |  previous stack    |
             |       frame        |
             + - - - - - - - - -  +
             |  previous stack    |
             |       frame        |
             +--------------------+  ----------------------+
             | function arguments |                        |
             |        ...         |                        |
             +--------------------+                        |
             |   return address   |                        |
             +--------------------+                        +-- current stack frame
             | old frame pointer  | <-- frame pointer      |
             +--------------------+                        |
             |  local variables   |                        |
             |        ...         | <-- stack pointer      |
             +--------------------+ -----------------------+
 low address |  available memory  |
             + - - - - - - - - -  +
</code>```1

which will look something like4

```<code>             + - - - - - - - - -  +
high address |  previous stack    |
             |       frame        |
             + - - - - - - - - -  +
             |  previous stack    |
             |       frame        |
             +--------------------+  ----------------------+
             | function arguments |                        |
             |        ...         |                        |
             +--------------------+                        |
             |   return address   |                        |
             +--------------------+                        +-- current stack frame
             | old frame pointer  | <-- frame pointer      |
             +--------------------+                        |
             |  local variables   |                        |
             |        ...         | <-- stack pointer      |
             +--------------------+ -----------------------+
 low address |  available memory  |
             + - - - - - - - - -  +
</code>```2

Once again, we return n and exit the function, bringing us back to the previous call:

```<code> +--------------------+
 |         3          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer | <-- frame pointer, stack pointer
 +--------------------+
 |         2          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer |
 +--------------------+
 |         1          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer |
 +--------------------+
</code>```

Lather, rinse, repeat.  The value returned in %eax (2) is multiplied by the value in the argument 8(%ebp) (3), and we write 6 back to %eax.

Now, the C language definition says nothing about stacks, or stack frames, or registers, or anything like that; it only specifies the behavior of variables within a program, not how to implement that behavior.  However, much of C's design is based on what most computer systems already provide (this is what people mean when they say that C is "close to the hardware"), so this is a very natural way of implementing that behavior.  If you were working on a machine that had no stack, C programs would be somewhat more difficult to implement.

1.  By which I mean a virtual address space, which is an idealized model of memory that your program sees; the OS and memory controllers will map this idealized model to physical RAM.

2.  A register is a memory cell on the CPU itself.  There are usually several special-purpose registers (program counter, stack pointer, frame pointer) and some number of general-purpose registers.  Reading and writing to registers is faster than reading and writing to RAM.

3.  On 32-bit x86, the stack pointer register is esp and the frame pointer register is ebp (a.k.a. the base pointer).  On 64-bit x86, they're named rsp and rbp.

4.  This is how the compiled code on my system does it, anyway.

Body:
How could it be possible to use a single n box as my tutor taught? Won't a new n box be created whenever factorial(n - 1) is called?

Yes, exactly.  Each time you call a function, additional memory is set aside for the function arguments and local variables.

Let's drop a couple of levels below C and talk about how a compiled program is laid out in memory1.  We're going to assume a 32-bit, x86-like system for this discussion.

While the details vary from platform to platform, the general concepts are the same for most systems you're likely to work on.  When a compiled program is loaded into memory, it's usually divided up into several logical segments; one segment contains the machine code, another contains constant (read-only) data items, another contains space for non-constant, global data items, another contains space for the stack, another contains the space for the heap, etc.  The general layout looks something like the following (taken from this page):

              +------------------------+
high address  | Command line arguments |
              | and environment vars   |
              +------------------------+
              |         stack          |
              | - - - - - - - - - - -  |
              |           |            |
              |           V            |
              |                        |
              |           ^            |
              |           |            |
              | - - - - - - - - - - -  |
              |          heap          |
              +------------------------+
              |    global and read-    |
              |       only data        |
              +------------------------+
 low address  |     program text       |
              |    (machine code)      |
              +------------------------+

As your program runs, it uses the stack to store function arguments and local variables, along with some program state (previous frame pointer, address to the next instruction).  On x86-like systems, the stack grows "downwards", towards decreasing addresses.  Among the registers2 provided, there are usually two to keep track of what's on the stack.  There's the stack pointer, which points to the most recent item on the stack, and the frame pointer3, which points to the current stack frame.  A stack frame is a region of the stack that contains the arguments and local variables for the current function, along with any saved program state:

             + - - - - - - - - -  +
high address |  previous stack    |
             |       frame        |
             + - - - - - - - - -  +
             |  previous stack    |
             |       frame        |
             +--------------------+  ----------------------+
             | function arguments |                        |
             |        ...         |                        |
             +--------------------+                        |
             |   return address   |                        |
             +--------------------+                        +-- current stack frame
             | old frame pointer  | <-- frame pointer      |
             +--------------------+                        |
             |  local variables   |                        |
             |        ...         | <-- stack pointer      |
             +--------------------+ -----------------------+
 low address |  available memory  |
             + - - - - - - - - -  +

On the systems I'm familiar with, the function arguments and program state are stored "above" the location stored in the frame pointer, and local variables are stored "below" it.  Within the generated assembly code, arguments and variables are referred to by their offset from the address stored in the frame pointer.  On x86. it would look something like

cmpl  $1, 8(%ebp)   ;; compare the literal value 1 to the first function argument
movl  $1, -4(%ebp)  ;; write the literal value 1 to the first local variable

The first function argument is stored 8 bytes "above" the address value stored in the frame pointer %ebp, while the first local variable would be 4 bytes "below" it (note that this assumes a 32-bit system).

The exact size of the frame depends on how many arguments and local variables need to be stored, although the platform may also require it to be aligned to certain boundary (IOW, the size of the frame must be a multiple of some number of bytes, usually 4 or 8, sometimes 16; for the purposes of this discussion, we're not going to worry about alignment).

Suppose your factorial function is called with an argument value of 3:

x = factorial( 3 );

A new stack frame will be set up that looks something like this:

 +--------------------+
 |         3          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer | <-- frame pointer, stack pointer
 +--------------------+

where the "return address" is the address of the instruction immediately following the function call in the caller (in this case, it would be the instruction that assigns the result of factorial(3) to x).

Since there are no local variables, no space is allocated for them in the stack frame.  Now, since n is not less than 2, you execute the line

n = n * factorial( n - 1 );

This means factorial is called again, this time with an argument value of 2.  A new stack frame is created

 +--------------------+
 |         3          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer |
 +--------------------+
 |         2          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer | <-- frame pointer, stack pointer
 +--------------------+

n is still not less than 2, so we call factorial again with an argument of 1:

 +--------------------+
 |         3          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer |
 +--------------------+
 |         2          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer |
 +--------------------+
 |         1          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer | <-- frame pointer, stack pointer
 +--------------------+

1 is less than 2, so we execute the line

return n;

The common convention for returning values from functions is to write the value to a particular register.  On x86, integer values are returned through register %eax, so the compiled code will do something like

movl  8(%ebp), %eax

Now register %eax will contain the value 1.

When the function returns, the stack and frame pointers are restored to their previous values (the stack contents are left as-is):

 +--------------------+
 |         3          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer |
 +--------------------+
 |         2          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer | <-- frame pointer, stack pointer
 +--------------------+
 |         1          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer |
 +--------------------+

So now we need to execute the remainder of

n = n * factorial( n - 1 );

which will look something like4

movl %eax, %edx     ;; save the value returned from factorial(1) to register %edx
movl 8(%ebp), %eax  ;; move the value of n (2) to %eax
imull %eax, %edx    ;; multiply the values in %eax and %edx, save the result in
                    ;; %eax

Once again, we return n and exit the function, bringing us back to the previous call:

 +--------------------+
 |         3          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer | <-- frame pointer, stack pointer
 +--------------------+
 |         2          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer |
 +--------------------+
 |         1          | <-- n
 +--------------------+
 |   return address   |
 +--------------------+
 |  old frame pointer |
 +--------------------+

Lather, rinse, repeat.  The value returned in %eax (2) is multiplied by the value in the argument 8(%ebp) (3), and we write 6 back to %eax.

Now, the C language definition says nothing about stacks, or stack frames, or registers, or anything like that; it only specifies the behavior of variables within a program, not how to implement that behavior.  However, much of C's design is based on what most computer systems already provide (this is what people mean when they say that C is "close to the hardware"), so this is a very natural way of implementing that behavior.  If you were working on a machine that had no stack, C programs would be somewhat more difficult to implement.

1.  By which I mean a virtual address space, which is an idealized model of memory that your program sees; the OS and memory controllers will map this idealized model to physical RAM.

2.  A register is a memory cell on the CPU itself.  There are usually several special-purpose registers (program counter, stack pointer, frame pointer) and some number of general-purpose registers.  Reading and writing to registers is faster than reading and writing to RAM.

3.  On 32-bit x86, the stack pointer register is esp and the frame pointer register is ebp (a.k.a. the base pointer).  On 64-bit x86, they're named rsp and rbp.

4.  This is how the compiled code on my system does it, anyway.


问:
Why isn't testing a language a supported feature at the syntax level?
You can find an endless list of blogs, articles and websites promoting the benefits of unit testing your source code. It's almost guaranteed that the developers who programmed the compilers for Java, C++, C# and other typed languages used unit testing to verify their work.

So why then, despite its popularity, is testing absent from the syntax of these languages?

Microsoft introduced LINQ to C#, so why couldn't they also add testing?

I'm not looking to predict what those language changes would be, but to clarify why they are absent to begin with.

As an example: We know that you can write a for loop without the syntax of the for statement. You could use while or if/goto statements. Someone decided a for statement was more efficient and introduced it into a language.

Why hasn't testing followed the same evolution of programming languages?

答:
There's lots of reasons. Eric Lippert has stated many times that the reason feature X isn't in C# is because it's just not in their budget. Language designers don't have an infinite amount of time nor money to implement things, and each new feature has maintenance costs associated with it. Keeping the language as small as possible isn't just easier for the language designers - it's also easier for anyone writing alternative implementations and tools (e.g. IDEs) Additionally, when something is implemented in terms of the language rather than part of it, you get portability for free. If unit testing is implementing as a library, you only need to write it once and it'll work in any conforming implementation of the language.

It's worth noting that D does have syntax-level support for unit testing. I don't know why they decided to throw that in, but it's worth noting that D is meant to be a "high level systems-programming language". The designers wanted it to be viable for the kind of unsafe, low-level code C++ has traditionally been used for, and a mistake in unsafe code is incredibly costly - undefined behavior. So I suppose it made sense to them to expend extra effort on anything that helps you verify that some unsafe code works. For example, you can enforce that only certain trusted modules can perform unsafe operations like unchecked array accesses or pointer arithmetic.

Quick development was also a priority for them, so much so that they made it a design goal that D code compiles fast enough to make it usable as a scripting language. Baking unit tests right into the language so you can run your tests by just passing an extra flag to the compiler helps with that.

However, I think a great unit testing library does much more than just find some methods and run them. Take Haskell's QuickCheck for example, which lets you test things such as "for all x and y, f (x, y) == f (y, x)". QuickCheck is better described as a unit test generator and allows you to test things at a higher level than "for this input, I'm expecting this output". QuickCheck and Linq aren't all that different - they're both domain-specific-languages. So rather than bolting on unit testing support unto a language, why not add the features needed to make DSLs practical? You'll end up with not just unit testing, but a better language as a result.

ContentLicense: CC BY-SA 3.0


问:
What defines the dimensionality of an array?
I know that when we speak about an array having 1, 2, or 4 dimensions, we mean arrays like this:

```<code>1: [0]
2: [0,0]
3: [0,0,0]
4: [0,0,0,0]
...
</code>```

Is the first 'axis' of an array the only thing that defines its dimensionality?  Can an array with 4 dimensions be represented these ways?

```<code>[0, [0,0,0]]
[[0,0], [0,0]]
</code>```

or does this fall under some other definition of dimensionality?

Another option is that a 4-dimensional array would be of the form

```<code>[ [[ [0,..],[0,..] ], [ [0,..],[0,..] ]], [[ [0,..],[0,..] ], [ [0,..],[0,..] ]], [[ [0,..],[0,..] ], [ [0,..],[0,..] ]], [[ [0,..],[0,..] ], [ [0,..],[0,..] ]] ]
</code>```

e.g.

```<code>[
  [
    [ [0,..],[0,..] ],
    [ [0,..],[0,..] ]
  ],
  [
    [ [0,..],[0,..] ],
    [ [0,..],[0,..] ]
  ],
  [
    [ [0,..],[0,..] ],
    [ [0,..],[0,..] ]
  ],
  [
    [ [0,..],[0,..] ],
    [ [0,..],[0,..] ]
  ]
]
</code>```

Is this just a nomenclature nuance that I'm bringing up?  Is this definition relative to the field in which we are discussing (computation vs. physical systems)?

(the thoughts came from this question.)

答:
The dimensionality is the number of subscripts you can use to select elements.

Your example [0, [0,0,0]] is still a 2d array, albeit containing a 3d array as its second element. That doesn't make it a 4d or 5d array, just a nested data structure where the "dimensionality" concept breaks down and gets confusing real fast.

Examples like [[0,0], [0,0]] and [0, [0,0,0]] are thought of better not as arrays but as trees or other hierarchical data structures.


答:
```<code>1: [0]
2: [0,0]
3: [0,0,0]
4: [0,0,0,0]
...
</code>```

I think you've got it wrong. If you mean that these are one-/two-/three-/four-dimensional arrays, that's not the case: they're all one-dimensional, they just have different lengths.

But length is not dimensionality. As whatsisname explained, the dimensionality of an entire array is the number of subscripts you need to give in order to address a single element. The length is just  the number of different values you can legally give for one particular subscript in that expression (if the length is 4, the valid values are 0,1,2,3).

Title: What defines the dimensionality of an array?

Body:
I know that when we speak about an array having 1, 2, or 4 dimensions, we mean arrays like this:

```<code>1: [0]
2: [0,0]
3: [0,0,0]
4: [0,0,0,0]
...
</code>```

Is the first 'axis' of an array the only thing that defines its dimensionality?  Can an array with 4 dimensions be represented these ways?

```<code>[0, [0,0,0]]
[[0,0], [0,0]]
</code>```

or does this fall under some other definition of dimensionality?

Another option is that a 4-dimensional array would be of the form

```<code>[ [[ [0,..],[0,..] ], [ [0,..],[0,..] ]], [[ [0,..],[0,..] ], [ [0,..],[0,..] ]], [[ [0,..],[0,..] ], [ [0,..],[0,..] ]], [[ [0,..],[0,..] ], [ [0,..],[0,..] ]] ]
</code>```

e.g.

```<code>[
  [
    [ [0,..],[0,..] ],
    [ [0,..],[0,..] ]
  ],
  [
    [ [0,..],[0,..] ],
    [ [0,..],[0,..] ]
  ],
  [
    [ [0,..],[0,..] ],
    [ [0,..],[0,..] ]
  ],
  [
    [ [0,..],[0,..] ],
    [ [0,..],[0,..] ]
  ]
]
</code>```

Is this just a nomenclature nuance that I'm bringing up?  Is this definition relative to the field in which we are discussing (computation vs. physical systems)?

(the thoughts came from this question.)

Body:
1: [0]
2: [0,0]
3: [0,0,0]
4: [0,0,0,0]
...

I think you've got it wrong. If you mean that these are one-/two-/three-/four-dimensional arrays, that's not the case: they're all one-dimensional, they just have different lengths.

But length is not dimensionality. As whatsisname explained, the dimensionality of an entire array is the number of subscripts you need to give in order to address a single element. The length is just  the number of different values you can legally give for one particular subscript in that expression (if the length is 4, the valid values are 0,1,2,3).


问:
Was .NET's IObserver<T> intended for subscribing to multiple IObservables?
There are IObservable and IObserver interfaces in .NET (also here and here).  Interestingly, the concrete implementation of the IObserver does not hold a direct reference to the IObservable.  It doesn't know who it's subscribed to.  It can only invoke the unsubscriber.  "Please pull the pin to unsubscribe."

edit: The unsubscriber implements the IDisposable. I think, this scheme was employed to prevent the lapsed listener problem.

Two things are not entirely clear to me, though.

Does the inner Unsubscriber class provide the subscribe-and-forget behavior?  Who (and when exactly) calls IDisposable.Dispose() on the Unsubscriber?  Garbage collector (GC) is not deterministic.

[Disclaimer:  overall, I've spent more time with C and C++ than with C# .]

What should happen if I want to subscribe an observer K to an observable L1 and the observer is already subscribed to some other observable L2?

```<code>K.Subscribe(L1);
K.Subscribe(L2);
K.Unsubscribe();
L1.PublishObservation(1003);
L2.PublishObservation(1004);
</code>```

When I ran this test code against MSDN's example, the observer remained subscribed to L1.  This would be peculiar in real development.  Potentially, there are 3 avenues to improve this:

If the observer already has an unsubscriber instance (i.e. it’s already subscribed), then it quietly unsubscribes from the original provider before subscribing to a new one.  This approach hides the fact that it’s no longer subscribed to the original provider, which may become a surprise later.

If the observer already has an unsubscriber instance, then is throws an exception.  A well-behaved calling code has to unsubscribe the observer explicitly.

Observer subscribes to multiple providers.  This is the most intriguing option, but can this be implemented with IObservable and IObserver?  Let’s see.  It is possible for the observer to keep a list of unsubscriber objects: one for each source.  Unfortunately, IObserver.OnComplete() does not provide a reference back to the provider who have sent it.  So, the IObserver implementation with multiple providers would not be able to determine which one to unsubscribe from.

Was .NET's IObserver intended for subscribing to multiple IObservables?

Does the textbook definition of the observer pattern require that one observer has to be able to subscribe to multiple providers? Or is it optional and implementation-dependent?

答:
You're right.  The example works poorly for multiple IObservables.

I guess OnComplete() doesn't provide a reference back because they don't want the IObservable to have to keep it around.  If I were writing that I would probably support multiple subscriptions by having Subscribe take an identifier as a second parameter, which gets passed back to the OnComplete() call.  So you could say

```<code>K.Subscribe(L1,"L1")
K.Subscribe(L2,"L2")
K.Unsubscribe("L1")
</code>```

As it stands, it appears the .NET IObserver isn't suitable for multiple observers.  But I suppose your main object (LocationReporter in the example) could have

```<code>public Dictionary<String,IObserver> Observers;
</code>```

and that would enable you to support

```<code>K.Subscribe(L1,"L1")
K.Subscribe(L2,"L2")
K.Unsubscribe("L1")
</code>```

as well.

I suppose Microsoft could argue that therefore there is no need for them to directly support multiple IObservables in the interfaces.

Body:
You're right.  The example works poorly for multiple IObservables.

I guess OnComplete() doesn't provide a reference back because they don't want the IObservable to have to keep it around.  If I were writing that I would probably support multiple subscriptions by having Subscribe take an identifier as a second parameter, which gets passed back to the OnComplete() call.  So you could say

K.Subscribe(L1,"L1")
K.Subscribe(L2,"L2")
K.Unsubscribe("L1")

As it stands, it appears the .NET IObserver isn't suitable for multiple observers.  But I suppose your main object (LocationReporter in the example) could have

public Dictionary<String,IObserver> Observers;

and that would enable you to support

K.Subscribe(L1,"L1")
K.Subscribe(L2,"L2")
K.Unsubscribe("L1")

as well.

I suppose Microsoft could argue that therefore there is no need for them to directly support multiple IObservables in the interfaces.


答:
Because testing, and particularly test-driven development, is a deeply counter-intuitive phenomenon.

Almost every programmer begins their career believing they are much better at managing complexity than they actually are. The fact that even the greatest programmer cannot write large and complex programs without severe errors unless they use lots of regression tests is seriously disappointing and even shameful to many practitioners. Hence the prevalent disinclination against regular testing even among professionals who should already know better.

I think the fact that religious testing is slowly becoming more mainstream and expected is largely due to the fact that with the explosion in storage capacity and computing power, larger systems than ever are being built - and extremely large systems are particularly prone to complexity collapse that cannot be managed without the safety net of regression tests. As a result, even particularly obstinate and deluded developers now grudgingly admit that they need testing and will always need testing (if this sounds like the confession at an AA meeting, this is quite intentional - needing a safety net is psychologically hard to admit for many individuals).

Most languages popular today date from before this attitude shift, so they have little built-in support for tests: they have assert, but no contracts. I'm fairly sure that if the trend persists, future languages will have more support on the language rather than the library level.

Title: Why isn't testing a language a supported feature at the syntax level?

Body:
You can find an endless list of blogs, articles and websites promoting the benefits of unit testing your source code. It's almost guaranteed that the developers who programmed the compilers for Java, C++, C# and other typed languages used unit testing to verify their work.

So why then, despite its popularity, is testing absent from the syntax of these languages?

Microsoft introduced LINQ to C#, so why couldn't they also add testing?

I'm not looking to predict what those language changes would be, but to clarify why they are absent to begin with.

As an example: We know that you can write a for loop without the syntax of the for statement. You could use while or if/goto statements. Someone decided a for statement was more efficient and introduced it into a language.

Why hasn't testing followed the same evolution of programming languages?


问:
How does the "Fourth Dimension" work with arrays?
Abstract:

So, as I understand it (although I have a very limited understanding), there are three dimensions that we (usually) work with physically:

The 1st would be represented by a line.

The 2nd would be represented by a square.

The 3rd would be represented by a cube.

Simple enough until we get to the 4th -- It is kinda hard to draw in a 3D space, if you know what I mean...  Some people say that it has something to do with time.

The Question:

Now, though that doesn't all make much sense, that is all great with me.  My question isn't about this, or I'd be asking it on MathSO or PhysicsSO.  My question is: How does the computer handle this with arrays?

I know that you can create 4D, 5D, 6D, etc... arrays in many different programming languages, but I want to know how that works.

答:
In the Cartesian coordinate system, you have the x and y axes on a plane. You can represent any number on the plane as (x,y).

In three-"space" (otherwise known as a cube), you can have the x, y, and z axes. You can represent any element of the cube as (x,y,z).

In multivariate space, you can have the x, y, z and, w axes (where the w axis is "imaginary").
You can represent any element of that space as (x, y, z, w).

All of these points in space are denoted by vectors. In four-space, you can have two vectors, where v1 =(x1, y1, z1, w1), and v2 =(x2, y2, z2, w2). Then you manipulate these vectors as you would numbers. For instance, the sum of the two vectors, v1+ v2 would be (x1, y1, z1, w1)+ (x2, y2, z2, w2). Then you add these vectors term by term as you would numbers, to get: (x1+x2, y1+y2, z1+z2, w1+w2).

Your program will define the vectors using appropriate arrays, and then perform arithmetic operations on them in the appropriate order.


问:
Redundant function to clarify purpose?
Since what matters is not how the code does it but what it does, would you consider wrapping a function with a different name just to clarify it's behavior in certain situations a good practice?

Real life example with pseudo-code:

Let's say I have a small module to generate hardware signals. Now naturally one expects to find somewhere in the API a function to start a signal once all the configurations are done and the hardware is ready to fire:

```<code>startSignal(myProperlyConfiguredInstance);
</code>```

Now, my user would naturally ask himself what happens if this function is called multiple times.

Does the code detects the signal is running and ignores the call?

Does it throw an exception because it assumes it's an error to try to start the signal multiple times?

Does it cause hardware glitches?

Does is reset the hardware and starts a new signal?

The obvious answer seems to be "specific behavior should be in the doc" but we all know how documentation seems to decay faster than we write it and clear code is better than clear doc.

My solution to this problem was to do this:

```<code>void restartSignal(Instance myInstance){
    startSignal(myInstance);
</code>```

}

Now it seems to me that it is clear that the intended behavior is the 4th bullet and my user doesn't have to ask himself this question; he can just call restart if the signal is running or start if it's not.

But now I have redundant code which doesn't actually acomplishes anything no? It seems like I'm repeating myself and it's perfectly fine to call restart to start an idle signal and start on a running signal!

Which do you prefer? Richer API vs simpler API that requires a peak at the doc / tests / source code?

答:
In general, I'm against writing a method with a semantically different name that simply calls another method but does not have different behavior, unless you're implementing the Adapter Pattern.

The only way this might makes sense is if you name the method something like:

restartSignalIsReallyJustAStart()

which completely explains what you're doing without making the programmer after you wonder why you wrote another method with a different name that does nothing but call the original method.

...except that it's kinda ridiculous, isn't it?  Avoid this, and just make sure you have good documentation that explains why "start" and "restart" are the same thing.

Further Reading

Is it a good idea to provide different function signatures that do the same thing?

Title: Redundant function to clarify purpose?


答:
would you consider wrapping a function with a different name just to clarify it's behavior in certain situations a good practice?

Absolutely.

The key thing here is that for almost all code, the interface matters more than the implementation. If it makes sense to have a Restart method in your interface, then add it. Because while it's true that for this class, today the implementations are the same... it's not exactly uncommon for other implementations of the interface to differ, or for changing requirements to cause your implementations to drift apart.

All that said, I would do this as a relatively last resort. Having two different methods that do the same thing is a sign that my design/naming is poor. Users of the interface will often think "What is the difference between these things?".

Title: Redundant function to clarify purpose?

Body:
Since what matters is not how the code does it but what it does, would you consider wrapping a function with a different name just to clarify it's behavior in certain situations a good practice?

Real life example with pseudo-code:

Let's say I have a small module to generate hardware signals. Now naturally one expects to find somewhere in the API a function to start a signal once all the configurations are done and the hardware is ready to fire:

```<code>startSignal(myProperlyConfiguredInstance);
</code>```

Now, my user would naturally ask himself what happens if this function is called multiple times.

Does the code detects the signal is running and ignores the call?

Does it throw an exception because it assumes it's an error to try to start the signal multiple times?

Does it cause hardware glitches?

Does is reset the hardware and starts a new signal?

The obvious answer seems to be "specific behavior should be in the doc" but we all know how documentation seems to decay faster than we write it and clear code is better than clear doc.

My solution to this problem was to do this:

```<code>void restartSignal(Instance myInstance){
    startSignal(myInstance);
</code>```

}

Now it seems to me that it is clear that the intended behavior is the 4th bullet and my user doesn't have to ask himself this question; he can just call restart if the signal is running or start if it's not.

But now I have redundant code which doesn't actually acomplishes anything no? It seems like I'm repeating myself and it's perfectly fine to call restart to start an idle signal and start on a running signal!

Which do you prefer? Richer API vs simpler API that requires a peak at the doc / tests / source code?


答:
I like the question.  It's definitely an idea that merits some thought.  I have seen similar code in the wild, but only in cases like restart being a part of a public interface you are implementing for one of several chips, some of which require different logic to accomplish a clean restart.

For the sake of argument, let's assume for a moment that your intention behind adding restart was completely clear to any future maintainers, which is probably not a valid assumption considering all the confusion just from people commenting on this question.

You still haven't accomplished your original goals, as a lot of open questions remain just from looking at the function signatures, and you might have even created new ones.  Your first two questions still very much apply.  You still don't know what happens if you call start twice.  Adding restart actually would make me more wary of accidentally calling start twice.  How important is it to check if it's already started before calling start?

Your second two questions just got moved to the restart function.  You still haven't communicated whether a restart causes glitches, does a complete shut down and restart, or whatever.

In the end, you can't avoid documenting certain aspects of your code in the comments.  Don't mistake the admonition to avoid over-commenting as an admonition to never comment.  The sorts of questions you mention are perfect candidates for API docs.

Title: Redundant function to clarify purpose?


答:
Yes the examples given are all 1 dimensional as Kilan states, though it could also depend on exactly what you are using, e.g. computer languages which have different format to represent such constructs.

Dimensionality itself can also be thought of as 'nesting', e.g. if there is one set of discrete elements that is 1 dimension, if each elements also has elements, that's 2 dimensional, if each of those also is compose of elements,  3 dimensionsal, etc.

In ruby (for example) this is represented by:

```<code>[n] # One Dimension
[n][o] # Two Dimensions
[n][o][p] # Three Dimensions
[n][o][p][q] # Four Dimensions
</code>```

For each case n, o, p and q are the number of elements at that level.

So, for example if you wanted to represent 6 US states, the top 4 cities in each and the tallest 5 buildings in each city you could use [5][3][4] (assuming the use of zero based arrays).

I have also worked with languages though where a 3 dimensional array such as the above would be represented by

```<code>(5,3,4)
</code>```

Body:
Yes the examples given are all 1 dimensional as Kilan states, though it could also depend on exactly what you are using, e.g. computer languages which have different format to represent such constructs.

Dimensionality itself can also be thought of as 'nesting', e.g. if there is one set of discrete elements that is 1 dimension, if each elements also has elements, that's 2 dimensional, if each of those also is compose of elements,  3 dimensionsal, etc.

In ruby (for example) this is represented by:

[n] # One Dimension
[n][o] # Two Dimensions
[n][o][p] # Three Dimensions
[n][o][p][q] # Four Dimensions

For each case n, o, p and q are the number of elements at that level.

So, for example if you wanted to represent 6 US states, the top 4 cities in each and the tallest 5 buildings in each city you could use [5][3][4] (assuming the use of zero based arrays).

I have also worked with languages though where a 3 dimensional array such as the above would be represented by

(5,3,4)


问:
Charles Barkley syndrome
Charles Barkley was an excellent basketball player, a hall of fame, and a dream team member.  He played for the 76ers, Suns, and Rockets.  Yet he never won an NBA championship.  Some might argue this was because he was never surrounded by other players of his caliber, and in the NBA, you can't win on your own.

So what does this have to do with programming?

How many of you out there feel like Sir Charles?  Leading your team in every category, KLOCs, bugs fixed, systems configured...  Always the one pushing for improvements, upgrading systems, negotiating with customers...  Feeling like you are carrying the team.  Anger just under the surface.

Only to retire eventually, without "the ring"1.

1: Keep in mind, Charles never blamed his team.  He just performed at his best.

答:
Yes, so I left.

Now I'm in a group with people smarter than me and I have to try and keep up.  It's refreshing.

Maybe Barkley should have done what LeBron did and switched to a team he thought could win something.

You never know how a potential job/team change will work about before you make it, but if you are that unhappy you should find somewhere that will appreciate your skillset and passion.

ContentLicense: CC BY-SA 2.5

Title: Charles Barkley syndrome


答:
Dimensionality comes from ... dimensions!

A one-dimensional array is like one of those daily pill containers:

It's a vector, with a single index, and you can select one specific element at a time by specifying where along the line it lies.

A two-dimensional array is like a chessboard:

It's a matrix, with two indices, and you can select one specific element at a time by specifying where the two lines intersect.  In chess notation, "a1" is the bottom left cell in the image, "h8" the top right, in most languages that would be [0,0] and [7,7] or [0][0] and [7][7].

A three-dimensional array is like a Rubik's cube (except that you can access more than just the surface elements):

It's a cube, with three indices, and you can select one specific element at a time by specifying where the three lines intersect.

A four-dimensional array is like ... well ... nothing real.  But mathematicians have been modeling higher-dimensional structures for a long time, and some even have names.  You'll have to just extend your mind to grasp them.  But the computer equivalent is an even-more-natural extension,


答:
In physics, we assume each spatial dimension to be infinite, which makes finding space for new dimensions pretty difficult.

When dealing with finite arrays, it's easy to find space.

Imagine a sheet of paper with a grid printed on it; you can write some information in each cell of the grid. That's a 2D array: row and column.

Put several of those sheets of paper in a file folder; that's a 3D array: page, row, and column.

Put several of those folders in a file box. 4D array: folder, page, row, column.

Arrange boxes in a rectangular grid on a wooden pallet. 6D array: box-row, box-column, folder, page, row, column.

Stack more grids of boxes on top of those. 7D array: box-depth, box-row, box-column, folder, page, row, column.

Start cramming pallets into a shipping container: 9D array. (Assuming each stack is as tall as the inside of the container, so you can only get 2 more dimensions here.)

Stack up shipping containers on the deck of a container ship: 12D array.

Your fleet of container ships is now a 13D array.

Title: How does the "Fourth Dimension" work with arrays?

Body:
Abstract:

So, as I understand it (although I have a very limited understanding), there are three dimensions that we (usually) work with physically:

The 1st would be represented by a line.

The 2nd would be represented by a square.

The 3rd would be represented by a cube.

Simple enough until we get to the 4th -- It is kinda hard to draw in a 3D space, if you know what I mean...  Some people say that it has something to do with time.

The Question:

Now, though that doesn't all make much sense, that is all great with me.  My question isn't about this, or I'd be asking it on MathSO or PhysicsSO.  My question is: How does the computer handle this with arrays?

I know that you can create 4D, 5D, 6D, etc... arrays in many different programming languages, but I want to know how that works.


问:
Why are F# exceptions generally not suffixed with 'Exception'?
In .NET, it is idiomatic to suffix exception types with Exception. But most, if not all, sources I have seen for custom exception types in F# don't follow this idiom.

Most seem to use the suffix Error.

From F# For Fun and Profit

```<code>exception MyFSharpError1 of string
exception MyFSharpError2 of string * int
</code>```

From Microsoft Documentation*

```<code>exception MyError of string
</code>```

The book 'Expert F# 3.0', co-authored by Don Syme, has an example that doesn't even seem to follow any idiom:

```<code>exception BlockedURL of string
</code>```

Why don't custom exceptions in F# follow the standard idioms for .NET? Is it because of the OCaml heritage?

* Link is to Google cache, as I cannot connect to MS at the time of writing.

答:
I think you're too quick to generalize based on just a few data points. There is some diversity there, but on the whole you're still more likely to see *Exception than anything else, in my experience at least.

As for why there is more variation out there, I think there are a couple of different factors at play:

F# is a .NET language and uses the same standard libraries which follow the *Exception convention. Also, a great number of users comes to F# from C#, and they're likely to use what has worked for them so far. Look at github results, there's plenty of *Exceptions there (admittedly, some *Errors as well).

You seem to be correct about OCaml heritage - again, going by github results, it's a widespread practice to name exceptions without any suffixes. The few *Exceptions I saw came from .fs files classified as OCaml.

C# has its golden standard code guideline that everyone seems to follow unanimously; I don't think F# had anything comparable from the start. Now there's F# Component Design Guidelines document from FSF, and it actually advices to follow the .NET *Exception style.

Previous point is further aggravated by the fact that compared to C#, there's very little tooling support for F#. There's no Resharper/StyleCop/FxCop for F# to enforce a code style for you (heck, there's not even a "Rename" out of the box in VS!).


问:
Git branches avoided by the office where I work
The place I work at does the following:

They manage a dev version of an app

They manage another replicate version of that app, they call this the rep
version

The live version of the app that is running

They believe branches are evil

We are asked to manually copy paste the code from one version to another. What are the circumstances under which git branches are considered harmful?(we all add code to master)

答: To answer your question: This seems to be the most brain dead process using git. The whole point of using git is because of easy branching and merging. Manually copying / pasting changes is just asking for trouble, because some day someone will forget to copy something and you will have no track of who did that.</p>


答:
Some proponents of strongly typed functional languages would argue that these language features reduce or eliminate the need for unit tests.

Two, imho, good example of this for this is from F# for Fun and Profit here and here

Personally, I am still believe in the value of unit tests, but there are some valid points. E.g. if an illegal state is unrepresentable in code, then it is not only unnecessary to write a unit tests for this case, it is impossible.


答:
My previous company had a manual copy/paste code deployment process. Everyone loved it except the Release Engineers. It wasn't changed until an accident wiped out several days worth of work and restoring from backup wasn't an option.

Using a version control tool with proper branches was an easy sell after that.

If you can demonstrate to your management that it is more cost effective and less risky to use branches properly, the "branches are evil" mantra should begin to dissipate.

tldr: Saving Money > Branches Are Evil

Title: Git branches avoided by the office where I work

Body:
The place I work at does the following:

They manage a dev version of an app

They manage another replicate version of that app, they call this the rep
version

The live version of the app that is running

They believe branches are evil

We are asked to manually copy paste the code from one version to another. What are the circumstances under which git branches are considered harmful?(we all add code to master)


问:
Testing of personal projects
I'm developing a web based personal project that will hopefully be used by thousands.  Obviously prior to releasing it in the wild as Beta I was wondering,  are there any communities out there that will test my web app and provide feedback?  Free would be great, but I'm open to suggestions.</p>

答:
I use three stages of testing:

Alpha

Alpha testing is primarily done among the developers. It sounds like you're in this stage. Here people are responsive from a technical angle, they can identify errors and know what causes them along with fix recommendations. Programmers.SE might be the crowd you're looking for here.

Beta

Beta testing is done among your target audience. Advertise a beta period, keep it to a manageable size and have a public wiki / bug / issue tracker available.

Release Candidates

This is an optional step for developing applications. Here you would advertise to your target audience and beyond a potential release. Freeze the version number and consolidate features here. Limit work to bug fixing and minor UI issues.

Title: Testing of personal projects


答:
A lot of languages have support for testing. C's asserts are tests that the program can fail. That's where most languages stop, but Eiffel and more recently Ada 2012 have preinvariants (things the arguments to a function must pass) and postinvariants (things the output of a function must pass), with Ada offering the ability to reference the initial arguments in the postinvariant. Ada 2012 also offers type invariants, so whenever a method is called on an Ada class, the type invariant is checked before return.

That's not the type of full-out testing a good testing framework can give you, but it's an important type of testing that languages can best support.


问:
System state design composition
Consider the following Java code:

```<code>public class HumanStateImpl implements HumanState {
    private boolean alive;
    private Color skinColor;

    // getters and setters, other state fields

    @Override
    public boolean isAlive() {
        return alive;
    }
}
</code>```

Now imagine I want to have a class that represents HandState, and a corresponding HandController. Is it better to inject the state objects of each level of state separately, or compose them into one most-specific state object? If it depends, what does it depend on?

To clarify what I mean, here is an implementation of both sides, respectively:

```<code>public class HandState {
    private final Side handSide;
    private boolean closed;
}

public class HandController {
    private final HumanState humanState;
    private final HandState handState;

    public HandController(HumanState humanState, HandState handState) {
        this.humanState = humanState;
        this.handState = handState;
    }
}
</code>```

Versus:

```<code>public class HandState implements HumanState {
    private final HumanState outerState;
    private final Side handSide;

    public HandState(HumanState outerState, Side handSide) {
        this.outerState = outerState;
        this.handSide = handSide;
    }

    @Override
    public boolean isAlive() {
        return outerState.isAlive();
    }
}

public class HandController {
    private final HandState handState;

    public HandController(HandState handState) {
        this.handState = handState;
    }
}
</code>```

答:
I would recommend using composition instead of inheritance in this scenario. Also, I would reverse the model to match the logical flow of control.

A HumanState can contain member variables for the HandStates. In this way, you have a logical composition of elements.

```<code>HumanState ->
--> contains HandState x2
--> contains HeadState x1
    --> contains MouthState x1
</code>```

and so on.

Now the controllers can also follow the same pattern. The HumanController contains instances of HandControllers. This pattern also matches intuitive assumptions - a human controls their hands, etc.

```<code>HumanController ->
--> contains HandController x2
--> contains HeadController x1
    --> contains MouthController x1
</code>```

Title: System state design composition

Body:
I would recommend using composition instead of inheritance in this scenario. Also, I would reverse the model to match the logical flow of control.

A HumanState can contain member variables for the HandStates. In this way, you have a logical composition of elements.

HumanState ->
--> contains HandState x2
--> contains HeadState x1
    --> contains MouthState x1

and so on.

Now the controllers can also follow the same pattern. The HumanController contains instances of HandControllers. This pattern also matches intuitive assumptions - a human controls their hands, etc.

HumanController ->
--> contains HandController x2
--> contains HeadController x1
    --> contains MouthController x1


答:
Branches can be hard to understand for people who are not used to them, and can be tricky to explain to managers if you need to avoid saying things like "different versions". To a manager who is using a mental model based on clean division of labour and a waterfall process, the idea that you would even want to permit more than one person to work on a file at a time is bad, let alone having a tool that's designed to encourage it.

A further problem is that manual merging can be problematic, and manual deployment more so. It only takes one mistake in a new process to push some people back to the familiar one. You might be better off first automating the existing process as much as possible, then later merging the repositories.

I've found that programmers who are used to older tools have often experienced considerable trauma with branch/merge operations. This is especially true for users of the misnamed "Visual Source Safe" where merging was difficult to impossible and in some versions of that tool used to be a really effective way to corrupt the database. But even the better tools often struggled to deal well with concurrent changes to single files (people often struggle too, which is one reason for the move to smaller units of code over time).

For those programmers I suggest first getting them to use git, which you seem to have done, and ideally one of the pretty GUI front ends for it. The pretty front ends usually present things in a fairly familiar way. Once you have that you can show them how you use branches on your local machine to manage workflow. Specifically, that they're easy to understand and that merging is 90% trivial. I've had some success moving developers this way.


问:
Let applications share a database or keep them in sync with web services?
We have decided to build separate applications for user authentication and user management.  The reason is that the the former is a "this just needs to always work, and do so instantly" style service, and the latter includes a much-larger user-interface component with many requirements and features.

Unfortunately, while white-boarding, prototyping, and getting more information about required features, we discovered that they need to share several types of information. For example, both apps need to know whether a user is locked out or needs to reset their password.

We are considering connecting the applications to the same database.  We considered using web services for communication, but that has a higher up-front cost, is more complex, and will have worse performance (assuming the same query will be made in either case). We'd have to keep some pieces of information in sync across two database instances, which is obviously not an optimal setup.

On the other hand, sharing the database instance would require the ORM's entity schemas to stay in sync somewhat (even if we weren't using one, we'd still need to make sure our queries still worked in both apps whenever the database schema changed).  It creates a shared dependency. In addition, the database becomes a single-point of failure/poor performance. In addition, I'm not sure it would be possible to hide irrelevant data from either app, so encapsulation is reduced.

Has anyone here worked this dilemma before and gained any insights? I'm sure there are other considerations here that I haven't thought of yet.  It's not exactly unusual to have different applications connect to a central database.

Edit (much later):

The outcome of this story almost two years later is that we ended up merging the applications into one (which thankfully was easy because they were both just modules using the same framework). The reasoning for splitting them into two made sense at the time, but in retrospect they shared too many responsibilities to make it practical.

答:
Something to consider might be a Master Data Management (MDM) approach.  It would basically consist of an operational data store for each application, each using an ETL job or replication to synchronize with a master data store.

Each operational data store schema can evolve independently, with the ETL job handling any necessary translations.  How often you synchronize and in what direction(s) would depend on your requirements.

This pattern is often used in data warehousing scenarios, but it can also work for transactional data.  You'd put your applications or web services in front of the operational data stores, and perhaps reporting or other downstream services could consume from the master data store if so desired.

There are several commercial MDM solutions available, which can provide:

additional features

architectural flexibility

security

data integrity

scalability

However, this pattern can also be implemented without a commercial MDM solution or tool.  Databases would be designated as operational and master, and the necessary replication jobs to move data between them would need to be built.

Whatever the specific implementation, this pattern can help decouple the two operational schemas from one another.


问:
Should ALL divs float left?
I'm designing within an application that I inherited.  I have done a lot of work to "consolidate" the CSS which was extremely overworked through much copying and pasting without a lot of strategy behind it.  One curious thing I found was to style ALL divs as:

```<code><style>
div{ float: left; }
</style>
</code>```

Do any other applications do this?  I would be "unfloating" divs all the time because the majority of my use of divs is in fact a division of content, forcing a new line for items like cell phones and tablets.  In my practices, I will style a div float-left if I specifically need it to do that.

答:
Element-based selectors such as a, img or div are mostly used for two purposes:

To clean up browser inconsistencies.

For example, h1 { font-size: 3em; } will remove inconsistencies in default size between different browsers and versions of browsers.

To set the default behavior instead of a specific behavior.

For example, img { border: none; } ensures that Internet Explorer will not display blue border around images when they are embedded in a link. If, on a page, there are a few images where I want to display a border and a few dozen of images where I don't, it's easier to img { border: none; }, then to set a border on those images where I want a border.

In most websites, elements are positioned according to the browser defaults, and are float: left only when needed. For those websites, div { float: left; } wouldn't make sense: it doesn't remove any browser inconsistencies and it sets the specific behavior, rather than the default one.

On the other hand, some very specific websites may prefer float: left to be the default. svidgen suggested fluid layouts. I think more about games. For example, I'm currently working on a game and nearly every element is position: absolute, so #map div { position: absolute; } makes sense.

To determine whether you should keep the div { float: left; }, study:

How many divs are actually float: left; on the page,

How many are not,

Where float: left; effect is cancelled, and how painful is that.

You may as well find that the effect is cancelled nearly in every class. I had that several times when maintaining legacy applications, encountering some weird styles such as div { font-size: 13px !important; }.

Title: Should ALL divs float left?


答:
I would argue that you have missed the addition of some of the necessary features because they weren't being highlighted as for unit testing.

For example, unit testing in C# is mainly driven by using attributes. The Custom Attributes feature provides a rich extension mechanism that allows frameworks like NUnit to iterate and compete, with things like Theory-based and Parameterized testing.

This brings me to my second major point - we don't know enough about what makes good testability to bake it into a language. The pace of innovation in testing is much faster than other language constructs so we need to have flexible mechanisms in our languages to leave freedom to innovate.

I'm a user but not fanatic about TDD - it is very helpful in some cases especially for improving your design thinking. It is not necessarily useful for larger legacy systems - higher-level testing with good data and automation will probably yield more benefit along with a strong code inspection culture.

Other relevant reading:

Designing the 50-year language

Previous SO question about language designed to be testable

Eiffel Automatic Testing


答:
I work in an office thats taken over 2 years (and still counting) to move to a Git/Branch workflow model from an RCS based config management tool. i.e. Git with gerrit was installed 2 years ago, yet releases and half the team still use the old tool. The old tool was a state of the art configuration management tool in 1994, and has features that Git/Gerrit do not provide, but branch based revision control is not its strength and manual copy/paste is how branches are managed.

The guys who have used this tool for 20 years have no awareness of the benefits of properly managed branches and merging, and strongly believe if you do not make every source change by typing it in yourself at a keyboard it cannot possibly be correct.

Another problem with branches also happens when code branches diverge to the point that they are no longer the same code base. This often happens in the above scenario as keeping everthing in sync is hard - if a change is not needed in one repo, the manual effort to merge it is seen as a waste of time. Do this a few times over a few years, and automatic merging becomes more difficult to manage than manual merging.

Some simple things for a person to resolve are impossible to automate. As the merges were not automated, no understanding or disipline exists around these things, and automatic branch merging usually fails. A couple of difficult merge conflicts reinforces the mindset that its not reliable. Code layout changes are a really good example, as are changing tabs to white space and training white space changes in files - things a person does not see or care about, that stop a merge dead in its tracks. Refactoring while making a one line defect fix, or worse - doing multiple unrelated changes in one commit - its easy for a person to tell which bits are needed, but a merge tool cannot.

No amount of technical training or refering to current best practice will change their belief system. Until they move over and start using branching, they will not be comfortable with it. Hence a catch 22. They won't move because the are not confident in it, they won't become confident until the move.

Putting it bluntly, most of the circumstances that branches are considered harmful is when dinasours who are not prepared to change and have never used it are in control.


答:
The people are afraid of things that they don't understand, this is why they think branch are evil.

The problem its that decide about the version control politics of a company without understanding branching its... well, not very professional.

You are using a very similar approach that the one that the tool git-flow (https://github.com/nvie/gitflow) propose with dev/production branches, the good thing about this tool is that its very, very easy to use and define a rigid but very easy to understand branching model. Can be a very good way to introduce the proper use of git to people new to the tool.


问:
What is the proper way to use an IDE to work on remote code?
One of the code bases I work on has a development environment that is running on a dev server and cannot be copied over to my PC to locally test and develop. I am wondering what is the proper way to work with this code base? It is object oriented and I have found it to be very tedious and time consuming to do my work using Vim when working on such a codebase.

I have another project which I have running locally and I like to use Eclipse and sometimes Sublime text to make changes to the codebase.

Is there a way to utilize such tools that I use locally with a remote project, and if so what is the proper way to set this up?

Should I remotely mount my system? We do have git/hg setup with these environments however I like to test and debug things in very small changes and this would produce a lot of commits that are un-needed. As well it is also time consuming. Ideally it would be great to just be able to work like it is a local environment and when I save and refresh a page the change is there.

Is my best solution mounting?

答:
Our software is developed and executes on AIX, but the AIX boxes a locked down so running Eclipse in AIX is not posisble (let alone what happens when 10 poeple fire eclipse on one server).

I mount my source folder locally (NFS on a Linux box) and run Eclipse on the linux box. Builds are done by shelling across to the AIX server and runnig the build. The outbput is captured by eclipse.

In my case we use SCons. I used to have a Makefile that shelled and ran SCons, now I use sconsolidar and the SConstruct file detects its running on a linux box and the working folder is mounted, looks up the mount point and sheels to the AIX box.

Its not just Eclipse, any tool availble on Linux is not able to be used on my source files. Mounting is a very versilitle solution.


答:
I've been faced with a couple of hard speed bumps that I've been surprised by:

1) having to using git from the command line (I've always been lucky & lazy enough to run it through one GUI or another :P)

2) a shop where the development flow relies heavily on rebasing instead of merging.

After stubbing my toes a bunch of times, I finally whipped up a "git cookbook" that I use to keep track of how I need to do each process I commonly run through, and a few of the recovery steps when something goes whacky. That's been really helpful for me.

It's also helped me to identify the steps that are "easy", and the steps that are good to know, but "hard" or "dangerous" (like "checkout --" or "push -f", which can result in code loss.)

Also -- and this goes to your question -- getting the mental model right, and branching it adds a layer of complication. So there are local changes, staged changes, changes committed locally, and changes in the origin repository. And figuring out where your changes are currently can be kind of baffling. The messages git provides can be very obscure, and sometimes there's inconsistent syntax in how you specify source and branch.

So it's like any other adaptation, or mal-adaption: the current shop has figured out how to make an extremely bad process work, but easing the learning curve and moving to best practices will largely be a matter of helping make the learning curve less steep, and the downside of learning less risky.


问:
confusion on using nodejs within an actual web application or ide
I am new to using nodejs completely, and it seems to be pretty much the go to thing for everything right now. But I program in Visual Studio, and I'm a bit confused about how this works. I will cite an example;

One task I want to do is to get a list of all the files in a directory and all of its sub-directories, and return them as a string[] for a javascript .config file. I started searching for that and found a lot of answers, but they all kept going back to nodejs, for instance, this one, and this one, and this one.

I really wasn't looking for anything having to do with nodejs, it just seems to be part of every solution out there. I've installed it, and gotten it to where I can do some simple things like create a very basic server that listens to a port - thanks to simple tutorials written for a moron like me - but I'm having a hard time figuring out how to use these kinds of things in my real programs - specifically ASP.NET MVC. I've searched pretty hard on this topic too, and discovered things like iisnode and the like that do some partial integration.

But even with all of this, this wealth of information, I am extremely confused.

I understand that I can use it from a command line, like PowerShell, I can run commands from a terminal, and install packages into projects, but I'm having a hard time seeing and finding how this actually translates into literal, real usage in an existing application. I have scoured around for days and days for examples, I've read at least 3 books on nodejs, The Node Beginner Book, What is Node, and Professional Node.js and to be very honest I am still as lost as ever.

Everything I read keeps assuming I am doing things from the command line or a terminal, but all of the applications I see for node assume you're writing a web application. I'm having a really hard time wrapping my head around how you use it within an application. Can anyone assist me with this? Perhaps a working example of an actual program that uses node? I'll take almost anything at this point, though ASP.NET MVC is my core system of choice.

I was originally going to post this on StackOverflow, but someone suggested that this community was more appropriate for this question.

Update

I want to make a more clear example of what is confusing me, I'm already learning because of the 1 proposed answer, but let me give more examples.

I program in Visual Studio, it has no real concept of node.js - in fact, if I try to do things that will run against node, it gives me problems. I often have to code anything related to node in WebStorm from JetBrains.

I understand that I can 'compile' things with node, what I don't understand is how I can invoke it within my program, not inside of a command line. For example let's say there is a node module that takes an array and does something to it - for sake of example let's say that it sorts everything in the array alphabetically, and it is a module called supersort.

So if I were at the console, I would just type in ...

node supersort.js

Okay, but now I'm not at the command line. I have published my web application. My user is at a page, let's say /account/history and they are seeing a list of every product they have bought. For the sake of argument, say I've got that list as a object[] or string[] - I realize that is completely absurd and it would be far more complex, but just jive with me.

I want to run supersort on this page. But it's live! How do I do it? How do I run this module on their live, active data without manually being there at the console? Is there a set of javascript files I'm supposed to download and call http requests a certain way? Do I wire up a special IHttpHandler in IIS? I think you can start to see where I am lost.

Update 2

Attempting to further emphasize my question, I'll try and cite a more specific example. I want to use the library Q.js in my ASP.NET MVC application. Now, there is a version 1 that I can seem to run out of the box, but I want to try out version 2 - you can find it linked Q.js v2 (beta)

So I am using Visual Studio, and I'll download the q.js file and load it up, but immediately we already have trouble now - if you look at the file's source code right away I see this.

```<code>require("collections/shim");
var WeakMap = require("collections/weak-map");
var Iterator = require("collections/iterator");
var asap = require("asap");
</code>```

Now I certainly don't have folders with those names in my application - and even though I have node.js installed, putting this file in a

答: It seems to me that you've gone down a rabbit hole. If you're writing an application in ASP.Net, why not just research how to solve a particular problem in that platform? I'd need to have a pretty damn good reason to add another tool/language/platform to my solution, and I don't get the impression that such a compelling reason exists for you. Node.js may be the hip thing right now and offer some pretty neat ways to solve problems, but you probably could have solved your problem natively 10 times over by now. That's just my two cents.</p>


问:
Is any one of these the right way to write a license for your opensource project forked and modified from an existing one with different authors?
I've used parts of source from an existing Java library project with what appears to be a 3-clause BSD license.

I've made significant changes to the library which makes it possible to use it in a new platform, and also added several new features, and new example projects using the modified library.

I want to know if any one of these is the correct way to write a license for the project (no change in type of license)

Please read both versions and provide a comparative answer:

EITHER:

**<New library name for another platform>**

**Copyright (c) 2014
new author name**

**All rights reserved.**

**This project incorporates code from the project titled
<original library name for different platform>
which has its source code repository at
<git repository link> with the following copyright holders:**

**Copyright (c) 200x-200y
original library author name 1
original library author name 2
original library author name 3**

**All rights reserved.**

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

    Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

    Neither the name of **<author name>, <old library author name 1>,
    <old library author name 2>, <old library author name 3>**, nor the names of its
    contributors may be used to endorse or promote products derived from
    this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
```

<p>OR:</p>

```**<New library name for another platform>
Copyright (c) 2014
new library author name
All rights reserved.**

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

    Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

    Neither the name of **<new library author name>**, nor the names of its
    contributors may be used to endorse or promote products derived from
    this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

**This project incorporates code from the project titled
<original library name for different platform>
which has its source code repository at <git repository link>
and which is covered by the following terms:**

**<Original library name for different platform>
Copyright (c) 200x-200y
original library author name 1
original library author name 2
original library author name 3
All rights reserved.**

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

    Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

    Neither the name of **<original library author name 1>,
    <original library author name 2>, <original library author name 3>**,
    nor the names of its
    contributors may be used to endorse or promote products derived from
    this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
```

答:
As you copied parts of the other library into your library, the authors/copyright holders of the parts you copied must also be mentioned as (joint) copyright holders of your library. For that reason, neither option is correct.

A correct way to provide the right copyright and license informations is

Copyright 2014 <original author names>, <new library author>

  All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

This library is derived from the <XXX> library, which is distributed under the same license terms and can be found at <URL>.

In the copyright line, you give proper attribution to all persons/legal entities that can claim copyright on parts of the code.

The mention of the library you based your work on is not required, but shows you are a nice guy who is not out to steal other one's credits. As it is distributed under the same license, there is no need to reproduce the license again.


问:
Understanding JAVA generic keyword 'super'
Recently some people said that I was wrong when I explained why one cannot insert a Number object into a list declared as List<? super RationalNumber>.
(This assumes that RationalNumber is a subclass of Number)

My explanation was that in List<? super RationalNumber> the <? super RationalNumber> stands for an unknown super class of RationalNumber. This means that <? super RationalNumber> indicates that a valid object for List<? super RationalNumber> is an object that extends an unknown super class of RationalNumber.

Since an unknown super class of RationalNumber is really unknown (e.g. it can be an interface X instead of Number), there is not guarantee that Number is a sub-class of X i.e. implements X, so Number is not a valid substitution of <? super RationalNumber>.

What is wrong with this explanation?
Edit: Note that I am asking for what wrong with the way I explain, my explanation. Not another explanation for the original question.

Thanks.

答:
List<? super RationalNumber> is a list of some type X that is a superclass of RationalNumber.  Your assumption is that RationalNumber is a subclass of Number, so the possible candidates for X are RationalNumber, Number, or Object.  The most restrictive possibility is that X is RationalNumber itself.  A List<RationalNumber> can contain only instances of RationalNumber, and cannot contain instances of Number.

In short, a List<? super T> is a list that can accept instances of T, but the current contents are of unknown type.  This contrasts with List<? extends T>, which contains instances of T, but does not allow adding new elements because the type accepted is unknown.

This example illustrates the use of super:

```<code>void storePies(List<? super RationalNumber> list) {
    list.add(new RationalNumber(22, 7))
    list.add(new RationalNumber(355, 113))
}

...
List<Number> list = new ArrayList<Number>();
storePies(list);
list.add(3.14159265358979);
</code>```

This example illustrates the use of extends:

```<code>double sum(Collection<? extends Number> numbers) {
    double s = 0;
    for (Number n: numbers) { s += n.doubleValue(); }
    return s;
}

List<Integer> somePrimes = new ArrayList<Integer>();
somePrimes.add(5);
somePrimes.add(17);
double total = sum(somePrimes);
</code>```

Body:
List<? super RationalNumber> is a list of some type X that is a superclass of RationalNumber.  Your assumption is that RationalNumber is a subclass of Number, so the possible candidates for X are RationalNumber, Number, or Object.  The most restrictive possibility is that X is RationalNumber itself.  A List<RationalNumber> can contain only instances of RationalNumber, and cannot contain instances of Number.

In short, a List<? super T> is a list that can accept instances of T, but the current contents are of unknown type.  This contrasts with List<? extends T>, which contains instances of T, but does not allow adding new elements because the type accepted is unknown.

This example illustrates the use of super:

void storePies(List<? super RationalNumber> list) {
    list.add(new RationalNumber(22, 7))
    list.add(new RationalNumber(355, 113))
}

...
List<Number> list = new ArrayList<Number>();
storePies(list);
list.add(3.14159265358979);

This example illustrates the use of extends:

double sum(Collection<? extends Number> numbers) {
    double s = 0;
    for (Number n: numbers) { s += n.doubleValue(); }
    return s;
}

List<Integer> somePrimes = new ArrayList<Integer>();
somePrimes.add(5);
somePrimes.add(17);
double total = sum(somePrimes);


问:
What is selection and what is projection
I am working on Android with the query() method of the ContentResolver class and it accepts 6 parameters, (uri,projection,selection,selectionArgs,sortOrder,cancellationSignal) for selection and projection parameters.

I am little bit confused with the selection and projection part of query.

In below example, what is selection and project part in the query?

```<code>select * from Person
where name='zeus';
</code>```

答:
Selecting means choosing some records from a table and leaving others out.

Projecting means choosing some columns from each record and leaving others out.

Therefore, your query performs selection (records with name='zeus' are chosen, but others are rejected) but not projection (those records that are chosen are returned with all of their columns).

Broadly, the select keyword performs projection and the where keyword performs selection. (The fact that select is a language feature for choosing columns rather than rows, i.e. it performs projection, not selection, is unfortunate, but the syntax is far too established now to be corrected.)