答:
Cohesion refers to the degree that elements of a module belong together.  The more cohesive a module is, relative to other modules in the software, the more independently it can operate.  Encapsulation is one of the techniques by which cohesion can be achieved.  While encapsulation is certainly an important element of cohesion, cohesion also addresses other concerns that affect cohesion.

The degree in which components depend on each other for their proper operation is called coupling.  Coupling is achieved primarily by the mechanisms chosen to interact between components.  The less coupled a system is, the more cohesive it is.  Hence, low coupling is a desirable feature.

Let's explore a few examples of relationships between components, in order of increasing cohesivity:

Inheritance

Inheritance is very tightly-coupled, and therefore has relatively low cohesivity; if you break the inheritance, you break the program.  But inheritance is desirable for systems where you want and need that kind of tight coupling, because you want the components to work closely together.  It is used quite effectively in Graphical User Interfaces, for example.

Composition

Composition is less tightly-coupled than Inheritance; you can replace a local object in a class with a different implementation without breaking an inheritance chain.  But you still have to change the class's internal implementation; it's just that the changes are confined to a single class.

Composition with interfaces

Here, the class is only dependent on an Interface.  Consequently, you can change out the implementation without changing the class at all, provided the implementing class conforms to the specified interface.  You can even change out the implementation of the interface at runtime, by handing an instance of the desired class to the constructor of your class.

Data Transfer Objects and View Models

This technique allows you to create classes that serve as data containers, without any behavior associated with them.  Now, the modules between which you are communicating don't need to know anything about each other at all, not even a common interface.  All they need to know about is the DTO or View Model object.  But things are beginning to become a bit more complicated, because now you're spending a lot of time mapping fields to other fields and copying data between different structures.

Streams, strings and pipes

With strings and streams, you take advantage of a well-known mechanism to communicate between modules.  This arrangement is the most loosely-coupled, because the module doesn't have any dependencies at all, except for widely-available, cross-platform compatible primitive data structures.  Strings are the most ubiquitous of all data types; examples of their use in an API include database connection strings and communication protocols that use strings or binary arrays to transmit data.  The disadvantage of this mechanism is that you now need a parser, a serializer, or some similar mechanism in your modules to translate the raw data being transmitted between modules into a usable form.

As you can see, high cohesivity isn't a perfect ideal, nor is it universally desirable.  As with many other things in computing, it is a tradeoff between competing objectives.

Title: What is the difference between Encapsulation and High cohesion?

Body: I've looked at encapsulation and cohesion, but they look like the same thing to me.  Isn't an encapsulated object already highly-cohesive?</p>


问:
Undefined behavior, in principle
Whether in C or C++, I think that this illegal program, whose behavior according to the C or C++ standard is undefined, is interesting:

```<code>#include <stdio.h>

int foo() {
    int a;
    const int b = a;
    a = 555;
    return b;
}

void bar() {
    int x = 123;
    int y = 456;
}

int main() {
    bar();
    const int n1 = foo();
    const int n2 = foo();
    const int n3 = foo();
    printf("%d %d %d\n", n1, n2, n3);
    return 0;
}
</code>```

Output on my machine (after compilation without optimization):

```<code>123 555 555
</code>```

I think that this illegal program is interesting because it illustrates stack mechanics, because the very reason one uses C or C++ (instead of, say, Java) is to program close to the hardware, close to stack mechanics and the like.

However, on StackOverflow, when a questioner's code inadvertently reads from uninitialized storage, the most heavily upvoted answers invariably quote the C or C++ (especially C++) standard to the effect that the behavior is undefined.  This is true, of course, as far as the standard goes—the behavior is indeed undefined—but it is curious that alternate answers that try, from a hardware or stack-mechanical perspective, to investigate why a specific undefined behavior (such as the output above) might have occurred, are rare and tend to be ignored.

I even remember one answer that suggested that undefined behavior could include reformatting my hard drive.  I didn't worry too much about that, though, before running the program above.

My question is this:  Why is it more important to teach readers merely that behavior is undefined in C or C++, than it is to understand the undefined behavior?  I mean, if the reader understood the undefined behavior, then would he not be the more likely to avoid it?

My education happens to be in electrical engineering, and I work as a building-construction engineer, and the last time I had a job as a programmer per se was 1994, so I am curious to understand the perspective of users with more conventional, more recent software-development backgrounds.

答:
If the documentation for a particular compiler says what it will do when code does something which is considered "Undefined Behavior" by the standard, then code which relies upon that behavior will work correctly when compiled with that compiler, but may behave in arbitrary fashion when compiled using some other compiler whose documentation does not specify the behavior.

If the documentation for a compiler does not specify how it will handle some particular "undefined behavior", the fact that a program's behavior seems to obey certain rules says nothing about how any similar programs will behave. Any variety of factors may cause a compiler to emit code which handles unexpected situations differently--sometimes in seemingly-bizarre fashion.

Consider, for example, on a machine where int is a 32-bit integer:

```<code>int undef_behavior_example(uint16_t size1, uint16_t size2)
{
  int flag = 0;
  if ((uint32_t)size1 * size2 > 2147483647u)
    flag += 1;
  if (((size1*size2) & 127) != 0) // Test whether product is a multiple of 128
    flag += 2;
  return flag;
}
</code>```

If size1 and size2 were both equal to 46341 (their product is 2147488281) one might expect that the function would return 3, but a compiler could legitimately skip the first test entirely; either the product would be small enough that the condition would be false, or the upcoming multiplication would overflow and relieve the compiler of any requirement to do, or have done, anything.  While such behavior may seem bizarre, some compiler authors seem to take great pride in their compilers' abilities to eliminate such "unnecessary" tests.  Some people might expect that an overflow on the second multiply would, at worst, cause the all bits of that particular product to be arbitrarily corrupted; in fact, however, in any case where a compiler can determine that overflow either must have occurred or would be inevitable before the next sequenced observable side-effect, a compiler would be free to do anything it likes.

OwnerDisplayName: thb

ContentLicense: CC BY-SA 3.0

Title: Undefined behavior, in principle

Body:
If the documentation for a particular compiler says what it will do when code does something which is considered "Undefined Behavior" by the standard, then code which relies upon that behavior will work correctly when compiled with that compiler, but may behave in arbitrary fashion when compiled using some other compiler whose documentation does not specify the behavior.

If the documentation for a compiler does not specify how it will handle some particular "undefined behavior", the fact that a program's behavior seems to obey certain rules says nothing about how any similar programs will behave. Any variety of factors may cause a compiler to emit code which handles unexpected situations differently--sometimes in seemingly-bizarre fashion.

Consider, for example, on a machine where int is a 32-bit integer:

int undef_behavior_example(uint16_t size1, uint16_t size2)
{
  int flag = 0;
  if ((uint32_t)size1 * size2 > 2147483647u)
    flag += 1;
  if (((size1*size2) & 127) != 0) // Test whether product is a multiple of 128
    flag += 2;
  return flag;
}

If size1 and size2 were both equal to 46341 (their product is 2147488281) one might expect that the function would return 3, but a compiler could legitimately skip the first test entirely; either the product would be small enough that the condition would be false, or the upcoming multiplication would overflow and relieve the compiler of any requirement to do, or have done, anything.  While such behavior may seem bizarre, some compiler authors seem to take great pride in their compilers' abilities to eliminate such "unnecessary" tests.  Some people might expect that an overflow on the second multiply would, at worst, cause the all bits of that particular product to be arbitrarily corrupted; in fact, however, in any case where a compiler can determine that overflow either must have occurred or would be inevitable before the next sequenced observable side-effect, a compiler would be free to do anything it likes.


问:
How have languages influenced CPU design?
We are often told that the hardware doesn't care what language a program is written in as it only sees the compiled binary code, however this is not the whole truth. For example, consider the humble Z80; its extensions to the 8080 instruction set include instructions like CPIR which is useful for scanning C-style (NULL-terminated) strings, e.g. to perform strlen(). The designers must have identified that running C programs (as opposed to Pascal, where the length of a string is in the header) was something that their design was likely to be used for. Another classic example is the Lisp Machine.

What other examples are there? E.g. instructions, number and type of registers, addressing modes, that make a particular processor favour the conventions of a particular language? I am particularly interested in revisions of the same family.

答:
When the 8087 numerical coprocessor was designed, it was fairly common for languages to perform all floating-point math using the highest-precision type, and only round the result to lower precision when assigning it to a lower-precision variable.  In the original C standard, for example, the sequence:

```<code>float a = 16777216, b = 0.125, c = -16777216;
float d = a+b+c;
</code>```

