问:
Merge sort versus quick sort performance
I have implemented merge sort and quick sort using C (GCC 4.4.3 on Ubuntu 10.04 running on a 4 GB RAM laptop with an Intel DUO CPU at 2GHz) and I wanted to compare the performance of the two algorithms.

The prototypes of the sorting functions are:

```<code>void merge_sort(const char **lines, int start, int end);

void quick_sort(const char **lines, int start, int end);
</code>```

i.e. both take an array of pointers to strings and sort the elements with index i : start <= i <= end.

I have produced some files containing random strings with length on average 4.5 characters. The test files range from 100 lines to 10000000 lines.

I was a bit surprised by the results because, even though I know that merge sort has complexity O(n log(n)) while quick sort is O(n^2), I have often read that on average quick sort should be as fast as merge sort. However, my results are the following.

Up to 10000 strings, both algorithms perform equally well. For 10000 strings, both require about 0.007 seconds.

For 100000 strings, merge sort is slightly faster with 0.095 s against 0.121 s.

For 1000000 strings merge sort takes 1.287 s against 5.233 s of quick sort.

For 5000000 strings merge sort takes 7.582 s against 118.240 s of quick sort.

For 10000000 strings merge sort takes 16.305 s against 1202.918 s of quick sort.

So my question is: are my results as expected, meaning that quick sort is comparable in speed to merge sort for small inputs but, as the size of the input data grows, the fact that its complexity is quadratic will become evident?

Here is a sketch of what I did.
In the merge sort implementation, the partitioning consists in calling merge sort recursively, i.e.

```<code>merge_sort(lines, start, (start + end) / 2);
merge_sort(lines, 1 + (start + end) / 2, end);
</code>```

Merging of the two sorted sub-array is performed by reading the data from the array lines and writing it to a global temporary array of pointers (this global array is allocate only once). After each merge the pointers are copied back to the original array. So the strings are stored once but I need twice as much memory for the pointers.

For quick sort, the partition function chooses the last element of the array to sort as the pivot and scans the previous elements in one loop. After it has produced a partition of the type

```<code>start ... {elements <= pivot} ... pivotIndex ... {elements > pivot} ... end
</code>```

it calls itself recursively:

```<code>quick_sort(lines, start,          pivotIndex - 1);
quick_sort(lines, pivotIndex + 1, end);
</code>```

Note that this quick sort implementation sorts the array in-place and does not require additional memory, therefore it is more memory efficient than the merge sort implementation.

So my question is: is there a better way to implement quick sort that is worthwhile trying out? If I improve the quick sort implementation and
perform more tests on different data sets (computing the average of the running times on different data sets) can I expect a better performance
of quick sort wrt merge sort?

EDIT

Thank you for your answers.

My implementation is in-place and is based on the pseudo-code I have found
on wikipedia in Section In-place version:

```<code>function partition(array, 'left', 'right', 'pivotIndex')
</code>```

where I choose the last element in the range to be sorted as a pivot, i.e. pivotIndex := right.
I have checked the code over and over again and it seems correct to me.
In order to rule out the case that I am using the wrong implementation
I have uploaded the source code on github (in case you would like
to take a look at it).

Your answers seem to suggest that I am using the wrong test data. I will look into it and try out different test data sets. I will report as soon as I have some results.

答:
Note that the pseudo-code in wiki is not practical. It is written to undestand.

If an array is [0,0,0,1] pivot is 1 and other elements are less than the pivot,

then swapping(t <-- a, a <-- b, b <--t) works as t <-- a, a <-- a, a <-- t.

In this case swapping works nothing.

If an array is [4,2,1,3] then [4,2,1,3] --> [2,4,1,3] --> [2,1,4,3] --> [2,1,3,4].

In this case '4' moves like in bubble sort.

I suggest a new pseudo-code.

```<code>quicksort(A, i, k)
    if i < k
        p := partition(A, i, k)
        quicksort(A, i, p - 1)
        quicksort(A, p + 1, k)

partition(array, left, right)
    hole := choosePivot(Array, left, right)
    pivot := array[hole]        // dig a hole
    array[hole] := array[right]
    hole := right               // move the hole
    while left < hole
        if array[left] >= pivot
            array[hole] := array[left]
            hole := left
            while right > hole
                if array[right] < pivot
                    array[hole] := array[right]
                    hole := right
                right := right - 1
        left := left + 1
    array[hole] := pivot        // bury the hole
    return hole
</code>```

Performance comparison is difficult, because it depends on some factors.

Implementation

Good code run fast, ugly code run slow, you know.

Data size

a. Size of array element.

b. Whole array size exceed a cache memory or not.

c. Whole array size exceed a main memory or not.

Data structure

a. An array is stored in a continuous memory as C language.

b. An array consist of pointers to a continuous memory.

c. Pointer is gotten by malloc(3) or "new" operator.

Data spread

If random number is used then ESD(estimated standard deviation) of processing time is 5%. Not used then 2%. I researched.

OS, H/W

Linux/Unix, microsoft windows is multi-task OS. Program is often interrupted.

Many core CPU is better. Test before GUI login is better. Single-task OS is better.

Example: N=100000, 32 byte/element, pivot is a middle element, strcmp(3), continuous memory

```<code>qsort_middle()  usec = 522870   call = 999999   compare = 28048465  copy = 15404514
merge_sort()    usec = 533722   call = 999999   compare = 18673585  copy = 19673584
</code>```

Source C programs and scripts are posted in github. Thre is various quicksort and merge sort.

Body:
Note that the pseudo-code in wiki is not practical. It is written to undestand.

If an array is [0,0,0,1] pivot is 1 and other elements are less than the pivot,

then swapping(t <-- a, a <-- b, b <--t) works as t <-- a, a <-- a, a <-- t.

In this case swapping works nothing.

If an array is [4,2,1,3] then [4,2,1,3] --> [2,4,1,3] --> [2,1,4,3] --> [2,1,3,4].

In this case '4' moves like in bubble sort.

I suggest a new pseudo-code.

quicksort(A, i, k)
    if i < k
        p := partition(A, i, k)
        quicksort(A, i, p - 1)
        quicksort(A, p + 1, k)

partition(array, left, right)
    hole := choosePivot(Array, left, right)
    pivot := array[hole]        // dig a hole
    array[hole] := array[right]
    hole := right               // move the hole
    while left < hole
        if array[left] >= pivot
            array[hole] := array[left]
            hole := left
            while right > hole
                if array[right] < pivot
                    array[hole] := array[right]
                    hole := right
                right := right - 1
        left := left + 1
    array[hole] := pivot        // bury the hole
    return hole

Performance comparison is difficult, because it depends on some factors.

Implementation

Good code run fast, ugly code run slow, you know.

Data size

a. Size of array element.

b. Whole array size exceed a cache memory or not.

c. Whole array size exceed a main memory or not.

Data structure

a. An array is stored in a continuous memory as C language.

b. An array consist of pointers to a continuous memory.

c. Pointer is gotten by malloc(3) or "new" operator.

Data spread

If random number is used then ESD(estimated standard deviation) of processing time is 5%. Not used then 2%. I researched.

OS, H/W

Linux/Unix, microsoft windows is multi-task OS. Program is often interrupted.

Many core CPU is better. Test before GUI login is better. Single-task OS is better.

Example: N=100000, 32 byte/element, pivot is a middle element, strcmp(3), continuous memory

qsort_middle()  usec = 522870   call = 999999   compare = 28048465  copy = 15404514
merge_sort()    usec = 533722   call = 999999   compare = 18673585  copy = 19673584

Source C programs and scripts are posted in github. Thre is various quicksort and merge sort.


