问:
Find all possible subarrays of an Array
I am lost I just can't seem to get my head around backtracking/recursion approaches. I understand how simple recursion problems like factorials work I can even trace those by hand. But when it comes to backtracking problems I am so lost. I keep trying. its been 5 hours I have been reading various approaches on forums and stack exchange but nothing has clicked.

For instance say I have a array with [1,2,3,4] and my destination value is 5. I am trying to find all possible combinations that equal to my destination value.

I broke this problem down further to make it even more simple for my self to understand. First I can find all possible combinations of the array and then pass them to another function which checks if the sum of that array equals destination value and then only does it print it.

Can someone advice how to approach this? I am not looking for code/answer I want to be able to think and imagine this in my head clearly.

答:
I'm assuming for the purpose of this exercise that you don't want any repeats.  For example, the combinations for [1..4] are

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

If not, the process is really the same for all recursive functions:  figure out your bases cases, and figure out your larger problem in terms of a smaller problem.

We're going to create a function subarrays that takes a list and returns a list of lists—one for every combination, so:

```<code>subarrays :: [a] -> [[a]]
</code>```

The base case is usually very easy.  In this case, the subarrays for an empty list is an empty list, so:

```<code>subarrays [] = []
</code>```

The recursive step for list functions almost always breaks it into the first element, called the "head" (denoted here by x), and the rest of the list, called the "tail" (denoted here by xs).  We assume we already know the correct answer for the tail, and we use that to build an answer for the head.  Here we assign the symbol combos to the answer for the tail:

```<code>subarrays (x:xs) = let combos = subarrays xs
</code>```

So far this is relatively boilerplate code that you find on almost every recursive function in one form or another.  The tricky part is now that we've solved it for a smaller list, how do we add another layer?

For an example, assume combos contains all the solutions for [2,3,4] and you're building a list that also contains solutions containing 1.  In this case, you can do one of three things to build the larger list.

Just have 1 by itself. ([x])

Just have all the other combos by themselves. (combos)

Have all the other combos with a 1 added. (map (x:) combos)

Then return a list containing all those possibilities:

```<code>[x] : map (x:) combos ++ combos
</code>```

That's really all there is to it.  Here's the complete program in Haskell with the sum test function as well:

```<code>subarrays :: [a] -> [[a]]
subarrays [] = []
subarrays (x:xs) = let combos = subarrays xs
                   in [x] : map (x:) combos ++ combos

combosSumTo :: Int -> [Int] -> [[Int]]
combosSumTo x = filter (\y -> sum y == x) . subarrays
</code>```

As far as how I came up with the three things, you just sort of have to practice, and test and repeat.  When I first wrote this just now, I accidentally forgot the [x] part, but that showed up in my tests.  The trick is don't try to recurse down the stack in your head.  Just assume the recursive call gives you the correct answer for the tail of the list.

Title: Find all possible subarrays of an Array

Body:
I'm assuming for the purpose of this exercise that you don't want any repeats.  For example, the combinations for [1..4] are

[[1],[1,2],[1,2,3],[1,2,3,4],[1,2,4],[1,3],[1,3,4],
 [1,4],[2],[2,3],[2,3,4],[2,4],[3],[3,4],[4]]

If not, the process is really the same for all recursive functions:  figure out your bases cases, and figure out your larger problem in terms of a smaller problem.

We're going to create a function subarrays that takes a list and returns a list of lists—one for every combination, so:

subarrays :: [a] -> [[a]]

The base case is usually very easy.  In this case, the subarrays for an empty list is an empty list, so:

subarrays [] = []

The recursive step for list functions almost always breaks it into the first element, called the "head" (denoted here by x), and the rest of the list, called the "tail" (denoted here by xs).  We assume we already know the correct answer for the tail, and we use that to build an answer for the head.  Here we assign the symbol combos to the answer for the tail:

subarrays (x:xs) = let combos = subarrays xs

So far this is relatively boilerplate code that you find on almost every recursive function in one form or another.  The tricky part is now that we've solved it for a smaller list, how do we add another layer?

For an example, assume combos contains all the solutions for [2,3,4] and you're building a list that also contains solutions containing 1.  In this case, you can do one of three things to build the larger list.

Just have 1 by itself. ([x])

Just have all the other combos by themselves. (combos)

Have all the other combos with a 1 added. (map (x:) combos)

Then return a list containing all those possibilities:

[x] : map (x:) combos ++ combos

That's really all there is to it.  Here's the complete program in Haskell with the sum test function as well:

subarrays :: [a] -> [[a]]
subarrays [] = []
subarrays (x:xs) = let combos = subarrays xs
                   in [x] : map (x:) combos ++ combos

combosSumTo :: Int -> [Int] -> [[Int]]
combosSumTo x = filter (\y -> sum y == x) . subarrays

As far as how I came up with the three things, you just sort of have to practice, and test and repeat.  When I first wrote this just now, I accidentally forgot the [x] part, but that showed up in my tests.  The trick is don't try to recurse down the stack in your head.  Just assume the recursive call gives you the correct answer for the tail of the list.


答:
Lets take an array of size n.  There 2n possible subarrays of this array. Lets take the example array of size 4: [1, 2, 3, 4].  There are 24 sub arrays.

Sub array of the empty set ([]) is the 0th one (0000).  The subarray of [1], is the second one (0001), the subarray of [2] is the second one... (0010) and the subarray [1, 2] is the third one (0011).  You should see where this is going.

No recursion is necessary for this.  The set of the sub arrays is the binary representation of the the nth value ranging from 0 to 2n - 1.

With this realization, the generation of all of the subarrays for a given arrays should be a trivial matter of iterating of the integers and looking at them as bit fields for if a particular element is in the subarray or not.

See also Number of k combinations for all k on Wikipedia.

I would point out that this is probably the right way to do it in C and similar languages.  Trying to force recursion, lists, and backtracking onto what would otherwise be a simple iterative problem with a clear and understandable answer may not the best approach.

Note that other proposed answers to this quickly become functional programming examples and solutions.  Functional programming is great.  However, in a language not suited for such trying to force this paradigm of programming on it would be akin to writing C code in Lisp - it might not be the best way to approach the problem.

I should further point out that the problem hinted at in the question is:

For instance say I have a array with [1,2,3,4] and my destination value is 5. I am trying to find all possible combinations that equal to my destination value.

This is a well known problem known as the subset sum problem and has a number of approaches to solve it... generating all the subsets of the array is not required (or even desired) for the faster approaches to solve it.

ContentLicense: CC BY-SA 3.0

Title: Find all possible subarrays of an Array

Body:
I am lost I just can't seem to get my head around backtracking/recursion approaches. I understand how simple recursion problems like factorials work I can even trace those by hand. But when it comes to backtracking problems I am so lost. I keep trying. its been 5 hours I have been reading various approaches on forums and stack exchange but nothing has clicked.

For instance say I have a array with [1,2,3,4] and my destination value is 5. I am trying to find all possible combinations that equal to my destination value.

I broke this problem down further to make it even more simple for my self to understand. First I can find all possible combinations of the array and then pass them to another function which checks if the sum of that array equals destination value and then only does it print it.

Can someone advice how to approach this? I am not looking for code/answer I want to be able to think and imagine this in my head clearly.


答:
You want to enumerate recursively the set of sublists of 1 :: 2 :: 3 :: 4 :: [] which sums to 5. (The :: is the OCaml notation for the list construction.) The recursive step in list processing is splitting the list in its head 1 and its tail 2 :: 3 :: 4 :: [] — can we describe our set in these terms?

There is two kinds of sublists of 1 :: 2 :: 3 :: 4 :: [] which sums to 5:

The first kind consists of lists starting with 1 and followed by a list which sums to 4 = 5 - 1.

The second kind consists of sublists of 2 :: 3 :: 4 :: [] summing to 5.

Wonderful! If we call partition the function int list -> int -> int list list finding all the required sublists, the description above just describes how to define partition lst for lists lstof length n given its definition for lists of length n-1.

Writing the function in OCaml is then staightforward:

```<code>let rec partition lst w =
  if w = 0 then
    [[]]
  else
    match lst with
      | [] -> []
      | hd :: tl -> firstkind hd tl (w - hd) @ partition tl w
and firstkind hd tl w =
  List.map (fun lst -> hd :: lst) (partition tl w)
</code>```

Title: Find all possible subarrays of an Array

Body:
You want to enumerate recursively the set of sublists of 1 :: 2 :: 3 :: 4 :: [] which sums to 5. (The :: is the OCaml notation for the list construction.) The recursive step in list processing is splitting the list in its head 1 and its tail 2 :: 3 :: 4 :: [] — can we describe our set in these terms?

There is two kinds of sublists of 1 :: 2 :: 3 :: 4 :: [] which sums to 5:

The first kind consists of lists starting with 1 and followed by a list which sums to 4 = 5 - 1.

The second kind consists of sublists of 2 :: 3 :: 4 :: [] summing to 5.

Wonderful! If we call partition the function int list -> int -> int list list finding all the required sublists, the description above just describes how to define partition lst for lists lstof length n given its definition for lists of length n-1.

Writing the function in OCaml is then staightforward:

let rec partition lst w =
  if w = 0 then
    [[]]
  else
    match lst with
      | [] -> []
      | hd :: tl -> firstkind hd tl (w - hd) @ partition tl w
and firstkind hd tl w =
  List.map (fun lst -> hd :: lst) (partition tl w)


问:
Test-Driven Design is not Unit Testing
Ran across this statement by Martin Fowler circa 2002:

Unit testing in XP is often unlike classical unit testing, because in
  XP you're usually not testing each unit in isolation. You're testing
  each class and its immediate connections to its neighbors.

Is this still correct, and if so, why?

答:
What he's describing is a difference between unit testing (testing a unit in isolation, in this case a class but you can test each method if you're masochistic enough) and integration testing where you test the class and also how it works with other classes. That's not unit testing - you're not testing the unit but 'many units'.

I believe the latter is better, the trouble with it is that it is more difficult to achieve total code coverage - ie to test every part through the system. IMHO even if you unit test each and every method, you still have to test the paths through the system anyway to make sure they work together. (for example, I can test a usb plug and guarantee it works, and test a usb socket and prove it works.. and then they'll work perfectly when assembled.. but my plug is a type A and my socket is a type B, d'oh. This design flaw should never have been there in the first place, but we can say that about any bug, which is why we test things).

Title: Test-Driven Design is not Unit Testing


问:
How to signal that a method chain should not continue?
When doing method chaining, you have methods that return the object allowing you to continue the chain. However, you need to get values out of the object somehow.

Usually I've added a method that returns a value at the end, but this complicates matters if you add to the chain and that return method may not be valid anymore.

The way I view it each time you add a method onto a chain you are refining your result until you get your desired answer in the last method call. Having a final output method creates a restriction in that it needs to know about the last operation to know how to display the result.

Maybe you have a method that results in a string and one that results in an array your output method has to deal with both those cases. What if you add a method that stores your string result somewhere new? Now you have to update the output method to handle that case too.

Is there a way of letting a method know it's the last in the chain so should output its result?

答:
You get the values out of the returned object in the usual way.

```<code>var result = myObject.SomeProperty;
</code>```

For extended chaining techniques, chained methods will often return a result that conforms to a particular interface.  For example, most Linq methods in the .NET Framework return a result that conforms to IEnumerable<T> or IQueryable<T> (i.e. a generic collection).

Body:
You get the values out of the returned object in the usual way.

var result = myObject.SomeProperty;

For extended chaining techniques, chained methods will often return a result that conforms to a particular interface.  For example, most Linq methods in the .NET Framework return a result that conforms to IEnumerable<T> or IQueryable<T> (i.e. a generic collection).


问:
Standardization and official guidelines for C++ template parameter naming
What are some explicit and official guidelines or standards for template parameter naming in C++? I've done something like this in the past:

```<code>template<typename TContainer, typename TKey>
void AddKeyToMap(TContainer& the_map, TKey const& the_key);
</code>```

I've also seen names like container_t and key_t.  I'd also accept advice against standardization here, if it makes sense.

答:
As with any question of naming, this is more about consistency in an arbitrary choice than objective measures. However, there is precedent toward specific conventions. The Google C++ Style Guide says nothing about type parameters, but since they constitute type names, the usual rules apply:

Type names start with a capital letter and have a capital letter for each new word, with no underscores: MyExcitingClass, MyExcitingEnum.

The names of all types — classes, structs, typedefs, and enums — have the same naming convention. Type names should start with a capital letter and have a capital letter for each new word. No underscores. For example:

```<code>// classes and structs
class UrlTable { ...
class UrlTableTester { ...
struct UrlTableProperties { ...

// typedefs
typedef hash_map<UrlTableProperties *, string> PropertiesMap;

// enums
enum UrlTableErrors { ...
</code>```

According to this standard, you would write:

```<code>template<typename Container, typename Key>
void AddKeyToMap(Container& the_map, Key const& the_key);
</code>```

The T prefix could be construed as Hungarian notation, specifically systems Hungarian in which the identifier includes an encoding of its type—here, typename. This is widely seen as redundant and potentially harmful, including by Stroustrup:

I don’t like naming a variable after its type; what do I like and recommend? Name a variable (function, type, whatever) based on what it is or does. Choose meaningful name; that is, choose names that will help people understand your program.

I agree that in some cases, building type hints into variable names can be helpful, but in general, and especially as software evolves, this becomes a maintenance hazard and a serious detriment to good code.

It boils down to the semantics you have in mind when you write the program. If you think of type parameters as types, use the same convention you would for type names. If you think of them as parameters or variables, use the same convention you would for parameter or variable names. It’s as simple as that.

Body:
As with any question of naming, this is more about consistency in an arbitrary choice than objective measures. However, there is precedent toward specific conventions. The Google C++ Style Guide says nothing about type parameters, but since they constitute type names, the usual rules apply:

Type names start with a capital letter and have a capital letter for each new word, with no underscores: MyExcitingClass, MyExcitingEnum.

The names of all types — classes, structs, typedefs, and enums — have the same naming convention. Type names should start with a capital letter and have a capital letter for each new word. No underscores. For example:

// classes and structs
class UrlTable { ...
class UrlTableTester { ...
struct UrlTableProperties { ...

// typedefs
typedef hash_map<UrlTableProperties *, string> PropertiesMap;

// enums
enum UrlTableErrors { ...

According to this standard, you would write:

template<typename Container, typename Key>
void AddKeyToMap(Container& the_map, Key const& the_key);

The T prefix could be construed as Hungarian notation, specifically systems Hungarian in which the identifier includes an encoding of its type—here, typename. This is widely seen as redundant and potentially harmful, including by Stroustrup:

I don’t like naming a variable after its type; what do I like and recommend? Name a variable (function, type, whatever) based on what it is or does. Choose meaningful name; that is, choose names that will help people understand your program.

I agree that in some cases, building type hints into variable names can be helpful, but in general, and especially as software evolves, this becomes a maintenance hazard and a serious detriment to good code.

It boils down to the semantics you have in mind when you write the program. If you think of type parameters as types, use the same convention you would for type names. If you think of them as parameters or variables, use the same convention you would for parameter or variable names. It’s as simple as that.


问:
Is a long list of parameter checks an anti-pattern?
Background:  I'm working on an application that will manage backup generators.  These generators need to be able to be "linked" together.  For example, Generator B might serve as a backup for Generator A.  If A fails, then the software turns B on.  Or they might be linked in a load-sharing configuration, where Generator A and B run together, and share the load.

I'm making a function that will make the link, given 2 generators and the type of link desired.

```<code>public void LinkGenerators(Generator A, Generator B, Type linkType);
</code>```

In writing my tests, I've come with a large number of invalid parameter configurations.  My LinkGenerators function looks like this:

```<code>public void LinkGenerators(Generator A, Generator B, Type linkType)
{
     if (linkType.BaseType != typeof(Link))
     {
        throw new ArgumentException("linkType is not a valid link type");
     }
     if (linkAlreadyExistsFor(A, B))
     {
        throw new InvalidOperationException("Link for A and B already exists");
     }
     if (A.Equals(B) || B.Equals(A))
     {
        throw new InvalidOperationException("A and B cannot be the same generator");
     }
     if (A == null || B == null || linkType == null)
     {
        throw new ArgumentException("Cannot pass a null argument");
     }
     .....
     //Actually make the link after making sure all the arguments are valid.
}
</code>```

Most of the LinkGenerator functions consists of verifying that the parameters are good.  The actual link creation takes 2 lines of code.  There's a bit of business logic (verifying that link doesn't already exist and that the generators are not the same) mixed in with a bit functional logic (making sure that the linkType derives from Link, arguments aren't null...), and makes me.......uncomfortable.

Is a long list of parameter checks an anti-pattern or a code smell?  And if so, what can one do about it?

(Just to make this clear to close-voters probably misunderstanding the question: this is not a question about "coding style for conditions" like this one).

答:
When you need to check conditions that aren't business rules, that's where it gets suspect and a bit smelly. I try to avoid those where possible.

Some of your tests seem suspect:

```<code> if (linkType.BaseType != typeof(Link))
</code>```

This looks like a check that should be made by the type system. i.e. its a type restriction and ideally your function signature should, as much as possible, only accept parameters of the correct type. How to do that depends on more details of what you are doing.

```<code> if (A.Equals(B) || B.Equals(A))
</code>```

Why do you feel the need to check it both ways? If A.Equals(B) != B.Equals(A) you are in for a world of hurt.

```<code> if (A == null || B == null || linkType == null)
</code>```

There is no way to tell which parameter was null from the resulting exception. It's also done after the other checks which means that you probably already caused an exception trying to dereference a null parameter.

I avoid null checks in general. Typically, they aren't that helpful because the code in question will end up throwing an exception after tripping on the null anyways and I haven't gained anything by strewing null checks throughout my code. If you do insist on a null check, I suggest extracting it into a utility function.

Body:
When you need to check conditions that aren't business rules, that's where it gets suspect and a bit smelly. I try to avoid those where possible.

Some of your tests seem suspect:

 if (linkType.BaseType != typeof(Link))

This looks like a check that should be made by the type system. i.e. its a type restriction and ideally your function signature should, as much as possible, only accept parameters of the correct type. How to do that depends on more details of what you are doing.

 if (A.Equals(B) || B.Equals(A))

Why do you feel the need to check it both ways? If A.Equals(B) != B.Equals(A) you are in for a world of hurt.

 if (A == null || B == null || linkType == null)

There is no way to tell which parameter was null from the resulting exception. It's also done after the other checks which means that you probably already caused an exception trying to dereference a null parameter.

I avoid null checks in general. Typically, they aren't that helpful because the code in question will end up throwing an exception after tripping on the null anyways and I haven't gained anything by strewing null checks throughout my code. If you do insist on a null check, I suggest extracting it into a utility function.


问:
Are EventHandler<T> and IObservable<T> interchangable?
I have an object which will periodically raise an event based on an action performed in an application.  This will be heard by any listener(s) and acted upon accordingly.

I do not wish to use a custom type for this and would like to make use of either EventHandler<T> or IObservable<T> to manage the pub/sub mechanism I am looking to put in place.

I have had a play with both and they both do what I require.

I have read through the MSDN Observer Design Pattern and MSDN Events Programming Guide, however, I remain uncertain as to if one mechanism is more appropriate than the other.

Is one more suited for my scenario than the other or are both suitable and merely down to personal choice?

Edit 1

My pub/sub requirements are not at the UI layer at this point and are lower down.  My publisher is monitoring network activity and raising an event based on certain network events.  The subscriber is responsible for listening for raised events and performing an associated action.  The UI is not involved at this point.

答:
When I think about events, I usually think about them in the context of how tightly coupled they are.

EventHandler style eventing is very concrete and tightly coupled. I feel it is appropriate in the same sorts of situations you would use a concrete class vs. an interface for something. It is the "built-in" approach to .NET and mirrors get/set on properties with add/remove. Make sure you consider locking within your add/remove's if you go this route.

IObservable< T> style eventing is less concrete. You may have one or more objects that could be passed around as the same IObservable< T>. It also provides an error-handling and a completion mechanism.

Event aggregation is a third option, one that I've used and liked. It provides even looser coupling and helps subscribers and publishers be quite ignorant of the details of each other. It also makes dispatching events on different threads easier.

In general, tightly coupled mechanisms are simple to write and simple to debug, but provide less flexibility as an application grows. Loosely coupled mechanisms are still easy to write but can be much less simple to trace when you're looking at an unfamiliar code base. At any rate, make sure you also understand the lifetime of subscriber objects when implementing these patterns (primarily the tightly coupled ones), as not letting go of objects is a trap. MSDN has a nice little section on event coupling.

Unfortunately, I don't see enough description about your program to understand what level of coupling you need but I hope this helps you make the right choice.


答:
As I understand it, the Observable pattern concerns itself traditionally with real-time binding of a User Interface, based on changes in the underlying data store.  In other words, a UI that subscribes to an IObservable<T> has updates pushed to it when the underlying data store changes.

Event Handlers are a more generalized mechanism.  They are used for all sorts of things, both inside the UI and elsewhere.  Fundamentally, EventHandler<T> is really just a formal definition for a delegate signature that's been around since the beginning of Windows Forms.

Title: Are EventHandler<T> and IObservable<T> interchangable?

Body:
I have an object which will periodically raise an event based on an action performed in an application.  This will be heard by any listener(s) and acted upon accordingly.

I do not wish to use a custom type for this and would like to make use of either EventHandler<T> or IObservable<T> to manage the pub/sub mechanism I am looking to put in place.

I have had a play with both and they both do what I require.

I have read through the MSDN Observer Design Pattern and MSDN Events Programming Guide, however, I remain uncertain as to if one mechanism is more appropriate than the other.

Is one more suited for my scenario than the other or are both suitable and merely down to personal choice?

Edit 1

My pub/sub requirements are not at the UI layer at this point and are lower down.  My publisher is monitoring network activity and raising an event based on certain network events.  The subscriber is responsible for listening for raised events and performing an associated action.  The UI is not involved at this point.


答:
Method chaining is not so much a technique as a useful bit of syntactic sugar, and the details will generally depend on the semantics that you want to provide.

One common approach is for each method to mutate the object and return this; for example, new Person().setName(name).setRank(rank).setSerialNumber(serialNumber). With this approach, there's no need to know what the "last" method is, because you can terminate the chain at any point and still have the same Person object.

Another common approach is to have a dedicated mutable "builder" object that lets you apply method chaining to modify the builder, before ultimately calling a build method to create an immutable object; for example, new StringBuilder().append(s1).append(s2).append(s3).toString(). The build method is then automatically the "last" method. (In fact, this is a special case of the previous approach; the real "last" method was append(s3), and then I called toString() on the result object after I finished modifying it.)

A less-common approach is to split the difference between the above two approaches: if the target class is not completely immutable, but has some requirements for its initial setup, you can still use a builder class just for that initial setup. The build method can then perform the necessary validation (or delegate to a constructor that does so). For example, if Person requires name and age, then we might allow both new PersonBuilder().setName(name).setAge(age).build().setHeight(height) and new PersonBuilder().setName(name).setAge(age).setHeight(height).build().

Title: How to signal that a method chain should not continue?

Body:
When doing method chaining, you have methods that return the object allowing you to continue the chain. However, you need to get values out of the object somehow.

Usually I've added a method that returns a value at the end, but this complicates matters if you add to the chain and that return method may not be valid anymore.

The way I view it each time you add a method onto a chain you are refining your result until you get your desired answer in the last method call. Having a final output method creates a restriction in that it needs to know about the last operation to know how to display the result.

Maybe you have a method that results in a string and one that results in an array your output method has to deal with both those cases. What if you add a method that stores your string result somewhere new? Now you have to update the output method to handle that case too.

Is there a way of letting a method know it's the last in the chain so should output its result?


答:
Well, why don't we just ask the man himself?

Despite the variations, there are some common elements. Firstly there
  is a notion that unit tests are low-level, focusing on a small part of
  the software system. Secondly unit tests are usually written these
  days by the programmers themselves using their regular tools - the
  only difference being the use of some sort of unit testing framework.
  Thirdly unit tests are expected to be significantly faster than
  other kinds of tests.

So there's some common elements, but there are also differences. One
  difference is what people consider to be a unit. Object-oriented
  design tends to treat a class as the unit, procedural or functional
  approaches might consider a single function as a unit. But really it's
  a situational thing - the team decides what makes sense to be a unit
  for the purposes of their understanding of the system and its testing.
  Although I start with the notion of the unit being a class, I often
  take a bunch of closely related classes and treat them as a single
  unit. Rarely I might take a subset of methods in a class as a unit.
  However you define it doesn't really matter.

...

Isolation

A more important distinction is whether the unit you're testing should
  be isolated from its collaborators. ... But not all unit testers use
  this isolation. Indeed when xunit testing began in the 90's we made no
  attempt to isolate unless communicating with the collaborators was
  awkward ...

On his blog he shows some pretty nice illustrations and explains what he means in a pretty good depth.

So when wondering what Martin Fowler means and whether or not it's still true today, I think Martin Fowler of 2014 is the best possible source.

Title: Test-Driven Design is not Unit Testing

Body:
Ran across this statement by Martin Fowler circa 2002:

Unit testing in XP is often unlike classical unit testing, because in
  XP you're usually not testing each unit in isolation. You're testing
  each class and its immediate connections to its neighbors.

Is this still correct, and if so, why?


答:
Is a long list of parameter checks an anti-pattern?

Literally no.  I've never heard of an "anti-pattern" that says lots of parameter checking is a bad thing.  Parameter checking implemented as a sequence of if statements isn't an anti-pattern either.

However, that doesn't necessarily mean that what you are doing is right.

Up-front error checking in an API method has pros and cons:

On the "pro" side, you pick up problems (programming errors or problems in the "inputs") e*arly.  This (typically) makes it easier to diagnose the problems, and before the errors can cause damage (or waste resources).

On the "con" side, if the error checking is excessive or in the wrong place, it can be wasteful, or ineffective.

Take this code snippet for example:

```<code> if (A == null || B == null || linkType == null)
 {
    throw new ArgumentException("Cannot pass a null argument");
 }
</code>```

There are two problems with this:

You are doing this too late.  If any of those are null, then you will already have triggered an exception.

The tests are arguably redundant anyway, since the CLR will already have implicitly tested for null in the earlier parameter checks.  And the resulting exceptions are just as effective for diagnostic purposes ... provided that you have source code and a stack trace.

Or this:

```<code> if (A.Equals(B) || B.Equals(A))
 {
    throw new InvalidOperationException("A and B cannot be the same");
 }
</code>```

Does it really matter that A and B are unequal?  (Or could this be a harmless error, or possibly even something that is useful?)

Is it really necessary to test equality both ways?  (Can't you assume that the Equals method has been implemented to be reflexive?)

Finally, there is the larger problem of whether the checks are (too) repetitious.  By the sounds of it, they are not in your example.  But in general, they could be.

In summary.  No anti-pattern, but you still need to think about how much error checking is advisable, and how best to implement it.

Body:
Background:  I'm working on an application that will manage backup generators.  These generators need to be able to be "linked" together.  For example, Generator B might serve as a backup for Generator A.  If A fails, then the software turns B on.  Or they might be linked in a load-sharing configuration, where Generator A and B run together, and share the load.

I'm making a function that will make the link, given 2 generators and the type of link desired.

```<code>public void LinkGenerators(Generator A, Generator B, Type linkType);
</code>```

In writing my tests, I've come with a large number of invalid parameter configurations.  My LinkGenerators function looks like this:

```<code>public void LinkGenerators(Generator A, Generator B, Type linkType)
{
     if (linkType.BaseType != typeof(Link))
     {
        throw new ArgumentException("linkType is not a valid link type");
     }
     if (linkAlreadyExistsFor(A, B))
     {
        throw new InvalidOperationException("Link for A and B already exists");
     }
     if (A.Equals(B) || B.Equals(A))
     {
        throw new InvalidOperationException("A and B cannot be the same generator");
     }
     if (A == null || B == null || linkType == null)
     {
        throw new ArgumentException("Cannot pass a null argument");
     }
     .....
     //Actually make the link after making sure all the arguments are valid.
}
</code>```

Most of the LinkGenerator functions consists of verifying that the parameters are good.  The actual link creation takes 2 lines of code.  There's a bit of business logic (verifying that link doesn't already exist and that the generators are not the same) mixed in with a bit functional logic (making sure that the linkType derives from Link, arguments aren't null...), and makes me.......uncomfortable.

Is a long list of parameter checks an anti-pattern or a code smell?  And if so, what can one do about it?

(Just to make this clear to close-voters probably misunderstanding the question: this is not a question about "coding style for conditions" like this one).

Body:
Is a long list of parameter checks an anti-pattern?

Literally no.  I've never heard of an "anti-pattern" that says lots of parameter checking is a bad thing.  Parameter checking implemented as a sequence of if statements isn't an anti-pattern either.

However, that doesn't necessarily mean that what you are doing is right.

Up-front error checking in an API method has pros and cons:

On the "pro" side, you pick up problems (programming errors or problems in the "inputs") e*arly.  This (typically) makes it easier to diagnose the problems, and before the errors can cause damage (or waste resources).

On the "con" side, if the error checking is excessive or in the wrong place, it can be wasteful, or ineffective.

Take this code snippet for example:

 if (A == null || B == null || linkType == null)
 {
    throw new ArgumentException("Cannot pass a null argument");
 }

There are two problems with this:

You are doing this too late.  If any of those are null, then you will already have triggered an exception.

The tests are arguably redundant anyway, since the CLR will already have implicitly tested for null in the earlier parameter checks.  And the resulting exceptions are just as effective for diagnostic purposes ... provided that you have source code and a stack trace.

Or this:

 if (A.Equals(B) || B.Equals(A))
 {
    throw new InvalidOperationException("A and B cannot be the same");
 }

Does it really matter that A and B are unequal?  (Or could this be a harmless error, or possibly even something that is useful?)

Is it really necessary to test equality both ways?  (Can't you assume that the Equals method has been implemented to be reflexive?)

Finally, there is the larger problem of whether the checks are (too) repetitious.  By the sounds of it, they are not in your example.  But in general, they could be.

In summary.  No anti-pattern, but you still need to think about how much error checking is advisable, and how best to implement it.


问:
Should `setX(Object o)` methods perform deep or shallow copies of objects?
My particular situation is related to Java, but I believe this is a more general OOP question than just Java programming.

The Question: Should "mutator" methods perform deep or shallow copies?

An example:

Let's assume my object has the following structure:

public class MyObj {
  ArrayList<Integer> myList;
  //constructors, etc.

  public void setMyList(ArrayList<Integer> list) {
    this.myList = list; //Option 1
    //OR
    this.myList = new ArrayList<Integer>(list); //Option 2
  }
}
```

<p>My assumption is that Option 2 is best.  This is because it prevents an external class from having direct access to <code>MyObj</code>'s list.  For example, if I did:</p>

<pre class="lang-java prettyprint-override"><code>public class SomeOtherClass {
  public static void main(String[] args) {
    ArrayList<Integer> exampleList = new ArrayList<>(Arrays.asList(1, 2, 3));

    MyObj a = new MyObj();
    a.setMyList(exampleList);

    exampleList.add(4);
  }
}
</code>```

At the end of main, Option 1 means that a.myList contains 4, while Option 2 means a.myList still consists of 1, 2, 3.  To me, the second seems preferable.

Is there a standard/convention regarding this situation?

答:
Either approach can be correct; it depends on the semantics you want. Basically, the difference is that the version with the copy means "set myList to contain these elements: list", whereas the version without the copy means "set myList to be this list object: list". I think the former semantics are more often desirable (especially since lists are fairly "transparent": we usually think of lists solely in terms of the elements they contain, and not in terms of some stable "identity" independent of the contents); but there are valid uses for the latter.

If you go with the copy approach, by the way, here are a few things to keep in mind:

It's a good idea to make sure your get method returns an unmodifiable list, using either Collections.unmodifiableList or something like Guava's ImmutableList.copyOf. (Note that you probably do not want to just return new ArrayList<Integer>(myList), because although that protects myList from being modified by client code, it does not make it obvious that modifying the returned list does not affect the original object. It's better for myObj.getMyList().add(3) to fail noisily.)

List may not be the appropriate abstraction if you don't actually want client code to manipulate the list as a list. And even if your getter returns List<Integer>, it might be appropriate for your setter to accept Iterable<Integer>.


答:
Note that the same question arises for getters. Not copying a mutable field in a getter means exposing the content for modification.

You're speaking about shallow vs deep copy, but you snippet show no vs shallow copy. A deep copy would go like

```<code>void setTwoLevelList(List<List<Integer>> twoLevelList) {
    this.twoLevelList = Lists.newArrayList();
    for (List l : twoLevelList) this.twoLevelList.add(Lists.newArrayList(l));
}
</code>```

or even more complicated for deeper structures or infeasible for something like

```<code>void setListOfT(List<T> t) {
    ??? how to copy T?
}
</code>```

The problem in Java is that it has neither a shallow nor a deep copy. It has clone, which is broken by design and underspecified:

Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object.

Back to the question

So should we do no, shallow, or deep copy in setters?

Ideally, there should be no setters at all. Immutable objects are the easiest to use, but unfortunately, not always possible.

There's no general rule for setters, except that you should avoid them (even more than mutable state in general). Often, an immutable object with a builder or a wither is an alternative.

If you have to write a setter, then I'd recommend to make the field immutable, e.g., use an ImmutableList. If its members are immutable too, then there's no reason to copy anything.

Otherwise, I would copy as deep as I can. Sometimes, an exception must be made for performance reasons, e.g., when passing large objects frequently. In a such a case it's advisable to make the method package private

A good solution is often something like

```<code>void setMyList(List<Integer> list) {
    this.list = ImmutableList.copyOf(list);
}
</code>```

Title: Should `setX(Object o)` methods perform deep or shallow copies of objects?

Body:
My particular situation is related to Java, but I believe this is a more general OOP question than just Java programming.

The Question: Should "mutator" methods perform deep or shallow copies?

An example:

Let's assume my object has the following structure:

public class MyObj {
  ArrayList<Integer> myList;
  //constructors, etc.

  public void setMyList(ArrayList<Integer> list) {
    this.myList = list; //Option 1
    //OR
    this.myList = new ArrayList<Integer>(list); //Option 2
  }
}
```

<p>My assumption is that Option 2 is best.  This is because it prevents an external class from having direct access to <code>MyObj</code>'s list.  For example, if I did:</p>

<pre class="lang-java prettyprint-override"><code>public class SomeOtherClass {
  public static void main(String[] args) {
    ArrayList<Integer> exampleList = new ArrayList<>(Arrays.asList(1, 2, 3));

    MyObj a = new MyObj();
    a.setMyList(exampleList);

    exampleList.add(4);
  }
}
</code>```

At the end of main, Option 1 means that a.myList contains 4, while Option 2 means a.myList still consists of 1, 2, 3.  To me, the second seems preferable.

Is there a standard/convention regarding this situation?

Body:
Note that the same question arises for getters. Not copying a mutable field in a getter means exposing the content for modification.

You're speaking about shallow vs deep copy, but you snippet show no vs shallow copy. A deep copy would go like

void setTwoLevelList(List<List<Integer>> twoLevelList) {
    this.twoLevelList = Lists.newArrayList();
    for (List l : twoLevelList) this.twoLevelList.add(Lists.newArrayList(l));
}

or even more complicated for deeper structures or infeasible for something like

void setListOfT(List<T> t) {
    ??? how to copy T?
}

The problem in Java is that it has neither a shallow nor a deep copy. It has clone, which is broken by design and underspecified:

Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object.

Back to the question

So should we do no, shallow, or deep copy in setters?

Ideally, there should be no setters at all. Immutable objects are the easiest to use, but unfortunately, not always possible.

There's no general rule for setters, except that you should avoid them (even more than mutable state in general). Often, an immutable object with a builder or a wither is an alternative.

If you have to write a setter, then I'd recommend to make the field immutable, e.g., use an ImmutableList. If its members are immutable too, then there's no reason to copy anything.

Otherwise, I would copy as deep as I can. Sometimes, an exception must be made for performance reasons, e.g., when passing large objects frequently. In a such a case it's advisable to make the method package private

A good solution is often something like

void setMyList(List<Integer> list) {
    this.list = ImmutableList.copyOf(list);
}


问:
What complexity do DI frameworks add?
The currently most upvoted answer to a very recent question states that

DI containers are an "enterprise software" pattern, used when the object graph is very large and complex. I suspect that 95% of applications do not require it.

which is something I strongly disagree with. Maybe I've got the terminology wrong, but for me DI framework means just "something wiring my objects together". Am I missing something?

I'm using Guice even for really tiny projects (like 10 classes) in order to simplify them. Sure, it's a 400 kB JAR file, but this isn't what I'd care about. For a small project I hardly ever need any configuration and the only "overhead" is adding the @Inject annotation.

So I really wonder, what added complexity do DI frameworks cause?

Update addressing the answers

In a 82 class project, I have

32 @Inject annotations

15 @Singleton and 1 @ProvidedBy annotations

4 Providers (all of which I'd need also without DI as they're my factories)

1 Module containing a single line

0 lines XML !!!

That's all. Sure, it's small project, but exactly this was my point. The additional work was a few words rather than lines.

I'm using solely constructor injection in order to get immutable "easygoing" objects. Whenever a new dependency appears, I add a final field, let Lombok's RequiredArgsConstructor take care of the declaration, and let Guice take care of calling it properly.

答:
To summarize: It looks like the only complexity comes from using improper configuration methods (yes, XML is not type-safe) and possibly also from frameworks doing much more work (Spring manages the object lifecycle, which goes far beyond DI).

For a simple project, DI doing right is extremely useful:

it allows to write services as tiny immutable classes with minimum effort

it ensures singletonness in the right scope while staying testable

it needs hardly any configuration (about 1 line per 20 DI classes)

It's also pretty harmless, as it all could be done manually. It's just creating the instances, passing them to constructors in order to create more instance, and so on. Boring and long, but simple.

A typical service using Guice and Lombok looks like this

```<code>@Singleton
@RequiredArgsConstructor(onConstructor=@__(@Inject))
public class TotalCostsComputer {
    public CostsResult getCosts(Goods goods, Shippment shippment) {
        return taxComputer.applyTax(composeResult(
                    goodsCostComputer.getCosts(goods),
                    shippmentCostComputer.getCosts(shippment));
    }
    ...

    private final GoodsCostComputer goodsCostComputer;
    private final ShippmentCostComputer shippmentCostComputer;
    private final TaxComputer taxComputer;
}
</code>```

Now, adding a dependency means just adding a new private final field. It can't be null (Guice guarantees this even without @NonNull).

Testing means either creating your own instances or getting them from the Injector (possibly configured to return some stubs). Both is pretty simple.

Title: What complexity do DI frameworks add?

Body:
To summarize: It looks like the only complexity comes from using improper configuration methods (yes, XML is not type-safe) and possibly also from frameworks doing much more work (Spring manages the object lifecycle, which goes far beyond DI).

For a simple project, DI doing right is extremely useful:

it allows to write services as tiny immutable classes with minimum effort

it ensures singletonness in the right scope while staying testable

it needs hardly any configuration (about 1 line per 20 DI classes)

It's also pretty harmless, as it all could be done manually. It's just creating the instances, passing them to constructors in order to create more instance, and so on. Boring and long, but simple.

A typical service using Guice and Lombok looks like this

@Singleton
@RequiredArgsConstructor(onConstructor=@__(@Inject))
public class TotalCostsComputer {
    public CostsResult getCosts(Goods goods, Shippment shippment) {
        return taxComputer.applyTax(composeResult(
                    goodsCostComputer.getCosts(goods),
                    shippmentCostComputer.getCosts(shippment));
    }
    ...

    private final GoodsCostComputer goodsCostComputer;
    private final ShippmentCostComputer shippmentCostComputer;
    private final TaxComputer taxComputer;
}

Now, adding a dependency means just adding a new private final field. It can't be null (Guice guarantees this even without @NonNull).

Testing means either creating your own instances or getting them from the Injector (possibly configured to return some stubs). Both is pretty simple.


问:
The advantage of using __attribute__((aligned( )))
I found in more than one SIMD program the instruction  __attribute__((aligned(16))) . When I looked for an explanation I found

The keyword attribute allows you to specify special attributes of
  variables or structure fields.

Apparently variables have attributes. Are these attributes language-specific? what attributes can a variable have? where are these attributes stored?
Regarding the subject of aligned(16), I found this it

causes the compiler to allocate [a variable] on a 16-byte
  boundary

But is it mandatory for SIMD variables (m128i for example) to be aligned on a 16 bytes?
If yes, I suppose this is the reason why we use __attribute((aligned(16))) like so:

```<code>int a[16] __attribute__((aligned(16))) = {  1,  2,  3,  4,  5,  6,  7, 8,  9, 10, 11, 12, 13, 14, 15, 16 };

__vector signed int *va = (__vector signed int *) a;
</code>```

答:
attributes like above are an extension (to the standard C99 language specification) provided by GCC (and some few other compilers, e.g. Clang/LLVM). The aligned attribute forces the compiler to align that variable (your a array) to the specified alignment. The GCC documentation lists the attributes you can give, and you could even extend your GCC compiler (with some plugin or some MELT extension; however MELT was abandoned in 2017) to add your additional attributes.

This __attribute__((aligned(16))) is indeed useful (on x86-64) for vector instructions like SSE3 or AVX, since it is aligning to 16 bytes your a  array. It should enable the optimizing compiler to generate more efficient machine code. (You probably need also to give some optimization flags like -mtune=native -O3 to gcc). So using it is useful (but not mandatory) for "SIMD" code.

Attributes are a compile-time annotation. Of course they change the behavior of the compiler, but such attributes do not exist at run-time (like C types do not exist at runtime neither).

If you didn't align your a array I guess that the compiler would have to emit additional instructions and they would run slower. BTW, you could compile with gcc -O3 -fverbose-asm -S (and other optimization flags) and, by looking inside the generated assembly code, see what the use of that attribute changes in the emitted assembly code. You could also benchmark your application (on Linux, see time(1) and time(7)...)

ContentLicense: CC BY-SA 4.0


问:
Function only returns unchanged parameter, useless?
I just found this function in the project I'm working at:

```<code>  -- Just returns the text unchanged.
  -- Note: <text> may be nil, function must return nil in that case!
  function Widget:wtr(text)
      return text
  end
</code>```

Too sad, the coder does not work in the company anymore. Why would one make a function that does nothing, but returns the parameter it's called with?

Is there any use to such a function, not specified to this example, but overall in any case?

Due to

```<code>function aFunction(parameter)
    return parameter
end
</code>```

Ends in

```<code>aFunction(parameter) == parameter
</code>```

Why would I write something like

```<code>aFunction(parameter) == whatIWantToCheck
</code>```

instead of

```<code>parameter == whatIWantToCheck
</code>```

?

答:
Isn't that just a polymorphysm?

From my experience with Qt tr() and wtr() methods are supposed to be used (there, in Qt) in localization of Widget's text.

So, by returning unchanged text this method just says: Widget does no localization (translation of the text) by default. Override this function to enable your own logic.


问:
How do I avoid duplicating utility functions across modules?
I've seen this question but it doesn't help me because I'm writing functional code (Standard ML) and the answers there are heavily focused towards OOP (the OP is advised to use the Facade pattern, to use inheritance, etc -- answers that are not relevant to an SML programmer).

In two separate, largely unrelated modules, Foo and Bar, I need to accomplish the same task: given functions equal and equals with the signatures:

```<code>val equal: t * t -> bool
val equals: t list * t list -> bool
</code>```

make two new functions with the following signatures:

```<code>val equal': t * t -> t option
val equals': t list * t list -> t list option
</code>```

Here, t stands for either Foo.t or Bar.t. The natural solution is to use a higher order function:

```<code>local
  fun boolToOpt (comparison: ('a * 'a) -> bool) (left, right) =
    if comparison (left, right) then
      SOME left
    else
      NONE
in
  val equal' = boolToOpt equal
  val equals' = boolToOpt equals
end
</code>```

I need to repeat exactly this code snippet in both modules.

Now, this is a tiny, minor implementation detail, and it would be a bad idea to let it be publicly visible from either Foo or Bar. At the same time, it seems too small -- and too tightly coupled to the two equal(s) functions -- to be factored out in to a module of its own. Maybe in another language, the equals' functionality would merit its own class, say, ComparisonDecorator, that overrides equal(s) to give me functions with the return type t option, but that's not an option here.

I run in to situations like these at least once per day. Is there a sane way to avoid just copy+pasting here?

答:
If you have absolutely no idea of a good abstraction for a module, put the function in a generic utility module, at least temporarily. And after you found several utility functions, you will probably identify some of them "belonging together". That will give you a hint for a common module name for these group of functions, so you can finally move them from the utility module into a module with a better name.

Just be careful not to let your utility module grow arbitrarily - from time to time, you have to clean up things there, otherwise you will reach a point where you don't know what's in there and what's not.


答:
Have you looked at Reactive Extensions?  Reactive Extensions is a library that allows the composition of aysynchronous and event based code.  I'd have a look at Intro To Rx, it has lots of information on when IObservable is appropriate and as J Trana has said one of the benefits is a reduction in coupling.

Without more information about your application it's hard to advise specifically which approach I would recommend.


问:
async+await == sync?
Stumbled upon this post that talks about making async web requests.

Now simplicity aside, if in real world, all you do is make an async request and wait for it in the very next line, isn't that the same as making a sync call in the first place?

答:
Please allow me to clarify things in regards to async/await.

When await is encountered the underlying state machine allows control to be returned immediately.  Then, when the awaited call is completed, the underlying state machine allows execution to resume at the line after the awaited call.

Therefore, the async block is not blocked nor is it waiting for the awaited call to finish; Control is returned immediately when the await command is encountered.

The underlying state machine is part of the "magic" behind the use of async/await that is not disused and missed.

Title: async+await == sync?


问:
What is more efficient, a single square root or multiple divisions?
Say I make a program that calculates all possible (integral) factors of a certain number that has been input.

Is it theoretically more efficient to check with all integers up to the square root of the number or till half of the number.

Calculating the square root will take more time and power but will result in fewer divisions and vice-versa for the other option.

答:
A square root isn't that long to compute for modern CPUs.  It is better to compute the square root than to continue running your loop up to n/2.  Except maybe for very small n's.

There are ways to reduce the cost of square roots:  Precompute the square root:

```<code>int max = (int)Math.sqrt(n);
for(int k=2 ; k <= max ; k++)...
</code>```

or use an integer multiplication in your test

```<code>for(int k=2 ; k*k <= n ; k++)...
</code>```

Body:
A square root isn't that long to compute for modern CPUs.  It is better to compute the square root than to continue running your loop up to n/2.  Except maybe for very small n's.

There are ways to reduce the cost of square roots:  Precompute the square root:

int max = (int)Math.sqrt(n);
for(int k=2 ; k <= max ; k++)...

or use an integer multiplication in your test

for(int k=2 ; k*k <= n ; k++)...


问:
When should you call yourself a senior developer?

Possible Duplicate:

  Whats the difference between Entry Level/Jr/Sr developers?

I'm curious what senior developer means because apparently the definition doesn't mean what I thought it would. I keep seeing these teens at 22-23 years old who call themselves senior X developer or senior Y developer. To me, a senior must have 10 years or so experience in programming to call himself 'senior'. I've seen a lot of these teens here (hence the question). Am I wrong? Why?

答:
It's a title like many other titles. These "teens" on here might even have a PhD, that doesn't necessarily mean anything. But it will clearly get them a higher salary. The same applies to the Senior Developer or Senior Architect. Or the Senior Project Manager, etc.

Considering that fact, it is better to be called "Our Senior Developer" by your workmates, rather than adding that title to your own card after whatever many years of experience - which I did when I had the opportunity. :-)

Other than that, I'd say 10 years is a minimum (including college or other education).

ContentLicense: CC BY-SA 2.5


答:
```<code>if (linkType.BaseType != typeof(Link))
     {
        throw new ArgumentException("linkType is not a valid link type");
     }
</code>```

should be

```<code>checkArgument(linkType.BaseType != typeof(Link),
    "linkType is not a valid link type");
</code>```

In Java, there's a library with a class Preconditions for this (no idea about c#, but it's easy to write).

This way you get shorter code and it's clean what is what. Incidentally, it can also be faster as the method gets shorter leaving better chances for inlining (at least in the JVM). Hoisting out all checks into one method... maybe.

In general, input validation is good (fail early). For non-public methods consider asserts instead.

Most of the LinkGenerator functions consists of verifying that the parameters are good.

This is a code smell... it seems like you should look for alternatives, how to ensure some conditions so that this method could be simplified. But this is not always possible.

Title: Is a long list of parameter checks an anti-pattern?

Body:
if (linkType.BaseType != typeof(Link))
     {
        throw new ArgumentException("linkType is not a valid link type");
     }

should be

checkArgument(linkType.BaseType != typeof(Link),
    "linkType is not a valid link type");

In Java, there's a library with a class Preconditions for this (no idea about c#, but it's easy to write).

This way you get shorter code and it's clean what is what. Incidentally, it can also be faster as the method gets shorter leaving better chances for inlining (at least in the JVM). Hoisting out all checks into one method... maybe.

In general, input validation is good (fail early). For non-public methods consider asserts instead.

Most of the LinkGenerator functions consists of verifying that the parameters are good.

This is a code smell... it seems like you should look for alternatives, how to ensure some conditions so that this method could be simplified. But this is not always possible.


问:
Is there any reason to override Equals for an Entity?
An entity has identity, which implies there should only be one object (e.g. a particular customer) in memory.

As such, reference equality (which is what the base version of object.equals checks for) should be the only equality we care about.

A value object on the other hand would need to overrride Equals as there may be many in memory.

Are there any issues with the above reasoning?

I just can't imagine why I would have two customer objects representing the same customer, and in any case where I did (e.g. took a clone to do something with it), I can't think of any circumstances where I would need to check if it was equal to the orginal object.

Even in a distributed environment, any client process should only contain one object for a certain customer.

答:
I just can't imagine why I would have two customer objects representing the same customer, and in any case where I did (e.g. took a clone to do something with it), I can't think of any circumstances where I would need to check if it was equal to the orginal object.

This can easily happen: You read a list of objects from somewhere (e.g., from the database) and receive one object from elsewhere (e.g., from a web request). Now you don't call equals, you look up the object in the list, so equals gets called anyway.

That's where a field based equals makes sense. However, selecting the fields which should participate in the checks is something between hard and impossible. Consider class Person, what business property never changes? Name? Surely not. SSN? Neither.

That's why many prefer an ID-based equality. This has other problems, e.g., assigning the ID to newly created objects and some others. There's lengthy discussion about it somewhere on Hibernate pages.

Not defining equals is a way I've never heard about.

Even in a distributed environment, any client process should only contain one object for a certain customer.

What if one process sends an entity to another one?


答: Nowadays processors 'enjoy' working on float numbers and provides support for square roots and   powers. I think engeeners which implemented Math.sqrt(n) method, took care of efficiency better than multiplying in a loop.

Title: What is more efficient, a single square root or multiple divisions?

Body:
Say I make a program that calculates all possible (integral) factors of a certain number that has been input.

Is it theoretically more efficient to check with all integers up to the square root of the number or till half of the number.

Calculating the square root will take more time and power but will result in fewer divisions and vice-versa for the other option.


问:
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.

答:
Frama-C's value analysis, a static analyzer the purported goal of which is to find all undefined behaviors in a C program, considers the assignment const int b = a; as okay. This is a deliberate design decision in order to allow memcpy() (typically implemented as a loop over unsigned char elements of a virtual array, and that the C standard arguably allows to re-implement as such) to copy a struct (which can have padding and uninitialized members) to another.

The “exception” is only for lvalue = lvalue; assignments without an intervening conversion, that is, for an assignment that amounts to a copy of a slice of memory for a memory location to another.

I (as one of the authors of Frama-C's value analysis) discussed this with Xavier Leroy at a time when he was himself wondering about the definition to pick in the verified C compiler CompCert, so he may have ended up using the same definition. It is in my opinion cleaner than what the C standard tries to do with indeterminate values that can be trap representations, and the type unsigned char that is guaranteed not to have any trap representations, but both CompCert and Frama-C assume relatively non-exotic targets, and perhaps the standardization committee was trying to accommodate platforms where reading an uninitialized int can indeed abort the program.

Returning b, or passing n1, n2 or n3 to printf in the end at least can be considered undefined behavior, because copying an uninitialized slice of memory does not making it initialized. With an oldish Frama-C version:

```<code>$ frama-c -val t.c
…
t.c:19:… accessing uninitialized left-value: assert \initialized(&n1);
</code>```

And in an oldish version of CompCert, after minor modifications to make the program acceptable to it:

```<code>$ ccomp -interp t.c
Time 33: in function foo, expression <loc> = <undef>
ERROR: Undefined behavior
</code>```

OwnerDisplayName: thb

Title: Undefined behavior, in principle

Body:
Frama-C's value analysis, a static analyzer the purported goal of which is to find all undefined behaviors in a C program, considers the assignment const int b = a; as okay. This is a deliberate design decision in order to allow memcpy() (typically implemented as a loop over unsigned char elements of a virtual array, and that the C standard arguably allows to re-implement as such) to copy a struct (which can have padding and uninitialized members) to another.

The “exception” is only for lvalue = lvalue; assignments without an intervening conversion, that is, for an assignment that amounts to a copy of a slice of memory for a memory location to another.

I (as one of the authors of Frama-C's value analysis) discussed this with Xavier Leroy at a time when he was himself wondering about the definition to pick in the verified C compiler CompCert, so he may have ended up using the same definition. It is in my opinion cleaner than what the C standard tries to do with indeterminate values that can be trap representations, and the type unsigned char that is guaranteed not to have any trap representations, but both CompCert and Frama-C assume relatively non-exotic targets, and perhaps the standardization committee was trying to accommodate platforms where reading an uninitialized int can indeed abort the program.

Returning b, or passing n1, n2 or n3 to printf in the end at least can be considered undefined behavior, because copying an uninitialized slice of memory does not making it initialized. With an oldish Frama-C version:

$ frama-c -val t.c
…
t.c:19:… accessing uninitialized left-value: assert \initialized(&n1);

And in an oldish version of CompCert, after minor modifications to make the program acceptable to it:

$ ccomp -interp t.c
Time 33: in function foo, expression <loc> = <undef>
ERROR: Undefined behavior

OwnerDisplayName: Complicated see bio


答:
Undefined behavior ultimately means the behavior is non-deterministic. Programmers who are unaware that  they are writing non-deterministic code are <s>just bad</s> ignorant programmers. This site aims to make programmers better (and less ignorant).

Writing a correct program in the face of non-deterministic behavior is not impossible. However, it is a specialized programming environment, and requires a different kind of programming discipline.

Even in your example, if the program receives an externally raised signal, the values on the "stack" may change in such a way that you don't get the expected values. Moreover, if the machine has trap values, reading random values may very well cause something strange to happen.

Title: Undefined behavior, in principle

Body:
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.

OwnerDisplayName: jxh


问:
XML in the attribute of other XML
Today, another developer was talking to me about how he addressed an issue he was working on.  The solution he found was to stick a string of escaped XML into the attribute of another XML element.  In my head I was screaming "Is that even safe and wise to do???".  According to him, that has been done on tons of other projects within the company that transmit XML back and forth.

My question is this -

Is that a safe/smart thing to do
(xml in an xml attribute)?

If not, should I bring that up?  I have
only been with the company for 2
years and have noticed many things
that are just asking for a major
catastrophe to happen someday (both
in and not in projects I work on).
I don't want to be the one that
always says that they are doing
things wrong...

Any thoughts would be greatly appreciated!

FYI - UPDATED INFO RE: APPLICATION -
Flash is calling this API and parsing the XML it gets in the response.  I do not think the Flash is using XPath or anything, just string parsing (but I could be wrong).  I do not work on the Flash aspect, so I do not know where to look (nor would I understand it).

答:
I did exactly this and I want to explain in what sense it was correct.

I was using a framework that duplicates data across a network.  A server maintains the data.  Clients can subscribe to a view on the data.  They receive the current state and are later notified of any changes.  Changes would be adding or removing a data entity, setting an entity field value, or setting a relation between entities.

The current state and data was encoded in XML.  For instance, if a product is reserved and availability changes, the client could receive an update like:

```<code><upd type="product" id="678" available="19" reserved="1" />
</code>```

All primitive fields values are given as attributes.

What happened then is that one field coming from the DB contained XML.  It was stored as an XML string because only the client needed to interpret it.  So, the XML, as any string, was properly escaped and passed as an attribute.

Morality

There is nothing wrong, it is just isolation between two layers.

The lower layer transports strings, among other things, and happens to represent strings as XML attributes.  The upper layer needed to transport XML and naturally used the string representation of XML.  The combined effect is that you get XML encoded in an attribute.

Detecting that situation and moving that XML to a nested element (as my boss wanted me to do) would break the independence of the layers.  The upper layer would have to tag the field as "this is properly formed XML", and the lower layer would then say "nice, I will pass it as a nested element".

To show that it is wrong, imagine the lower layer is one day replaced to use JSON.  Now it needs to be notified of data that is properly formatted JSON.  But the upper layer shouldn't be affected by changes in the implementation of the lower layer.

Title: XML in the attribute of other XML

Body:
I did exactly this and I want to explain in what sense it was correct.

I was using a framework that duplicates data across a network.  A server maintains the data.  Clients can subscribe to a view on the data.  They receive the current state and are later notified of any changes.  Changes would be adding or removing a data entity, setting an entity field value, or setting a relation between entities.

The current state and data was encoded in XML.  For instance, if a product is reserved and availability changes, the client could receive an update like:

<upd type="product" id="678" available="19" reserved="1" />

All primitive fields values are given as attributes.

What happened then is that one field coming from the DB contained XML.  It was stored as an XML string because only the client needed to interpret it.  So, the XML, as any string, was properly escaped and passed as an attribute.

Morality

There is nothing wrong, it is just isolation between two layers.

The lower layer transports strings, among other things, and happens to represent strings as XML attributes.  The upper layer needed to transport XML and naturally used the string representation of XML.  The combined effect is that you get XML encoded in an attribute.

Detecting that situation and moving that XML to a nested element (as my boss wanted me to do) would break the independence of the layers.  The upper layer would have to tag the field as "this is properly formed XML", and the lower layer would then say "nice, I will pass it as a nested element".

To show that it is wrong, imagine the lower layer is one day replaced to use JSON.  Now it needs to be notified of data that is properly formatted JSON.  But the upper layer shouldn't be affected by changes in the implementation of the lower layer.


答:
"Undefined Behavior" is shorthand for "This behavior is not deterministic; not only will it probably behave differently in different compilers or hardware platforms, it may even behave differently in different versions of the same compiler."

Most programmers would consider this an undesirable characteristic, especially since C and C++ are standards-based languages; that is, you use them, in part, because the language specification makes certain guarantees about how the language will behave, if you are using a standards-compliant compiler.

As with most things in programming, you have to weight the advantages and disadvantages.  If  the benefit of some operation that is UB exceeds the difficulty of getting it to behave in a stable, platform-agnostic fashion, then by all means, use the undefined behavior.  Most programmers will think it is not worth it, most of the time.

The remedy for any undefined behavior is to examine the behavior that you actually get, given a particular platform and compiler.  That sort of examination is not one that an expert programmer is likely to explore for you in a Q&A setting.

Title: Undefined behavior, in principle


问:
how to upgrade software
I am a beginner in computer programming with C/C++.  I have previous experience in programming for the web.  There is some confusion that I am having with the software development process in desktop applications.

Web applications are easy to upgrade because it is basically a bunch of source files, but I have a question about desktop applications.  The major thing I notice about desktop applications is that they are released in different versions.  This requires the user to go through the uninstall/re-install process in order to obtain a newer version of the software.

In C/C++ software for various platforms, how would a programmer implement an "upgrade" option that would allow a user to update an already installed application without having to go back to a website.  How hard is it to upgrade an executable file on platforms like Windows and Linux.  I understand that the process may be different for different platforms.

Say, for example, I have a desktop application (version 1) that the user has already downloaded and installed onto their own PC.  After a while, I make some changes to the software and make improvements that the user would want applied to their software.  The user has made customizations to the software, but would like to upgrade to version 2 without having to re-customize their application all over again.  Originally, I thought that an "upgrade" feature would replace certain parts of an executable file, but is that really what you would have to do?

My main question is:  How exactly would someone go about accomplishing this "upgrade" process?  Is it possible?

答:
Upgrading software which is packaged is complex and is best done with a software installation tool.  This is a classic case of build vs. buy.  You couldn't build something yourself that does the job of InstallShield, for example.

Upgrading software which has been customized is a very tricky proposition.  In general this is next to impossible to do in an automated way.

If you knew in advance that some kinds of customization needed to be supported, you could architect your application to have features that are modular in nature.  Perhaps a plugin architecture or some method of table driven logic configuration.  In this kind of scenario you can automate the replacement of your application's core without disturbing the modules or data stores that contain the customizations.

This type of customization must necessarily be limited in nature.  Some kinds of changes that you might eventually want to make to your core application are bound to break even the most carefully planned and isolated user configurations/customizations.

If you build package software and also perform customizations on that software, then you are sooner or later going to have to either branch your code and let some customers live with the old version or you're going to have to reapply some customizations.  Just ask anybody who has bought a major ERP like SAP.

Title: how to upgrade software


问:
What is a good design pattern for generating an Excel (xlsx) file in code?
See my Update at the bottom for more.

I occasionally have projects where I have to output some data as an Excel file (xlsx format).  The process is usually:

User clicks some buttons in my application

My code runs a DB query and processes the results somehow

My code generates an *.xlsx file using either the Excel com interop libraries or some third-party library (e.g., Aspose.Cells)

I can easily find code examples for how to do this online, but I am looking for a more robust way to do this.  I'd like my code to follow some design principles to ensure that my code is maintainable and easily understandable.

Here is what my initial attempt to generate an xlsx file looked like:

```<code>var wb = new Workbook();
var ws = wb.Worksheets[0];
ws.Cells[0, 0].Value = "Header";
ws.Cells[1, 0].Value = "Row 1";
ws.Cells[2, 0].Value = "Row 2";
ws.Cells[3, 0].Value = "Row 3";
wb.Save(path);
</code>```

Pros: Not much.  It works, so that's good.

Cons:

Cell references are hardcoded, so I have magic numbers littered throughout my code.

It's difficult to add or remove columns and rows without updating many cell references.

I need to learn some third-party library.  Some libraries are used like other libraries, but there can still be problems.  I had a problem where the com interop libraries use 1-based cell referencing whereas Aspose.Cells uses 0-based cell referencing.

Here is one solution that addresses some of the cons I listed above.  I wanted to treat a table of data as its own object that can be moved around and changed without digging into cell manipulation and disturbing other cell references.  Here is some pseudocode:

```<code>var headers = new Block(new string[] { "Col 1", "Col 2", "Col 3" });
var body = new Block(new string[,]
    {
        { "Row 1", "Row 1", "Row 1" },
        { "Row 2", "Row 2", "Row 2" },
        { "Row 3", "Row 3", "Row 3" }
    });

body.PutBelow(headers);
</code>```

As a part of this solution, I'll have some BlockEngine object that takes a container of Blocks and performs the cell manipulations required to output the data as an *.xlsx file.  A Block object can have formatting attached to it.

Pros:

This removes most of the magic numbers that my initial code had.

This hides a lot of cell manipulation code, although cell manipulation is still required in the BlockEngine object that I mentioned.

It's much easier to add and remove rows without effecting other parts of the spreadsheet.

Cons:

It's still difficult to add or remove columns.  If I wanted to swap the position of columns two and three, I'd have to directly swap the cell contents.  In this case that'd be eight edits, and thus eight opportunities to make a mistake.

If I have any formatting in place for those two columns, I have to update that as well.

This solution doesn't support horizontal block placement; I can only place one block below another.  Sure I could have tableRight.PutToRightOf(tableLeft), but that would cause problems if tableRight and tableLeft had different numbers of rows.  To place tables, the engine would have to be aware of every other table.  This seems unnecessarily complicated to me.

I still need to learn third-party code, though through a layer of abstraction via Block objects and a BlockEngine the code will be less tightly-coupled to the third-party library than my initial attempt.  If I wanted to support lots of different formatting options in a loosely-coupled way, I'd probably have to write a lot of code; my BlockEngine would be a huge mess.

Here is a solution that takes a different route.  Here's the process:

I take my report data and generate an xml file in some format that I choose.

I then use an xsl transformation to convert the xml file to an Excel 2003 XML Spreadsheet file.

From there I simply convert the xml Spreadsheet to an xlsx file using a third party library.

I found this page that describes a similar process and includes code examples.

Pros:

This solution requires almost no cell manipulation.  You instead use xsl/xpath to do your manipulations.  In order to swap two columns in a table, you move the whole columns in the xsl file unlike my other solutions which would require cell-swapping.

While you still need a third-party library that can convert an Excel 2003 XML Spreadsheet to an xlsx file, that's about all you'll need the library for.  The amount of code you need to write that would call into the third-party library is tiny.

I think this solution is the easiest to understand and requires the least amount of code.

The code that creates the data in my own xml format will be simple.

The xsl file will be complicated only because the Excel 2003 XML Spreadsheet is complicated.  However it's easy to check the output of the xsl file: just open the output in Excel and check for error messages.

It's easy to generate sample Excel 2003 XML Spreadsheet files: just create a spreadsheet that looks like your desired xlsx file, and then save it as an Excel 2003 XML Spreadsheet.

Cons:

Excel 2003 XML Spreadsheets don't support certain features.  You can't autofit column widths for instance.  You can't include images in headers or footers.  If you're going to export the resultant xlsx file to pdf, you can't set pdf bookmarks.  (I hacked together a fix for this using cell comments.).  You have to do this using your third-party library.

Requires a library that supports Excel 2003 XML Spreadsheets.

Uses an 11-year old MS Office file format.

Note: I realize that xlsx files are actually zip files containing xml files, but the xml formatting seems too complicated for my purposes.

Finally, I've looked into solutions involving SSRS, but it seems too bloated for my purposes.

Back to my initial question, what is a good design-pattern for generating Excel files in code?.  I can think of a few solutions, but none seem to stick out as ideal.  Each has drawbacks.

Update: So I tried both my BlockEngine solution and my XML Spreadsheet solution for generating similar XLSX files.  Here are my opinions of them:

The BlockEngine solution:

This simply requires too much code considering the alternatives.

I found it too easy to overwrite one block with another if I had an offset wrong.

I originally stated that formatting could be attached at the block level.  I found this to be not much better than doing the formatting separately from the block content.  I can't think of a good way to combine the content and the formatting.  Nor can I find a good way to keep them separate.  It's just a mess.

The XML Spreadsheet solution:

I'm going with this solution for now.

It bears repeating that this solution requires much less code.  I'm effectively replacing the BlockEngine with Excel itself.  I still do need a hack for features like bookmarks and page breaks.

The XML Spreadsheet format is finicky, but it's easy to make a small change and compare the results to an existing file in your favorite Diff program.  And once you figure out some idiosyncrasy, you can put it in place and forget about it from there.

I'm still concerned that this solution relies on an older Excel file format.

The XSLT file I created is easy to work with.  Dealing with formatting is much simpler here than it is with the BlockEngine solution.

答:
There are two things to consider:

Complexity of creating a file in a given format

Susceptibility of code to breakage when the structure of content of the file needs to change.

Regarding the first:

If the spreadsheets you need to generate don't contain any formatting or formulas, then you it is pretty straight-forward to generate a CSV or Tab-Delimited file instead of an actual XLSX.  Excel opens these files, often by default on a lot of PCs.  This won't help you with hard coding around columns and rows but it will save you the extra work of manipulating the Excel object model.

If you need formatting or formulas, then working with the Excel object model is a reasonable way to go, especially if you build a spreadsheet that isn't too "hard-coded" itself.  In other words, if your spreadsheet uses relative formulas and range names appropriately then it can go together with less hard coding of magic numbers.

Regarding the second:

You can work through cell by cell with hard-coded row and column references, or you can work with arrays/List collections and for loops to generalize the population of cells.


问:
UML representation of type being passed as a parameter
I want to draw a UML diagram of my program. Class Barney has a method Yabadaba(Doo d) which takes a parameter of type Doo.

How do I represent that class Doo is used in class Barney in my UML diagram?

答: The Class Barney have not any relationship, but next class Barney you put enumeration class Doo with the Doo property.</p>


答:
Before we start,

Know what the use case is for

Learn how to measure performance scientifically, like a pro. Takes years to learn but there is no recurring cost applying the knowledge.

Firstly, optimize for use case.

For an interview, just use the standard library sqrt, floored to integer, take out factor of 2 as a special case, so that you only need to loop over odd integer factors beginning with 3.

For absolute awesomeness, implement Sieve of Eratosthenes -

But don't try to impress with an interviewer with this (aside from just name-dropping) - you don't want to risk timeouts or typos proportional to amount of code.

If for some reason one has to implement square-roots on CPUs without native support,

Your standard library may have it; if so, use it.

Otherwise, the first two often-quoted strategies are:

Method of bisection, or binary search, or bit-guessing. Works 1 bit of root estimate at a time.

Given r^2 <= floor(n/4) < (r+1)^2, test (2*r+1)^2 against n

Make use of the identity (2*r+1)^2 == (4*r^2 + 4*r + 1)

Newton-Raphson method.

The choice comes down to whether the CPU has good division performance or not.

Method of bisection only requires fast bit shifts, addition, subtraction and comparisons.

Newton-Raphson requires division (integer or float).

If you are synthesizing hardware, you can use a table lookup for the highest 10 bits or so, and then continue with either bisection or Newton-Raphson method.

All of the information above can be gathered by searching on Google, Wikipedia, Stackoverflow, and other hobbyist sites.

https://stackoverflow.com/questions/1100090/looking-for-an-efficient-integer-square-root-algorithm-for-arm-thumb2

http://www.finesse.demon.co.uk/steven/sqrt.html


问:
SPA Applications: AJAX to fetch templates or build from strings
I'm working on a large angular application and I'm currently using a factory class that builds HTML templates from strings.  We don't have to worry about mobile support for the application and I'm wondering from an architectural standpoint, which method would you rather implement and why: static HTML files that are fetched on request, or a class that builds the templates as strings?</p>

答:
I think this question will be highly opinion-driven, but since I have one, I'll share: I think it is much uglier to build the templates from strings. It is also objectively more difficult to work with, collaborate, etc.

I would keep the templates in appropriately-typed script tags with id's in a single HTML file, or if you must, split the template groupings up by purpose or module within your application. But I would highly discourage you from building them as strings.

For instance,

com.acme.app.assets.templates.account-templates.html

```<code><script type="text/x-mustache-template" id="account-login-template">
    ...
</script>

<script type="text/x-mustache-template" id="account-signup-template">
    ...
</script>
</code>```

com.acme.app.assets.templates.shop-templates.html

```<code><script type="text/x-mustache-template" id="shop-home-template">
    ...
</script>

<script type="text/x-mustache-template" id="shop-cart-template">
    ...
</script>
</code>```

Body:
I think this question will be highly opinion-driven, but since I have one, I'll share: I think it is much uglier to build the templates from strings. It is also objectively more difficult to work with, collaborate, etc.

I would keep the templates in appropriately-typed script tags with id's in a single HTML file, or if you must, split the template groupings up by purpose or module within your application. But I would highly discourage you from building them as strings.

For instance,

com.acme.app.assets.templates.account-templates.html

<script type="text/x-mustache-template" id="account-login-template">
    ...
</script>

<script type="text/x-mustache-template" id="account-signup-template">
    ...
</script>

com.acme.app.assets.templates.shop-templates.html

<script type="text/x-mustache-template" id="shop-home-template">
    ...
</script>

<script type="text/x-mustache-template" id="shop-cart-template">
    ...
</script>