问:
Extend, wrap, or both to add generics to a class that should have had them?
So I'm using a C# framework that has a great example of where generics would be useful, except they weren't used.  For simplicity's sake, we will say it was a list (I know C# has its own list), but instead of being List where I can specify the T, they made it List, resulting in nightmarish type checking throughout the code.

I want to fix this, but I can't edit the framework.

So I see three ways to fix this.

Extend, wrap, or both.

So the basic question is, which is the best way to add generics?

Is there a design pattern particulary for this?

Now, while I'm not sure wrapping or extending is better, if this was a simple case I would have gone with one of them and not even considered doing both.

But, the CustomList is used everywhere, and I only want to replace it bit by bit.

Extending allows me to use the TypedCustomList as a CustomList, so that if I change where CustomList are being created to instead by TypedCustomList, later in code's execution the code can still treat it like a CustomList.

But, I can't treat a CustomList object as a TypedCustomList (even if I ensure the generic type is correct for that given CustomList).  (Or am I missing how to do this, which would solve the problem?)

If a wrap it, I can now work with existing CustomLists, but I have to expose the internal CustomList object to pass it on to other code (for example, if I call a method expecting CustomList, I have to do instanceOfTypedCustomList._customList, I cannot pass instanceOfTypedCustomList).

If I wrap and extend it, I get take an existing CustomList and treat it like a TypedCustomList while still being able to treat my TypedCustomList as a CustomList.  But, as you can see below, the 'Both' option looks the worst.

Extending

```<code>public class TypedCustomList<T> : CustomList
{
  public TypedCustomList()
    :base()
  {
  }

  public T getElementAt(int i)
  {
    return (T) base.getElementAt(i);
  }

  public void addElement(T element)
  {
    base.addElement(element);
  }

  ...ect.
}
</code>```

Wrapping:

```<code>public class TypedCustomList<T>
{
  CustomList _customList { get; private set;}
  public TypedCustomList(CustomList cl)
  {
    _customList = cl;
  }

  public T getElementAt(int i)
  {
    return (T) _customList.getElementAt(i);
  }

  public void addElement(T element)
  {
    _customList.addElement(element);
  }

  ...ect.
}
</code>```

Both:

```<code>public class TypedCustomList<T> : CustomList
{
  private CustomList _customList;

  public TypedCustomList()
    :base()
  {
    _customList = null;
  }

  public TypedCustomList(CustomList cl)
  {
    _customList = cl;
  }

  public T getElementAt(int i)
  {
    if(_customList == null)
    {
      return (T) base.getElementAt(i);
    }
    else
    {
      return (T) _customList.getElementAt(i);
    }
  }

  public void addElement(T element)
  {
    if(_customList == null)
    {
      base.addElement(element);
    }
    else
    {
      _customList.addElement(element);
    }
  }

  ...ect.
}
</code>```

P.S.

More background which may be relevant to the problem.

There is one class that has a CustomList that is used all over the application, with different parts of the application with each instance having different object types (over a dozen in total).  I want to eventually have this class have a unique TypedCustomList for every use.  But until I can be sure that all references to it's CustomList are gone, I wanted to add some error handling.  So I was adding something like the following:

```<code>public ClassThatUsesCustomList
{
...
private CusotmList _list;
private TypedCustomList<SomeObject> _SomeObjectCustomList;

public CustomList list
{
    get
    {
      //Already existing code
      if(_list == null)
      {
        _list = new CustomList();
      }

      //My code
      catchMissedGetSet(_list);

      return _list;
    }
    set
    {
      catchMissedGetSet(value);
      _list = value;
    }
}

public SomeObjectCustomList
{
  get
  {
    if(_SomeObjectCustomList == null)
    {
      _SomeObjectCustomList = new TypedCustomList<SomeObject>();
    }

    return _SomeObjectCustomList;
  }
  set
  {
    _SomeObjectCustomList = value;
  }
}

private void catchMissedGetSet(CustomList cl)
{
  bool findMissedSpots = true;

  if(cl == null || cl.Count == 0 || cl[0] is SomeObject)
  {
    SomeObjectCustomList = new SomeObjectCustomList(cl);  //Using wrapping.
    if(findMissedSpots && System.Diagnostics.Debugger.IsAttached)
    {
      System.Diagnostics.Debugger.Break();
      //Hey, you missed a place.  Use step out to find it.
    }
  }
}

...
}
</code>```

I did this to catch any spots I missed and to avoid any bugs.  It requires me wrapping it (as far as I can tell).

答:
The answer is wrapping, but it is considerably more work than implied here. I see why you are trying to do this though, because after a certain size of the code base it indeed can be a nightmare to work with typecasting every time you call a library function. Subclassing CustomList is not advisable, as it would expose all the functions that return or expect an object. Having a public property as in the second example is, for the same reason, also unadvisable. I believe you are facing a situation similar to the following:

```<code>interface Producer
{
  CustomList produce();
}

interface Consumer
{
  void consume(CustomList list);
}
</code>```

This is how I would wrap it:

```<code>public class TypedCustomList<T>
{
  private readonly CustomList _customList;
  internal CustomList customList
  {
    get { return _customList; }
  }

  internal TypedCustomList(CustomList cl)
  {
    _customList = cl;
  }

  public T getElementAt(int i)
  {
    return (T) _customList.getElementAt(i);
  }

  public void addElement(T element)
  {
    _customList.addElement(element);
  }

  ... ect.
}
</code>```

The producer:

```<code>class TypedProducer<T>
{
  private readonly Producer producer = new Producer();
  public TypedCustomList<T> produce()
  {
    return new TypedCustomList<T>(producer.produce())
  }
}
</code>```

The consumer:

```<code>class TypedConsumer<T>
{
  private readonly Consumer consumer = new Consumer();
  public void consume(TypedCustomList<T> list)
  {
    consumer.consume(list.customList);
  }
}
</code>```

You will need to put the wrapping classes to their own assembly, so that they hide the internal parts.

I can safely suggest you this solution, which I beleive generally considered a good practice. You will need to wrap the subset of the library you are using in this manner.

Body:
The answer is wrapping, but it is considerably more work than implied here. I see why you are trying to do this though, because after a certain size of the code base it indeed can be a nightmare to work with typecasting every time you call a library function. Subclassing CustomList is not advisable, as it would expose all the functions that return or expect an object. Having a public property as in the second example is, for the same reason, also unadvisable. I believe you are facing a situation similar to the following:

interface Producer
{
  CustomList produce();
}

interface Consumer
{
  void consume(CustomList list);
}

This is how I would wrap it:

public class TypedCustomList<T>
{
  private readonly CustomList _customList;
  internal CustomList customList
  {
    get { return _customList; }
  }

  internal TypedCustomList(CustomList cl)
  {
    _customList = cl;
  }

  public T getElementAt(int i)
  {
    return (T) _customList.getElementAt(i);
  }

  public void addElement(T element)
  {
    _customList.addElement(element);
  }

  ... ect.
}

The producer:

class TypedProducer<T>
{
  private readonly Producer producer = new Producer();
  public TypedCustomList<T> produce()
  {
    return new TypedCustomList<T>(producer.produce())
  }
}

The consumer:

class TypedConsumer<T>
{
  private readonly Consumer consumer = new Consumer();
  public void consume(TypedCustomList<T> list)
  {
    consumer.consume(list.customList);
  }
}

You will need to put the wrapping classes to their own assembly, so that they hide the internal parts.

I can safely suggest you this solution, which I beleive generally considered a good practice. You will need to wrap the subset of the library you are using in this manner.


问:
Is there any material difference between queries joined by WHERE clauses, and queries using an actual JOIN?
In Learn SQL the Hard Way (exercise six), the author presents the following query:

```<code>SELECT pet.id, pet.name, pet.age, pet.dead
    FROM pet, person_pet, person
    WHERE
    pet.id = person_pet.pet_id AND
    person_pet.person_id = person.id AND
    person.first_name = "Zed";
</code>```

and then goes on to say that:

There are actually other ways to get these kinds of queries to work called "joins". I'm avoiding those concepts for now because they are insanely confusing. Just stick to this way of joining tables for now and ignore people who try to tell [you] that this is somehow slower or "low class".

Is that true? Why or why not?

答: There shouldn't be, the query parser should generate an equivalent internal representation for equivalent queries regardless of how they're written. The author's just using pre-SQL-92 syntax, which is why he mentions it might be seen as "old fashioned" or "low class". Internally, the parser and optimizer should generate the same query plan.</p>

ContentLicense: CC BY-SA 3.0


答:
With the author's approach, teaching OUTER JOINs is going to much more difficult. The ON clause in INNER JOIN was never mind-blowing to me like a lot of other stuff. Maybe it is because I never learned the old way. I'd like to think there is a reason we got rid of it and it wasn't to be smug and call this method low class.

It's true in the very narrow scenario the author has created:

Such an entry level of SQL that using ON is complex

Only considering JOIN/INNER JOIN and not any OUTER JOINs

The isolated coder who doesn't have to read other's code nor have any people with experience with the ON usage reading/using their code.

Not requiring complex querying with lots of: tables, if's, but's and or's.

As part of a teaching progression, I think it is easier to break it down and have a natural progression:

```<code>Select * from table
select this, something, that from table
select this from table where that = 'this'
select this from table join anothertable on this.id = that.thisid
</code>```

The concepts of joining and filtering tables are not really the same. Learning the correct syntax now will have more carry-over when you learn OUTER JOINS unless the author intends on teaching outdated/deprecated things like:  *= or =*.

Title: Is there any material difference between queries joined by WHERE clauses, and queries using an actual JOIN?