would promote a and b to double, add them, promote c to double, add it, and then store the result rounded to float.  Even though it would have been faster in many cases for a compiler to generate code that would perform operations directly on type float, it was simpler to have a set of floating-point routines which would operate only on type double, along with routines to convert to/from float, than to have separate sets of routines to handle operations on float and double.  The 8087 was designed around that approach to arithmetic, performing all all arithmetic operations using an 80-bit floating-point type [80 bits was probably chosen because:

On many 16- and 32-bit processors, it's faster to work with a 64-bit mantissa and a separate exponent than to work with value which divides a byte between the mantissa and exponent.

It's very difficult to perform computations which are accurate to the full precision of the numerical types one is using; if one is trying to e.g. compute something like log10(x), it's easier and faster to compute a result which is accurate to within 100ulp of an 80-bit type than to compute a result which is accurate to within 1ulp of a 64-bit type, and rounding the former result to 64-bit precision will yield a 64-bit value which is more accurate than the latter.

Unfortunately, future versions of the language changed the semantics of how floating-point types should work; while the 8087 semantics would have been very nice if languages had supported them consistently, if functions f1(), f2(), etc. return type float, many compiler authors would take it upon themselves to make long double an alias for the 64-bit double type rather than the compiler's 80-bit type (and provide no other means of creating 80-bit variables), and to arbitrarily evaluate something like:

```<code>double f = f1()*f2() - f3()*f4();
</code>```

in any of the following ways:

```<code>double f = (float)(f1()*f2()) - (extended_double)f3()*f4();
double f = (extended_double)f1()*f2() - (float)(f3()*f4());
double f = (float)(f1()*f2()) - (float)(f3()*f4());
double f = (extended_double)f1()*f2() - (extended_double)f3()*f4();
</code>```

Note that if f3 and f4 return the same values as f1 and f2, respectively, the original expression should clearly return zero, but many of the latter expressions may not.  This led to people condemning the "extra precision" of the 8087 even though the last formulation would generally be superior to the third and--with code that used the extended double type appropriately--would rarely be inferior.

In the intervening years, Intel has responded to language's (IMHO unfortunate) trend toward forcing intermediate results to be rounded to the operands' precision by designing their later processors so as to favor that behavior, to the detriment of code which would benefit from using higher precision on intermediate calculations.

Body:
When the 8087 numerical coprocessor was designed, it was fairly common for languages to perform all floating-point math using the highest-precision type, and only round the result to lower precision when assigning it to a lower-precision variable.  In the original C standard, for example, the sequence:

float a = 16777216, b = 0.125, c = -16777216;
float d = a+b+c;

would promote a and b to double, add them, promote c to double, add it, and then store the result rounded to float.  Even though it would have been faster in many cases for a compiler to generate code that would perform operations directly on type float, it was simpler to have a set of floating-point routines which would operate only on type double, along with routines to convert to/from float, than to have separate sets of routines to handle operations on float and double.  The 8087 was designed around that approach to arithmetic, performing all all arithmetic operations using an 80-bit floating-point type [80 bits was probably chosen because:

On many 16- and 32-bit processors, it's faster to work with a 64-bit mantissa and a separate exponent than to work with value which divides a byte between the mantissa and exponent.

It's very difficult to perform computations which are accurate to the full precision of the numerical types one is using; if one is trying to e.g. compute something like log10(x), it's easier and faster to compute a result which is accurate to within 100ulp of an 80-bit type than to compute a result which is accurate to within 1ulp of a 64-bit type, and rounding the former result to 64-bit precision will yield a 64-bit value which is more accurate than the latter.

Unfortunately, future versions of the language changed the semantics of how floating-point types should work; while the 8087 semantics would have been very nice if languages had supported them consistently, if functions f1(), f2(), etc. return type float, many compiler authors would take it upon themselves to make long double an alias for the 64-bit double type rather than the compiler's 80-bit type (and provide no other means of creating 80-bit variables), and to arbitrarily evaluate something like:

double f = f1()*f2() - f3()*f4();

in any of the following ways:

double f = (float)(f1()*f2()) - (extended_double)f3()*f4();
double f = (extended_double)f1()*f2() - (float)(f3()*f4());
double f = (float)(f1()*f2()) - (float)(f3()*f4());
double f = (extended_double)f1()*f2() - (extended_double)f3()*f4();

Note that if f3 and f4 return the same values as f1 and f2, respectively, the original expression should clearly return zero, but many of the latter expressions may not.  This led to people condemning the "extra precision" of the 8087 even though the last formulation would generally be superior to the third and--with code that used the extended double type appropriately--would rarely be inferior.

In the intervening years, Intel has responded to language's (IMHO unfortunate) trend toward forcing intermediate results to be rounded to the operands' precision by designing their later processors so as to favor that behavior, to the detriment of code which would benefit from using higher precision on intermediate calculations.


问:
How Byte loading/storing is implemented By the CPU?
I know that in 32bit machine, cpu read from memory 32bits at a time. since the registers in this case is 32bit in size too, I can understand how this works.

What I don't understand is how the cpu implement load instructions of 1 byte. does it load the whole word where the single byte is located to the register, then perform some kind of "byte shifting", or does the cpu can load a single byte, in this case when does the byte masking happen, is it until the byte got loaded in the register, or it happen when byte is send through the data bus ?

P.S. The cpu Im using is MIPS, the instructions Im talking about are: lb or lbu

答:
In many 32-bit machines without a memory cache, the memory will be divided into four 8-bit-wide sections, each of which will be connected to eight bits of the system bus and will have its own "enable" logic.  If a processor executes a 16-bit store instruction, it will enable two of the eight sections and output the appropriate data on the wires that connect to them.  The other two sections won't be enabled, so their contents won't be affected.

Note that while some machines split up both write and read operations the same way, it's really only necessary that the memory subsystem allow "partial" writes.  If the processor performs a 16-bit load, it will expect to receive data from the two 8-bit sections that contain the address in question, but won't care if the other sections supply data as well.  Each section has its own separate set of eight data pins, and the processor would ignore whatever data was placed on the unused sets.

Note also that in systems with memory caches, things get more complicated.  Depending upon the caching architecture, a 16-bit store might cause the two memory banks that are being written to be set for "write" while those which aren't would be set for "read"; all 32 bits of the cache would then be set to "write" (16 bits would grab data being stored by the CPU, while the other 16 would grab the other half of that same word, fetched from memory).  Alternatively, it might only write 16 bits to the cache, but set flags indicating that the other 16 bits of that word are "unknown".  Despite this complexity, most CPU designers believe the semantic cleanliness of allowing 8- and 16-bit "store" instructions is worth the cost.


问:
What is the best way to initialize a child's reference to its parent?
I'm developing an object model that has lots of different parent/child classes.  Each child object has a reference to its parent object.  I can think of (and have tried) several ways to initialize the parent reference, but I find significant drawbacks to each approach.  Given the approaches described below which is best ... or what is even better.

I'm not going to make sure the code below compiles so please try to see my intention if the code is not syntactically correct.

Note that some of my child class constructors do take parameters (other than parent) even though I don't always show any.

Caller is responsible for setting parent and adding to the same parent.

```<code>class Child {
  public Child(Parent parent) {Parent=parent;}
  public Parent Parent {get; private set;}
}
class Parent {
  // singleton child
  public Child Child {get; set;}
  //children
  private List<Child> _children = new List<Child>();
  public List<Child> Children { get {return _children;} }
}
</code>```

Downside: setting parent is a two-step process for the consumer.

```<code>var child = new Child(parent);
parent.Children.Add(child);
</code>```

Downside: error prone.  Caller can add child to a different parent than was used to initialize the child.

```<code>var child = new Child(parent1);
parent2.Children.Add(child);
</code>```

Parent verifies that caller adds child to parent for which was initialized.

```<code>class Child {
  public Child(Parent parent) {Parent = parent;}
  public Parent Parent {get; private set;}
}
class Parent {
  // singleton child
  private Child _child;
  public Child Child {
    get {return _child;}
    set {
      if (value.Parent != this) throw new Exception();
      _child=value;
    }
  }
  //children
  private List<Child> _children = new List<Child>();
  public ReadOnlyCollection<Child> Children { get {return _children;} }
  public void AddChild(Child child) {
    if (child.Parent != this) throw new Exception();
    _children.Add(child);
  }
}
</code>```

Downside: Caller still has a two-step process for setting parent.

Downside: runtime checking – reduces performance and adds code to every add/setter.

The parent sets the child's parent reference (to itself) when the child is added/assigned to a parent.  Parent setter is internal.

```<code>class Child {
  public Parent Parent {get; internal set;}
}
class Parent {
  // singleton child
  private Child _child;
  public Child Child {
    get {return _child;}
    set {
      value.Parent = this;
      _child = value;
    }
  }
  //children
  private List<Child> _children = new List<Child>();
  public ReadOnlyCollection<Child> Children { get {return _children;} }
  public void AddChild(Child child) {
    child.Parent = this;
    _children.Add(child);
  }
}
</code>```

Downside: The child is created without a parent reference.  Sometimes initialization/validation requires the parent which means some initialization/validation must be performed in the child’s parent setter.  The code can get complicated.  It would be so much easier to implement the child if it always had its parent reference.

Parent exposes factory add methods so that a child always has a parent reference.  Child ctor is internal.  Parent setter is private.

```<code>class Child {
  internal Child(Parent parent, init-params) {Parent = parent;}
  public Parent Parent {get; private set;}
}
class Parent {
  // singleton child
  public Child Child {get; private set;}
  public void CreateChild(init-params) {
      var child = new Child(this, init-params);
      Child = value;
  }
  //children
  private List<Child> _children = new List<Child>();
  public ReadOnlyCollection<Child> Children { get {return _children;} }
  public Child AddChild(init-params) {
    var child = new Child(this, init-params);
    _children.Add(child);
    return child;
  }
}
</code>```

Downside: Can’t use initialization syntax such as new Child(){prop = value}.
Instead have to do:

```<code>var c = parent.AddChild();
c.prop = value;
</code>```

Downside: Have to duplicate the parameters of the child constructor in the add-factory methods.

Downside: Can’t use a property setter for a singleton child.  It seems lame that I need a method to set the value but provide read access via a property getter.  It’s lopsided.

Child adds itself to the parent referenced in its constructor.  Child ctor is public.  No public add access from parent.

```<code>//singleton
class Child{
  public Child(ParentWithChild parent) {
    Parent = parent;
    Parent.Child = this;
  }
  public ParentWithChild Parent {get; private set;}
}
class ParentWithChild {
  public Child Child {get; internal set;}
}

//children
class Child {
  public Child(ParentWithChildren parent) {
    Parent = parent;
    Parent._children.Add(this);
  }
  public ParentWithChildren Parent {get; private set;}
}
class ParentWithChildren {
  internal List<Child> _children = new List<Child>();
  public ReadOnlyCollection<Child> Children { get {return _children;} }
}
</code>```

Downside: calling syntax is not great.  Normally one calls an add method on the parent instead of just creating an object like this:

```<code>var parent = new ParentWithChildren();
new Child(parent); //adds child to parent
new Child(parent);
new Child(parent);
</code>```

And sets a property rather than just creating an object like this:

```<code>var parent = new ParentWithChild();
new Child(parent); // sets parent.Child
</code>```

...

I just learned that SE does not allow some subjective questions and clearly this is a subjective question.  But, maybe it is a good subjective question.

答:
Great listing. I do not know which method is the "best" but here is one to find the most expressive methods.

Start with the simplest possible parent and child class.
Write your code with those. Once you notice code duplication that can be named you put that into a method.

Maybe you get addChild(). Maybe you get something like addChildren(List<Child>) or addChildrenNamed(List<String>) or loadChildrenFrom(String) or newTwins(String, String) or Child.replicate(int).

If your problem is really about forcing a one-to-many relationship maybe you should

force it in the setters which may lead to confusion or throw-clauses

you remove the setters and create special copy or move methods - which is expressive and understandable

This is not an answer but I hope you find one while reading this.


问:
Does any other language use the uniform initialization syntax found in c++?
Are there any other languages that use the new C++11 uniform initialization syntax thoroughly throughout the entire language, or is this entirely a C++ idiom at this point?

I tried googling and thinking of any off the top of my head and couldn't really find any.

For those not familiar with C++11:

Basically, your typical initialization in C++ used to be an assignment/copy initializer similar to other languages:

```<code>int x = 5;
</code>```

Now, the new syntax that is recommended for use is:

```<code>int x{5};
</code>```

This is called the new uniform initialization syntax.

答:
C# has something similar; they're called Object/Collection Initializers.  They have several, but similar, forms:

```<code>// Object initialization
var cat = new Cat { Age = 10, Name = "Fluffy" };

// Object initialization with anonymous type
var pet = new { Age = 10, Name = "Fluffy" };

// Collection initialization
var digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// Collection initialization with Linq and anonymous type
var productInfos =
    from p in products
    select new { p.ProductName, p.UnitPrice };
</code>```

Note that var in C# has the same function as auto in C++.

Also note that the form:

```<code>int x{5}
</code>```

is really just the "scalar" form of a collection initializer (it is a single element, potentially belonging to some collection).

Body:
C# has something similar; they're called Object/Collection Initializers.  They have several, but similar, forms:

// Object initialization
var cat = new Cat { Age = 10, Name = "Fluffy" };

// Object initialization with anonymous type
var pet = new { Age = 10, Name = "Fluffy" };

// Collection initialization
var digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// Collection initialization with Linq and anonymous type
var productInfos =
    from p in products
    select new { p.ProductName, p.UnitPrice };

Note that var in C# has the same function as auto in C++.

Also note that the form:

int x{5}

is really just the "scalar" form of a collection initializer (it is a single element, potentially belonging to some collection).


问:
Is it good practice to catch a checked exception and throw a RuntimeException?
I read some code of a colleague and found that he often catches various exceptions and then always throws a 'RuntimeException' instead. I always thought this is very bad practice. Am I wrong?</p>

答:
TL;DR

Premise

Runtime exceptions should be thrown when the error is irrecoverable: when the error is in the code, and does not depend on external state (thus, the recovery would be correcting the code).

Checked exceptions should be thrown when the code is correct, but external state is not as expected: no network connectivity, file not found or is corrupt, etc.

Conclusion

We may rethrow a checked exception as a runtime exception if the propagating or interface code assumes that the underlying implementation depends on external state, when it clearly does not.

This section discusses the topic of when either of the exceptions should be thrown. You can skip to the next horizontal bar if you just want to read a more detailed explanation for the conclusion.

When is it appropriate to throw a runtime exception? You throw a runtime exception when it is clear that the code is incorrect, and that recovery is appropriate by modifying the code.

For instance, it is appropriate to throw a runtime exception for the following:

```<code>float nan = 1/0;
</code>```

This will throw a division by zero runtime exception. This is appropriate because the code is defective.

Or for instance, here's a portion of HashMap's constructor:

```<code>public HashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " +
                loadFactor);
    // more irrelevant code...
}
</code>```

In order to fix the initial capacity or load factor, it is appropriate that you edit the code to ensure that the correct values are being passed in. It is not dependent on some far away server being up, on the current state of the disk, a file, or another program. That constructor being called with invalid arguments depends on the correctness of the calling code, be it a wrong calculation that led to the invalid parameters or inappropriate flow that missed an error.

When is it appropriate to throw a checked exception? You throw a checked exception when the issue is recoverable without changing the code. Or to put it in different terms, you throw a checked exception when the error is related to state while the code is correct.

Now the word "recover" may be tricky here. It could mean that you find another way to achieve the goal: For instance, if the server doesn't respond then you should try the next server. If that sort of recovery is possible for your case then that's great, but that's not the only thing recovery means -- recovery could simply be displaying an error dialog to the user that explains what happened, or if that's a server application then it could be sending an email to the administrator, or even merely logging the error appropriately and concisely.

Let's take the example that was mentioned in mrmuggles' answer:

```<code>public void dataAccessCode(){
   try{
       ..some code that throws SQLException
   }catch(SQLException ex){
       throw new RuntimeException(ex);
   }
}
</code>```

This is not the correct way to handle the checked exception. The mere incapacity to handle the exception in this method's scope does not mean that the app should be crashed. Instead, it is appropriate to propagate it to a higher scope like so:

```<code>public Data dataAccessCode() throws SQLException {
    // some code that communicates with the database
}
</code>```

Which allows for the possibility of recovery by the caller:

```<code>public void loadDataAndShowUi() {
    try {
        Data data = dataAccessCode();
        showUiForData(data);
    } catch(SQLException e) {
        // Recover by showing an error alert dialog
        showCantLoadDataErrorDialog();
    }
}
</code>```

Checked exceptions are a static-analysis tool, they make it clear for a programmer what could go wrong in a certain call without requiring them to learn the implementation or going through a trial and error process. This makes it easy to ensure that no portions of the error flow will be ignored. Rethrowing a checked exception as a runtime exception is working against this labor-saving static analysis feature.

It is also worth mentioning that the calling layer has a better context of the grander scheme of things as has been demonstrated above. There could be many causes for that dataAccessCode would be called, the specific reason for the call is only visible to the caller -- thus it is able to make a better decision at the correct recovery upon failure.

Now that we've got this distinction clear, we may proceed to deduce when it's ok to rethrow a checked exception as a runtime exception.

Given the above, when is it appropriate to rethrow a checked exception as a RuntimeException? When the code you are using assumes dependency on external state, but you can clearly assert that it does not depend on external state.

Consider the following:

```<code>StringReader sr = new StringReader("{\"test\":\"test\"}");
try {
    doesSomethingWithReader(sr); // calls #read, so propagates IOException
} catch (IOException e) {
    throw new IllegalStateException(e);
}
</code>```

In this example, the code is propagating IOException because the API of Reader is designed to access external state, however we know that StringReader implementation does not access external state. At this scope, where we can certainly assert that the parts involved in the call don't access IO or any other external state, we can safely rethrow the exception as a runtime exception without astonishing colleagues who are unaware of our implementation (and are possibly assuming that IO-accessing code will throw an IOException).

The reason for strictly keeping external state dependent exceptions checked is that they are non-deterministic (unlike logic dependent exceptions, which will predictably be reproduced every time for a version of the code). For example, if you try to divide by 0, you will always produce an exception. If you don't divide by 0, you will never produce an exception, and you don't have to handle that exception case, because it will never happen. In the case of accessing a file, however, succeeding once does not mean that you will succeed next time -- the user might have changed permissions, another process might have deleted or modified it. So you always have to handle that exceptional case, or you likely have a bug.

Body:
TL;DR

Premise

Runtime exceptions should be thrown when the error is irrecoverable: when the error is in the code, and does not depend on external state (thus, the recovery would be correcting the code).

Checked exceptions should be thrown when the code is correct, but external state is not as expected: no network connectivity, file not found or is corrupt, etc.

Conclusion

We may rethrow a checked exception as a runtime exception if the propagating or interface code assumes that the underlying implementation depends on external state, when it clearly does not.

This section discusses the topic of when either of the exceptions should be thrown. You can skip to the next horizontal bar if you just want to read a more detailed explanation for the conclusion.

When is it appropriate to throw a runtime exception? You throw a runtime exception when it is clear that the code is incorrect, and that recovery is appropriate by modifying the code.

For instance, it is appropriate to throw a runtime exception for the following:

float nan = 1/0;

This will throw a division by zero runtime exception. This is appropriate because the code is defective.

Or for instance, here's a portion of HashMap's constructor:

public HashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " +
                loadFactor);
    // more irrelevant code...
}