问:
Should an object load itself?
although I'm programming in C++ for some time now, I'm always faced with design decisions (probably due to the language's flexibility). One such problem is deciding if a method should be part of the class or not.

As an example, oftentimes, I have a Simulation class similar to the following,

```
<code>
class Simulation{
public:
    Simulation(void);
    bool init(const char* init_file){
        //...
        particles_ = read_particles(init_file);
        //etc
    }
    //or even,
    bool init(int argc, char* argv[]);
    void run(void);
private:
    std::vector particles_;
    //Other private members
};
</code>
```

Here, I'm not sure if this init method, which parses a file and initializes the simulation should really be a class method. A different way to implement similar functionality, would be to have an external function or class which handles the parsing of either the command line arguments or the initialization file, and calls appropriate methods of the Simulation class.

```
<code>
bool init_simulation(Simulation& sim, const char* init_file){
    //...
    Particles particles = read_particles(init_file);
    sim.set_particles(particles);
    //etc
}
</code>
```

On the one hand it's easier to implement the functionality as a class method and it avoids having to introduce new classes/structs, specifically for passing parameters. On the other hand, externally handling the initialization, means that one can more easily extend it, although any changes on the Simulation class will propagate to the function.

What is the preferred design in situations similar to the one described above, and how should I approach similar design decisions?

答:
For discussion, I'm going to present a counter-argument to @itsbruce.  YMMV.

What is more likely to change, the file format or the object itself?   (as in additional or changed fields).

In my experience, if the file format is standard, and accessed through abstract interfaces (e.g. standard XML, JSON libraries), the core code for that doesn't change.  It's much more likely for the object to change than the file format.

In that case, it does make some sense for the object to be able to read and write itself.  When the Foo object changes, only one file, Foo, needs to change.

If you have a separate FooPersister, and the Foo object adds or changes a field, you are likely to have to modify FooPersister.  e.g., in Foo, you'd add a .newField, appropriate setters getters and logic.  And, in FooPersister.read(Foo) and FooPersister.write(Foo), you have to remember to add that field to both methods.  What if a field changes from int to double?  Likely some FooPersister code changes there.

Of course, it depends on your persistence framework, if it automagically reads the fields, or it's as simple as adding an annotation somewhere.  And how mature your project is, if your Foo object is already a gazillion lines of code, etc..  As said before, YMMV.  (You could farm out the actual persistence code to a friend class, or, in Java-ese, a private internal class, so your code remains somewhat separated, but the public API rests in the Foo class.

One huge advantage of having the object be able to persist itself is that you may be able to eliminate many of your getters and setters.  If you have a FooPersister, you pretty much must expose all your non-transient internal fields to it.  If you persist yourself, sometimes you can keep a lot more internal and hidden (and final)

Now, I wouldn't  do exactly as OP does, reading/writing to files:

bool init(const char* init_file)

I'd probably have it read/write from/to a Stream, a Node or Element, or something like that, more abstract than a file.  Also, even though it "feels weird", consider having the read/write methods be instance methods (read should returns a new Foo, not overwrite the old one), not a static class function.  This opens a lot of interesting doors in your design.

ContentLicense: CC BY-SA 3.0

Title: Should an object load itself?


问:
I'm confused about which is the correct way to work with TDD
I'm trying to grasp what's the idea behind TDD and how a team is supposed to work with it. I have the following test case with NUnit + Moq (just writing by memory, it is not assured the example compiles but it should be explanatory):

```<code>[Test]
public void WhenUserLogsCorrectlyIsRedirectedToLoginCorrectView() {
    Mock<IUserDatabaseRepository> repoMock = new Mock<IUserDatabaseRepository>();
    repoMock.Setup(m => m.GetUser(It.IsAny())).Returns(new User { Name = "Peter" });

    Mock<ILoginHelper> loginHelperMock = new Mock<ILoginHelper>();
    loginHelperMock.Setup(m => m.Login(It.IsAny(), It.IsAny())).Returns(true);
    Mock<IViewModelFactory> factoryMock = new Mock<IViewModelFactory>();
    factoryMock.Setup(m => m.CreateViewModel()).Returns(new LoginViewModel());

    AccountController controller = new AccountController(repoMock.Object, loginHelperMock.Object, factoryMock.Object)

    var result = controller.Index(username : "Peter", password: "whatever");

    Assert.AreEqual(result.Model.Username, "Peter");
}
</code>```

AccountController has 3 dependencies which I mock that, when orchestrated inside the controller, allows me to verify if a login was correct or not.

What stumbles my mind is that... if in TDD in theory you have to write first your test suite and build your code up from it, how am I supposed to know beforehand that in order to perform my operation I'll need to use those three dependencies and that the operation will call certain operations? It's like I need to know the innards of the Subject Under Test before even implementing it in order to Mock the dependencies and isolate the class, creating some kind of write test - write code - modify test if necessary cycle.

Naturally, without any knowledge of the innards of my code and just expressing the test, I could express it like it could just need the ILoginHelper and "magically" suppose before writing the code that it will return the user on a successful login (and ultimately realize that the underlying framework doesn't work that way, for instance returning just an ID instead of the full object).

Am I understanding TDD in an incorrect way? Which is a typical TDD practice on a complex case?

Thank you

答:
What stumbles my mind is that... if in TDD in theory you have to write first your test suit and build your code up from it, how am I supposed to know beforehand that in order to perform my operation I'll need to use those three dependencies and that the operation will call certain operations? It's like I need to know the innards of the Subject Under Test before even implementing it in order to Mock the dependencies and isolate the class, creating some kind of write test - write code - modify test if necessary cycle.

It feels wrong, right? And it should - not because your tests for the controller are incorrect or "bad" in any way, but because you want to test the controller before you have anything at all to be "controlled". :)

My point is: TDD will feel more natural to you once you start doing it at the level of "business rules" and "real application logic", which is also where it is the most useful. Controllers usually deal only with delegation to other components, so it is natural that, in order to test if the delegation is done correctly, you need to know to which object it is going to delegate to. The only problem is when you try to do it before you have any real logic implemented. My suggestion is that you try to implement the LoginHelper, for instance, by doing TDD in a more "behavior-oriented" way. It will feel more natural and you'll probably see more of its benefits.

So to a more generic answer: TDD is a practice with which we produce tests before writing the code we need, but it does not specifiy which kind of tests. Controllers are usually integrators of components, so you write unit tests which usually require a lot of mocking. When you write the application logic (business rules, such as placing an order, validating user authrozations, etc...), you write behavior tests, which will usually be state-based tests (given input vs. desired output). This difference is often referred to as Mockism vs. Statism by the TDD community. I am part of the (small) group that insists that both ways are correct, its just that they offer different trade-offs, thus being useful for different scenarios such as described above.


问:
Who writes the technical 'user stories' in scrum
I know that a product owner should write a user story in scrum.

A user story is describing a feature for the end user.

But who describes what needs to be technically developed and how it needs to be implemented

and where is that information stored concerning scrum?

That would really interest me!

I see a big lack of knowledge in our company when developer start to implement the story but they do not know HOW to implement it!

For example they have to deal with a legacy COM API and have no idea how to handle it or they are not that technically skilled with WPF/WEB or whatever.

How does scrum help that people to start with the user story?

答:
Whoever is best qualified on the team needs to break down the requirements from product owners into actionable user stories. In my experience, we've used the following approach:

It has always been a developer that writes the stories based on discussions with product owners.

These stories are then estimated (based on points or time) by developers

The product owners then decide on how things are prioritized.

If the developers don't know how to implement a story, then one of theses cases might be true:

The task might not be clear enough (add more
details/screenshots/mockups)

It needs to be broken down further so
that the specific tasks are clearer

It needs more time so the
developer can research, and learn how to implement it. (When estimating this task, add more time to account for this)

The developer
is not qualified enough to implement it and it might need to be
assigned to someone else, or the developer needs to be helped by
someone else.

You can take this course on SCRUM at Udemy for free and learn about individual aspects of the SCRUM process - https://www.udemy.com/scrum-methodology/


问:
Can I use US-ASCII and UTF-8 encoding interchangeably for an XML file without a XML root declaration?
My source XML does NOT contain the root declaration i.e.

```<code><?xml version="1.0" encoding="utf-8" ?>
</code>```

And when I run the file command on it, I get:

```<code>ASCII text, with very long lines, with CRLF line terminators
</code>```

Can I confidently use US-ASCII or UTF-8 interchangeably when reading the XML ?

答:
US-ASCII is a 7-bit code, and it's a true subset of UTF-8. In other words, every ASCII file is by definition also an UTF-8 file. The file command classifies it as 'ASCII' because there are no 8-bit characters in it, and it's totally right in doing that.

Nevertheless you should always read XML files assuming that they're UTF8-encoded. It doesn't hurt even if there aren't any 8-bit characters in it, but if there are, reading it as ASCII would simply be wrong.


答:
ASCII is a subset of UTF-8. You can read any ASCII-encoded document as UTF-8, and it will work. ASCII only uses 7 bits, and UTF-8 uses the unused eight bit to mark non-ASCII code units.

The XML spec has an informal algorithm for detecting the encoding which is necessary to read the <?xml declaration, if one is present. An encoding might also be implied by a Byte Order Mark at the beginning of the document.

If no encoding information is present in the document, you may have encoding information from a transport protocol, e.g. HTTP or MIME. Then use that.

But the default assumption is UTF-8. Citing the XML 1.0 and XML 1.1 spec:

In the absence of information provided by an external transport protocol […], it is a fatal error […] for an entity which begins with neither a Byte Order Mark nor an encoding declaration to use an encoding other than UTF-8. Note that since ASCII is a subset of UTF-8, ordinary ASCII entities do not strictly need an encoding declaration.

Something that appears to be encoded in UTF-8 and only uses the ASCII-compatible subset in the beginning might actually be encoded in any other ASCII-compatible encoding, such as an encoding in the ISO 8859 family (e.g. Latin-9). So you still need to determine the proper encoding through encoding declarations, BOMs, or transport metadata. Do not try to sniff the encoding. If the encoding does not match the actual contents, that's an error and you must not process the malformed document.

Title: Can I use US-ASCII and UTF-8 encoding interchangeably for an XML file without a XML root declaration?

Body:
My source XML does NOT contain the root declaration i.e.

```<code><?xml version="1.0" encoding="utf-8" ?>
</code>```

And when I run the file command on it, I get:

```<code>ASCII text, with very long lines, with CRLF line terminators
</code>```

Can I confidently use US-ASCII or UTF-8 interchangeably when reading the XML ?

ContentLicense: CC BY-SA 4.0


问:
What programmable system can provide persistent scheduling?
I want to write an application that creates scheduled events at specific times. When the delay elapses the event notifies the application. The scheduled events must not be stored in the application's memory because if the application shuts down all scheduled events will be lost - I do not want to write a custom persistence layer for event scheduling. What system can provide persistent scheduling for my application that will call my application back when each event elapses?

I've been looking at message queues and Redis. I am not interested in Java solutions. The closest solution I found was RabbitMQ. Rabbit messages can be assigned a TTL and placed on a queue that is never consumed. Messages that expire fire DLX messages which can be examined to determine whether the message failed due to TTL expiry. However, messages will not necessarily expire in the correct order due to a caveat applicable to message TTLs whereby the message at the head of the queue will block other messages (with potentially shorter TTLs) from expiring earlier than itself. This caveat means RabbitMQ is unsuitable for this purpose and I cannot find any non-Java message broker that satisfies the requirement for a persistent scheduler.

Does programmable persistent scheduling software exist for Linux?

答:
Does programmable persistent scheduling exist for Linux? Yes.

The at command is designed to execute commands once at a specified time in the future. But caveat emptor. Like cron, Unix's repeating-event scheduler, at has been available essentially forever. But it doesn't get as much attention as cron, and in some quarters it has a bit of a reputation for occasionally forgetting events.

I concur with your choice to not use the time-to-live feature of message routing middleware. Blocking behavior and other likely failure modes make that a depends-on-many-assumptions, probably-fragile approach.

If your application has only a modest number of such future signaling events, and if it can withstand the possibility that an external system might not always signal at the appointed time, farming out to at might make sense. If you have a high volume of future signals, and/or need a very-high-fidelity / guaranteed delivery, consider bringing that feature in under your own development and control. If you store your event records in a standard, proven persistence manager (e.g. RDBMS), the "fire event" logic is straightforward.


问:
Function guaranteed to never return the same value twice
This is a question I was asked at a job interview, and I can't figure out the answer they were looking for, so I'm hoping someone here might have some ideas. The goal is to write a function that is guaranteed to never return the same value twice. Assume that this function will be accessed by multiple machines concurrently.

My idea was to assign each machine a unique id and pass that value into the unique value generator function:

```<code>var i = 0;
function uniq(process_id, machine_id) {
   return (i += 1).toString() + machine_id + "-" + process_id;
}
</code>```

This would avoid the fallout from race conditions since even if two or more processes read the same value for i, each return value is tagged a unique combination of process id and machine id. However, my interviewer didn't like this answer because bringing another machine online involves assigning it an id.

So can anybody think of another way to solve this that doesn't involve configuring each machine to have a unique id? I'd like to have an answer in case this question comes up again. Thanks.

答:
```<code>string uniq(string machine_id)
{
   static long u = long.MinValue;
   Interlocked.Increment(ref u);

   //Time stamp with millisecond precison
   string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff",
                                            CultureInfo.InvariantCulture);

   return machine_id + "-" + timestamp + "-" + u;
}
</code>```

In the above way we can make sure that return value is different even if there are restart or even if called simultaneous from different machines.

Body:
string uniq(string machine_id)
{
   static long u = long.MinValue;
   Interlocked.Increment(ref u);

   //Time stamp with millisecond precison
   string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff",
                                            CultureInfo.InvariantCulture);

   return machine_id + "-" + timestamp + "-" + u;
}