Body:
In Learn SQL the Hard Way (exercise six), the author presents the following query:

```<code>SELECT pet.id, pet.name, pet.age, pet.dead
    FROM pet, person_pet, person
    WHERE
    pet.id = person_pet.pet_id AND
    person_pet.person_id = person.id AND
    person.first_name = "Zed";
</code>```

and then goes on to say that:

There are actually other ways to get these kinds of queries to work called "joins". I'm avoiding those concepts for now because they are insanely confusing. Just stick to this way of joining tables for now and ignore people who try to tell [you] that this is somehow slower or "low class".

Is that true? Why or why not?

Body:
With the author's approach, teaching OUTER JOINs is going to much more difficult. The ON clause in INNER JOIN was never mind-blowing to me like a lot of other stuff. Maybe it is because I never learned the old way. I'd like to think there is a reason we got rid of it and it wasn't to be smug and call this method low class.

It's true in the very narrow scenario the author has created:

Such an entry level of SQL that using ON is complex

Only considering JOIN/INNER JOIN and not any OUTER JOINs

The isolated coder who doesn't have to read other's code nor have any people with experience with the ON usage reading/using their code.

Not requiring complex querying with lots of: tables, if's, but's and or's.

As part of a teaching progression, I think it is easier to break it down and have a natural progression:

Select * from table
select this, something, that from table
select this from table where that = 'this'
select this from table join anothertable on this.id = that.thisid

The concepts of joining and filtering tables are not really the same. Learning the correct syntax now will have more carry-over when you learn OUTER JOINS unless the author intends on teaching outdated/deprecated things like:  *= or =*.


问:
Saving to file before storing into a database in a REST service
A mobile back-end I am building should receive a larger amount of data (some sensor recordings) from an Android phone. The phone does not have much use of it so it was most efficient to store the data into plain files (SQLite can get quite slow with larger amounts). Now when we upload the data to a REST service backed with a distributed database, we have another issue. Storing to it takes some time, since it is really a lot. I thought of uploading the file to the web service as fast as possible, leave the phone alone, cache the file somewhere on the server and then some long-running workers will pick the data up and chunk it into databases. We have some other mechanisms to verify the data is properly stored and so on, but that is not important.

I would like to know is the REST->file->database approach valid? My concern is where to store the file? Disk, some in-memory database, a cache? Web servers fail (we can request a re-upload, but I would rather mitigate the risk earlier), or the server can get cluttered. I'm afraid the local storage on the web servers does not scale really well, if we have multiple workers and servers.

Thank you in advance.

答: It's perfectly valid, and is usually done in situations like the one you have. Others have suggested message queues, which are nice but they'll either take up memory or wind up writing the data to a backing store anyway, so now you've got another layer of software doing what you could do directly. That said, it may be easier and cleaner to use a message queue's API instead of rolling your own solution; it all depends on your environment and performance requirements. I would imagine the message queue would provide a cleaner separation of concerns, but you'll have to determine for yourself if there's going to be a performance hit.</p>


问:
Implementing Continuous Integration with a volatile hierarchy of library dependencies
Recently my company setup a build server using Bamboo and a private Nuget Feed which is populated by the successful builds being deployed from the build server.

There is a hierarchy of projects under heavy development setup for use in bamboo with a fairly simple, linear dependency graph. Before being setup on bamboo all devs had to clone the repository being worked on and all of its dependencies and make a new branch in each project. As almost all changes at this point are breaking changes, this was a bit of headache.

So now with the new tool of Bamboo in the mix, as a dev, what would my workflow look like if I needed to make some changes in Project A that will also require changes in Project C where Project B and C is dependent on A and C is also dependent on B.

```<code>  A
 | |
 | B
 | |
  C
</code>```

I want to make certain all tests still pass in Project B after my changes to project A before moving on to make the changes in Project C. Are there any resources that help explain what developers workflow should be at this point? It seems he can either pull down, setup the dependencies manually and test B. Or he can setup special builds on Bamboo to handle the this intermediate state of the projects and then download the resulting nuget packages. I feel uneasy with that solution because it requires a deeper understanding by the devs of Bamboo and the build server (And I don't understand it all well at this point, to explain it all to them).

This problem compounds the more dependencies there become on a lower level library. Are there any resources that explain the accepted approach to this problem?

答:
Use a layered architecture. Place each project in a layer, where each project is dependent only on lower layer projects, so no lower layer project depends on a higher layer project. Without layers, the dependencies become unmanageable as the number of projects multiplies.

Once your architecture is layers, you test the lowest layers first, then the layer above, etc. This design has proven itself useful for decades.


问:
How do you prioritize initial sprints to maximise the chance of catching architecture errors early?
I've worked on several projects that have used agile successfully as a means of providing continuous improvement on an already mature piece of software. But I've found it's much harder to be "agile" when pre-planning something. An element of waterfall is necessary to produce initial functional specifications and a sensible architecture, as per this question: How do you explain to an "agile" team that they still need to plan the software they write?

However, you still want to be as fast, as light and most of all as flexible as possible. One of the big dangers in traditional software design is misunderstandings, resulting in major architectural changes that are only caught late in the process.

I have recently joined a project which had woefully insufficient planning and is in the most horrendous mess. While salvaging what I can, I'm left wondering what previous developers could have done (besides some planning) to catch the huge architectural problems in the system at an early stage.

If we presume a moderate amount of pre-project planning, how can I best allocate work in initial sprints to catch the (probably inevitable) architectural issues in the solution as early as possible?

EDIT: After reading the answers, and some suggested articles, I feel I made need a bit of clarity in the question. I understand that Agile requires some upfront design, but that it ought to be kept to a minimum, and it needs to be done with an eye to flexibility.

What I'm trying to discover are whether there are any tricks, tips or techniques to ensure that we correctly identify the parts of the project that need the most rigidity, prototype and iterate them first, and catch problems there as early as possible?

答:
Grooming and spikes is the way we addressed this sort of thing, not always successfully I might add, all depends on how (of even if) the stories are written. We also have a dedicated architect, well some time from them.

So in grooming people familiar with the backlog and the proposed architecture should be looking at how a 'new' story impacts what has or will be done. Think of it as a sort of meta dependency.

The other thing we did when there was uncertainty about whether there was an impact or the best way to ameliorate it was a Spike Story. Basically this was a timeboxed proof of concept story as in all the non-trivial and therefore most problematic cases, a lot of the problems don't surface until a developer actually has a go at it.


问:
How is encoding handled correctly during copy-paste between programs?
Suppose

a program A opens a text file A using encoding A to decode the file, and

a program B opens a text file B using encoding B.

When we copy some text from file B in program B to file A in program A using mouse selection, ctrl+c and then ctrl+v, I heard that the GUI of the OS (e.g. X window system in Linux, and I guess something similar in Windows) handles the transfer between the programs.

For example, program A can be any program which accepts text-paste, such as a text editor (e.g. emacs, gedit) or any other program, and program B can be any program which accepts text-copy, such as a text viewer (e.g. a web browser such as firefox, chrome), a text editor, or any other program.

Question:

Note that encoding A and encoding B can be different. What should happen under the hook of ctrl+c and ctrl+v so that the pasted text in file A in program A can be consistent with the original text in file A?

When hitting ctrl+c in file B and program B, is the binary content of the copied text in the "clipboard" of GUI of the OS the same as the binary content of the original text in file B? I.e. is the encoding for the copied text in the "clipboard" still encoding B? What program should determine the encoding of the copied text in the "clipboard"?

When hitting ctrl+v in file A and program A, is the binary content of the pasted text in file A the same as the binary content of the original text in file B? I.e. in the new file A, the original text should be decoded with encoding A, and the pasted text should be decoded with encoding B? What program should determine the encoding of the pasted text in file A?

答:
The simplest solution is to use a standard encoding. For example, in Windows, one standard encoding is "unicode", which refers to UTF-16, the encoding recommended for Windows applications. The programs which accept clipboard input have to be able to interpret the encoding. This is all documented on MSDN.

Unicode (Windows)
Standard Clipboard Formats


问:
How would you know if you've written readable and easily maintainable code?
How would one know if the code one has created is easily readable, understandable, and maintainable? Of course from the author's point of view, the code is readable and maintainable, because the author wrote it and edited it, to begin with. However, there must be an objective and quantifiable standard by which our profession can measure code.

These goals are met when one may do the following with the code without the expert advice of the original author:

It is possible to read the code and understand at a basic level the flow of logic.

It is possible to understand at a deeper level what the code is doing to include inputs, outputs, and algorithms.

Other developers can make meaningful changes to the original code such as bug fixes or refactoring.

One can write new code such as a class or module that leverages the original code.

How do we quantify or measure code quality so that we know it readable, understandable, and maintainable?

答:
The most maintainable code is code that isn't there. So instead of adding to the LOC count, new code that 'reduces' the LOC count (even if slightly less maintainable when viewed in isolation) could make the total code-base more maintainable simply by reducing its size. Thus the primary rule for maintainable code:

maximize DRY.

Secondly, there is nothing worse for maintainability than hidden dependencies. So for rule number 2:

Make all of your dependencies explicit.

Thirdly, not all programmers are equally skilled at maintaining or writing using specific more advanced techniques language features or idioms. Dumbing down the whole code base will get you a large code base that due to its size is hard to maintain. Allowing advanced techniques features and idioms throughout the code will make all of the code maintainable only by senior developers what also is bad. The key to maintainability is skill level based layering For example:

Cross-project libraries: senior devs, full back of tricks code/idiom/techniques
Project specific libraries and system backend: medior developers, avoid most advanced and hard to explain stuff. Seniors will go trough this code looking for DRY improvement opportunities.

Front-end: junior devs, use a strict style guide and set of techniques language constructs and idioms to avoid. Medior devs will go trough this code looking for DRY opportunities and hidden business logic.

So for rule number 3:

Layer your code by developer skill level and write maintainable code accordingly.

I


答:
how can I best allocate work in initial sprints to catch the (probably inevitable) architectural issues in the solution as early as possible?

By not mistaking quality of planning with quantity of planning.

The entire point of agile is that planning is inadequate. Business people don't really know what they need until they can have customers try it out. Technical people don't really know what is going to work until they can run it and measure it.

So the best allocation of work is to get something working ASAP. Sure, you should spend some time in a room discussing what business thinks they need. And you should spend some time with a whiteboard discussing the relative merits of potential architectures. That will take you a day. Maybe.

Then take your best guess and prototype it out. See what works. See what sucks. Show the business and see what you mis-communicated. Then iterate. It sounds as though your predecessors didn't iterate. They didn't stop and evaluate how things were going and course correct as necessary. They just tacked onto the existing mess making it worse.

Title: How do you prioritize initial sprints to maximise the chance of catching architecture errors early?

Body:
I've worked on several projects that have used agile successfully as a means of providing continuous improvement on an already mature piece of software. But I've found it's much harder to be "agile" when pre-planning something. An element of waterfall is necessary to produce initial functional specifications and a sensible architecture, as per this question: How do you explain to an "agile" team that they still need to plan the software they write?

However, you still want to be as fast, as light and most of all as flexible as possible. One of the big dangers in traditional software design is misunderstandings, resulting in major architectural changes that are only caught late in the process.

I have recently joined a project which had woefully insufficient planning and is in the most horrendous mess. While salvaging what I can, I'm left wondering what previous developers could have done (besides some planning) to catch the huge architectural problems in the system at an early stage.

If we presume a moderate amount of pre-project planning, how can I best allocate work in initial sprints to catch the (probably inevitable) architectural issues in the solution as early as possible?

EDIT: After reading the answers, and some suggested articles, I feel I made need a bit of clarity in the question. I understand that Agile requires some upfront design, but that it ought to be kept to a minimum, and it needs to be done with an eye to flexibility.

What I'm trying to discover are whether there are any tricks, tips or techniques to ensure that we correctly identify the parts of the project that need the most rigidity, prototype and iterate them first, and catch problems there as early as possible?


问:
Difference between server Jobs and Workers?
I am trying to understand the difference between server workers and server jobs. Google has not been very helpful because the keyword "jobs" is being construed as an employment term... I have yet to find an article answering my question. :/

Would someone please elaborate on the distinction between server jobs and workers?

答: The term "job" generally refers to a specific task that needs to be performed, that will take some time to perform, where the amount of time needed is great enough, that someone decide to turn it into a "job." A "worker" is an object that performs some task. It's task might be to execute a job. Generally, a worker performs a task, finishes, then becomes available for another task. But this terminology is all vague.</p>


问:
Turn on gzip on nginx, upstream (nodejs) or both?
I have an application running behind a proxy, both on the same machine. Which approach is more suited regarding compression, while preserving reasonable performance.

turn on compression at the application level (which happens to be in nodejs)

leave it out to the proxy (which is nginx)

答:
While this is probably a better question for ServerFault, I believe there is a clear answer: do compression on nginx.

There are a couple of reasons for this:

Compression is moderately CPU-intensive, and Node is single-threaded. Therefore, compression in node will potentially reduce the total number of requests a single server is able to handle.

You will almost certainly use nginx to serve static assets such as JavaScript, CSS, images, and static HTML. Which you will want to compress. So why not compress everything that goes through nginx, including forwarded traffic?

As for both: that's just wasted CPU.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
It should be noted that no ethically-trained software engineer would ever consent to write a DestroyBaghdad procedure. Basic professional ethics would instead require him to write a DestroyCity procedure, to which Baghdad could be given as a parameter.

Nathaniel Borenstein

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5


答: Presuming your nginx server fronting node is proximate to said node server you get just about nothing out of using things like compression between the two. You've got plenty of bandwidth between the two, why waste CPU saving it? Moreover, if you are doing any rewrites in nginx it gets ugly as nginx has to unzip the contents, replace, and re-zip. If it lets ya do it at all.</p>

Title: Turn on gzip on nginx, upstream (nodejs) or both?

Body:
I have an application running behind a proxy, both on the same machine. Which approach is more suited regarding compression, while preserving reasonable performance.

turn on compression at the application level (which happens to be in nodejs)

leave it out to the proxy (which is nginx)


问:
Where should I put functions that are not related to a class?
I am working on a C++ project where I have a bunch of math functions that I initially wrote to use as part of a class. As I've been writing more code, though, I've realized I need these math functions everywhere.

Where is the best place to put them? Let's say I have this:

```<code>class A{
    public:
        int math_function1(int);
        ...
}
</code>```

And when I write another class, I can't (or at leat I don't know how to) use that math_function1 in that other class. Plus, I've realized some of this functions are not truly related to class A. They seemed to be at the beginning, but now I can see how they're just math functions.