In order to fix the initial capacity or load factor, it is appropriate that you edit the code to ensure that the correct values are being passed in. It is not dependent on some far away server being up, on the current state of the disk, a file, or another program. That constructor being called with invalid arguments depends on the correctness of the calling code, be it a wrong calculation that led to the invalid parameters or inappropriate flow that missed an error.

When is it appropriate to throw a checked exception? You throw a checked exception when the issue is recoverable without changing the code. Or to put it in different terms, you throw a checked exception when the error is related to state while the code is correct.

Now the word "recover" may be tricky here. It could mean that you find another way to achieve the goal: For instance, if the server doesn't respond then you should try the next server. If that sort of recovery is possible for your case then that's great, but that's not the only thing recovery means -- recovery could simply be displaying an error dialog to the user that explains what happened, or if that's a server application then it could be sending an email to the administrator, or even merely logging the error appropriately and concisely.

Let's take the example that was mentioned in mrmuggles' answer:

public void dataAccessCode(){
   try{
       ..some code that throws SQLException
   }catch(SQLException ex){
       throw new RuntimeException(ex);
   }
}

This is not the correct way to handle the checked exception. The mere incapacity to handle the exception in this method's scope does not mean that the app should be crashed. Instead, it is appropriate to propagate it to a higher scope like so:

public Data dataAccessCode() throws SQLException {
    // some code that communicates with the database
}

Which allows for the possibility of recovery by the caller:

public void loadDataAndShowUi() {
    try {
        Data data = dataAccessCode();
        showUiForData(data);
    } catch(SQLException e) {
        // Recover by showing an error alert dialog
        showCantLoadDataErrorDialog();
    }
}