In the above way we can make sure that return value is different even if there are restart or even if called simultaneous from different machines.


答:
if in TDD in theory you have to write first your test suit and build your code up from it

Here is your misunderstanding. TDD is not about writing a full test suite first - that's is a false myth. TDD means to work in small cycles,

writing one test at a time

implement only as much code as needed to make the test "green"

refactor (the code and the tests)

So the creation of a test suite is not done in one step, and not "before the code is written", it is interwoven with the implementation of the code in stake.

Applied to your example: you should try to start with a simple test for a controller without any dependencies (something like a prototype). Then you implement the controller, and refactor. Afterwards you either add a new test which expects your controller to do a little bit more, or you refactor/extend your existing test. Then you modify your controller until the new test becomes "green".  That way you start with a simple combination of tests & subject under test, and end up with a complex test & subject under test.

When going this route, at some point in time you will find out what additional data you need as input for the controller to do its work. This can indeed happen at a moment where you try to implement a controller method, and not when designing the next test. That is the point where you stop to implement the method for a short time, and start introducing the missing dependencies first (maybe by a refactoring of your controller's constructor). This leads straightforward to a refactoring of your existing tests - in TDD, you will typically first change the tests calling the constructor, and add the new constructor attributes afterwards. And that's where coding and writing of the tests become completly entangled.

Title: I'm confused about which is the correct way to work with TDD

Body:
I'm trying to grasp what's the idea behind TDD and how a team is supposed to work with it. I have the following test case with NUnit + Moq (just writing by memory, it is not assured the example compiles but it should be explanatory):

```<code>[Test]
public void WhenUserLogsCorrectlyIsRedirectedToLoginCorrectView() {
    Mock<IUserDatabaseRepository> repoMock = new Mock<IUserDatabaseRepository>();
    repoMock.Setup(m => m.GetUser(It.IsAny())).Returns(new User { Name = "Peter" });

    Mock<ILoginHelper> loginHelperMock = new Mock<ILoginHelper>();
    loginHelperMock.Setup(m => m.Login(It.IsAny(), It.IsAny())).Returns(true);
    Mock<IViewModelFactory> factoryMock = new Mock<IViewModelFactory>();
    factoryMock.Setup(m => m.CreateViewModel()).Returns(new LoginViewModel());

    AccountController controller = new AccountController(repoMock.Object, loginHelperMock.Object, factoryMock.Object)

    var result = controller.Index(username : "Peter", password: "whatever");

    Assert.AreEqual(result.Model.Username, "Peter");
}
</code>```

AccountController has 3 dependencies which I mock that, when orchestrated inside the controller, allows me to verify if a login was correct or not.

What stumbles my mind is that... if in TDD in theory you have to write first your test suite and build your code up from it, how am I supposed to know beforehand that in order to perform my operation I'll need to use those three dependencies and that the operation will call certain operations? It's like I need to know the innards of the Subject Under Test before even implementing it in order to Mock the dependencies and isolate the class, creating some kind of write test - write code - modify test if necessary cycle.

Naturally, without any knowledge of the innards of my code and just expressing the test, I could express it like it could just need the ILoginHelper and "magically" suppose before writing the code that it will return the user on a successful login (and ultimately realize that the underlying framework doesn't work that way, for instance returning just an ID instead of the full object).

Am I understanding TDD in an incorrect way? Which is a typical TDD practice on a complex case?

Thank you


问:
How can I make a case for "dependency management"?
I'm currently trying to make a case for adopting dependency management for builds (ala Maven, Ivy, NuGet) and creating an internal repository for shared modules, of which we have over a dozen enterprise wide.  What are the primary selling points of this build technique?  The ones I have so far:

Eases the process of distributing and importing shared modules, especially version upgrades.

Requires the dependencies of shared modules to be precisely documented.

Removes shared modules from source control, speeding and simplifying checkouts/check ins (when you have applications with 20+ libraries this is a real factor).

Allows more control or awareness of what third party libs are used in your organization.

Are there any selling points that I'm missing?  Are there any studies or articles giving improvement metrics?

答:
I'm not 100% sure on the positives. Here's a few negatives

You often end up adding dependencies to 3rd party servers/endpoints that might
not be stable.

I've had it happen with bower that the repo of some dependencies
was deleted or moved. So a new dev comes along, clones my repo, types
bower install and gets errors for un-accessible repos. If instead I
had checked in the 3rd party code into my repo that problem disappears.

This is solved like the OP suggests if you're pulling deps from copies
kept on a server you run.

Harder for noobs.

I work with art students with very little command line experience.
They make art with Processing, arduino, Unity3D, and get by with very
little tech knowledge. They wanted to use some HTML5/JavaScript I wrote.
Steps because of bower

Download Zip of repo from github  (notice that's on the right of every
repo on github. Because they don't know git)

Download and install node (so we can run npm to install bower)

Install git or msysgit (because bower requires it and it's not installed
on many students' machines)

Install bower (npm install -g bower)

bower install (finally to get our dependencies)

Steps 2-5 can all be deleted if we just check in the files to our github repo.
Those steps likely sound super easy to you and me. To the students they were
very confusing and they wanted to know what all the steps where and what
they were for which might be good learning possibly but was entirely
orthogonal to the class topic and so likely quickly forgotten.

It adds another step when pulling.

It's happened many times I do a git pull origin master and then test my
code and it takes 5 to 10 minutes to remember I needed to type bower install
to get the latest deps. I'm sure that's easily solved with some pull script
hook.

It makes git branching harder

If 2 branches have different deps you're kind of screwed. I suppose you can
type bower install after every git checkout. So much for speed.

As for your positives I think there are counter examples to each of those

Eases the process of distributing and importing shared modules, especially version upgrades.

vs what? It's certainly not easier to distribute. Pulling one repo instead of 20 is not easier and is more likely to fail. See #1 above

Removes shared modules from source control, speeding and simplifying checkouts/check ins (when you have applications with 20+ libraries this is a real factor).

Conversely it means your dependent on others for fixes. Meaning if your deps are pulling from a 3rd party source and you need a bug fixed you have to wait for them to apply your patch. Worse, you probably can't just take the version you want plus your patch, you'd have to take the latest which might not be backward compatible with your project.

You can solve that by cloning their repos separately and then you point your project deps to your copies. Then you apply any fixes to your copies. Of course you could also do that if you just copy the source into your repo

Allows more control or awareness of what third party libs are used in your organization.

That seems arguable. Just require devs to put 3rd party libraries in their own folder under <ProjectRoot>/3rdparty/<nameOfDep>.  It's just as easy to see what 3rd party libs are used.

I'm not saying there are no positives. The last team I was on had > 100 3rdparty deps. I'm just pointing out it's not all roses. I'm evaluating if I should get rid of bower for my needs for example.


问:
Should I use relational or noSQL databases for this problem
I'm working on a project where one part is to save data of different people. A typical person might have the following structure:

```<code>Email: Multiple values possible
City: Multiple values possible
Contact no.: Multiple values possible
...
</code>```

As you can see, the point here is the possibility of multiple values for different fields. If I store this in a relational database (say, MySQL), I think queries will become a mess because I'll have to either maintain too many tables with foreign keys, or store delimited values (which I find extremely ugly and inconvenient).

Will a NoSQL database, such as MongoDB, be a better solution here? That's because I think data can then be stored in objects, and multiple values can be handled easily as arrays within arrays, etc.

Will this be a good decision or do you see some problems in the long run? The volume of transactions will not be too much (say, a few hundred a day at most).

Thanks in advance!

答:
What you really need is an additional "address type" column containing values like "home", "work", "summer home", "winter home" etc. and have several "address" rows per person.

You will need something like this to decide which address is the most useful for a given use case.


答:
Actually, I would not change the whole type of database system because there is one minor problem with modeling one artifact. Assumed you will stick to a relational DB system, you have the following options:

live with multiple tables for each type of information about persons. Yes, some queries may become a little bit more complicated, but to my experience, that does not mean they "become a mess", that is an exaggeration. If you need the same kind of complictated JOIN over and over again, add some views to the model providing the JOINed data and allowing omre simple queries.

live with delimited values (typically, only for some of your information fields). That's acceptable if you not intend to use that data in a WHERE condition, and you not intend to modify parts of that data by SQL.

store the complex information like a list of mail adresses in XML or JSON strings. Some relational DB systems directly support such kind of attributes (most modern relational DBs have some kind of XML support, some support even JSON). This will also allow you to store more complex information like a whole address in one attribute, with different structure variants for each person

make a more generic relational model with tables InformationField (n:1 relation to Person) and InformationFieldType (1:n relation to InformationField). This will allow you to add an arbitrary number of information fields to persons at run time without changing the DB schema afterwards (somewhat similar to a NoSQL DB). The drawback is that some queries become indeed even more complicated.

Title: Should I use relational or noSQL databases for this problem

Body:
I'm working on a project where one part is to save data of different people. A typical person might have the following structure:

```<code>Email: Multiple values possible
City: Multiple values possible
Contact no.: Multiple values possible
...
</code>```

As you can see, the point here is the possibility of multiple values for different fields. If I store this in a relational database (say, MySQL), I think queries will become a mess because I'll have to either maintain too many tables with foreign keys, or store delimited values (which I find extremely ugly and inconvenient).

Will a NoSQL database, such as MongoDB, be a better solution here? That's because I think data can then be stored in objects, and multiple values can be handled easily as arrays within arrays, etc.

Will this be a good decision or do you see some problems in the long run? The volume of transactions will not be too much (say, a few hundred a day at most).

Thanks in advance!


问:
Why Do B+ Trees Have a Minimum Occupancy of 50%?
As far as I can tell, the basic operations (add, delete, search) on a B+ Tree would function the same if minimum occupancy was 1, or 1/3, or any other function on node size.

All the sources available give the minimum occupancy as 50%.  Why 50%?

答:
A minimum occupancy of 1 isn't possible with a B+ tree as each node has to have one entry from the parent node.

Occupancies of less than 50% means that the tree can be made more efficient by redistributing entries between nodes and if two nodes have less than 50% occupancy, they get merged into one node. Or as Billy ONeal points out, the tree grows by splitting nodes, to have less than 50% occupancy, you would need to split one node into 3 or more.


问:
Why are self-hosting compilers considered a rite of passage for new languages?
I've heard in a number of places now that people expect languages to use, or at least have, a self-hosting compiler in order to deserve respect.

I'm curious as to why this is. A compiler seems like a very significant piece of software to write, and I imagine not all languages are well-suited to creating them. Wouldn't it make more sense to spend the effort working in something that will give better results?

答:
Is it possible to produce a programming language that is not well designed for writing a compiler but is well designed for some other purpose?

Looking at a language like SQL I suppose the answer is yes. But languages of that nature are not general purpose.


问:
How to prevent race conditions in a web application?
Consider an e-commerce site, where Alice and Bob are both editing the product listings. Alice is improving descriptions, while Bob is updating prices. They start editing the Acme Wonder Widget at the same time. Bob finishes first and saves the product with the new price. Alice takes a bit longer to update the description, and when she finishes, she saves the product with her new description. Unfortunately, she also overwrites the price with the old price, which was not intended.

In my experience, these issues are extremely common in web apps. Some software (e.g. wiki software) does have protection against this - usually the second save fails with "the page was updated while you were editing". But most web sites do not have this protection.

It's worth noting that the controller methods are thread-safe in themselves. Usually they use database transactions, which make them safe in the sense that if Alice and Bob try to save at the precise same moment, it won't cause corruption. The race condition arises from Alice or Bob having stale data in their browser.

How can we prevent such race conditions? In particular, I'd like to know:

What techniques can be used? e.g. tracking the time of last change. What are the pros and cons of each.

What is a helpful user experience?

What frameworks have this protection built in?

答:
I have seen 2 main ways:

Add the timestamp of the last update of the page the use is editing in a hidden input. When committing the timestamp is checked against the current one and if they don't match it has been updated by someone else and return an error.

pro: multiple users can edit different parts of the page. The error page can lead to a diff page where the second user can merge his changes in the new page.

con: sometime large parts of effort gets wasted during large concurrent edits.

When a user starts editing the page lock it for a reasonable amount of time, when another user then tries to edit he gets an error page and has to wait until either the lock expires or the first user has committed.

pro: edit efforts are not wasted.

con: an unscrupulous user can lock a page indefinitely. A page with an expired lock may still be able to commit unless otherwise dealt with (using technique 1)


答:
It's like I need to know the innards of the Subject Under Test before
  even implementing it in order to Mock the dependencies and isolate the
  class, creating some kind of write test - write code - modify test if
  necessary cycle.

Yes, to some extent you do. So I don't think you're misunderstanding how TDD works.

The problem is that - as others have mentioned - it feels very odd at first, almost wrong to do it this way. In my opinion that's actually showcasing the what I feel is the biggest benefit of TDD: you have to properly understand the requirement before you write code.

As programmers, we like to write code. So what feels "right" and "natural" to us it to skim requirements and get stuck in as quickly as possible. The design problems then gradually become apparent as you build up and test the codebase. So you refactor and fix them and things gradually improve and move toward your goal.

Although fun, this isn't a particularly efficient way to do things. Far better to have a proper grasp of what a software module should be doing first, get your tests down and then write the code. It's less refactoring, less test maintenance and it forces you into better architecture out of the block.

I don't do a whole lot of TDD, and I think the "100% code coverage" mantra to be pointless. Especially in cases like yours. But adopting TDD still has a lot of value because it's such a boon in making sure things are well designed and well maintained across your code.

So in summary, the fact you're finding this bizarre is probably a good sign that you're on the right path.


问:
Domain-Driven-Design - external dependencies in the Entity problem
I'd like to start Domain-Driven-Design, but there are several problems I'd like to solve before starting :)

Let's imagine I have a Groups and Users and when user wants to join a group, I'm calling groupsService.AddUserToGroup(group, user) method. In DDD I should do group.JoinUser(user), which looks pretty good.

The problem appears if I there are some validation rules for adding a user, or some external tasks need to be started when user is added to the group. Having these tasks will lead to the entity having external dependencies.

An example could be - a restriction that user can only participate in 3 groups max. This will require DB-calls from inside group.JoinUser method to validate this.

But the fact that an Entity depends on some external services/classes doesn't seem so good and "natural" to me.

What's the proper way to deal with this in DDD?

答:
The way I would approach the problem of validation is this way:
Create a Domain Service called MembershipService:

```<code>class MembershipService : IMembershipService
{
   public MembershipService(IGroupRepository groupRepository)
   {
     _groupRepository = groupRepository;
   }
   public int NumberOfGroupsAssignedTo(UserId userId)
   {
        return _groupsRepository.NumberOfGroupsAssignedTo(userId);
   }
}
</code>```

The Group entity needs to be injected with IMemberShipService. This can be done at the class level or the method level. Lets assume we do it at the method level.

```<code>class Group{

   public void JoinUser(User user, IMembershipService membershipService)
   {
       if(membershipService.NumberOfGroupsAssignedTo(user.UserId) >= 3)
         throw new BusinessException("User assigned to more than 3 groups. Cannot proceed");

       // do some more stuff
   }
}
</code>```

The Application service: GroupService can be injected with IMemberShipService using Constructor injection, which it can then pass to JoinUser method of the Group class.

Body:
The way I would approach the problem of validation is this way:
Create a Domain Service called MembershipService:

class MembershipService : IMembershipService
{
   public MembershipService(IGroupRepository groupRepository)
   {
     _groupRepository = groupRepository;
   }
   public int NumberOfGroupsAssignedTo(UserId userId)
   {
        return _groupsRepository.NumberOfGroupsAssignedTo(userId);
   }
}

The Group entity needs to be injected with IMemberShipService. This can be done at the class level or the method level. Lets assume we do it at the method level.

class Group{

   public void JoinUser(User user, IMembershipService membershipService)
   {
       if(membershipService.NumberOfGroupsAssignedTo(user.UserId) >= 3)
         throw new BusinessException("User assigned to more than 3 groups. Cannot proceed");

       // do some more stuff
   }
}

The Application service: GroupService can be injected with IMemberShipService using Constructor injection, which it can then pass to JoinUser method of the Group class.


问:
What to send when a client wants a sample of my code to test my qualities?
We've all faced this. You apply to a cool project and they ask you to send them a piece of your code. On the surface, this look OK and I am fine with it.

But what shall I send them? My cool utility? Snapshot of structure in complex project? Something else?

So far, I have tried to persuade them to have a desktop share via Skype and that I lead them through code and structure. But somehow clients do not like this approach.

So I'd like to hear your thoughts.

答:
I say, don't send a sample. You're not a perfume maker. You're a problem solver who uses code and software as your main tool, and the code you'll write for the client will be made to fit their needs.

Send references. Send testimonials. Send descriptions of past problems you've solved and how you went about designing the solutions.

If it's an open source project, it's best to start by submitting patches and fixing bugs.

Don't sell code by the pound. Code samples are meaningless.


问:
Why is it so bad to read data from a database "owned" by a different microservice
I have recently read this excellent article on the microservice architecture: http://www.infoq.com/articles/microservices-intro

It states that when you load a web page on Amazon, then 100+ microservices cooperate to serve that page.

That article describes that all communication between microservices can only go through an API. My question is why it is so bad to say that all database writes can only go through an API, but you are free to read directly from the databases of the various micro services. One could for example say that only a few database views are accessible outside the micro service so that the team maintaining the micro service know that as long as they keep these views intact then they can change the database structure of their micro service as much as they want.

Am I missing something here? Is there some other reason why data should only be read via an API?

Needless to say, my company is significantly smaller than Amazon (and always will be) and the maximum number of users we can ever have is about 5 million.

答:
Microservice Architecture is hard to describe but the best way to think about it is a marriage between Component Oriented Architecture and Service Oriented Architecture.  Software as a suite is composed of many small business components with a very specific business domain responsibility.  Their interface to the outside world either in provided services or required services is through an API of clearly defined services.

Writing to and even reading from a database that is outside of your components business domain is against this style of architecture.

The primary reason for this is that an API provided through a service by another software component has the reasonable expectation that the API will most likely be backwards compatible as new releases of the service providing component become available.  If I am the developer of a "providing" component then I only have to worry about backwards compatibility to my API.  If I know that there are three other development teams that wrote custom queries against my database directly then my job has become much more complicated.

Even worse, maybe that other team that wrote these is mid sprint in a critical project and they can't accept this change now from your component.  Now software development for your component on a business domain that you own is being driven by development on another business domain.

Full interaction through services reduce coupling between various software components so situations like this do not occur so frequently. When it comes to other components using a View in the database, then you have more capability to make the View backwards compatible if anybody else wrote queries against it.  I still feel however that this should be the exception case and only should be done for perhaps reporting or batch processing where an application will need to read in enormous amounts of data.

Clearly this works well in large distributed teams where development teams are separated out by business domain like Amazon.  If you are a small development shop you can still benefit by this model, especially if you need to ramp up for a big project quickly, but also if you have to deal with vendor software.


问:
How to ensure objects unique by equality?
I frequently have this problem but didn't find it as an established programming pattern. I have some Class C whose equality is determined by some key k and I want to prevent time-consuming initialisation of additional equal objects.

This is my implementation but the synchronized get method prevents parallel instantiation.

```<code>Class C
{
 Key key;

 private static Map<Key,C> cs = new HashMap<Key,C>();

 private C(Key key)
 {
  // this takes a long time
 }

 synchronized static C get(Key key)
 {
  C c = cs.get(key);
  if(c==null)
  {
   c = new C(key);
   cs.put(key,c);
  }
  return c;
 }

 @Override public boolean equals(Object o)
 {
    if (this == o) return true;
    if (o == null) return false;
    if (getClass() != o.getClass()) return false;
    C other = (C) o;
    if (key == null)
    {
        if (other.key != null) return false;
    }
    else if (!key.equals(other.key)) return false;
    return true;
 }

 @Override public int hashCode() {..}
}
</code>```

Can you point me to an existing best-practise to this, if it exists, or show me how to implement this optimally? My criteria are clarity, brevity, performance and thread-safeness.

答:
In his book Effective Java, Josuha Bloch mentions this pattern as a good practice for this sort of scenario (Item 1: Consider static factory methods instead of constructors).

Some common alternative names for the method that here is called C.getare the following C.getInstance, C.valueOf, C.of.


答:
You need to "read your writes", which means before you write down a change, you need to read the record again and check if any changes where made to it since you last read it. You can do this field-by-field (fine-grained) or based on a timestamp (coarse-grained). While you do this check you need an exclusive lock on the record.
If no changes were made, you can write down your changes and release the lock. If the record has changed in the meantime, you abort the transaction, release the lock and notify the user.</p>

Title: How to prevent race conditions in a web application?

Body:
Consider an e-commerce site, where Alice and Bob are both editing the product listings. Alice is improving descriptions, while Bob is updating prices. They start editing the Acme Wonder Widget at the same time. Bob finishes first and saves the product with the new price. Alice takes a bit longer to update the description, and when she finishes, she saves the product with her new description. Unfortunately, she also overwrites the price with the old price, which was not intended.

In my experience, these issues are extremely common in web apps. Some software (e.g. wiki software) does have protection against this - usually the second save fails with "the page was updated while you were editing". But most web sites do not have this protection.

It's worth noting that the controller methods are thread-safe in themselves. Usually they use database transactions, which make them safe in the sense that if Alice and Bob try to save at the precise same moment, it won't cause corruption. The race condition arises from Alice or Bob having stale data in their browser.

How can we prevent such race conditions? In particular, I'd like to know:

What techniques can be used? e.g. tracking the time of last change. What are the pros and cons of each.

What is a helpful user experience?

What frameworks have this protection built in?


答:
This is a variation of the singleton pattern, called Multiton.

You will have to manage the global state introduced with the HashMap. This can lead to diffucult unit testing.

The implementation of the synchronized method looks the same, as shown in the Wikipedia article. But if you can restructure your use case, so that you can avoid the synchronizing of objects it would be preferable.

Title: How to ensure objects unique by equality?

Body:
I frequently have this problem but didn't find it as an established programming pattern. I have some Class C whose equality is determined by some key k and I want to prevent time-consuming initialisation of additional equal objects.

This is my implementation but the synchronized get method prevents parallel instantiation.

```<code>Class C
{
 Key key;

 private static Map<Key,C> cs = new HashMap<Key,C>();

 private C(Key key)
 {
  // this takes a long time
 }

 synchronized static C get(Key key)
 {
  C c = cs.get(key);
  if(c==null)
  {
   c = new C(key);
   cs.put(key,c);
  }
  return c;
 }

 @Override public boolean equals(Object o)
 {
    if (this == o) return true;
    if (o == null) return false;
    if (getClass() != o.getClass()) return false;
    C other = (C) o;
    if (key == null)
    {
        if (other.key != null) return false;
    }
    else if (!key.equals(other.key)) return false;
    return true;
 }

 @Override public int hashCode() {..}
}
</code>```

Can you point me to an existing best-practise to this, if it exists, or show me how to implement this optimally? My criteria are clarity, brevity, performance and thread-safeness.


问:
Domain models with properties not always set
I don't know if to have domain models with properties that not always are set, it's a some kind of code smell or design error. I put an example:

I have an app that lets read internet magazines using Rss. For domain models, I use cases of use. Briefly I have:

There is a magazines library.

You can consult the profile of the magazine.

You can explore news magazine.

For that, I extracted this entities: library, magazine, magazine profile, magazine news.

My classes are:

```<code>class Magazine
    private int id; // BD id row
    private MagazineProfile magazineProfile;
    private List<MagazineNews> news;

class MagazineProfile
    private String title;
    private String webUrl;
    [...]

class MagazineNews
    private String title;
    private String body;
    private Date pubDate;
    [...]
</code>```

In some points of my app, I will be exploring only the magazines using their magazine profile (displaying a list of all magazines), in other points I will be exploring only the news and in other I will be exploring news and the magazine profile at the same time.

Depending on the case, sometimes, my object magazine will have the properties magazineProfile news set or empty.

So my question is, if this design is an error approach to have properties that will be established according to the window in which the user is browsing. Should I work only with the objects that interest me, in my case, magazineProfile and news?

答:
I don't believe that your design is an issue but the implementation can give you some problems. Use the Null Object Pattern to fill in the fields that otherwise would be missing.

In your case, a "missing" MagazineProfile would be marked by a singleton that returned an empty title, webUrl, etc.


答:
Databases are not very good at information hiding, which is quite plausible, because their job is to actually expose information. But this makes them a lousy tool when it comes to encapsulation. Why do you want encapsulation?

Scenario: you tie a couple of components to an RDBMS directly, and you see one particular component becoming a performance bottle-neck for which you might want to denormalize the database, but you can't because all other components would be affected. You may even realize that you'd be better off with a document store or a graph database than with an RDBMS. If the data is encapsulated by a small API, you have a realistic chance to reimplement said API any way you need. You can transparently insert cache layers and what not.

Fumbling with the storage layer directly from the application layer is the diametrical opposite of what the dependency inversion principle suggests to do.

Title: Why is it so bad to read data from a database "owned" by a different microservice

Body:
I have recently read this excellent article on the microservice architecture: http://www.infoq.com/articles/microservices-intro

It states that when you load a web page on Amazon, then 100+ microservices cooperate to serve that page.

That article describes that all communication between microservices can only go through an API. My question is why it is so bad to say that all database writes can only go through an API, but you are free to read directly from the databases of the various micro services. One could for example say that only a few database views are accessible outside the micro service so that the team maintaining the micro service know that as long as they keep these views intact then they can change the database structure of their micro service as much as they want.

Am I missing something here? Is there some other reason why data should only be read via an API?

Needless to say, my company is significantly smaller than Amazon (and always will be) and the maximum number of users we can ever have is about 5 million.


答:
What is more important and significant about a microservice: its API or its database schema?  The API, because that is its contract with the rest of the world.  The database schema is simply a convenient way of storing the data managed by the service, hopefully organised in a way that optimises the microservice´s performance.  The development team should be free to reorganise that schema - or switch to an entirely different datastore solution - at any time.  The rest of the world should not care.  The rest of the world cares when the API changes, because the API is the contract.

Now, if you go peeking into their database

You add an unwanted dependency on their schema.  They cannot change it without having an impact on your service.

You add unwanted and unpredictable load to their internals.

The performance of your own service will be affected by the performance of their database (they will be trying to optimise their service to perform well for clients and their database to perform well only for their service)

You are tying your implementation to a schema which may well not accurately and distinctively represent the resources in their data store - it may have extra details which are only needed to track internal state or satisfy their particular implementation (which you should not care about).

You may unwittingly destroy or corrupt the state of their service (and they will not know you are doing this)

You may update/delete/remove resources from their database without them knowing this has happened.

The last two points may not happen if you are only granted read access, but the other points are more than a good enough reason.  Shared databases are a bad thing.

It is common for less experienced developers (or those who do not learn) to see the database as more important than the service, to see the database as the real thing and the service just a way of getting to it.  That is the wrong way round.


问:
How to prevent others from using non-thread safe variables in a multithreading environment?
I have an application written in C++ that was originally single threaded, but, due to the increasing complexity of this project, I'll need to expand it to at least two or three threads.

There are only a total of four variables that will be used between more than one thread threads, making it useless to make everything thread-safe. The obvious solution is to just create a mutex for each variable and move on with my life.

However, looking back, this seems like a horrible idea! I'm afraid that another programmer may forget that the majority of the methods and variables are not thread-safe and use a variable in another thread.

Since I'm the main programmer for this project, it doesn't seem like this would be an issue, but I honestly feel like this is bad programming and it feels really messy.

What are some ways to keep the variables separate to make it easier to tell which variable is for which thread? I've been thinking about isolating the code for the thread so it cannot access the other global variables (giving a compile error instead of silently creating a bug). I could also create a namespace or class for each thread. Is there a best practice for this?

答:
There are two elements to this problem: #1, the technical change to the existing code base to support multi-threading, and #2 changing the culture of the company in order to be aware of thread safety in the code.

The first is relatively simple. First, document the functions in the class that are thread safe and are not thread safe. I agree with Jeffery Thomas that you should treat it as a major new feature. Often, I'll write an entirely new class with some (relation to the original class to keep it DRY) that is thread safe. While there is no explicit "thread safe" tag in c++, I find making the class const correct can do a lot to help out. You should also clearly document what is thread safe or not (follow a convention, be CONSISTENT, and make the assumed state not thread safe).

The larger problem is changing the culture of the company to make sure everyone is aware of thread safety. I find this is where things like a style guide and code reviews can be very helpful. A style guide can inform people exactly how to mark things as thread safe. We do a lot of C programming, so I'm partial to decorating names, but you should choose a style that works for you. Some companies lean towards making everything thread safe by default, but I find that tends to add a lot of unnecessary code complexity, and can add non-insignificant overhead on occasion.

Code reviews, when done correctly, are a way to educate everyone on the style and to pass around information about programming in general.


问:
URLs in javascript in the browser
We are trying to continually improve our source code base and a question came up recently which throws open a new area to improvement. Where best to put URLs that are needed in JavaScript?

Do we put the URLs in the JavaScript files themselves?

```
    function onButtonClick() {
        $.ajax({url:"/my/url/directly/in/the/javascript"});
    }
```

Note: The magic string above is incidental. There could be an object that returns URLs or whatever. The point is that the URLs are stored in the JavaScript files.

Do we have some mechanism to inject the URLs into the JavaScript. e.g. Having a small script on the page that sets up the URLs from which the JavaScript in the files can access.

```
    <script>
        var ps = new pageScript();
        ps.initUrls({someUrl:<%= Url.Action("SomeAction", "SomeController").ToJson() %>);
        ps.run();
    </script>
```

The .ToJson() method is an extension method that turns an object into its JSON serialised version, so, for a string it outputs the quotation marks and escapes it if need be.

Then in the JavaScript file it can pick up the URLs from where ever the initUrls() function stored them.

```
    function onButtonClick() {
        $.ajax(myUrls.someUrl);
    }
```

Or something else?

We already use 1 and 2 in our code base from various developers over the years, but is there a better way? Or is either of the above a good overall solution?

答:
What you want to do is start with a config object:

```<code>myApp.config = {
  myUrls: {
    someUrl: "http://default.com";
  },
  someSharedPropAcrossAllEnvs: 'something'
};
</code>```

And then create environment specific versions that override the appropriate values:

```<code>var envs = {};

var envs.dev = {
  myUrls: {
    someUrl: "http://localhost:8080";
  }
};

var envs.test = {
  myUrls: {
    someUrl: "http://test.com";
  }
};

var evns.production = {
  myUrls: {
    someUrl: "http://productiob.com";
  }
};
</code>```

You then somehow need to set the appropriate environment that you are running in:

```<code>var env = envs['<%= SOME_SERVER_VALUE_OR_SOMETHING%>'];
</code>```

Which should bind to:

```<code>env = env['dev'] // test or production
</code>```

Then mixin the appropriate config in and override the default values

```<code>config = $.extend({}, config, env);
</code>```

This will mixin the correct environment vars which you can use:

```<code>   function onButtonClick() {
        $.ajax(myApp.config.myUrls.someUrl);
    }
</code>```

Title: URLs in javascript in the browser

Body:
What you want to do is start with a config object:

myApp.config = {
  myUrls: {
    someUrl: "http://default.com";
  },
  someSharedPropAcrossAllEnvs: 'something'
};

And then create environment specific versions that override the appropriate values:

var envs = {};

var envs.dev = {
  myUrls: {
    someUrl: "http://localhost:8080";
  }
};

var envs.test = {
  myUrls: {
    someUrl: "http://test.com";
  }
};

var evns.production = {
  myUrls: {
    someUrl: "http://productiob.com";
  }
};

You then somehow need to set the appropriate environment that you are running in:

var env = envs['<%= SOME_SERVER_VALUE_OR_SOMETHING%>'];

Which should bind to:

env = env['dev'] // test or production

Then mixin the appropriate config in and override the default values

config = $.extend({}, config, env);

This will mixin the correct environment vars which you can use:

   function onButtonClick() {
        $.ajax(myApp.config.myUrls.someUrl);
    }


问:
Sharing development test cases (unit and development integration) with the QA (test) team?
The testing team (the so-called QA team in some organizations) insists that the development team should share their (the development team's) test cases with them. Their arguments are that the development test cases are the starting point for the QA testing.

As a development team member, I don’t understand the request. Per me, the tester should test the solution based on the requirements. I don’t know if the test team should be shared with the detailed design (low-level design) document. However, we are sharing them the detailed design.

I have read some posts here that say the QA team should share their test cases with the development team for a better solution and for better throughput. But, nothing sort of the development team sharing their test cases with the QA test team.

It looks like my QA team is very happy if I share my development unit and integration test cases and the test results.

答:
When your dev team and your QA team don't not talk to each other, there is a certain risk that some tests are unnecessarily done twice, and some others are forgotten. One worst case scenario is when your dev team has implemented some nice automatic integration tests, which run in a few minutes or hours, and your QA people tests the same things manually, spending days or weeks for that task. Another bad scenario is when both groups think that the other group is responsible for some type of tests, and so those tests are omitted.

So, assuming both groups work as a team and not against each other, it makes sense to inform each other in detail which tests are made by which group, and let the two groups coordinate there activities.


问:
What is the best and most optimized way to return a filestream from a .NET WCF SOAP service?
To give some background, i have a WCF SOAP service in .NET that needs to return pdf files. This service will be used by multiple application, many times in a day. The size of the files returned varies from 10KB to 10MB. Also, there is no shared location where the file can be kept and the path can be returned. It can be done using byte[], but that will increase the load on service, which I want to avoid. Any suggestions are welcome.

Application is hosted as a windows service. It is being used mostly by Java Clients. When I am trying to directly return the file stream, at client side the return type does not get mapped to a proper class and returns a null object in an automatically generated empty class. Only in the case when I returned byte[], it was able to read the file.

答:
Message Transmission Optimization Mechanism (MTOM) is a mechanism for transmitting large binary attachments with SOAP messages as raw bytes, allowing for smaller messages.

please refer : http://msdn.microsoft.com/en-us/library/aa395209.aspx
 for more details.


答:
Testing team (the so called QA team in some organization) insists that the dev team should share their (Dev team's) test cases with them.

Sure, QA should have a general understanding of what is covered by unit/integration tests, and what is not.

Their arguments are Dev test cases are the starting point for the QA testing.

...even if their reasoning is flawed. The #1 mantra of a QA person is don't trust the developers. "Don't worry about it! I checked that thoroughly!" is the first step towards a giant production issue.

As Doc Brown says, it's not good to spend a whole bunch of QA time on something that is well covered by automated tests. But it is foolhardy to spend no time on something that is well covered by automated tests. And it's wasteful to spend a whole bunch of time documenting your unit tests in detail when QA shouldn't really trust them anyways (and because that level of documentation drives your developers to make less/bad unit tests).

Title: Sharing development test cases (unit and development integration) with the QA (test) team?

Body:
The testing team (the so-called QA team in some organizations) insists that the development team should share their (the development team's) test cases with them. Their arguments are that the development test cases are the starting point for the QA testing.

As a development team member, I don’t understand the request. Per me, the tester should test the solution based on the requirements. I don’t know if the test team should be shared with the detailed design (low-level design) document. However, we are sharing them the detailed design.

I have read some posts here that say the QA team should share their test cases with the development team for a better solution and for better throughput. But, nothing sort of the development team sharing their test cases with the QA test team.

It looks like my QA team is very happy if I share my development unit and integration test cases and the test results.


答:
In that case I would do something like this (pardon my Razor syntax):

HTML Link code:

```<code>    @Html.ActionLink("Link Text","ActionMethod","MyController", new { someArgument }, new{ id="mylink"})
</code>```

Javascript code:

```<code>$("#mylink").click(function(e){
   e.preventDefault();
   $.ajax({url:'@Url.Action("ActionMethod","MyController",new{ someArgument })'});
});
</code>```

This gives you a few benefits:

Ease of adaptation to routing changes -- Your ASP.NET MVC app has routing configurations set up.  What happens if your routing configuration changes so that your URIs look different?  By using the helper methods you don't have to worry about manually changing them.  The framework is injecting the correct URI on your behalf, and when you change your routing configuration your links will be updated for you.

Graceful degredation -- You're building your site in a way that allows the link to work without Javascript.  When the DOM is ready you're then blocking the href action that's been created in the HTML and enhancing it with an AJAX call.  If you subscribe to the Unobstrusive Javascript train of thought, this is a huge plus.

As you can see it's quite similar to what you're doing in #2 with some minor changes.  I don't think there's much benefit in optimizing any further than this.  You know where URLs are, and the server-side framework is determining how to build them correctly.  Your developers decide where and how they are created.

Title: URLs in javascript in the browser

Body:
We are trying to continually improve our source code base and a question came up recently which throws open a new area to improvement. Where best to put URLs that are needed in JavaScript?

Do we put the URLs in the JavaScript files themselves?

```
    function onButtonClick() {
        $.ajax({url:"/my/url/directly/in/the/javascript"});
    }
```

Note: The magic string above is incidental. There could be an object that returns URLs or whatever. The point is that the URLs are stored in the JavaScript files.

Do we have some mechanism to inject the URLs into the JavaScript. e.g. Having a small script on the page that sets up the URLs from which the JavaScript in the files can access.

```
    <script>
        var ps = new pageScript();
        ps.initUrls({someUrl:<%= Url.Action("SomeAction", "SomeController").ToJson() %>);
        ps.run();
    </script>
```

The .ToJson() method is an extension method that turns an object into its JSON serialised version, so, for a string it outputs the quotation marks and escapes it if need be.

Then in the JavaScript file it can pick up the URLs from where ever the initUrls() function stored them.

```
    function onButtonClick() {
        $.ajax(myUrls.someUrl);
    }
```

Or something else?

We already use 1 and 2 in our code base from various developers over the years, but is there a better way? Or is either of the above a good overall solution?

Body:
In that case I would do something like this (pardon my Razor syntax):

HTML Link code:

    @Html.ActionLink("Link Text","ActionMethod","MyController", new { someArgument }, new{ id="mylink"})

Javascript code:

$("#mylink").click(function(e){
   e.preventDefault();
   $.ajax({url:'@Url.Action("ActionMethod","MyController",new{ someArgument })'});
});

This gives you a few benefits:

Ease of adaptation to routing changes -- Your ASP.NET MVC app has routing configurations set up.  What happens if your routing configuration changes so that your URIs look different?  By using the helper methods you don't have to worry about manually changing them.  The framework is injecting the correct URI on your behalf, and when you change your routing configuration your links will be updated for you.

Graceful degredation -- You're building your site in a way that allows the link to work without Javascript.  When the DOM is ready you're then blocking the href action that's been created in the HTML and enhancing it with an AJAX call.  If you subscribe to the Unobstrusive Javascript train of thought, this is a huge plus.

As you can see it's quite similar to what you're doing in #2 with some minor changes.  I don't think there's much benefit in optimizing any further than this.  You know where URLs are, and the server-side framework is determining how to build them correctly.  Your developers decide where and how they are created.


问:
Who writes the technical 'user stories' in scrum
I know that a product owner should write a user story in scrum.

A user story is describing a feature for the end user.

But who describes what needs to be technically developed and how it needs to be implemented

and where is that information stored concerning scrum?

That would really interest me!

I see a big lack of knowledge in our company when developer start to implement the story but they do not know HOW to implement it!

For example they have to deal with a legacy COM API and have no idea how to handle it or they are not that technically skilled with WPF/WEB or whatever.

How does scrum help that people to start with the user story?

答:
The short answer is this: the product owner is responsible for creating the stories that the team must deliver. It is the team that decides how to deliver the stories. If part of the delivery involves some technical stories, it is the team that writes those stories. The team then works with the product owner to decide priority.

Again, the PO decides what to build, the team gets to decide how to implement those stories.


答:
Minimum occupancies of greater than 50% don't work, because when you need to split a node because the node is too full, it would be impossible to cut a node such that the two resulting nodes were greater than 50% full. (You could do 60/40 or something like that but the smaller node would always fail the data structure's invariant of each node being greater than 60% full, for example)

Minimum occupancies of less than 50% waste space because the goal is to need to read in the fewest number of nodes from secondary storage / memory, and increasing the amount of empty space in each node means that the average request needs to read a greater number of nodes from disk. (It would also be tricky to implement effectively given that the split operation needs to split into 1/(ratio) chunks instead of 2 chunks)

Title: Why Do B+ Trees Have a Minimum Occupancy of 50%?

Body:
As far as I can tell, the basic operations (add, delete, search) on a B+ Tree would function the same if minimum occupancy was 1, or 1/3, or any other function on node size.

All the sources available give the minimum occupancy as 50%.  Why 50%?


答:
There's no reason that you shouldn't share what you've tested with the QA team, however they should be duplicating the tests of yours that they feel are important to properly verifying the application.

1) They are responsible for testing the code/application/whatever. By duplicating your tests where appropriate, they verify that your test was done properly.

2) As a developer, you're responsible for unit testing your code (generally, however some organizations have started having dev's test their code as well). This is a different approach, and typically is focused more on covering the decision points in a method.

3) As you mentioned, it's important for your test team to share their test cases with you to help you think of cases that you may not have originally considered.

4) Someone mentioned that it's the test teams responsibility to test to the requirements, and while this is true, the detailed design is quite helpful as well. By having the design, the test team not only can make sure that you're covering the requirements, but helps them to understand some of the design decisions, and will help them to ultimately create better test cases.