What is good practice in this situation? Right now I've been copy-pasting them into the new classes, which I'm sure is the worst practice.

答:
You might want to put it in a template function as to make it available for different types of integers and/or floats:

```<code>template <typename T>
T math_function1(T){
 ..
}
</code>```

You could than also create neat custom types that represent for example huge numbers or complex numbers by overloading relevant operators for your custom type to make them template friendly.

Body:
You might want to put it in a template function as to make it available for different types of integers and/or floats:

template <typename T>
T math_function1(T){
 ..
}

You could than also create neat custom types that represent for example huge numbers or complex numbers by overloading relevant operators for your custom type to make them template friendly.


答:
I learned SQL this way, including the *= syntax for outer joins. To me, it was very intuitive since all relations were given equal precedence and did a better job of setting up queries as a series of questions: What do you want? Where do you want them from? Which ones do you want?

By doing join syntax, it disrupts the thought process towards the relations more strongly. And personally, I find the code far less readable with the tables and relations intermingled.

At least in MSSQL, there's no meaningful difference in the performance of the queries, assuming you use the same join ordering. That said, there is one clear, huge issue with learning (and using) SQL this way. If you forget one of your relations, you would get unexpected cross-products. Which on a database of any non-trivial size is prohibitively expensive (and dangerous for non-selects!). It's much harder to forget a relation when using the join style syntax.


答:
When I hear this argument against Agile versus waterfall, it sounds like they envision the history as,

"We create these great specifications that the clients love because
  all of our projects are always on time and budget, but if only we could be lazy and
  accomplish the same thing without having to write requirements."

That's not the way I understand what was happening. I also don't fall under the trap of thinking of things as all or nothing. There is nothing wrong with writing requirements up front, but that doesn't mean that ALL requirements have to be written in advance of any programming. That's the biggest difference.

Even if you truly think you can completely write out all of the specifications for a complex project, don't do it if it is going to take a long period of time. If you talk to a client for weeks on end, go through a lengthy contract negotiation process, build the entire application and return months later with a finished project, don't be surprised when the client tells you that's not what they expected and more likely it doesn't really work the way you thought it would.

I worked as head of technical support and after months of not seeing our programmers during the building of yet another version of our application completely from scratch (much better architecture this time - yeah right) I couldn't get it to install on my PC. It broke every step of the way. I was so pissed-off, I made them stay all night and keep fixing the thing until I could actually see the app.

They spent so much time writing specs, they didn't have time for the much bally-hooed pseudo-code phase of the project. OK, maybe taking to much time to write specs can be a good thing.


答:
The author presents a simple case where either the old or new syntax can be used.  I do not agree on his/her statement that joins are insanely confusing, because joining tables is a fundamental SQL query concept.  So, maybe the author should have spent some time prior in explaining how JOINS work before uttering an opinionated statement as well as doing a multiple table query example.

One should use the newer syntax.  The main argument for this is that your query will have:

Select Criteria

Join Criteria

Filter Criteria

Using the old style, the join and filter criteria are combined which in more complex cases can lead to confusion.

Also, one can get a Cartesian product by forgetting a join criteria in the filter clause:

```<code> person_pet.person_id = person.id
</code>```

using the older syntax.

Using the newer syntax also specifies how the join should occur which is important on whether you want an INNER, LEFT OUTER, etc. so it is more explicit in regards to JOIN syntax which IMHO increases readability for those unfamiliar with joining tables.

Body:
The author presents a simple case where either the old or new syntax can be used.  I do not agree on his/her statement that joins are insanely confusing, because joining tables is a fundamental SQL query concept.  So, maybe the author should have spent some time prior in explaining how JOINS work before uttering an opinionated statement as well as doing a multiple table query example.

One should use the newer syntax.  The main argument for this is that your query will have:

Select Criteria

Join Criteria

Filter Criteria

Using the old style, the join and filter criteria are combined which in more complex cases can lead to confusion.

Also, one can get a Cartesian product by forgetting a join criteria in the filter clause:

 person_pet.person_id = person.id

using the older syntax.

Using the newer syntax also specifies how the join should occur which is important on whether you want an INNER, LEFT OUTER, etc. so it is more explicit in regards to JOIN syntax which IMHO increases readability for those unfamiliar with joining tables.


问:
Is there a pattern for a more "natural" way of adding items to collections?
I think the most common way of adding something to a collection is to use some kind of Add method that a collection provides:

```<code>class Item {}
var items = new List<Item>();
items.Add(new Item());
</code>```

and there is actually nothing unusual about that.

I wonder however why don't we do it this way:

```<code>var item = new Item();
item.AddTo(items);
</code>```