Checked exceptions are a static-analysis tool, they make it clear for a programmer what could go wrong in a certain call without requiring them to learn the implementation or going through a trial and error process. This makes it easy to ensure that no portions of the error flow will be ignored. Rethrowing a checked exception as a runtime exception is working against this labor-saving static analysis feature.

It is also worth mentioning that the calling layer has a better context of the grander scheme of things as has been demonstrated above. There could be many causes for that dataAccessCode would be called, the specific reason for the call is only visible to the caller -- thus it is able to make a better decision at the correct recovery upon failure.

Now that we've got this distinction clear, we may proceed to deduce when it's ok to rethrow a checked exception as a runtime exception.

Given the above, when is it appropriate to rethrow a checked exception as a RuntimeException? When the code you are using assumes dependency on external state, but you can clearly assert that it does not depend on external state.

Consider the following:

StringReader sr = new StringReader("{\"test\":\"test\"}");
try {
    doesSomethingWithReader(sr); // calls #read, so propagates IOException
} catch (IOException e) {
    throw new IllegalStateException(e);
}

In this example, the code is propagating IOException because the API of Reader is designed to access external state, however we know that StringReader implementation does not access external state. At this scope, where we can certainly assert that the parts involved in the call don't access IO or any other external state, we can safely rethrow the exception as a runtime exception without astonishing colleagues who are unaware of our implementation (and are possibly assuming that IO-accessing code will throw an IOException).

The reason for strictly keeping external state dependent exceptions checked is that they are non-deterministic (unlike logic dependent exceptions, which will predictably be reproduced every time for a version of the code). For example, if you try to divide by 0, you will always produce an exception. If you don't divide by 0, you will never produce an exception, and you don't have to handle that exception case, because it will never happen. In the case of accessing a file, however, succeeding once does not mean that you will succeed next time -- the user might have changed permissions, another process might have deleted or modified it. So you always have to handle that exceptional case, or you likely have a bug.


问:
Which HTTP verb should I use to trigger an action in a REST web service?
I am implementing a RESTful web service and one of the available actions will be reload. It will be used to reload configurations, cache, etc.

We started with a simple GET to an URI like this: ${path}/cache/reload (no parameters are passed, only the URI is called). I am aware that data should not be modified with a GET request.

Which is the correct verb to use to invoke an action/command in a RESTful web service?

The reload is a command of the REST web service that reload its own cache/configuration/etc. It is not a method that returns information to the client.

Probably what I am trying to do isn't REST, but it is still something that need to be done this way. The reload method was only a real example that makes sense in the scope of the application and most answers focused on it, but in fact, I just needed to know which verb to trigger an action that doesn't do CRUD, but still changes data/state.

I found this detailed asnwer on Stack Overflow abot the subject: https://stackoverflow.com/questions/16877968/

答:
Some of the other answers, including the accepted one, advise you to use a GET (though not very enthusiastically).

I disagree.

First of all, all the others telling you that this is not ideal and not really RESTful are correct. In a proper RESTful scenario, you are manipulating resources on the server and adding, updating, deleting, retrieving, etc those resources. A PUT should send a payload that represents what the resource should be when the request is complete, and POST should send a payload that represents a resource to be added to the server. And a GET should return a resource on the server.

You have an RPC (remote procedure call), which isn't RESTful - you want to DO something on the server. So if you're trying to create a purely RESTful API, you should reconsider what you're doing.

That said, sometimes you do need to bend the rules a bit. Especially if you're developing an internal api that isn't going to be exposed to the public, you may decide that the trade-off is worth it.

If you do, I would recommend a PUT or POST, depending on whether or not the RPC is idempotent or not.

In general, we say that HTTP PUT maps to SQL UPDATE and that HTTP POST maps to SQL INSERT, but that's not strictly true. A purer way to state that is that HTTP PUT should be idempotent and HTTP POST needn't be. This means that you can call the same PUT request as many times as you want with no side-effects. Once you've called it once it's harmless to call it again. But you should not repeatedly call POST requests unless you mean to - each POST changes data on the server again.

In your case, if you need to have this reload function, I'd recommend a PUT because it sounds like it's idempotent. But I would still urge you to consider what the others said about not needing it at all.

ContentLicense: CC BY-SA 4.0


答:
The whole "checked exception" thing is a bad idea.

Structured programming only allows information to be passed between functions (or, in Java parlance, methods) when they are "nearby". More precisely, information can only move across functions in two ways:

From a caller to a callee, via argument passing.

From a callee to its caller, as return values.

This is a fundamentally good thing. This is what allows you to reason about your code locally: if you need to understand or modify a part of your program, you only need to look at that part and other "nearby" ones.

However, in some circumstances, it is necessary to send information to a "distant" function, without anyone in the middle "knowing". This is precisely when exceptions have to be used. An exception is a secret message sent from a raiser (whatever part of your code might contain a throw statement) to a handler (whatever part of your code might contain a catch block that is compatible with the exception that was thrown).

Checked exceptions destroy the secrecy of the mechanism, and, with it, the very reason for its existence. If a function can afford to let its caller "know" a piece of information, just send that piece of information directly as a part of the return value.

Title: Is it good practice to catch a checked exception and throw a RuntimeException?

Body: I read some code of a colleague and found that he often catches various exceptions and then always throws a 'RuntimeException' instead. I always thought this is very bad practice. Am I wrong?</p>


问:
Java Streams API Documentation
Currently learning Java so this may be a question resulting from lack of understanding of Java (while also learning Streams API)

In the declarations of function I often see two templated types for the return values. For instance below we have <T,U> and also Collector<T,?,U>. How should I read this? That it returns one of two possible types? This just looks odd since I've always thought functions return one type of data.

```<code>public static <T,U> Collector<T,?,U> reducing(U identity,
                                          Function<? super T,? extends U> mapper,
                                          BinaryOperator<U> op)
</code>```

答:
That signifies that the itself method is generic. It allows creation of static utility methods or use generic variables without needing to include those parameters in the whole class.

in order the parts are:

public: visibility

static: it's a static method

<T,U>: it's a generic method with parameters T and U

Collector<T,?,U>: returns a Collector<T,?,U>

reducing: the name of the method

(U identity,Function<? super T,? extends U> mapper,BinaryOperator op): the parameter list

To call the method and specify the parameters you can do Collectors.<Foo1,Foo2>reducing(...)

Title: Java Streams API Documentation

Body:
That signifies that the itself method is generic. It allows creation of static utility methods or use generic variables without needing to include those parameters in the whole class.

in order the parts are:

public: visibility

static: it's a static method

<T,U>: it's a generic method with parameters T and U

Collector<T,?,U>: returns a Collector<T,?,U>

reducing: the name of the method

(U identity,Function<? super T,? extends U> mapper,BinaryOperator<U> op): the parameter list

To call the method and specify the parameters you can do Collectors.<Foo1,Foo2>reducing(...)


答:
<T,U> is the method declaring that it uses the generic types T and U.

T is the type of the input elements
U is the type of the mapped values

The return type is a Collector<T,?,U>

Taken from the javadoc.

The best place to start is with is the oracle lambda tutorial, which touches on aggregation and generics.

Then look at aggregation, and specifically, more info on reduction in an oracle tutorial

(disclaimer: opinion based) This is probably the most horrible thing you could do when starting with java.  The aggregation framework uses the most mind mangling generics and lambdas.

Title: Java Streams API Documentation

Body:
Currently learning Java so this may be a question resulting from lack of understanding of Java (while also learning Streams API)

In the declarations of function I often see two templated types for the return values. For instance below we have <T,U> and also Collector<T,?,U>. How should I read this? That it returns one of two possible types? This just looks odd since I've always thought functions return one type of data.

```<code>public static <T,U> Collector<T,?,U> reducing(U identity,
                                          Function<? super T,? extends U> mapper,
                                          BinaryOperator<U> op)
</code>```


答:
Uniform initialization syntax seems geared to aggregate types. Looking at the FAQ, UIS's purpose is to solve a variety of loosely (or subtly?) related problems (ambiguities and impossibilities), some of which don't exist or have other solutions in other languages. Consequently, I don't think you'll find anything exactly the same in other languages; you may find similar syntax, but less so the semantics.

The problems that UIS addresses include:

initializing aggregate types that don't have constructors (including arrays) outside of definition statements (such as in member initialization lists). UIS addresses this by expanding the initializer list feature (in a sense, UIS is an expansion of initializer lists), which exists in other language. Robert Harvey's answer is one example. Initializer lists also exist in previous versions of C++ and C, going back to at least C99

ambiguous declarations. The following could be a function declaration or variable definition, depending on context:

```<code> int b(foo);
</code>```

This isn't a common issue in other languages.

need to repeat class in constructor name, when it could be inferred from context:

```<code> Complex c = {1,1};
 Complex conjugate(const Complex& c) {
     return {c.real(), -c.imaginary()};
 }
 Complex d = conjugate({1,1});
</code>```

Other languages generally approach the first from another angle, using type inference:

```<code>    var c = Complex(1,1);
</code>```

Other languages also use type conversion to cover some instances of the other two cases (function argument and return type inference). UIS is more general in that it supports converting a bunch of values, where most languages only support converting a single value (i.e. multiple parameter constructors can participate in conversions in C++, where usually only unary converters are supported in other languages; however, see "Implicit Conversions" under Scala for a workaround).
4. addressing the above (which add bare "{...}" expressions to C++) adds a new issue: constructor argument list delimiters aren't consistent with UIS. Allowing constructor argument lists to use brackets instead of parentheses makes various other construction expressions consistent with implicit constructor names:

```<code>    Foo f{x};   // direct initialization
    new Foo{x}; // explicit constructor name
    z = Foo{x}; // cast
    Foo{x};     // temporary
</code>```

Scala#