答:
Short Answer

The Dev Team writes the technical things. Scrum helps you a bit but not much with the technical breakdown resp. getting started on a User Story. Scrum is almost What-World-only. The technical breakdown is How-World.

The breakdown provided by Scrum is:

User Story -> Acceptance Criteria

The breakdown people often use on top of this is:

Epic -> User Stories

User Story -> Subtasks

Acceptance Criteria -> Acceptance Tests

Plus, the team might write Technical Tasks for things they know need to be done (i.e. install IntelliJ IDEA for everyone at the start of the project) but which have no Business Value.

For further guidance on how to breakdown work, look out for XP (Extreme Programming), Clean Code, Pragmatic Programming, Software Engineering, CRC-Cards, OOP / OOA / OOD, Design Patterns, Refactoring, Working Effectively with Legacy Code, TDD (Test-Driven Development), BDD (Behavior-Driven Development), ATDD (Acceptance-Test Driven Development).

Long Answer

How Scrum Thinks

What-World and How-World

There is a What-World and a How-World. As you felt correctly, User Story is for Users, generating Business Value aka Secondary Value in the What-World. Scrum is mostly What-World only. It says little to nothing about the How-World, basically no more than "How-World is the responsibility of the Dev-Team".

User Story vs Task

Usually, Backlog Items which are for the How-World are not called User Story but Technical Task or Subtask. Many tools allow breaking down the User Story from the What-World into Subtasks in the How-World.