it seems to be somehow more natural then the first method. This would have the andvantange that when the Item class has a property like Parent:

```<code>class Item
{
    public object Parent { get; private set; }
}
</code>```

you can make the setter private. In this case of course you cannot use an extension method.

But perhaps I'm wrong and I've just never seen this pattern before because it's so uncommon? Do you know whether there is any such pattern?

In C# an extension method would be useful for that

```<code>public static T AddTo(this T item, IList<T> list)
{
    list.Add(item);
    return item;
}
</code>```

How about other languages? I guess in most of them the Item class had to provide a let's call it ICollectionItem interface.

Update-1

I've been thinking about it a little bit more and this pattern would be really usefull for example if you don't want an item to be added to multiple collections.

test ICollectable interface:

```<code>interface ICollectable<T>
{
    // Gets a value indicating whether the item can be in multiple collections.
    bool CanBeInMultipleCollections { get; }

    // Gets a list of item's owners.
    List<ICollection<T>> Owners { get; }

    // Adds the item to a collection.
    ICollectable<T> AddTo(ICollection<T> collection);

    // Removes the item from a collection.
    ICollectable<T> RemoveFrom(ICollection<T> collection);

    // Checks if the item is in a collection.
    bool IsIn(ICollection<T> collection);
}
</code>```

and a sample implementation:

```<code>class NodeList : List<NodeList>, ICollectable<NodeList>
{
    #region ICollectable implementation.

    List<ICollection<NodeList>> owners = new List<ICollection<NodeList>>();

    public bool CanBeInMultipleCollections
    {
        get { return false; }
    }

    public ICollectable<NodeList> AddTo(ICollection<NodeList> collection)
    {
        if (IsIn(collection))
        {
            throw new InvalidOperationException("Item already added.");
        }

        if (!CanBeInMultipleCollections)
        {
            bool isInAnotherCollection = owners.Count > 0;
            if (isInAnotherCollection)
            {
                throw new InvalidOperationException("Item is already in another collection.");
            }
        }
        collection.Add(this);
        owners.Add(collection);
        return this;
    }

    public ICollectable<NodeList> RemoveFrom(ICollection<NodeList> collection)
    {
        owners.Remove(collection);
        collection.Remove(this);
        return this;
    }

    public List<ICollection<NodeList>> Owners
    {
        get { return owners; }
    }

    public bool IsIn(ICollection<NodeList> collection)
    {
        return collection.Contains(this);
    }

    #endregion
}
</code>```

usage:

```<code>var rootNodeList1 = new NodeList();
var rootNodeList2 = new NodeList();

var subNodeList4 = new NodeList().AddTo(rootNodeList1);

// Let's move it to the other root node:
subNodeList4.RemoveFrom(rootNodeList1).AddTo(rootNodeList2);

// Let's try to add it to the first root node again...
// and it will throw an exception because it can be in only one collection at the same time.
subNodeList4.AddTo(rootNodeList1);
</code>```

答:
Although there is no such pattern for the general case (as explained by others), the context in which a similar pattern does have its merits is a bidirectional one-to-many association in ORM.

In this context you'd have two entities, let's say Parent and Child.  A parent can have many children, but each child belongs to one parent. If the application requires the association to be navigable from both ends (bidirectional), you would have a List<Child> children in the parent class and a Parent parent in the child class.

The association should always be reciprocal of course. ORM solutions typically enforce this on entities that they load. But when the application is manipulating an entity (either persisted or new), it has to enforce the same rules. In my experience, you'd most often find a Parent.addChild(child) method that invokes Child.setParent(parent), which is not for public use. In the latter you'd typically find the same checks as you have implemented in your example. The other route can however also be implemented: Child.addTo(parent) which calls Parent.addChild(child). Which route is best differs from situation to situation.


问:
How should nodes in a chain be connected?
Suppose you were building a system that receives data on one end and sends filtered data on the other end.

The system is a chain of nodes, each receiving data from the node before and sending filtered data to the next one.

You have two approaches to choose from regarding the way the nodes would be connected:

A- Each node holds a reference to the next one through a particular interface.

B- Each node exposes an event, and the next node in line would be registered to that event, notified when that event is fired (when the previous node in line sends data).

In both cases, an outside entity connects the nodes to one another; they have no direct knowledge of each other.

Currently, I think events may be better because this way, a node doesn't care what the next node does; only what it has to send it. Thus enabling us to insert nodes in the middle easily.

There is a possibility nodes would need to be inserted in the middle, in the future.

Taking that into account, which approach would you prefer, and why? What are the pros and cons of each approach?

答:
It depends on the layering of the design. If "nodes" are all in the same layer conceptually, then I would prefer references over events, especially read-only references. References are simpler and easier to trace with static analysis tools:

References can be read-only fields, whereas event fields are always mutable.

A reference field refers to a single object instance, whereas event fields contain a linked list of delegates.

A reference field is strongly typed. An event field is weakly typed, as any method can be hooked to the event. Stronger typing can reduce errors, as they occur at compile time, and makes it easier to browse or analyze the compiler output using analysis tools.

If some nodes are in a lower-level layer, I would use events for communication from the lower to the upper layer, in order to avoid references from a lower to a higher layer.

Your question is vague, and there is not enough information to make specific recommendations.


问:
What algorithm can be used for a more complex version of the bin packing problem?
I'm currently developing a plugin for World of Warcraft in LUA to help optimize a recently introduced part of the game, namely Garrison missions.

A Warcraft Garrison (basically a player fortress) has a place where you can assign your followers to go on an mission for you. If these missions succeed, your followers get some experience and you get a small reward, ranging from a bit of money to powerful equipment for you or your followers. A garrison has 20-25 followers and has about 25-30 missions to choose from per day.

A mission has the following attributes:

A level between 90 and 100, inclusive.

(for level 100 missions) An equipment level between 615 and 645, in steps of 15.

between 1 and 3 slots to send followers with.

between 0 and 6 mission threats. There are about 10 categories of threats, the names of which are irrelevant. What is relevant is that a follower can have 1 or 2 abilities that can counter these threats. A mission can have the same threat twice.

A zone type where this mission occurs.

an enemy type which this mission is fighting against.

A duration.

A follower has the following attributes:

the race of the follower.

A level between 90 and 100, inclusive. followers of equal or higher level contribute more to mission success. A follower that is one level beneath the level of the mission is less effective, but still has an effect. A follower 2 or more levels below the level of the mission does not have an influence on the mission success and cannot counter any threats.

(Starting at level 100) An equipment level between 600 and 655, inclusive. Like normal level, followers of equal or higher equipment level are more effective.

1 or 2 abilities that are counters for mission threats. A countered threat increases the chance at success. if all threats are countered with followers of equal of higher level, a mission has a 100% chance of success. A follower can have 2 abilities that counter the same threat.

1, 2 or 3 traits that can give minor chance of success bonuses in specific mission conditions. These don't give as much bonus chance as a full counter, but are useful to optimize for. A trait can counter a zone, a duration or an enemy type. They can also give a bonus for having a specific type of follower on the same mission, or even give an always-on chance of success bonus.

What I understand from some brief chatting with Gamedev.SE, this is basically the Bin Packing problem, with the missions being the packages and the followers being the bins. However, in this case, the bins can combine and are different sizes.

The algorithm I'm looking for aims to do the following in the least amount of time:

Maximize the amount of missions with 100% chance of success;

Maximize the individual chance of success of each mission that doesn't have 100% chance;

I could probably bruteforce it, but I'm hoping for a somewhat more sophisticated solution.

What algorithm should I use for this?

答:
The thing about these sorts of problems is the solution doesn't have to be perfect.  Often the difference between a reasonable heuristic and the optimal solution is very minimal.

So just start out with a greedy algorithm.  Sort the missions by best payoff first, and assign the best possible set of followers to the first mission, then the best possible set of remaining followers to the second mission, and so on.  By "best" I mean neither overmatched nor undermatched.  This is basically how most players would make the assignments manually.

Then backtrack and assign the second best set to the first mission and see if that improves the overall score, then the second best set to the second mission, and so on.  Then the second best set to different combinations of two missions, then three missions, and so on.  Then repeat with the third best set.  Basically a breadth-first search of possible assignments.

What you should find is that after only a few layers deep in the search tree, the improvements start to get smaller and smaller.  You cut it off after exceeding a certain threshold in absolute score, after falling below a certain threshold in difference in score between iterations, or after a certain time limit.


答:
I believe the concept of "Sprint 0" which might typically be a longer initial sprint covers this, doesn't it?  Here's an article (What is Sprint Zero?) that I think describes what should be done in Sprint 0, including sufficient initial design to facilitate emergent design in subsequent sprints.

The article describes some of the common misperceptions and 'malpractices' of an 'initial sprint' to help new development projects get off the ground.  Both the article and the comments below are useful to read.  I can quite understand the challenge of deciding what the initial user stories should be when starting development of a large/ complex app or product.  Given that many (most?) teams come from some waterfall-ish background, doing away with BDUF and a lot of planning up-front can be scary!

I found the article's 3 points of a working definition of a Sprint 0 useful - one, that it should be used to create the 'basic skeleton and plumbing' for the project to facilitate future sprint planning; two, doing a minimum design up front to enable emergent design possible as the project proceeds; and three, ensuring that even this sprint delivers value in terms of some completed stories, some of which include the product skeleton/ framework.

Hope this helps!


问:
Updating particular properties of EF objects every X amount of days in MVC
I'm building an MVC ASP.NET IMDb-like website which presents various information about movies to users, relying on 3rd party APIs to (initially) fetch movie info.

The IDs representing each movie on the website are identical to IMDb's (ID tt1234567 points to the same movie on both websites).