Scala has a similar syntax (closer to C#'s than C++'s) for instance creation expressions that covers the initializer-list use-case:

```<code>class Foo(var bar:String=null) {}
var foo = new Foo() {bar="Bar"}
</code>```

However, the semantics are different. Rather than simply initializing object fields, the bracketed expression after the constructor creates a new anonymous class that's a child of the named class, which is then instantiated. The constructor for the anonymous class includes the initializations in the brackets. The variable's type is the anonymous class, rather than the named class.

Since a new class is defined, it can also include just about any statement allowed in a class definition, such as field and method definitions.

```<code>class Foo(var bar:String=null) {}
var foo = new Foo() {bar="Bar"; var baz="Baz", def qux()=bar+baz}
</code>```

Unlike C++ and like C#, the equals symbol is required.

Something like the example definition in the question is valid in Scala, but it has different semantics from anything previously mentioned:

```<code>var i = {5}
</code>```

In this case, the bracketed expression is simply a compound expression and equivalent to the following C++ statement:

```<code>int i = (5);
</code>```

Implicit Conversions

Conversions in Scala are handled with views and implicit classes. When coupled with tuples, these can be used to convert multiple values to a single type without specifying the type, similar to UIS when the list contains constructor arguments and no class name is given. Like UIS, the type can be inferred from context. Unlike UIS, parentheses are used rather than brackets (as tuples are delimited with parentheses).

Note that Scala has another kind of implicit thing, the implicit parameter, which makes an appearance below in sign. Rather than being used when implicitly converting values, it's used to implicitly provide arguments to a function (i.e. when an argument isn't explicitly passed to a function, a value is automatically created and passed). The use of the word "implicit" for different things isn't a naming collision; all the implicit things work together to extend behavior (more on this below).

Implicit class:

```<code>// note: sign[T](n)(num) is a curried function
def sign[T : Numeric](x:T)(implicit num:Numeric[T]) = num.compare(x, num.zero)

implicit class Complex(ri:(Double,Double)) {
  val real = ri._1
  val imaginary = ri._2
  def conjugate = new Complex((real, -imaginary))
}
// could also be methods of Complex
def abs(c:Complex) = Math.sqrt(c.real * c.real + c.imaginary * c.imaginary)
def sqrt(c:Complex) = {
  val real = Math.sqrt((abs(c)+c.real)/2)
  val imaginary = sign(c.imaginary) * Math.sqrt((abs(c)-c.real)/2)
  new Complex((real, imaginary))
}

val c:Complex = (1.0,2.0)
sqrt((3.0,4.0))
// Conversions can even be used for method calls, which I don't think UISs can do
(1.0,2.0).conjugate
</code>```

View:

```<code>def sign[T : Numeric](n:T)(implicit num:Numeric[T]) = num.compare(n, num.zero)

class Complex(val real:Double, val imaginary:Double) {
  def conjugate = new Complex(real, -imaginary)
}
implicit def complexify(ab:(Double, Double)) = new Complex(ab._1, ab._2)

def abs(c:Complex) = Math.sqrt(c.real * c.real + c.imaginary * c.imaginary)
def sqrt(c:Complex) = {
  val real = Math.sqrt((abs(c)+c.real)/2)
  val imaginary = sign(c.imaginary) * Math.sqrt((abs(c)-c.real)/2)
  new Complex(real, imaginary)
}

val c:Complex = (1.0,2.0)
sqrt((3.0,4.0))
(1.0,2.0).conjugate
</code>```