How Scrum Helps and Where that Help Ends

The help of Scrum for the How-World ends at a few points in the Sprint Planning Meeting:

[Sprint Planing Meeting] The team discovers misunderstanding of the story if different team mates come up with different Story Point estimates during the Planning Poker -> Discussion.

[Definition of Ready] The team does not accept User Stories which are too big (Story Points too high). A rule of thumb found in many Definition of Ready is that the Story Points must be less than half the team's velocity.

[Definition of Ready] The team does not accept User Stories without sufficient description of Acceptance Criteria. Acceptance Criteria are sufficient if the team has enough confidence on how to start writing the Acceptance Tests.

A few tips on the Level of Scrum

I found it helpful to do a break-down of User Stories into Subtasks during the Backlog Refinement meetings or at least the second part of the Sprint Planning Meeting (for some teams Sprint Planning 2 Meeting).

With inexperienced teams I found it helpful to strive for Atomic User Stories during the Backlog Refinement and Sprint Planning. An Atomic User Story is a User Story which cannot be broken down further into Smaller User Stories without loosing its Business Value entirely. In general User Stories don't need to be Atomic, I just found that it helps me with inexperienced teams.

And don't do "(Architecture|Design|Implementation|Test) of Feature X" as User Stories. I recommend that you even try to avoid this as a Subtask.