The way movie info are fetched (and subsequently stored on SQL server) is as follows:

User requests movie with id tt1234567

MVC checks if movie with id tt1234567 exists in the database.

If not, it queries external APIs to fetch movie information and stores it in the database.

If yes, it fetches the information directly from the database.

This works fine and I'm at the point where I'm implementing caching. There are some particular columns for each row in the Movie table which change every certain amount of days (e.g. overall rating and number of votes for that movie in IMDb). As such, I need to implement a function where relevant columns of the row are updated after certain amount of time (e.g. every 10 days).

What would be the correct approach to do this? Should I implement a scheduled task which runs every 10 days and updates the needed columns in the DB, or should I somehow add caching into the mix?

答:
Yes, a scheduled task could be one way of retrieving and updating your data.

You should consider setting up a windows service, quartz.net or hangfire.io are all alternatives for creating schedule based job execution.


问:
What is the best way to structure and name files which contain generic classes with the same name?
In my current project I have come across the requirement to create generic classes with the same name, but different numbers of generic parameters.  For example:

```<code>MyClass<T1>
MyClass<T1, T2>
MyClass<T1, T2, T3>
</code>```

Given that I want all of these in the same namespace, I am confused as to how to structure and name my classes and files?

If we follow the idea that we should have classes limited to one per file and that files should be in a folder structure that represents namespace hierarchy and that the name of the file should match the name of the class, how do I deal with this situation?

What I am really asking here is what should I name the file that contains MyClass<T1>, and what should I name the file that contains MyClass<T1, T2>?  I am not asking what the names of the type parameters should be.

答:
```<code>MyGenericClass`1.cs
MyGenericClass`2.cs
MyGenericClass`3.cs
</code>```

And so on, where the number after the backtick is the number of generic type parameters.  This convention is used by Microsoft.

Alternatively, you can use something like

```<code>MyGenericCollectionClass[TKey, TValue].cs
</code>```

which preserves not only the number of generic type parameters, but also their specific names.  Granted, it doesn't preserve the angle brackets, but we can't have everything in life we want, can we?

Body:
MyGenericClass`1.cs
MyGenericClass`2.cs
MyGenericClass`3.cs

And so on, where the number after the backtick is the number of generic type parameters.  This convention is used by Microsoft.

Alternatively, you can use something like

MyGenericCollectionClass[TKey, TValue].cs

which preserves not only the number of generic type parameters, but also their specific names.  Granted, it doesn't preserve the angle brackets, but we can't have everything in life we want, can we?


答:
In the case of Tuple and Action that Pete has mentioned, Microsoft themselves use a single file - see Tuple.cs and Action.cs.

I think it partly depends on whether or not the functionality for all the classes is basically the same. Personally I dislike lumping classes into a single file, but this might be an exception. In the source code where I work I added an autogenerated (using T4) NamedTuple class which acts in the same way as Tuple, but with a string name as the first argument into the constructor.

To answer your question, if you don't want to use a single file, perhaps use MyClass_1.cs for MyClass<T1>, MyClass_2.cs for MyClass<T1, T2>, etc.

Neither option is ideal though, so I'd be inclined to suggest the "Microsoft do it this way, so..." argument.

Title: What is the best way to structure and name files which contain generic classes with the same name?

Body:
In my current project I have come across the requirement to create generic classes with the same name, but different numbers of generic parameters.  For example:

```<code>MyClass<T1>
MyClass<T1, T2>
MyClass<T1, T2, T3>
</code>```

Given that I want all of these in the same namespace, I am confused as to how to structure and name my classes and files?

If we follow the idea that we should have classes limited to one per file and that files should be in a folder structure that represents namespace hierarchy and that the name of the file should match the name of the class, how do I deal with this situation?

What I am really asking here is what should I name the file that contains MyClass<T1>, and what should I name the file that contains MyClass<T1, T2>?  I am not asking what the names of the type parameters should be.


问:
Should I have all models done before I syncdb?
I'm not sure if I want to add more attributes to my models or create another model. I've coded up to the point where I need to syncdb to start using some data in the site, but I'm hesitant to do it. As long as I'm still in production for a while, I could clear the database and start fresh I suppose?

答:
syncdb is deprecated since version 1.7. migrate is used as it performs both the old behavior as well as executing migrations. So if you are using version smaller than 1.7, you would need to create new table in case any changes in table schema. Or you can use South.

Refer to : https://stackoverflow.com/questions/1605662/django-syncdb-and-an-updated-model

I would suggest to shift to latest version of Django to take advantage of build-in migration support.


答:
When you are working with multiple teams on multiple projects, you always had and will have most (if not all) of your troubles relating to interfacing between these projects. You can call it project/library/microservice/etc. - it's always the same as you describe. One team makes breaking changes, the other team(s) suffer.

As this problem is quite well-known, there is a simple acceptable path available. At least it's technically simple, but may involve office politics nevertheless. The basic idea is that you have clearly defined public interfaces and that a team must not make breaking changes in such an environment. Instead, your team is only allowed to break things via a standard deprecation mechanism.

In practice, this means that your outside interface of A must remain the same. This is more trouble for team A to somehow realize their change in a way that leaves the old A interface available and working as it used to. Essentially, this is the price that the company has to pay to ensure smooth operation of all other teams in presence of A's changes. A is, however, entitled to deprecate/version its interface in such a way that all other teams are informed that a certain functionality will be gone within X (this should be clear company-wide known time period. Can be days, weeks, or even months - depending on the agility of your teams).

After this period has elapsed, all other teams have had time to replace the outdated interface calls and team A is allowed to simply remove the deprecated part of the interface. Everything that breaks outside of A at that point is no longer considered team A's problem.

A best practice for working in such an environment is also for each dependency that your project has to setup a suite of tests, which ensures that a) you understand correctly how that interface is supposed to work and b) you immediately fail in case you missed the deprecation deadline and the interface is gone (as usual: fail fast is better).

Title: Implementing Continuous Integration with a volatile hierarchy of library dependencies

Body:
Recently my company setup a build server using Bamboo and a private Nuget Feed which is populated by the successful builds being deployed from the build server.

There is a hierarchy of projects under heavy development setup for use in bamboo with a fairly simple, linear dependency graph. Before being setup on bamboo all devs had to clone the repository being worked on and all of its dependencies and make a new branch in each project. As almost all changes at this point are breaking changes, this was a bit of headache.

So now with the new tool of Bamboo in the mix, as a dev, what would my workflow look like if I needed to make some changes in Project A that will also require changes in Project C where Project B and C is dependent on A and C is also dependent on B.

```<code>  A
 | |
 | B
 | |
  C
</code>```

I want to make certain all tests still pass in Project B after my changes to project A before moving on to make the changes in Project C. Are there any resources that help explain what developers workflow should be at this point? It seems he can either pull down, setup the dependencies manually and test B. Or he can setup special builds on Bamboo to handle the this intermediate state of the projects and then download the resulting nuget packages. I feel uneasy with that solution because it requires a deeper understanding by the devs of Bamboo and the build server (And I don't understand it all well at this point, to explain it all to them).

This problem compounds the more dependencies there become on a lower level library. Are there any resources that explain the accepted approach to this problem?


答:
In a single application references are easier. Above all, they will allow you to process data asynchronously.

If your nodes can be located in different applications (even in different computers) you'll need an event-based pattern like Message Queue. This pattern can be implemented with help of .NET events in each single application.

So, if you don't plan to scale your application, it's easier to use references instead of events.

Title: How should nodes in a chain be connected?

Body:
Suppose you were building a system that receives data on one end and sends filtered data on the other end.

The system is a chain of nodes, each receiving data from the node before and sending filtered data to the next one.

You have two approaches to choose from regarding the way the nodes would be connected:

A- Each node holds a reference to the next one through a particular interface.

B- Each node exposes an event, and the next node in line would be registered to that event, notified when that event is fired (when the previous node in line sends data).

In both cases, an outside entity connects the nodes to one another; they have no direct knowledge of each other.

Currently, I think events may be better because this way, a node doesn't care what the next node does; only what it has to send it. Thus enabling us to insert nodes in the middle easily.

There is a possibility nodes would need to be inserted in the middle, in the future.

Taking that into account, which approach would you prefer, and why? What are the pros and cons of each approach?


问:
Should I try it straight or should I first check if it can be done?
I have a set of items, and each item in the set must be unique. Item are composed from multiple properties and each property of each item can be changed. But after each change every item in the set must still be unique.

Should I simply try to change the property:

```<code>int err = setOfItems.SetPropertyOfItem( item, property, newValue )
if ( err != 0 ) {
    MessageBox( "You cannot change property to this value" );
    return;
}
// ( ...or similar exception based code )
</code>```

Or should I first check if the property can be changed and only then change it:

```<code>if ( !setOfItems.CanBePropertyChanged( item, property, newValue ) ) {
    MessageBox( "You cannot change property to this value" );
    return;
}
setOfItems.SetPropertyOfItem( item, property, newValue );
</code>```

Which approach is better and why?

答:
(disclaimer: use of Java knowledge below)

In your second solution, I presume one of the two approaches will take place for CanBePropertyChanged:

Loop through all the other entries of your Set to make sure none contain oldProperty1, oldProperty2... newPropertyN.

Construct a temporary object temp with oldProperty1, oldProperty2... newPropertyN and using a standard method, e.g. Set.contains(temp), check that the method returns false.

If there are no matches, then your SetPropertyOfItem will apply the new property without further checks.

In your first solution, I presume it is doing something similar to the approaches for CanBePropertyChanged, just that this is done as the first step within SetPropertyOfItem. If the Item cannot be modified, then you return a non-zero 'error code'.

The problem I see with (1) above is that you will be duplicating your class's equivalence checking, which may not be future-proof if your Items gain new properties or constraints that affects how this equivalence is done. For both solutions, concurrency, should you choose to implement that, introduces the small possibility that the actual modification of your Item object is not in sync with other concurrent read/write operations on either the Set or Item object.

Alternatives?

Therefore, I'll approach this by asking this question: How costly is it to re-construct a new updatedItem with oldProperty1, oldProperty2... newPropertyN? If that is a relatively cheap operation (e.g. you don't need to send these properties to a database to retrieve data that needs further parsing), why not consider making Item an immutable class? This will be similar to using approach (2), just that you will be adding the non-temporary (permanent till the next modification) new updatedItem into your Set, and removing the old originalItem from it. If it helps, you can even introduce a bit of syntactic sugar:

```<code>Item updatedItem = oldItem.createWithUpdate( property, newValue ); // creates a new object
if ( set.add( updatedItem ) ) {
    set.remove(oldItem);
} else {
    log.warn( "You cannot change property to this value" );
}
</code>```

Your code can be simpler as a result. Also, a Set by definition does not contain duplicate values, so the statement

But after each change every item in the set must still be unique

Is practically a given after an add() operation (which, in Java, returns true if the Set did not already contain the specified element). Also, when your class is immutable, there is less cause for worry introducing concurrency, since objects themselves wouldn't be mutated out-of-sync. You will only need to code defensively against concurrent operations on your Set object.

To answer the question directly

Ok, if Item is in fact already immutable, or you prefer not to make the proposed changes above, and I have to take my pick from either two approaches, I will go with the first solution. However, instead of an int-based return code, I will either return a boolean or use exception-handling. I will favor the first solution because it opens up the possibility in the future to change the implementation of SetPropertyOfItem, broadly speaking. @Kilian Foth's answer says it better in this regard.

Body:
(disclaimer: use of Java knowledge below)

In your second solution, I presume one of the two approaches will take place for CanBePropertyChanged:

Loop through all the other entries of your Set to make sure none contain oldProperty1, oldProperty2... newPropertyN.

Construct a temporary object temp with oldProperty1, oldProperty2... newPropertyN and using a standard method, e.g. Set.contains(temp), check that the method returns false.

If there are no matches, then your SetPropertyOfItem will apply the new property without further checks.

In your first solution, I presume it is doing something similar to the approaches for CanBePropertyChanged, just that this is done as the first step within SetPropertyOfItem. If the Item cannot be modified, then you return a non-zero 'error code'.

The problem I see with (1) above is that you will be duplicating your class's equivalence checking, which may not be future-proof if your Items gain new properties or constraints that affects how this equivalence is done. For both solutions, concurrency, should you choose to implement that, introduces the small possibility that the actual modification of your Item object is not in sync with other concurrent read/write operations on either the Set or Item object.

Alternatives?

Therefore, I'll approach this by asking this question: How costly is it to re-construct a new updatedItem with oldProperty1, oldProperty2... newPropertyN? If that is a relatively cheap operation (e.g. you don't need to send these properties to a database to retrieve data that needs further parsing), why not consider making Item an immutable class? This will be similar to using approach (2), just that you will be adding the non-temporary (permanent till the next modification) new updatedItem into your Set, and removing the old originalItem from it. If it helps, you can even introduce a bit of syntactic sugar:

Item updatedItem = oldItem.createWithUpdate( property, newValue ); // creates a new object
if ( set.add( updatedItem ) ) {
    set.remove(oldItem);
} else {
    log.warn( "You cannot change property to this value" );
}

Your code can be simpler as a result. Also, a Set by definition does not contain duplicate values, so the statement

But after each change every item in the set must still be unique

Is practically a given after an add() operation (which, in Java, returns true if the Set did not already contain the specified element). Also, when your class is immutable, there is less cause for worry introducing concurrency, since objects themselves wouldn't be mutated out-of-sync. You will only need to code defensively against concurrent operations on your Set object.

To answer the question directly

Ok, if Item is in fact already immutable, or you prefer not to make the proposed changes above, and I have to take my pick from either two approaches, I will go with the first solution. However, instead of an int-based return code, I will either return a boolean or use exception-handling. I will favor the first solution because it opens up the possibility in the future to change the implementation of SetPropertyOfItem, broadly speaking. @Kilian Foth's answer says it better in this regard.


答:
Have you asked yourself, if the classes do really have the same intent? If one class is more generic than the other, then it will be a GenericClass, a MoreGenericClass and a MostGenericClass. Imagine that each type parameter of a class adds a new dimension to the class, so it may help to ask what dimension it is.

Lets take this example:

Container<Thing>

MetricContainer<Thing, Metric>

MetricTransportableContainer<Thing, Metric, Transport>

I'm aware, that it is not the best example, but very expressive to show three dimensions:

inner Dimension, what it can load

metric Dimension, with which metric it can be loaded, only by count of things or by square measure or by cubical capacity or by weight

outer Dimension, where it can be loaded.

So you can model transportation of cars:

```<code>Container<Cars>
MetricContainer<Cars, CountMetric>
MetricTransportableContainer<Cars, CountMetric, Ship>
</code>```

Transportation of fluids:

```<code>Container<Fluid>
MetricContainer<Fluid, Volume>
MetricTransportableContainer<Fluid, Volume, Shelf>
</code>```

Transportation of energy:

```<code>Container<Energy>
MetricContainer<Energy, ElectricPower>
MetricTransportableContainer<Energy, ElectricPower, Box>
</code>```

Transportation of sugar, cereals:

```<code>Container<CrumblyMaterial>
MetricContainer<CrumblyMaterial, Weight>
MetricTransportableContainer<CrumblyMaterial, Weight, Silo>
</code>```

Oh, what a surprise: a List<T> has one dimension that represents the things the list can hold; and this is a Map<T, S> with two dimensions that represent the things the map can hold and the access keys.

Body:
Have you asked yourself, if the classes do really have the same intent? If one class is more generic than the other, then it will be a GenericClass, a MoreGenericClass and a MostGenericClass. Imagine that each type parameter of a class adds a new dimension to the class, so it may help to ask what dimension it is.

Lets take this example:

Container<Thing>

MetricContainer<Thing, Metric>

MetricTransportableContainer<Thing, Metric, Transport>

I'm aware, that it is not the best example, but very expressive to show three dimensions:

inner Dimension, what it can load

metric Dimension, with which metric it can be loaded, only by count of things or by square measure or by cubical capacity or by weight

outer Dimension, where it can be loaded.

So you can model transportation of cars:

Container<Cars>
MetricContainer<Cars, CountMetric>
MetricTransportableContainer<Cars, CountMetric, Ship>

Transportation of fluids:

Container<Fluid>
MetricContainer<Fluid, Volume>
MetricTransportableContainer<Fluid, Volume, Shelf>

Transportation of energy:

Container<Energy>
MetricContainer<Energy, ElectricPower>
MetricTransportableContainer<Energy, ElectricPower, Box>

Transportation of sugar, cereals:

Container<CrumblyMaterial>
MetricContainer<CrumblyMaterial, Weight>
MetricTransportableContainer<CrumblyMaterial, Weight, Silo>

Oh, what a surprise: a List<T> has one dimension that represents the things the list can hold; and this is a Map<T, S> with two dimensions that represent the things the map can hold and the access keys.


问:
confusion between these two networking terms: transmission rate vs. propagation speed
I read this in TCP/IP PROTOCOL SUITE second edition, written by Behrouz A. Forouzan and Sophia Chung Fegan.

In traditional Ethernet, the minimum frame length is 520 bits, the transmission rate is 10 Mbps, the propagation speed is almost the speed of light, and the collision domain is almost 2500 meters.

So what is transmission rate and propagation speed? Why they are not the same?

答:
Here's an analogy from Computer Networking: A Top-Down Approach (6th ed.), written by James F. Kurose and Keith W. Ross, found on page 38:

Consider a highway that has a tollbooth every 100 kilometers.
  You can think of the highway segments between
  tollbooths as links and the toll- booths as routers. Suppose that cars
  travel (that is, propagate) on the highway at a rate of 100 km/hour
  (that is, when a car leaves a tollbooth, it instantaneously acceleratesrates
  to 100 km/hour and maintains that speed between tollbooths).
  Suppose next that 10 cars, traveling together as a caravan, follow
  each other in a fixed order. You can think of each car as a bit and
  the caravan as a packet. Also suppose that each tollbooth services
  (that is, transmits) a car at a rate of one car per 12 seconds, and
  that it is late at night so that the caravan’s cars are the only cars
  on the highway. Finally, suppose that whenever the first car of the
  caravan arrives at a tollbooth, it waits at the entrance until the
  other nine cars have arrived and lined up behind it. (Thus the entire
  caravan must be stored at the tollbooth before it can begin to be
  forwarded.) The time required for the tollbooth to push the entire
  caravan onto the highway is (10 cars)/(5 cars/minute) = 2 minutes.
  This time is analogous to the transmission delay in a router. The time
  required for a car to travel from the exit of one tollbooth to the
  next tollbooth is 100 km/(100 km/hour) = 1 hour. This time is
  analogous to propagation delay. Therefore, the time from when the
  caravan is stored in front of a tollbooth until the caravan is stored
  in front of the next tollbooth is the sum of transmission delay and
  propagation delay—in this example, 62 minutes.


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
At a credit bureau company, I was asked to replace a 100k C code service that checked fraud databases. Asynchronous multithreaded programming in Java replaced old C fork-join thechniques. The time frames were about 400-500 ms and 1-1.5 sec with stress. We managed to get 600 ms with ocassional peaks from databases' cache flushing.