Aside: as mentioned above, implicits in Scala are used to extend behavior. Implicit conversions for method calls ((1.0,2.0).conjugate in the examples) are usually used as an indirect way to add methods to an existing class by using the adapter pattern. Other languages (such as C#, Objective-C, Ruby and Python) take another approach and have open classes, allowing new methods to be added directly. For examples, consider C#'s extension methods, F#'s type extensions, Objective-C's categories and Haskell's type classes (which also addresses C++ overloading and template concepts). Scala's implicit parameters and objects can also be used like Haskell's type classes (instead of the adapter pattern you get with implicit conversions) basically the way you create traits classes in C++. For more on this topic:

Making Our Own Types and Typeclasses

Retroactive Supertyping in Scala: Adaptors, Rich Wrappers, Type Classes, and Structural Types

The Neophyte's Guide to Scala Part 12: Type Classes

A Small Example of the Typeclass Pattern in Scala

Type Classes as Objects and Implicits (PDF)

Looking at things like sign and (1.0,2.0).conjugate, I can't help but feel that Scala is weird and wonderful.

Erlang#

Erlang's record initializers use squiggly brackets and key-value pairs. The record name must be given (prefixed with "#"). Fields with default values can be left out of the initializer.

```<code> Complex c = {1,1};
 Complex conjugate(const Complex& c) {
     return {c.real(), -c.imaginary()};
 }
 Complex d = conjugate({1,1});
</code>```0

During compilation, records are converted to tuples, losing the field names.

Go#

In Go, composite literals can be used to initialize objects. Like similar features in other languages, brackets are used as delimiters. Unlike UIS (but like other languages), the type must be included. Within the brackets is an element list. An element can itself be a composite literal. Lists can be keyed or unkeyed (keys give struct field names, array indices or map keys); keys must be present or absent for all elements in a list (this restriction doesn't apply across separate lists within a literal). If keys are absent, all fields must be given values.

```<code> Complex c = {1,1};
 Complex conjugate(const Complex& c) {
     return {c.real(), -c.imaginary()};
 }
 Complex d = conjugate({1,1});
</code>```1

Haskell#

Haskell types can be declared with a record syntax, which are very similar to Erlang's records. Record constructors can take a initializers. Record syntax also declares accessor functions with the same name as the fields, and record fields can be updated using the same syntax as initialization. As far as I know, default values cannot be provided for fields, so all fields must be present in the initializer (though not when updating), though they can be given in any order.

```<code> Complex c = {1,1};
 Complex conjugate(const Complex& c) {
     return {c.real(), -c.imaginary()};
 }
 Complex d = conjugate({1,1});
</code>```2

Similar to Erlang, records are converted to plain types; the above results in:

```<code>data Foo = Foo String String
bar (Foo bar baz) = bar
baz (Foo bar baz) = baz
</code>```

(except that this doesn't support initializers or updates-by-name.)

Perl 5 & Javascript#

Perl 5 and Javascript don't have language level support for initializer lists, but constructors can take hashes (Perl 5) or objects (Javascript), which they can use to set object fields. Coincidentally, JS object literals and Perl hash refs use squiggly brackets (though Perl doesn't need to use hash refs to pass a hash to a constructor).

Perl 5:

```<code>package Foo;

sub new {
    my $class = shift;
    my $self = {@_};
    return bless $self, $class;
}

package main;

my $foo = new Foo(bar=>"Bar");
</code>```

JS:

```<code>function Foo(obj) {
    for (var p in obj) {
        this[p] = obj[p];
    }
}
var foo = new Foo({bar: "Bar"})
</code>```

Perl 6#

As with Perl 5, a hash can be passed to constructors to set attributes. Unlike Perl 5, Mu, the Perl 6 root class, has a constructor which takes a hash and defines attributes & accessors, so this doesn't need to be explicitly implemented.

```<code>class Foo {
    has $.bar as rw;
}
my $foo = Foo.new(bar=>"Bar");
</code>```

Powershell#

Powershell's new-object command supports initialization, property addition and method invocation using the -Property argument:

```<code>New-Object PSObject -Property @{
    foo = "bar"
}
</code>```

Title: Does any other language use the uniform initialization syntax found in c++?

Body:
Are there any other languages that use the new C++11 uniform initialization syntax thoroughly throughout the entire language, or is this entirely a C++ idiom at this point?

I tried googling and thinking of any off the top of my head and couldn't really find any.

For those not familiar with C++11:

Basically, your typical initialization in C++ used to be an assignment/copy initializer similar to other languages:

```<code>int x = 5;
</code>```

Now, the new syntax that is recommended for use is:

```<code>int x{5};
</code>```

This is called the new uniform initialization syntax.

Body:
Uniform initialization syntax seems geared to aggregate types. Looking at the FAQ, UIS's purpose is to solve a variety of loosely (or subtly?) related problems (ambiguities and impossibilities), some of which don't exist or have other solutions in other languages. Consequently, I don't think you'll find anything exactly the same in other languages; you may find similar syntax, but less so the semantics.

The problems that UIS addresses include:

initializing aggregate types that don't have constructors (including arrays) outside of definition statements (such as in member initialization lists). UIS addresses this by expanding the initializer list feature (in a sense, UIS is an expansion of initializer lists), which exists in other language. Robert Harvey's answer is one example. Initializer lists also exist in previous versions of C++ and C, going back to at least C99

ambiguous declarations. The following could be a function declaration or variable definition, depending on context:

 int b(foo);

This isn't a common issue in other languages.

need to repeat class in constructor name, when it could be inferred from context:

 Complex c = {1,1};
 Complex conjugate(const Complex& c) {
     return {c.real(), -c.imaginary()};
 }
 Complex d = conjugate({1,1});

Other languages generally approach the first from another angle, using type inference:

    var c = Complex(1,1);

Other languages also use type conversion to cover some instances of the other two cases (function argument and return type inference). UIS is more general in that it supports converting a bunch of values, where most languages only support converting a single value (i.e. multiple parameter constructors can participate in conversions in C++, where usually only unary converters are supported in other languages; however, see "Implicit Conversions" under Scala for a workaround).
4. addressing the above (which add bare "{...}" expressions to C++) adds a new issue: constructor argument list delimiters aren't consistent with UIS. Allowing constructor argument lists to use brackets instead of parentheses makes various other construction expressions consistent with implicit constructor names:

    Foo f{x};   // direct initialization
    new Foo{x}; // explicit constructor name
    z = Foo{x}; // cast
    Foo{x};     // temporary

Scala#

Scala has a similar syntax (closer to C#'s than C++'s) for instance creation expressions that covers the initializer-list use-case:

class Foo(var bar:String=null) {}
var foo = new Foo() {bar="Bar"}

However, the semantics are different. Rather than simply initializing object fields, the bracketed expression after the constructor creates a new anonymous class that's a child of the named class, which is then instantiated. The constructor for the anonymous class includes the initializations in the brackets. The variable's type is the anonymous class, rather than the named class.

Since a new class is defined, it can also include just about any statement allowed in a class definition, such as field and method definitions.

class Foo(var bar:String=null) {}
var foo = new Foo() {bar="Bar"; var baz="Baz", def qux()=bar+baz}

Unlike C++ and like C#, the equals symbol is required.

Something like the example definition in the question is valid in Scala, but it has different semantics from anything previously mentioned:

var i = {5}

In this case, the bracketed expression is simply a compound expression and equivalent to the following C++ statement:

int i = (5);

Implicit Conversions

Conversions in Scala are handled with views and implicit classes. When coupled with tuples, these can be used to convert multiple values to a single type without specifying the type, similar to UIS when the list contains constructor arguments and no class name is given. Like UIS, the type can be inferred from context. Unlike UIS, parentheses are used rather than brackets (as tuples are delimited with parentheses).

Note that Scala has another kind of implicit thing, the implicit parameter, which makes an appearance below in sign. Rather than being used when implicitly converting values, it's used to implicitly provide arguments to a function (i.e. when an argument isn't explicitly passed to a function, a value is automatically created and passed). The use of the word "implicit" for different things isn't a naming collision; all the implicit things work together to extend behavior (more on this below).

Implicit class:

// note: sign[T](n)(num) is a curried function
def sign[T : Numeric](x:T)(implicit num:Numeric[T]) = num.compare(x, num.zero)

implicit class Complex(ri:(Double,Double)) {
  val real = ri._1
  val imaginary = ri._2
  def conjugate = new Complex((real, -imaginary))
}
// could also be methods of Complex
def abs(c:Complex) = Math.sqrt(c.real * c.real + c.imaginary * c.imaginary)
def sqrt(c:Complex) = {
  val real = Math.sqrt((abs(c)+c.real)/2)
  val imaginary = sign(c.imaginary) * Math.sqrt((abs(c)-c.real)/2)
  new Complex((real, imaginary))
}

val c:Complex = (1.0,2.0)
sqrt((3.0,4.0))
// Conversions can even be used for method calls, which I don't think UISs can do
(1.0,2.0).conjugate

View:

def sign[T : Numeric](n:T)(implicit num:Numeric[T]) = num.compare(n, num.zero)

class Complex(val real:Double, val imaginary:Double) {
  def conjugate = new Complex(real, -imaginary)
}
implicit def complexify(ab:(Double, Double)) = new Complex(ab._1, ab._2)

def abs(c:Complex) = Math.sqrt(c.real * c.real + c.imaginary * c.imaginary)
def sqrt(c:Complex) = {
  val real = Math.sqrt((abs(c)+c.real)/2)
  val imaginary = sign(c.imaginary) * Math.sqrt((abs(c)-c.real)/2)
  new Complex(real, imaginary)
}

val c:Complex = (1.0,2.0)
sqrt((3.0,4.0))
(1.0,2.0).conjugate

Aside: as mentioned above, implicits in Scala are used to extend behavior. Implicit conversions for method calls ((1.0,2.0).conjugate in the examples) are usually used as an indirect way to add methods to an existing class by using the adapter pattern. Other languages (such as C#, Objective-C, Ruby and Python) take another approach and have open classes, allowing new methods to be added directly. For examples, consider C#'s extension methods, F#'s type extensions, Objective-C's categories and Haskell's type classes (which also addresses C++ overloading and template concepts). Scala's implicit parameters and objects can also be used like Haskell's type classes (instead of the adapter pattern you get with implicit conversions) basically the way you create traits classes in C++. For more on this topic:

Making Our Own Types and Typeclasses

Retroactive Supertyping in Scala: Adaptors, Rich Wrappers, Type Classes, and Structural Types

The Neophyte's Guide to Scala Part 12: Type Classes

A Small Example of the Typeclass Pattern in Scala

Type Classes as Objects and Implicits (PDF)

Looking at things like sign and (1.0,2.0).conjugate, I can't help but feel that Scala is weird and wonderful.

Erlang#

Erlang's record initializers use squiggly brackets and key-value pairs. The record name must be given (prefixed with "#"). Fields with default values can be left out of the initializer.

-record(foo, {bar, baz="Baz"}).
Foo = #foo{bar="Bar"}.

During compilation, records are converted to tuples, losing the field names.

Go#

In Go, composite literals can be used to initialize objects. Like similar features in other languages, brackets are used as delimiters. Unlike UIS (but like other languages), the type must be included. Within the brackets is an element list. An element can itself be a composite literal. Lists can be keyed or unkeyed (keys give struct field names, array indices or map keys); keys must be present or absent for all elements in a list (this restriction doesn't apply across separate lists within a literal). If keys are absent, all fields must be given values.

type Point3D struct { x, y, z float64 }
type Line struct { p, q Point3D }

// 3 different lists, 1 keyed and 2 unkeyed:
ln0 := Line{Point3D{x: 1}, Point3D{0,1,1}};
// array length could also be given as "...":
ns := [3]int32{0,1,2}
// strs[2] is given zero value for strings:
strs := [...]string{0:"", 1:"I", 3: "III"}

Haskell#

Haskell types can be declared with a record syntax, which are very similar to Erlang's records. Record constructors can take a initializers. Record syntax also declares accessor functions with the same name as the fields, and record fields can be updated using the same syntax as initialization. As far as I know, default values cannot be provided for fields, so all fields must be present in the initializer (though not when updating), though they can be given in any order.

data Foo = Foo {bar::String, baz::String}
foo = Foo {baz="Baz", bar="Bar"}
bar foo # "Bar"
# update by name
qux = foo {bar="qux"}

Similar to Erlang, records are converted to plain types; the above results in:

data Foo = Foo String String
bar (Foo bar baz) = bar
baz (Foo bar baz) = baz

(except that this doesn't support initializers or updates-by-name.)

Perl 5 & Javascript#

Perl 5 and Javascript don't have language level support for initializer lists, but constructors can take hashes (Perl 5) or objects (Javascript), which they can use to set object fields. Coincidentally, JS object literals and Perl hash refs use squiggly brackets (though Perl doesn't need to use hash refs to pass a hash to a constructor).

Perl 5:

package Foo;

sub new {
    my $class = shift;
    my $self = {@_};
    return bless $self, $class;
}

package main;

my $foo = new Foo(bar=>"Bar");

JS:

function Foo(obj) {
    for (var p in obj) {
        this[p] = obj[p];
    }
}
var foo = new Foo({bar: "Bar"})

Perl 6#

As with Perl 5, a hash can be passed to constructors to set attributes. Unlike Perl 5, Mu, the Perl 6 root class, has a constructor which takes a hash and defines attributes & accessors, so this doesn't need to be explicitly implemented.

class Foo {
    has $.bar as rw;
}
my $foo = Foo.new(bar=>"Bar");

Powershell#

Powershell's new-object command supports initialization, property addition and method invocation using the -Property argument:

New-Object PSObject -Property @{
    foo = "bar"
}


问:
Why is most SQL written in YELLING?
On MySQL at least, the following two queries are functionally identical:

```<code>select * from users limit 0, 1000;
SELECT * FROM users LIMIT 0, 1000;
</code>```

However, most example sites and most developers I've worked with use the latter, while I prefer the former.

Is there a reason to write SQL statements in all-caps? I find it to be more of a strain to hold the Shift key or to engage Caps-Lock for all SQL language statements.

Plus, I can't help but read statements as someone screaming:

```<code>DELETE FROM users WHERE id = 12345;
# OBLITERATE EVERYTHING FROM USERS WHERE THE ID IS 12345!!!!!!!!!!!!! NAO!
</code>```

答:
It's using case as a form of syntax highlighting.  It makes the logic distinct from the table names and field names.

It's a form that predates new-fangled things like having more than one colour on a screen.  We used to do it with UCSD pascal too.

Title: Why is most SQL written in YELLING?


答:
Is there a reason to write SQL statements in all-caps?

Shows keywords more clearly, even if your IDE is fancy and highlights/colors.

Some editors/languages still might not have syntax highlighting.

People did it this way on because color highlighting didn't exist

Related to the last, an example to make things clear:

Take five chimpanzees. Put them in a big cage. Suspend some bananas from the roof of the cage. Provide the chimpanzees with a stepladder. BUT also add a proximity detector to the bananas, so that when a chimp goes near the banana, water hoses are triggered and the whole cage is thoroughly soaked.

Soon, the chimps learn that the bananas and the stepladder are best ignored.

Now, remove one chimp, and replace it with a fresh one. That chimp knows nothing of the hoses. He sees the banana, notices the stepladder, and because he is a smart primate, he envisions himself stepping on the stepladder to reach the bananas. He then deftly grabs the stepladder... and the four other chimps spring on him and beat him squarely. He soon learns to ignore the stepladder.

Then, remove another chimp and replace it with a fresh one. The scenario occurs again; when he grabs the stepladder, he gets mauled by the four other chimps -- yes, including the previous "fresh" chimp. He has integrated the notion of "thou shallt not touch the stepladder".

Iterate. After some operations, you have five chimps who are ready to punch any chimp who would dare touch the stepladder -- and none of them knows why.

Taken from this answer as it is directly applicable.

After a while, conventions become the way people do things even if/when they no longer make sense.

Title: Why is most SQL written in YELLING?

Body:
On MySQL at least, the following two queries are functionally identical:

```<code>select * from users limit 0, 1000;
SELECT * FROM users LIMIT 0, 1000;
</code>```

However, most example sites and most developers I've worked with use the latter, while I prefer the former.

Is there a reason to write SQL statements in all-caps? I find it to be more of a strain to hold the Shift key or to engage Caps-Lock for all SQL language statements.

Plus, I can't help but read statements as someone screaming:

```<code>DELETE FROM users WHERE id = 12345;
# OBLITERATE EVERYTHING FROM USERS WHERE THE ID IS 12345!!!!!!!!!!!!! NAO!
</code>```


问:
Approach to develop an inline editor for enumerated lists

Background

Looking to develop a WYSIWYG editor for ordered lists so that people can directly edit lists of instructions on a web page.

Problem

The contentEditable attribute is woefully immature for editing ordered lists (e.g.,
...
). I discovered four bugs in Firefox 25.0.1 within seconds of editing; Chromium was acceptable; IE8+ will likely border on nightmarish.

A number of inline editors exist, and I've gone through almost all of them. Even the lightest-weight editors are far too heavy, or have too many bugs, for accomplishing such a seemingly simple task.

Question

What approach would you take to developing a browser-based WYSIWYG inline editor for enumerated lists? Some of my ideas have included:

Take the most robust inline editor and trim back all needless functionality.

Build up an inline editor that meets my needs.

Both approaches will be time-consuming.

What other approaches are worth considering?

答:
The core library for CodeMirror uses a <textarea> with JavaScript and CSS to provide rich text editing functionality. The disadvantage is that the code is 135kb, minified.

Still, the most functional cross-browser approach is likely to use a <textarea> and change the style as required:

```<code>textarea {
  font-family: Verdana, Tahoma, "DejaVu Sans", Arial, Helvetica, sans-serif;
}
</code>```

Body:
The core library for CodeMirror uses a <textarea> with JavaScript and CSS to provide rich text editing functionality. The disadvantage is that the code is 135kb, minified.

Still, the most functional cross-browser approach is likely to use a <textarea> and change the style as required:

textarea {
  font-family: Verdana, Tahoma, "DejaVu Sans", Arial, Helvetica, sans-serif;
}


答:
The SQL standard from 1992 required upper-case for keywords. Specifically, the list of reserved words is specified entirely in upper-case. See section 5.2 of the standard, ISO/IEC 9075:1992.

Now, almost all (possibly all) implementations didn't care. And, if I remember correctly, there have been subsequent editions of the SQL standard that did not require keywords be specified in upper-case.

Title: Why is most SQL written in YELLING?


问:
Tabs versus spaces—what is the proper indentation character for everything, in every situation, ever?
The coding standards for the code hosted in drupal.org suggest to use two spaces to indent the code; other sites suggest to use tabs to indent the code.

What is the proper indentation character for everything, and in every situation? Please explain the answer you give.

答:
I used to use spaces, but I've been using tabs lately purely because that's what Eclipse was set to when I finally noticed. All of the other developers on my team use Eclipse, so it made sense to standardise on tabs when we realised we'd already been using them for ages and there was no reason to bother changing to spaces. I've been surprised by how much of a non-issue it has been.

Setting the displayed tab size to 3 or 5 characters in your IDE greatly simplifies distinguishing between code sections that are indented by spaces (almost always 4 these days) and those that are indented by tab.

ContentLicense: CC BY-SA 2.5


问:
How can a Right-Brainer Deal with Massive Left-Brainer Code?
I'm an artist, mostly, though I describe myself as a artist/physicist.  While I can do math, deal with  words, and the "logical" stuff considered left-brain, it's an effort and I make mistakes, whereas I do well with and most of the time think in terms of those things associated with right-brain thinking - spatial relations, holistic big-picture context, etc.  Of course all that is fuzzy, as the right-left brain theory is oversimplified and no mental activity is so simple.   Yet I do sense that I fit in fine with artists, video directors, chefs, and other non-verbal thinking, creative types, while most people in "IT" or hardcore software engineers have minds that work differently, with attention to detail, holding many details in mind at one time, and strong rational and verbal capabilities.

So here I am in a job being paid to fix fussy and obscure bugs in a massive swarm of C++ software, very heavy on OO, and any one line of code makes no sense unless I hold in mind about twenty other class and method names, relations between them, the flow of execution (very spaghetti-like) and other detail.

Besides that,  I'm also rather strongly against much of contemporary C++ and OO styles.  Those who wrote this code really drank the deep OO and Modern C++ kool-ade.  I find it actually makes code much harder to follow, much harder to decide where to fix or change something.   I don't know if this is part of the left/right differnce (or whatever you want to call it) or not.

But work on the C++ I must - people depend on me for my income.  What are tips and techniques to deal with this situation, to be as effective as possible for my employer?

答:
Warning:  this answer is very long and has a lot of psychobabble (which I try to explain, but still).  What can I say?  Psychology is one of my favorite subjects outside programming.

I'm an artist, mostly, though I describe myself as a artist/physicist. While I can do math, deal with words, and the "logical" stuff considered left-brain, it's an effort and I make mistakes, whereas I do well with and most of the time think in terms of those things associated with right-brain thinking - spatial relations, holistic big-picture context, etc. Of course all that is fuzzy, as the right-left brain theory is oversimplified and no mental activity is so simple. Yet I do sense that I fit in fine with artists, video directors, chefs, and other non-verbal thinking, creative types, while most people in "IT" or hardcore software engineers have minds that work differently, with attention to detail, holding many details in mind at one time, and strong rational and verbal capabilities.

This is actually based on a somewhat outdated view of neuroscience.  At one point in time, scientists believed that the left brain was only responsible for logic and raw sensory data while the right brain was solely responsible for intuition and feeling.  As it turns out, the left brain is really capable of everything the right brain is and vice versa.  As someone who is extremely right-brained yet logical, terrible with directions and spatial orientation, and completely devoid of any of the artistic creativity that is traditionally associated with the right brain, I can attest to this.

The best way to think of the difference between the left and right brain is to think of them as mirror images of each other.  To understand this, you need some background data.  A psychologist named Carl Jung came up with a personality theory in the 20s that divided up personality along a couple of dimensions.  You've probably heard of one of them: introversion vs extraversion.  I've written a couple blogposts on this subject, but it basically boils down to this:  introversion differentiates itself from others while extraversion focuses on how it can connect to others.  This is referred to as an "attitude".

Then you have four different cognitive functions:  thinking, feeling, sensation, and intuition.  For simplicity's sake, let's just say that two of these functions are considered "judging" functions (thinking and feeling) while the other two are "perceiving" functions.  The judging functions make decisions.  When you're in a judging mindset, you are trying to avoid surprises.  You want to have made all of the right decisions beforehand so you don't have to adapt when surprises come along.  Because you've done so much planning in advance, you may have a tendency to become rigid and inflexible once a decision has been made.  On the other hand, a perceiving mindset tends to prefer flying by the seat of its pants and rolling with the punches.

Generally, you combine the function and an attitude to create a (creatively named) function-attitude (introverted thinking, extraverted feeling, etc).  Peoples' conscious personalities are defined mostly by a dominant function-attitude and an auxiliary function-attitude.  Eventually, psychologists came to a consensus that there are broadly two types of people:  people whose primary two functions consist of an introverted judging function and an extraverted perceiving function, or people whose primary two functions consist of an extraverted judging function and an introverted perceiving function.  If you've ever taken the MBTI or similar personality test, the last letter tells you which category you fall into.  If you're a P, it means you're an introverted judger/extraverted perceiver and J is the other way around.

Still with me thus far?  Here's where I get to what I meant by the two sides being mirror images of each other.  Nobody realized it at the time, but they were essentially building a sketch of where functionality lies in the brain.  Indeed, each of Jung's function-attitudes has been mapped to a rough location in the brain.  As it turns out, all of the P functions (introverted judging and extraverted perceiving) are on the right side of the brain and the J functions are on the left side of the brain.

Whenever you say that left-brained people are good at details and right-brained people are good at the "big picture" (although I would say "whole picture" would be more accurate), you're focusing on the extraverted side of things.  If a left-brained person manages a right-brained person, the lefty is going to want to know all the details about how the righty is going to do their job up front and in advance.  They want the requirements set in stone and hard deadlines decided in advance.  The righty just wants a very broad idea of what they need to do so they can fill in the details later.

However, note that this isn't doesn't seem to be what you are experiencing.  It seems as though the lefties' code probably wasn't terribly well thought out in advance and has some issues that could have been prevented by some forethought.  This is because when you build abstract models of things like code in your head, you're using your introverted function, which works the other way around.  The righty wants to build that model in advance and do so in such a manner that it fills in all the necessary details or easily can fill in all the details.  Plus, they might become rigid in terms of the best approach to take (note that you're taking a hard line on how you feel about C++'s more advance features).  The lefties' model will be more ad hoc and filled in as they go.

My experience is that because of this, the lefties will accuse the righties of over-engineering everything while the righties will accuse the lefties of being too quick and dirty.  Both sides have a grain of truth to them, but only when that approach is taken to the extreme.  Here's what's funny though:  they're taking opposite approaches to achieve the same goal (that is, getting things done).  The righties want to have their model decided upon up front so they can spend less time implementing the thing and therefore getting the entire project done sooner.  The lefties want to spend less time architecting so they can get things done sooner.

Incidentally, these two attitudes are reversed when it comes to project management type stuff (determining timelines, coming up with requirements, etc).  This can lead to a really confusing situation where one side is accusing the other of being too rigid while the other claims that the other side isn't planning ahead enough, and then the next argument has both sides taking the exact opposite stance.

What can you do about all of this?  Nothing other than being aware of these differences and trying to accomodate the other side's view as much as possible.  The problem though is that this goes both ways.  You can understand and accomodate the lefties as much as possible, but that won't make much difference unless they're trying to return the favor.  This is always the challenge.  Not because the lefties are assholes and want to make the righties' lives miserable, but because the lefties are used to being dominant in the field of programming.  If your way of thinking was echoed by pretty much everyone else, you'd be pretty convinced you're correct too.


问:
Should a getter throw an exception if its object has invalid state?
I often run into this problem, especially in Java, even if I think it's a general OOP issue. That is: raising an exception reveals a design problem.

Suppose that I have a class that has a String name field and a String surname field.

Then it uses those fields to compose the complete name of a person in order to display it on some sort of document, say an invoice.

```<code>public void String name;
public void String surname;

public String getCompleteName() {return name + " " + surname;}

public void displayCompleteNameOnInvoice() {
    String completeName = getCompleteName();
    //do something with it....
}
</code>```

Now I want to strengthen the behavior of my class by throwing an error if the displayCompleteNameOnInvoice is called before the name has been assigned. It seems a good idea, doesn't it?

I can add a exception-raising code to getCompleteName method.
But in this way I'm violating an 'implicit' contract with the class user; in general getters aren't supposed to throw exceptions if their values aren't set. Ok, this is not a standard getter since it does not return a single field, but from the user point of view the distinction may be too subtle to think about it.

Or I can throw the exception from inside the displayCompleteNameOnInvoice. But to do so I should test directly name or surname fields and doing so I would violate the abstraction represented by getCompleteName. It's this method responsibility to check and create the complete name. It could even decide, basing the decision on other data, that in some cases it is sufficient the surname.

So the only possibility seems to change the semantic of the method getCompleteName to composeCompleteName, that suggests a more 'active' behavior and, with it, the ability of throwing an exception.

Is this the better design solution? I'm always looking for the best balance between simplicity and correctness. Is there a design reference for this issue?

答:
It seems like no one is answering your question.

Unlike what people like to believe, "avoid invalid objects" is not often a practical solution.

The answer is:

Yes it should.

Easy example: FileStream.Length in C#/.NET, which throws NotSupportedException if the file is not seekable.


问:
Is it a good idea to use bloom filters for this scenario?
I have a theoretical social network where two people, A & C, can become friends if and only if, they have a common friend B amongst them.

The simplest solution is to iterate over the two lists and see if they have any friends in common. My question is, can I use bloom filters instead? I will have a bloom filter for every user with their friend list added. When I need to check if a common friend exists I check A's friend list with C's bloom filter first and if I get a positive result I actually perform iteration to confirm.

Given that the average friend list size if 100 friends, will this implementation be better than simple iteration?

答:
No, bloom filters are not suited for your case.

Bloom filters use case is following:

you have very large datasets that typically don't fit in memory

you want to check if it contains given elements, false positives being possible

In other words, it's a trick to fit something in memory that is actually bigger, but on the downside we accept false positives. This is both overkill and ill-suited for your case where you want to compare two lists of friends.

What you should do:

Just put one list in a hash set for O(1) "contain" operations, and iterate with the other list.

EDIT:

A reviewer changed this with does not contain, this is neither wrong nor true, it's just the other face of the medal. To make it more clear:

if the bloom filter gives a hit: the item is probably inside

if the bloom filter gives a miss: the item is certainly not inside

...in other words:

if an item is inside: you always get a hit

if an item is not inside: you probably get a miss

...yeah, that's the thing about probabilistic data structures. You can also see it that way: there are more keys hitting than items inside.


问:
My first SOLID re-factoring
I am trying to make use of SOLID principles for the first time. I am re-factoring a File class that stores file information and makes file operations available.
This class is then inherited to specific file types to make available methods for that type.

I have started with SRP and have tried to make a FileWriter and FileReader abstract class to read and write from different resources. Some include:

File System

Streams

Database

Other undefined services (SOAP, REST??).

I am happy to say that the file data is handled by a byte array, but I am not sure how to handle the file path/uid for a resource.

Here is what I have...

```<code>public abstract class EFileReader
{
    event EventHandler<IEFileEventArgs> ReadThreadedComplete;
    public abstract byte[] Read(object source);
    public abstract async Task<byte[]> ReadAsync(object source);
    public abstract void ReadThreaded(object source);
    protected virtual void OnFileRead(IEFileEventArgs e)
    {
        EventHandler<IEFileEventArgs> handler = this.ReadThreadedComplete;
        if (handler != null)
        {
            handler(this, e);
        }
    }
}
</code>```

I could cast the object as the required type in implementation.
Alternatively it could be a generic type somehow specified in implementation (not sure how).

```<code>public abstract class EFileReader<T>
{
    event EventHandler<IEFileEventArgs> ReadThreadedComplete;
    public abstract byte[] Read(T source);
    public abstract async Task<byte[]> ReadAsync(T source);
    public abstract void ReadThreaded(T source);
    protected virtual void OnFileRead(IEFileEventArgs e)
    {
        EventHandler<IEFileEventArgs> handler = this.ReadThreadedComplete;
        if (handler != null)
        {
            handler(this, e);
        }
    }
}
</code>```

...Or maybe there is some abstraction of the source I can write to accommodate the various possible use cases.
I guess I could make it take an abstract FileResource class that exposes a stream.

What is the best way to approach this?

答:
The whole purpose of creating System.IO.Stream in the framework, was to be able to handle data from different types of sources.

You should just make your source parameter a Stream type.

Also, you say your class handles data from different sources (including streams). This effectively no longer makes it a File class, doesn't it?

Title: My first SOLID re-factoring


问:
How have Guava unit tests been generated automatically?
Guava has unit test cases automatically generated:

Guava has staggering numbers of unit tests: as of July 2012, the
  guava-tests package includes over 286,000 individual test cases. Most
  of these are automatically generated, not written by hand, but Guava's
  test coverage is extremely thorough, especially for
  com.google.common.collect.

How they were generated? What techniques and technologies were used to design and generate them?

答:
A large part of this mass of tests is for the Guava collection implementations. They've written generic tests that exhaustively test the collection interfaces, and this generates a suite per implementation. See, for example, classes called CollectionAddAllTester, ListIndexOfTester.

This is all backed by a library called testlib, which ships as part of Guava. This is quite generic. It supports writing generic tests for any interface (not just collections). You can specify Features of possible implementations and test those (e.g. if your set is unmodifiable you expect a different outcome from set.add()), and when you run the tests you specify which features your implementation supports.

It's based on JUnit 3, not 4. Normally, you have a class extending TestCase full of methods named testSomething(), and JUnit runs them reflectively. The testlib library hooks into the running of these tests so that the lifecycle looks like this:

For each implementation you want to test

For each (applicable) test method

Create the TestCase instance

Initialise the TestSubjectGenerator – this is the testlib interface that you extend where you actually create the test subject

Reflectively run the test method. During this method, getSubjectGenerator() gives access to the test subject

The key bit is the extra initialisation step that allows them to inject a specific test subject into the generic test case.

I wrote a post on how to write testlib generating suites for your own interfaces.

(Also posted to the same question on the sqa site.)


问:
Best way to structure many-to-one allocation of users to projects in NoSQL
I apologise if this is a bit of a stupid or broad question, but I'd like some general feedback please!

Say I have this DB structure for users (in Mongo/JS, but really it's all pseudocode- and the IDs would actually be DB references, not basic integers):

```<code>users = [
  {
    id: 1,
    name: 'John Smith'
  },
  {
    id: 2,
    name: 'Sheila X. Ample'
  }
]
</code>```

... and I want to define some projects where one or more of these people can be collaborators on it. The project will define who has general access to it as well as who created it, who is the current primary collaborator (this will change regularly), who last updated it, etc etc.

Is this method best, where the IDs are represented directly onto the project object:

```<code>projects = [
  {
    id: 1,
    name: 'Project One',
    collaborators: [
      2
    ],
    primaryCollaborator: 2,
    lastUpdatedBy: 2,
    createdBy: 2
  },
  {
    id: 2,
    name: 'Another Project',
    collaborators: [
      1,
      2
    ],
    primaryCollaborator: 1,
    lastUpdatedBy: 2,
    createdBy: 1
  }
]

// Get the primary collaborator:
primaryID = projects.find({id: 2}).primaryCollaborator;
</code>```

Or this one, where the properties are booleans on each individual collaborator:

```<code>projects = [
  {
    id: 1,
    name: 'Project One',
    collaborators: [
      {
        id: 2,
        primaryCollaborator: true,
        lastUpdatedBy: true,
        createdBy: true
      }
    ]
  },
  {
    id: 2,
    name: 'Another Project',
    collaborators: [
      {
        id: 1,
        primaryCollaborator: true,
        lastUpdatedBy: false,
        createdBy: true
      },
      {
        id: 2,
        primaryCollaborator: false,
        lastUpdatedBy: true,
        createdBy: false
      }
    ]
  }
]

// Get the primary collaborator:
primaryID = projects.find({id: 2}).collaborators.find({primaryCollaborator: true}).id;
</code>```

As I said, I'm sure this kind of structural question has been asked a million times before but I wouldn't for the life of me know what to Google to find it!

What are the benefits or drawbacks of doing it in either way? Does it even make a difference? The first method would require that the IDs referenced on the project object existed and would cause a headache if, say, a collaborator was removed from the project. The second method seems a bit weighty and would cause a headache if something went awry and more than one collaborator was classed as being true as the primary collaborator, for example. Or is there a better method entirely?

Thanks in advance! :)

答: I came to the conclusion to use method B. This is because I realised that I needed to split my collaborators into different types of users and using method A, I wouldn't be able to join up the references as they would span across several documents. It's easier to do it with a bit of querying/scripting later than try and force it to work based purely on schemata.</p>


问:
How to introduce Agile to a team that uses rigid non-Agile methods?
Consider a company that is proudly certified for some non-Agile methodology, uses it as a selling point to its customers to demonstrate accountability.

How do you go about introducing Kanban or Scrum progressively without breaking their whole system and still making them confident that it can still be just as accountable / auditable?

I know this is possibly related to "How would you introduce an agile methodology like Scrum", but here I am wondering about ways to circumvent/work around the fact that the company imposes a certain way of managing the SDLC under the false pretense that it's the only way to have an audit trail.

答:
I'd separate Scrum from Kanban first.

With Kanban - and here's a pretty good source on how to do it right - the principle is that you respect the exiting process when you start.  Kanban is not what you replace the existing process with, but what you apply to it.  Map it out, visualize, and set up certain conditions for gradual improvement.

Scrum is fundamentally different in the sense that it is something that is going to displace the existing process.

A team that is used to 12-month (or longer) waterfall SDLC cycles is going to have a very hard time transitioning to Scrum.  Gradual shortening of the cycle to 6- or 3-month release trains with smaller scope could be a useful intermediate step.