If I have Atomic User Stories and they seem to need further breakdown apart from the Acceptance Criteria to be implemented, it means to me that something is not working at the optimum level. Either the architecture is wrong / too complicated, i.e. technical instead of business-oriented. Or the team is inexperienced. Or both. In any case, action would be required to improve the situation by training and spreading knowledge.

Beyond Scrum

The Scrum Master beyond Scrum

Today, the Scrum Master is mostly understood as a Managerial Role, and that's bullshit. Originally, the Scrum Master was, and I advocate this, a Technical Role, not a managerial role, just like the Coach in XP.

It is all too easy to rely on Scrum and the Scrum Master and thus fall into a huge gap because Scrum says almost nothing about the How-World.

Rotating Scrum Master

Ideally, the Scrum Master rotates among those experienced developers who also have sufficient managerial and communication skills until everybody in the team is living "Inspect and Adapt" so deeply by heart that the Scrum Master becomes redundant; nobody and everybody would be Scrum Master at the same time.

But beware, Scrum Mastery is more like cooking, not like cleaning the table and washing dishes. You might want to rotate who cleans the table and washes the dishes, as everybody could do that. But you wouldn't want to rotate the cooking onto everyone, because there are people who can't cook or don't like cooking, and you want to eat good food.

The good thing about rotating the Scrum Master between expert developers is that the team is more likely to learn about more methods.