My boss asked to configure it with 100 threads because "you never know" -- I did some research and testing and found 20 threads worked best.

The service depending on the one I wrote suddenly had trouble, my boss asked me to put a hardcoded timeout to cause more trouble, so we can assure I was not the faulty programmer.

My boss asked me to log every single operation to have control of all the process. That's ok I know. He asked me to go production with this version: Gigabyte logs every day.
Two monts later I managed to change log to INFO from DEBUG and got 30% faster.

I was asked to go to five or six installations at 3 a.m. to replace the jar and change the name of the jar in the script that launched the service (the old C app was a mess and they were afraid I did the same thing).

The worst: I was forced to manage a team of 8, 5 were outsourcers, at the middle of the project. 1 of us never did anything, the outsources did a web app that 2 years after is not in production yet.

OwnerDisplayName: Abdul


问:
How do you take advantage of your whiteboard in your development team?
Today we got our own website design. The theme is the "whiteboard".

I'm a big fan of them. I would like you to share with me how you use it. I'm sure I don't exploit its potential enough.

I will really enjoy answers that will come with pictures of your own whiteboard as an illustration ;)

I use it as an information radiator to support a light version of scrum.

How do you use this essential development tool?

Please note that I'm also interested in people using a virtual whiteboard or even big touchscreen whiteboard emulator.

答:
In it's infancy, I'm trying to promote more use of it then how we use it currently.

Ideally you should have a whiteboard on every wall of the room with "tablet" whiteboards for every programmer. Cheaper then an iPad and just as effective. When explaining almost anything the first place I go to is the whiteboard to visually show what I'm trying to explain.

In this layout we have the application's flow laid out. Then tasks for each part of the flow are added to the "incomplete" top box. As tasks are worked on they are moved to "in progress" and finally to "under review." This makes it easy to work on one area, get stuck, and switch to another. It's also very visually representative of the application as a whole. Ideally I would like a task manager application setup exactly like this, or a whiteboard for each project. Currently we don't have that many whiteboards (one currently) so the most active project gets priority.


问:
What is the best way to create REST API error response model and error codes system?
My REST implementation will return errors in JSON with next structure:

```<code>{
 "http_response":400,
 "dev_message":"There is a problem",
 "message_for_user":"Bad request",
 "some_internal_error_code":12345
}
</code>```

I suggest to create special response model, where I can pass needed values for properties(dev_message, message_for_user, some_internal_error_code), and return them. In code it would be similar to this:

```<code>$responseModel = new MyResponseModel(400,"Something is bad", etc...);
</code>```

How this model should look like? Should I implement methods e.g. successResponse() where I'll pass only text information, and code will be default 200 there? I'm stuck with this.
And this is first part of my question: do I need to implement this model, is this good practise? Because for now, I'm just returning arrays directly from code.

The second part is about error code system. Error codes will be described in documentation. But the problem I'm encountering is in code.
What is the best way to manage error codes? Should I write them inside model? Or it would be better to create separate service for handling this?

UPDATE 1

I've implemented model class for response. It is similar Greg's answer, the same logic, but additionaly I have hardcoded written errors in model  and here it is how it looks like:

```<code>    class ErrorResponse
    {
     const SOME_ENTITY_NOT_FOUND = 100;
     protected $errorMessages = [100 => ["error_message" => "That entity doesn't exist!"]];

     ...some code...
    }
</code>```

Why I did this? And what for?

It's looks cool in  code:
return new ErrorResponse(ErrorResponse::SOME_ENTITY_NOT_FOUND );

Easy to change error message. All messages are in one place instead of controller/service/etc or whatever you'll placed it.

If you have any suggestions to improve this, please, comment.

答:
I was facing something similar, I did 3 things,

Created a ExceptionHandler for myself called ABCException.

Since I am using Java & Spring,

I defined it as

```<code> public class ABCException extends Exception {
private String errorMessage;
private HttpStatus statusCode;

    public ABCException(String errorMessage,HttpStatus statusCode){
            super(errorMessage);
            this.statusCode = statusCode;

        }
    }
</code>```

Then called it wherever required, like this,

```<code>throw new ABCException("Invalid User",HttpStatus.CONFLICT);
</code>```

And yeah you need to make an ExceptionHandler in your controller if you are using REST based webservice.

Annotate it with @ExceptionHandler if using Spring

Body:
I was facing something similar, I did 3 things,

Created a ExceptionHandler for myself called ABCException.

Since I am using Java & Spring,

I defined it as

 public class ABCException extends Exception {
private String errorMessage;
private HttpStatus statusCode;

    public ABCException(String errorMessage,HttpStatus statusCode){
            super(errorMessage);
            this.statusCode = statusCode;

        }
    }

Then called it wherever required, like this,

throw new ABCException("Invalid User",HttpStatus.CONFLICT);

And yeah you need to make an ExceptionHandler in your controller if you are using REST based webservice.

Annotate it with @ExceptionHandler if using Spring


问:
Conceptually, is the single page web app more efficient than the web app that loads pieces of the page for every page?
I searched a lot, but nobody seems to have explained this nor given a proper example.

I have a page like this:

My team says they want to design the code such that the Title section, Menu section and Footer sections would each be kept in separate HTML files and they'd have separate JSP files for every page, where each JSP file would dynamically load the title.html, menu.html and footer.html files using JQuery.

My suggestion to them was to use a single JSP/HTML file which already contains the Title, Menu and Footer, and just load the Center content dynamically (single page app).

I have three questions:

1. For a web app that needs to use as less network bandwidth as possible, is it better to use a single page app approach or the load-multiple-pieces-of-a-page approach? Percentage-wise, would it result in a large change in bandwidth if the Title only contained a small brand logo and text, and the Menu and Footer just contained text and styles.

If content is to be loaded dynamically into a page, since frame is deprecated and I hear that iframe is not encouraged, is an ordinary div the best option to load Center content or the Title, Menu, Footer etc. OR is there a better way to load it such that it'd work in IE too?

When pages are kept split as title.html, menu.html etc., do they have to contain the ' andtags or can they just contain the necessary's? Do the loadedHTML` pages inherit the parent page's properties?

答:
Yes, but most browser already cache thing like image/css/js so the bandwidth saving wouldn't blow you mind but still no screen bleeping and less request is nice to have

iframe has it place but I think for your case, AJAX is the best. there's other technique like using knockout so server only send JSon (instead of partial view) and later it will be rendered into html by knockout.

if you don't want to use iframe html tag isn't necessary.


答:
It would be interesting to know what your team thought about your suggestion. I think it's got a lot of merit. To answer your questions.

Bandwidth, for both options I would say that caching either on the end-user's browser or via an ADN or CDN would solve this problem for you. If a web application is getting three files: Title, Menu and Footer, that don't change then these can be cached. For both there will be the initial hit whilst everything is got for the first-time.

If you are using jQuery then the AJAX methods within it should enable you to write content into any tag you choose. DIVs should be fine.

Included files that form part of a web-page shouldn't have  and  tags, otherwise you'll have invalid HTML in the final page.

Title: Conceptually, is the single page web app more efficient than the web app that loads pieces of the page for every page?

Body:
I searched a lot, but nobody seems to have explained this nor given a proper example.

I have a page like this:

My team says they want to design the code such that the Title section, Menu section and Footer sections would each be kept in separate HTML files and they'd have separate JSP files for every page, where each JSP file would dynamically load the title.html, menu.html and footer.html files using JQuery.

My suggestion to them was to use a single JSP/HTML file which already contains the Title, Menu and Footer, and just load the Center content dynamically (single page app).

I have three questions:

1. For a web app that needs to use as less network bandwidth as possible, is it better to use a single page app approach or the load-multiple-pieces-of-a-page approach? Percentage-wise, would it result in a large change in bandwidth if the Title only contained a small brand logo and text, and the Menu and Footer just contained text and styles.

If content is to be loaded dynamically into a page, since frame is deprecated and I hear that iframe is not encouraged, is an ordinary div the best option to load Center content or the Title, Menu, Footer etc. OR is there a better way to load it such that it'd work in IE too?

When pages are kept split as title.html, menu.html etc., do they have to contain the ' andtags or can they just contain the necessary's? Do the loadedHTML` pages inherit the parent page's properties?


问:
How did people write end-user software in Smalltalk?
There is something I've never understood about Smalltalk, since reading about it in a book when I was a child, tho' I have never used it "in anger". I know that it is turtles-all-the-way-down, that you can break into the program at any time, inspect the state of your objects, even change the code, and resume running. This is obviously a dream come true for a researcher, whether in CS or in industry, an engineer simulating a system, an analyst modelling a market, and so on. I also know that there was no concept of writing source in text files and compiling them into a binary, the editor and the runtime are the same thing. But how do you deliver software to an end user who wouldn't know a debugger if it bit them on the nose, and couldn't care less what an object is? Was there a secret keystroke to turn all those features off and make it behave like "normal" software? Or was Smalltalk software only ever sold to sophisticated users who were programmers too?</p>

答:
One point that Jörg did not mention in his answer: After the "deployment" step it is actually hard to tell that an application was written in Smalltalk, because the IDE was either stripped out or hidden. For example, try these:

http://scratch.mit.edu/scratch_1.4/

http://www.planet-plopp.com/english/download.html

Also, just by looking at the range of applications built with Smalltalk, you can tell that their users are certainly no programmers nowadays:
https://twitter.com/hashtag/thingsPeopleBuiltWithSmalltalk