The Self-Organizing Team

From Scrum's perspective, the team must find out itself, ideally with the help of the Scrum Master.

Scrum also just talks of the Dev Team. Roles like Architect or Lead Engineer do not exist in Scrum. That doesn't mean that they're forbidden, it only means that Scrum doesn't say anything about them. Scrum proclaims a Self-Organizing Team, which means if the team declares an Architect, the team has an Architect. That's not defined by Scrum, but it's compliant with Scrum. I'm not proclaiming dedicated Architects (I worked as a designated Architect for years, and although I liked it, I'm fundamentally against the idea of a designated Architect), just giving an example.

Acceptance Tests

User Stories have Acceptance Criteria. These Acceptance Criteria are turned into Acceptance Tests

Other stuff

For a list of more stuff for breakdown, see How to break up a programming project into tasks for other developers?

Hope this helps.

Title: Who writes the technical 'user stories' in scrum

Body:
I know that a product owner should write a user story in scrum.

A user story is describing a feature for the end user.

But who describes what needs to be technically developed and how it needs to be implemented

and where is that information stored concerning scrum?

That would really interest me!

I see a big lack of knowledge in our company when developer start to implement the story but they do not know HOW to implement it!

For example they have to deal with a legacy COM API and have no idea how to handle it or they are not that technically skilled with WPF/WEB or whatever.

How does scrum help that people to start with the user story?


问:
I'm confused about which is the correct way to work with TDD
I'm trying to grasp what's the idea behind TDD and how a team is supposed to work with it. I have the following test case with NUnit + Moq (just writing by memory, it is not assured the example compiles but it should be explanatory):

```<code>[Test]
public void WhenUserLogsCorrectlyIsRedirectedToLoginCorrectView() {
    Mock<IUserDatabaseRepository> repoMock = new Mock<IUserDatabaseRepository>();
    repoMock.Setup(m => m.GetUser(It.IsAny())).Returns(new User { Name = "Peter" });

    Mock<ILoginHelper> loginHelperMock = new Mock<ILoginHelper>();
    loginHelperMock.Setup(m => m.Login(It.IsAny(), It.IsAny())).Returns(true);
    Mock<IViewModelFactory> factoryMock = new Mock<IViewModelFactory>();
    factoryMock.Setup(m => m.CreateViewModel()).Returns(new LoginViewModel());

    AccountController controller = new AccountController(repoMock.Object, loginHelperMock.Object, factoryMock.Object)

    var result = controller.Index(username : "Peter", password: "whatever");

    Assert.AreEqual(result.Model.Username, "Peter");
}
</code>```

AccountController has 3 dependencies which I mock that, when orchestrated inside the controller, allows me to verify if a login was correct or not.

What stumbles my mind is that... if in TDD in theory you have to write first your test suite and build your code up from it, how am I supposed to know beforehand that in order to perform my operation I'll need to use those three dependencies and that the operation will call certain operations? It's like I need to know the innards of the Subject Under Test before even implementing it in order to Mock the dependencies and isolate the class, creating some kind of write test - write code - modify test if necessary cycle.

Naturally, without any knowledge of the innards of my code and just expressing the test, I could express it like it could just need the ILoginHelper and "magically" suppose before writing the code that it will return the user on a successful login (and ultimately realize that the underlying framework doesn't work that way, for instance returning just an ID instead of the full object).

Am I understanding TDD in an incorrect way? Which is a typical TDD practice on a complex case?

Thank you

答:
Mocking data is just the practice of using dummy data.. the Moq frameworks make creating dummy data "easier".

ARRANGE | ACT | ASSERT

TDD generally is about creating your tests and then validating those tests "pass". Initially, the first test will fail since the code to validate that test has not been created yet.. I believe this is actually a certain type of testing; "red/green" testing, which i'm sure is the source of "Test Driven" methods today.

Generally, the tests validate the little nuggets of logic that make the bigger picture code work. You could start at the smallest level of function, and then work your way up to the more complicated functions.

yes, sometimes the setup or "mocking" will be somewhat intense, which is why using a moq framework is a good idea, however, if you focused on the core business logic, then you're tests will result in beneficial assurance that it works as expected and intended.

Personally, I don't test my controllers because everything that the controller is using has been tested to work, and generally, we don't need to test the framework.


答:
In a modern software architecture the intent is that the tests not only test the code but they do so in a way that documents their functionality.

This documentation of what the code does (in addition to what it is intended to do in the specs) is useful for QA'ers to better understand the intent of the code and also whether it matches the requirements.  It is also useful information when QA'ers are writing test cases and it will help give them a sense of what is, in theory, being tested already.  Some of the areas under test might benefit from additional cases and others might be exposed as not having tests at all.

The actual details of this exposure will depend greatly on the organizational makeup and in particular on the technical depth of the testers (e.g. reading source code).

To be somewhat contrarian... I often like to ignore the developer tests and come up with my 'own' tests (I am a member of a large QE team).  I have found that ignoring developer tests helps to avoid the mindset of looking at the problem/issue/feature from a developers point of view only.

MY QE motto is:  QE should be adding value by testing the product.  "merge and run unit tests" alone is insufficient QA !


答:
If the only problem with initializing multiple copies of a single object value is the time/memory it takes, you may want to consider switching to a ConcurrentHashMap and using the computeIfAbsent method to initialize values. This has the side effect that two copies of a single value may be initialized, however only one will be retained (the second will be garbage collected at some point) and all threads will be able to precede simultaneously.

This solution is not applicable, however, if initialization has side effects.


问:
Organise C++ classes around SQL database
My question is about how best to organize C++ classes around a database
model, and I understand this may appear very elementary.

The software I propose to create will do the following. It is intended for
small FMCG manufacturers and will use Qt.

The software will record non-conformance's, product complaints,
corrective actions and serve as an electronic record keeping

There will be quite a bit of 'business logic', as the standout
feature is intended to be comprehensive reporting, searching and
analysis, as well as a flexible approach to entering data to smooth
workflows (ie, a break away from the "one screen per process stage"
paradigm)

The persistent store is an SQL database, with a table(s) for each
type of record (some records will be broken into separate tables for
investigations/solutions. This means that most work will be done on a
single row).

Each customer who uses this software will require amendments,
additional columns/fields or changes in column names and maybe
business logic. Each customer may require updates which change the
database structure. The idea is that anything that can be customized, any
client specific requirements will live within these classes.

There will be reporting, mainly involving pulling records matching
particular categories, word searches, etc.

I have the database schema done and laid out, and the logic of how tables
relate is clear.  I have used this very schema in another framework, but a web based app doesn't seem to offer the level of power to the user with regards to the GUI, which is essential to differentiate this product from the others.

My question is how to design classes around the database. It is important to
get this right, so that the architecture of the software doesn't have to be
redesigned later on. The classes will not be responsible for the persistent
store, only for acting as an intermediary between the layer responsible for
the persistent store and the controllers/views.

The most logical approach appears to be to have a class for non-conformances/complaints etc, which solely store the instance (ie, one object per non-conformance record), validate data and class specific business logic (ie, computations).  One class per table seems logical in this case.  What I'm struggling with, is whether it is standard practice to simply have data members for each column, define getters and setters, or whether I should create a class which isn't hard-coded to map to a table, but which populates a map based on the database schema or external file which defines the database and column properties. The former means that the coding for the class needs to be changed when columns are modified, the latter potentially not.  Keep in mind, for the majority of the time, each user will be working with one record at at time.

In short, I can see example of how to do SQL queries, but I've struggled to
find anything which shows me what the class should look like (or if this entire approach is wrong) and I'd like to compare what I'm doing, with what the industry would define as good practice (I'm not a programmer by trade).

Thank you,

答:
I recommend having one class per table, and one field per column. This pattern is widely used by Object Relational Mappers (ORMs) in many languages, and it works very well. These classes form your domain model. One issue, as others have noted, is that if you want to change your data schema, you need to change application code. If that is an issue for you, you may want to consider semi-structured data (e.g. JSON columns, or even NoSQL).

You can put some logic in your data classes, but I tend to keep this quite lightweight. And methods on a data class should only operate on that class. For more involved business logic, and anything that involves more than one class, create a service layer. The service layer offers an API to the rest of your application, and depends on the model.

By the way, it is quite unusual to write this kind of software in C++. Usually higher-level languages (C#, Java, Python, etc.) are more suitable.


答:
If the Key object is already unique itself, not by equals() but by instance, and in case the key would actually never be null (and the code could be changed / the null key case could be removed), you could change the get() function to:

```<code>static C get(Key key) {
    synchronized (key) {
        C c = cs.get(key);
        if (c==null) {
            c = new C(key);
            cs.put(key,c);
        }
        return c;
    }
}
</code>```

Body:
If the Key object is already unique itself, not by equals() but by instance, and in case the key would actually never be null (and the code could be changed / the null key case could be removed), you could change the get() function to:

static C get(Key key) {
    synchronized (key) {
        C c = cs.get(key);
        if (c==null) {
            c = new C(key);
            cs.put(key,c);
        }
        return c;
    }
}


问:
How to make a mobile application that interacts with a website
I am looking to make a mobile application (iOS and Android app) that will interact with a website. The app will need to log in with a provided username and password and also get some information from the website.

I have no access to the website other than that of any other user. The idea is to simplify, automate and make a complicated task easier to complete for the everyday user.

Any examples or suggestions on how to do this will be appreciated.

答:
Any programmatic access to a web resource involves an API. As implementations differ, you may hear different terms: REST, SOAP, web service.

If you're developing the website yourself, create an API.

If the website is developed by a different team within your company, ask them to create an API. Discuss with them precisely your needs and draft together the interface.

If the website is created by a different company, again, contact the owner asking for an API.

An API will have several benefits compared to a direct access to the interface of the website:

It never changes. It can become obsolete, but you won't see subtle changes like the ones which happen to the user interface of most web application.

It is usually faster than HTTP requests to the website pages themselves.

It contains features which are not necessarily easily done using a web interface, such as transparent authentication (for example in SOAP services).


答:
Some Object Relational Mapping (ORM) systems will detect which fields of an object have changed since being loaded from the database, and will construct the SQL update statement to only set those values. ActiveRecord for Ruby on Rails is one such ORM.

The net affect is that fields the user didn't change are not included in the UPDATE command sent to the database. People who update different fields at the same time don't overwrite each others changes.

Depending on which programming language you are using, research which ORMs are available, and see if any of them will only update columns in the database marked "dirty" in your application.