That every user should be able to modify their software is a Smalltalk idea that still has not made it to the mainstream (while many other of its ideas are commonplace nowadays - like GUIs or Object-Orientation).


答:
This is a tricky question :) If I really have to choose from only this two options, I would choose A for the simpler form of your task and B for the extended. That is because events does not really make sense until you are calling exactly one function.

The primary responsibility of your nodes is to filter the data that they receive. Still when you change the structure of your graph, you also have to change your node class, although the change has nothing to do with its primary function.

The way around this is to conform to the Single Responsibility Principle (SRP). Make the nodes sole responsibility the filtering, and create a class what transfers the data between nodes.

So here is option C:

```<code>interface InputNode
{
  DataBuffer getData();
}

interface OutputNode
{
  void setData(DataBuffer data);
}

class FilterNode : InputNode, OutputNode
{
  ...
}
</code>```

Implement this node in a manner that its sole responsibility is to do the filtering. Make it absolutly unaware of that other nodes exist at all! And this is the interface of the class that transfers the data between nodes:

```<code>interface DataTransfer
{
  InputNode {get; set;}
  OututNode {get; set;}
  void transfer();
}
</code>```

And thats how your graph should look like:

```<code>class Graph
{
  private List<DataTransfer> transfers;

  public Graph()
  {
    //initialize nodes and transfers
    ...
  }

  public void setData(DataBuffer data)
  {
    transfers[0].setData(data);
  }

  public void process()
  {
    foreach(var transfer in transfers)
      transfer.transfer();
  }

  public DataBuffer getData()
  {
    return transfers.Last().getData();
  }
}
</code>```

If you want to extend this solution as you described, you will need to change the DataTransfer interface to have a list of output nodes, and you will need to change the graph representation so that it can do the branching.

Body:
This is a tricky question :) If I really have to choose from only this two options, I would choose A for the simpler form of your task and B for the extended. That is because events does not really make sense until you are calling exactly one function.

The primary responsibility of your nodes is to filter the data that they receive. Still when you change the structure of your graph, you also have to change your node class, although the change has nothing to do with its primary function.

The way around this is to conform to the Single Responsibility Principle (SRP). Make the nodes sole responsibility the filtering, and create a class what transfers the data between nodes.

So here is option C:

interface InputNode
{
  DataBuffer getData();
}

interface OutputNode
{
  void setData(DataBuffer data);
}

class FilterNode : InputNode, OutputNode
{
  ...
}

Implement this node in a manner that its sole responsibility is to do the filtering. Make it absolutly unaware of that other nodes exist at all! And this is the interface of the class that transfers the data between nodes:

interface DataTransfer
{
  InputNode {get; set;}
  OututNode {get; set;}
  void transfer();
}

And thats how your graph should look like:

class Graph
{
  private List<DataTransfer> transfers;

  public Graph()
  {
    //initialize nodes and transfers
    ...
  }

  public void setData(DataBuffer data)
  {
    transfers[0].setData(data);
  }

  public void process()
  {
    foreach(var transfer in transfers)
      transfer.transfer();
  }

  public DataBuffer getData()
  {
    return transfers.Last().getData();
  }
}

If you want to extend this solution as you described, you will need to change the DataTransfer interface to have a list of output nodes, and you will need to change the graph representation so that it can do the branching.


问:
Integration between services in a SOA
Assume we have a Bounded Context for Inventory (InventoryBC) and another one for Shipments (ShipmentsBC). These 2 BCs need to communicate together. They are hosted on 2 different services on different servers with different databases.

When a Shipment is made I might need to fetch some data from the Inventory BC so I think a REST GET request should solve it. However, when a shipment is done I need to decrease the Inventory so an Event "ShipmentCompleted" would do the trick.

However, what if one of the services is down? The writes aren't lost as they will be persisted in a Queue till their consumption, but what about the reads? No reads= nothing working

Does this style of integration work in practice or is there better approach for a more scalable and loosely coupled system?

答:
If I may rephrase your question, you are asking "what happens to my system if something breaks?"  Well, the short answer is that your system no longer functions properly. This happens all the time in complex systems. The degree to which you experience degraded functionality will depend upon what broke and how important it is. For example, when the space shuttle flew, there were certain points in the flight trajectory where we could lose an engine and still make it to orbit. Other places in the trajectory meant a return to launch site abort, while still others meant landing across the Atlantic (most likely Zaragoza, Spain).

In your specific case, the system does not appear to be that complex. Nonetheless, in any system, there will be parts that are more critical than others. Databases in computer systems are often designed at points where they can be a single point of failure. It can be extremely expensive and unnecessary to design these SPFs out of the system, so you have to live with the probability that the system will be down from time to time. Good design practices, including using federated databases and multiple geographic regions can reduce this risk.

I think you have the right approach - having several small, self-contained pieces with very limited interface boundaries is the best way to ensure reliability of the system overall.

Title: Integration between services in a SOA


问:
How can I decouple query and context in a "query object" scenario?
I'm using a query object pattern (similar to this) to manage disparate queries while avoiding bloaded facades/repositories.

A query object takes a number of constructor parameters, representing query arguments. The query is then passed to an IQueryHandler by the caller, into which is injected the IDataContext. The IDataContext is then passed into an Execute method of the IQuery.

The thing I don't like is this:

```<code>public interface IQuery<TResult>
{
    public TResult Execute(IDataContext context);
}
</code>```

Because the IDataContext is passed into the method and thus explicitly declared in the interface, there is no option to have a query that fetches things via a different mechanism - IQuery is coupled to whatever defines the IDataContext interface. Suppose, for example, I want to switch from an SQL DB store to a document DB.

I've tried a couple of alternatives, but neither quite gets me where I want to be.

The first is to inject the data context into the query's constructor and use a factory to generate the query objects. This successfully decouples the interfaces, but now working with the queries is more cumbersome. Instead of using the constructor/object initializer to set up the query, callers have to do something like this:

```<code>var query = _queryFactory.Create<PersonQuery, Person>(); // Second type argument can't be inferred from first due to limitations in generic type inference.
query.Name = "Bob";
query.Age = 32;

var result = query.Execute();
</code>```

The second is to abstract the execution of the query - and thus the dependency on IDataContext - to a handler class, then have another class that resolves a handler for each query, which again abstracts the dependency away from any interfaces:

```<code>public class ISomeQueryHandler : IQueryHandler<SomeQuery, SomeQueryResult>
{
    private readonly IDataContext _context = ...;

    public SomeQueryResult Execute(SomeQuery query) { ... }
}
</code>```

I don't like this option because it means every new query involves writing two classes, which, again, is cumbersome and increases the potential for a query to exist with no way of handling it (it also involves an empty marker interface for queries since the Execute method is moved to the handler, which always feels off). It also involves some rather funky convention-based dependency resolution to get the right handler for each query.

Creating an abstraction over IDataContext is not really feasible due to its complexity.

Is there a happy medium I haven't seen?

答:
One solution I've used to this kind of problem is to add a layer of indirection to the context. In this case, I would rename IDataContext to ISQLDataContext, and create a new IDataContext with an "SQLContext" property to retrieve the existing context.  Your query objects can then be trivially changed to use the new interface, and you can add new context types at the top level as you need them.

This solution isn't ideal - it doesn't conform to the open/closed principle with regards to adding new data stores, but (a) that is unlikely to be a common type of change and (b) as the implementation of the data context object will be very simple, most of the logic behind the OCP (i.e. that changing existing code is more likely to break something existing than adding entirely new code) simply doesn't apply.


问:
Is it normal for service methods to correlate to your views?
I've been working on learning how to implement domain services and view models in my project and have noticed a suspicious trend:

When obtaining data for views from my controllers, if my domain services are producing view models, I end up with one service method for each view model being requested.

I'm wondering if perhaps there's something that I might have misunderstood in how/where I create view models?  Should I be creating a special set of services in my project that compose my more inner domain services to build view models?

答: Service methods correlate with individual services.  If the purpose of the service is to provide data for display in a UI, then you're also going to have a corresponding View Model.  But that's not the only thing that a service method can provide.


答:
Basically, I find it very good to keep the 'title', 'menu' and 'footer' in independent files.

What I really wonder about is: why don't you put them together on the server side???

<%@include file="title.jsp" %>
<%@include file="menu.jsp" %>
<%@include file="footer.jsp" %>

Don't worry about bandwith

The difference between your two solutions will be negligible and I wouldn't worry about. Most browser will cahche the files and retrieve them only once anyway. Having a picture on your website would consume much more bandwith, so avoid any picture. You want to save bandwitdh right? ...just kidding. It's just not a place to worry about. Bandwitdh is cheap.

There are much more important things to worry about

Is it safe?

The more javascript you have on your site, the more likely things can go wrong. With the large diversity of browsers/OSes/devices, you must be careful! If your javascript breaks somewhere, because of you or a dependency, it may cause that nothing works anymore. ...and your users will not be happy if the navigation on your site doesn't work anymore.

Taking this into account, your solution is more error-prone.

Is it webby?

You know, bookmarking pages? History? Previous page? Share a link? ;) ...with dynamic loading, you don't get all that stuff ...or it's a lot of extra work and bug sources.

Your solution doesn't provide that.

Is it maintainable?

...you know, easy to read/understand/change. I personnally find it easier to serve full pages with normal links rather than understanding javascripted navigation. My 2 cents.

I think your way is more complicated

Single page web apps is a trendy concept, but not all that is new and shiny is better than good ol' stuff.

Doing the "merging" on server side has several benefits

It's simple

It's easy to understand

It'll never break on the client because not javascript dependent

It's good for SEO because crawlers can index you easely

People can "bookmark" pages and so on, you know

The page is fully loaded in a single request