问:
How to construct a cubie representation of a rubik's cube, given an array
Just to get this out of the way, I have seen this, and it is not what I'm looking for.

So, let's say you are programming a Rubik's Cube. (I know, very unoriginal, but bored programmers have to do something..) This Rubik's Cube is defined by an array of six 2-D arrays (one for each face,) and these 2-D arrays' sizes vary, based on the size of the cube. For instance, if I had a 3x3x3 cube, the array would be 6x3x3. That is, it would have 6 3x3 arrays.

Now, let's say I wanted to get an array of the cubies which make up this cube. Each cubie is defined by two things (I think..): the colors of it and its location on the cube. For example, if you had a solved cube, one of the cubies would be the red, green, and yellow cubie, and, assuming yours is sitting in the same orientation as mine, that cubie would be the front, right, up cubie.

However, none of this answers my question: how do I go about defining a set of these cubies, given an array of variable sizes. I know, for instance, that the cubie previously mentioned could be defined as cube[0][0][dimension-1], cube[2][0][0], cube[4][dimension-1][dimension-1]. (For a bit of reference, the order in which I define my faces is front, back, right, left, up, down. Hence the 0, 2, and 4, making front, right, and up.)

Anyway, with that said, I'd rather not hard-code all of this and was wondering if there was a simpler way. So, what's the best way to do something like what I was just describing?

Edit: For clarification, I am trying to get the separate, individual, smaller cubes which make up the Rubik's Cube as a whole. For instance, the piece with the red, green, and white stickers on it.

答:
There are a few ways to do this.

In addition to the six 3x3 arrays containing the colors of the stickers, you could have a 3x3x3 array representing the solid cubies. (The interior cell of this array can be ignored.) The cells of the 3x3x3 array could then contain integers (or pointers to more detailed objects) describing the original location of each cubie.  You just have to make sure you do the appropriate "rotation" of the 3x3x3 array each time you "rotate" the stickers.

Or you could just put everything in one 5x5x5 array. The central 3x3x3 array could represent the solid parts of the cube and the central 3x3 array of cells on each face of the 5x5x5 array could represent the stickers.

Another alternative: just a 3x3x3 array, in which each cell contains a pointer to a structure. The structure identifies the original location of the cubie and the colors and locations of the stickers on its faces. The structure also contains a modifiable integer that describes the orientation of the cubie: a particular value (say, 0) for the orientation the cubie "should" have in a fully-solved cube, and 23 other values representing the other possible orientations of the cubie after a sequence of rotations.  You also need a function (which could be a simple table lookup) that says which orientation results from each possible quarter-turn applied to each possible orientation.  You will also probably find use for a function that says, for each orientation, what face of the original (orientation 0) cubie is on the top, bottom, left, and so forth.  To rotate a slice of the cube, you have to permute the contents of the moving cells, of course, but you also have to correctly modify the orientation of every cubie in the rotated slice (including the cubie in the center of the face for a face rotation, even though the location of the cubie does not move).


问:
Client auto-detect required server
I have a project that requires a client app to communicate with a server. I was wondering if there is a way for the client app to detect available servers and "know" by some method or another which server is the one it needs.

The client is built with .net and c#, the server is a simple SQL database.They are on the same network.

Is there a built in mechanism to do this or is the task more complex then it seems at first?

I don't have more details ATM, it's still just an idea. The reason behind it is that when a user uses the client app, we don't want him to enter connection strings manually if he doesn't have to.

答:
I can think of three main solutions to the issue:

Send a message to the network's broadcast address on a well-known port.  Your same-network server picks this up and sends a reply to the source address ("I'm here at: ...").

Make your server occasionally send a message to the broadcast address on a well-known port, once every so many seconds.  Clients can listen for this and then connect.

Have a master server responsible for coupling the two: the server sends "I'm not dead yet" packages to the master; client connects to master and gets a server list. (*)  I don't recommend this.

1 and 2 are essentially the same, but with active (1) or passive (2) scanning.  1 seems cleaner on the network; 2 is probably a little easier to implement.

(*)  This is a lot more hassle and requires another server on a well-known address, and represents a single point of failure, but it can solve discoverability issues.

ContentLicense: CC BY-SA 3.0

Title: Client auto-detect required server


问:
Best way to find whether a collection does or does not contain an element with a specific desired quality
It seems to be a very common thing to have to tell whether some list or set contains at least one object matching a given condition, yet my prior searching and reading have never found a satisfactory best practice or design pattern to speak of.  In the situations I am thinking of, merely using "contains" is not sufficient, as the test we want to perform is not strictly based on the equals method of the class in question.

Some things I have seen:

```<code>// for-each with break
private boolean doFoosHaveGoodQuality(List<Foo> candidates) {
    boolean foundIt = false;
    for (Foo item: candidates) {
        if (<< item passes some test >>) {
            fountIt = true;
            break;
        }
    }
    return foundIt;
}

// while-do with index counter
private boolean doFoosHaveGoodQuality(List<Foo> candidates) {
    boolean foundIt = false;
    int index = 0;
    while(!fountIt && index < candidates.size() - 1) {
        Foo item = candidates.get(index++);
        if (<< item passes some test >>) {
            fountIt = true;
        }
    }
    return foundIt;
}
</code>```

Both of these get the job done and quit as soon as a success is found, possibly saving some time if we are lucky
enough to have the desired item early in the list.  However, both require looping the entire list in
order to get a false result

Another technique I've seen in some circumstances is that at the same time the original List<Foo> is generated (i.e. retrieved from database) to then simultaneously generate a Map<FooKey, Foo>.  In this technique, FooKey is an additional (often inner) class
holding only those attributes of a Foo that form the "desired quality" and overrides equals and hash code methods based on that.  When you need to determine if there exists a desired Foo, you make a new FooKey() instance with exactly that you want, then call hasKey() on the map.  Extra effort up front, but quick and easy at the moment you need it.

I can't put a finger on it.  Each idea works, yet each feels just a little hacky and inefficient.

答:
Algorithmically, the for-each and the while-with-indexing version implement linear search. This is okay for small collections or when you only do such a check very occasionally, but if it's an important building block of your program, you'd want a dedicated mapping structure which speeds up these queries by doing something fundamentally different from linear search. Examples include binary search trees (where you need to define a consistent ordering) and hash tables (where you need to define a consistent hash function). For most predicates this is trivial, for others it would be some extra code (defining FooKey), and for yet others it is hard or completely impractical. This is a judgement call depending on the criteria by which you search.

When you've decided on linear search, there are several options to implement it (provided there isn't already a good implementation — if so, prefer that!). The for-each variant is quite general and IMHO elegant: It works with any iterable, it doesn't even have to be backed by a concrete collection (cf. streams in Java 8). The while loop with indexing, on the other hand, is very restricted: It's offensively slow for containers that can't do random access (e.g. linked lists), and it doesn't work at all for things that can't be indexed. I would never recommend this one. There are probably other variations, but they are even more specialized. If you implement linear search, implement it for iterables.

Another issue is how you supply the predicate. You could write essentially the same loop again and again with only the condition different. But this is error prone, verbose, and inefficient. There should be only one copy of this loop, with the condition being passed as parameter. If your language (version) can do this, use a first-class function/lambda. Otherwise, you could emulate it with an interface and anonymous classes. Once you do this, Maps lose some of their appeal: It's no longer a long loop versus map.get(whatIWant), it's list.find(whatIWant). Of course they still have a performance benefit for large collections.

Side note: The loops can be slightly simpler, for example I'd write the for-each loop as:

```<code>private boolean doFoosHaveGoodQuality(List<Foo> candidates) {
    for (Foo item: candidates) {
        if (<< item passes some test >>) {
            return true;
        }
    }
    return false;
}
</code>```

Body:
Algorithmically, the for-each and the while-with-indexing version implement linear search. This is okay for small collections or when you only do such a check very occasionally, but if it's an important building block of your program, you'd want a dedicated mapping structure which speeds up these queries by doing something fundamentally different from linear search. Examples include binary search trees (where you need to define a consistent ordering) and hash tables (where you need to define a consistent hash function). For most predicates this is trivial, for others it would be some extra code (defining FooKey), and for yet others it is hard or completely impractical. This is a judgement call depending on the criteria by which you search.

When you've decided on linear search, there are several options to implement it (provided there isn't already a good implementation — if so, prefer that!). The for-each variant is quite general and IMHO elegant: It works with any iterable, it doesn't even have to be backed by a concrete collection (cf. streams in Java 8). The while loop with indexing, on the other hand, is very restricted: It's offensively slow for containers that can't do random access (e.g. linked lists), and it doesn't work at all for things that can't be indexed. I would never recommend this one. There are probably other variations, but they are even more specialized. If you implement linear search, implement it for iterables.

Another issue is how you supply the predicate. You could write essentially the same loop again and again with only the condition different. But this is error prone, verbose, and inefficient. There should be only one copy of this loop, with the condition being passed as parameter. If your language (version) can do this, use a first-class function/lambda. Otherwise, you could emulate it with an interface and anonymous classes. Once you do this, Maps lose some of their appeal: It's no longer a long loop versus map.get(whatIWant), it's list.find(whatIWant). Of course they still have a performance benefit for large collections.

Side note: The loops can be slightly simpler, for example I'd write the for-each loop as:

private boolean doFoosHaveGoodQuality(List<Foo> candidates) {
    for (Foo item: candidates) {
        if (<< item passes some test >>) {
            return true;
        }
    }
    return false;
}


问:
Ticket/Raffle DB schema
I'm working on a project that, when all boiled down, is essentially a raffle. The twist is that due to the way we've set the ticket value, a user may be casting 10,000+ tickets.

Essentially, a user can chose to cast a certain number of tickets for any given raffle. At the end of a period of time, a winning ticket is chosen randomly. A users' likelihood of winning is proportional to the number of tickets he/she casts.

My issue is that due to the volume of tickets, storing each ticket individually in the database seems out of the question, but in some way every ticket needs to be accounted for because it will affect the odds.

My fallback option is storing "batches" of tickets per user, assuming that it's rare that a user casts a single ticket at once.

What would be the best and most efficient solution for storing a high volume of tickets in the database?

答:
There's no reason to rule out storing the tickets individually.  10's of millions of rows is easily handled by most modern DBMS's.  Many, many sites and applications handle data orders of magnitude larger than that.  Trying to use a non-normalized work-around would not be more efficient - you'd likely introduce more inefficiencies.

Just make sure you put in the right indexes.

Title: Ticket/Raffle DB schema


问:
Correct pattern for Worker Processes involving Queues & Tables
Edit:

OK, so, people said it is unclear what I am asking. I am asking for feedback on this design. Here is an example user story:

As a group admin on the website I want to be notified when a user in my group uploads a file to the group.

Easiest solution would be that in the code handling the upload, we just directly create an email message in there and send it. However, this seems like it isn't really the appropriate level of separation of concerns, so instead we are thinking to have a separate worker process which does nothing but send notifications. So, the website in the upload code handles receiving the file, extracting some metadata from it (like filename) and writing this to the database. As soon as it is done handling the file upload it then does two things: Writes the details of the notification to be sent (such as subject, filename, etc...) to a dedicated "notification" table and also creates a message in a queue which the notification sending worker process monitors. The entire sequence is shown in the diagram below.

My questions are: Do you see any drawbacks in this design? Is there a better design? The team wants to use Azure Worker Roles, Queues and Table storage. Is it the right call to use these components or is this design unnecessarily complex? Quality attribute requirements are that it is easy to code, easy to maintain, easy to debug at runtime, auditable (history is available of when notifications were sent, etc...), monitor-able. Any other quality attributes you think we should be designing for?

Original:

We are creating a cloud application (in Azure) in which there are at least 2 components. The first is the "source" component (for example a UI / website) in which some action happens or some condition is met that triggers a second component or "worker" to perform some job. These jobs have details or metadata associated with them which we plan to store in Azure Table Storage. Here is the pattern we are considering:

Steps:

Condition for job met.

Source writes job details to table.

Source puts job in queue.

Asynchronously:

Worker accepts job from queue.

Worker Records DateTimeStarted in table.

Queue marks job marked as "in progress".

Worker performs job.

Worker updates table with details (including DateTimeCompleted).

Worker reports completion to queue.

Job deleted from queue.

Please comment and let me know if I have this right, or if there is some better pattern. For example sake, consider the work to be "sending a notification" such as an email whose template fields are filled from the "details" mentioned in the pattern.

答:
I can't answer whether you should do this or not, but I can try to help with your decision-making process.

First, what you are proposing is a very standard mechanism for asynchronously processing data. So, you are doing something very conventional, and that is good. I use AWS and have done this a lot with SQS and SNS. I can't speak to what Azure offers. AWS gives an example of this pattern for batch processing.

Here are some advantages to this approach:

The initial request can be faster because there is less work being done. There is some time for putting the message in the queue, but it is probably faster than saving to disk and sending an email.

You can make the notifications more fault tolerant, or at the least, not interfere with the initial request which prompted that notification. If your email service goes down for a day, you can keep the message in the queue and the worker can try it again the next day.

It will scale well - both in terms of users, and as new features arise.

There are a few downsides:

There is now additional complexity. It would be simpler to just send the email.

Correctly handling errors can more complicated. What do you do if you can't send an email? Retry? Delete the message from the queue and forget? This error handling is important, but your use-case decides how sophisticated you need it to be.

You probably want another web service handling this, which adds another component. Though, on small-scale projects, I have put the worker thread in the same web service.

Separation of Concerns

You mentioned Separation of Concerns as one reason for your design. Regardless of how you end up architecting this, you should still separate concerns at a class level. Whatever class is receiving this data can call an "notifier" interface. You might have different implementations of this over time: send the email in the same thread, send the email in a different thread without a queue, put the email in a queue. Each time you change your architecture, you keep the servicing code the same.


问:
Should our team order Javascript class methods/properties consistently? If so, how?
As our team is growing I've noticed that different developers put their class methods in different orders.  For instance:

```<code>var Foo = Backbone.Model.extend({
    someVar: {},

    initialize: function() {...},

    fetch: function() {...},
    handleFetchRepsonse: function() {...},

    getFoo: function() {...},

    render: function() {...},
    renderFoo: function() {...},
});
</code>```

vs.

```<code>var Foo = Backbone.Model.extend({
    fetch: function() {...},
    getFoo: function() {...},
    handleFetchResponse: function() {...},
    initialize: function() {...},
    render: function() {...},
    renderFoo: function() {...},
    someVar: {},
});
</code>```

It seems like it'd be more convenient if everyone used roughly the same criteria when they order their methods (if for no other reason than to make it easier to find stuff).  However, I'm wondering if:

A) that is even possible/realistic (or should I simply accept the fact that everyone is going to have a different order)?

B) if so, what sort of ordering should that be (the only really consistent one I can think of is alphabetical, but that seems less than ideal)?

答:
It's a matter of team policy, just like naming conventions. It is a good idea to have an accepted order for the sake of readability, so long as most people follow it.

As you say, there are a couple of options:

No order at all.

Properties, methods, and fields grouped by subject (thing, readThing, writeThing, deleteThing...)

Members grouped by behavior (thingA, thingB, readThingA, readThingB, writeThingA, writeThingB)

And so on...

Before you agree on any policy, make sure that the expectation of how to follow it is clear.


答:
Both your suggestions are unnecessarily verbose, and the input type is too specific.  Prior to Java 8 I would write:

```<code>private boolean doFoosHaveGoodQuality(Iterable<Foo> candidates) {
    for (Foo item: candidates) {
        if (<< item passes some test >>) return true;
    }
    return false;
}
</code>```

With Java 8 these boring loops are unnecessary:

```<code>private boolean doFoosHaveGoodQuality(Collection<Foo> foos) {
    return foos.stream().anyMatch(foo -> ... some test ... );
}
</code>```

Title: Best way to find whether a collection does or does not contain an element with a specific desired quality

Body:
It seems to be a very common thing to have to tell whether some list or set contains at least one object matching a given condition, yet my prior searching and reading have never found a satisfactory best practice or design pattern to speak of.  In the situations I am thinking of, merely using "contains" is not sufficient, as the test we want to perform is not strictly based on the equals method of the class in question.

Some things I have seen:

```<code>// for-each with break
private boolean doFoosHaveGoodQuality(List<Foo> candidates) {
    boolean foundIt = false;
    for (Foo item: candidates) {
        if (<< item passes some test >>) {
            fountIt = true;
            break;
        }
    }
    return foundIt;
}

// while-do with index counter
private boolean doFoosHaveGoodQuality(List<Foo> candidates) {
    boolean foundIt = false;
    int index = 0;
    while(!fountIt && index < candidates.size() - 1) {
        Foo item = candidates.get(index++);
        if (<< item passes some test >>) {
            fountIt = true;
        }
    }
    return foundIt;
}
</code>```

Both of these get the job done and quit as soon as a success is found, possibly saving some time if we are lucky
enough to have the desired item early in the list.  However, both require looping the entire list in
order to get a false result

Another technique I've seen in some circumstances is that at the same time the original List<Foo> is generated (i.e. retrieved from database) to then simultaneously generate a Map<FooKey, Foo>.  In this technique, FooKey is an additional (often inner) class
holding only those attributes of a Foo that form the "desired quality" and overrides equals and hash code methods based on that.  When you need to determine if there exists a desired Foo, you make a new FooKey() instance with exactly that you want, then call hasKey() on the map.  Extra effort up front, but quick and easy at the moment you need it.

I can't put a finger on it.  Each idea works, yet each feels just a little hacky and inefficient.

Body:
Both your suggestions are unnecessarily verbose, and the input type is too specific.  Prior to Java 8 I would write:

private boolean doFoosHaveGoodQuality(Iterable<Foo> candidates) {
    for (Foo item: candidates) {
        if (<< item passes some test >>) return true;
    }
    return false;
}

With Java 8 these boring loops are unnecessary:

private boolean doFoosHaveGoodQuality(Collection<Foo> foos) {
    return foos.stream().anyMatch(foo -> ... some test ... );
}


问:
What is a good way to share internal helpers?
All my projects share the same base library that I have build up over quite some time. It contains utilities and static helper classes to assist them where .NET doesn't exactly offer what I want. Originally all the helpers were written mainly to serve an internal purpose and it has to stay that way, but sometimes they prove very useful to other assemblies. Now making them public in a reliable way is more complicated than most would think, for example all methods that assume nullable types must now contain argument checking while not charging internal utilities with the price of doing so. The price might be negligible, but it is far from right.

While refactoring, I have revised this case multiple times and I've come up with the following solutions so far:

Have an internal and public class for each helper

The internal class contains the actual code while the public class serves as an access point which does argument checking.

Cons:

The internal class requires a prefix to avoid ambiguity (the best presentation should be reserved for public types)

It isn't possible to discriminate methods that don't need argument checking

Have one class that contains both internal and public members (as conventionally implemented in .NET framework).

At first, this might sound like the best possible solution, but it has the same first unpleasant con as solution 1.

Cons:

Internal methods require a prefix to avoid ambiguity

Have an internal class which is implemented by the public class that overrides any members that require argument checking.

Cons:

Is non-static, atleast one instantiation is required. This doesn't really fit into the helper class idea, since it generally consists of independent fragments of code, it should not require instantiation.

Non-static methods are also slower by a negligible degree, which doesn't really justify this option either.

There is one general and unavoidable consequence, alot of maintenance is necessary because every internal member will require a public counterpart.

A note on solution 1:
The first consequence can be avoided by putting both classes in different namespaces, for example you can have the real helper in the root namespace and the public helper in a namespace called "Helpers".

答:
You may follow the convention used within the .NET Framework itself.

If you watch the source code of .NET Framework, public methods contain the required checks, then delegate the work itself to the private methods. Those private methods are named identically to the public methods, except that they have a specific suffix ("Internal"). Both methods are within the same class.

For example, System.String has a method Split (line 948), which delegates the work to SplitInternal (line 983).

The fact that the authors use suffixes instead of prefixes is crucial and makes it a very attractive solution: you can easily find the method in the list of methods within a class in Visual Studio, and you don't need to type "InternalS" to get to the Split method which does the job with Intellisense.


问:
What Kind of Source Control Do High Security Projects Use?
I was just reading this slightly older post on choosing a good source control system when I started thinking about how different projects use source control. Where I work we've essentially moved completely to Git and things have been mostly good.

I have wondered about high security projects such as military software projects. Using something like Git there would fundamentally be unsafe; even allowing repo clones under restricted circumstances could be problematic. Using SVN or TFS may not even provide enough security in itself.

Are there any VCS systems that have any stronger security considerations? Or are there additional considerations that go into using VCS for high security projects?

答:
We secure systems because there is some risk of an event happening that we'd like to mitigate, and there's always going to be a tradeoff between the ability to work effectively and avoid the potential problems. So first you need to know what specifically you're trying to avoid, and then you can look for ways of preventing that.

So let's say the military of North Bonanzallia is working on some top secret missile guidance software based on garbonzo rays. Everyone already knows how to drive the missile, so there's no risk in that part getting out. Also, even though Garbonzo rays are secret, guiding a missile using images is well known. So if the code for the missile guidance system gets out, it would reveal details of how the garbonzo ray generating hardware worked (let's say it needs special pulse timing or whatever), but it wouldn't reveal the secret of how the garbonzo rays are created.

So, only the team working on the API that translates the garbonzo rays into an image needs to work in an EM sealed room with strict network control and mandatory searches and scans.

They would run source control on a server in that room, and the machines in the room would not be able to communicate with anything outside. The other teams can then integrate their pieces in another room, without any code leaving the secure zone. The application code can then come into the secure zone for testing, and redacted reports can leave the secure zone.

So, really, any version control system will do.


答:
Now making them public in a reliable way is more complicated than most would think, for example all methods that assume nullable types must now contain argument checking while not charging internal utilities with the price of doing so. The price might be negligible, but it is far from right.

Why? Because internal code is somehow immune from mistakes?

No, the proper solution is to eat your own dogfood. If the class/function should do bounds checking, then it should do bounds checking for everyone. If the usage is clear enough that "garbage in-garbage out" is an acceptable approach, then it should do that for everyone.

Sure - occasionally you'll run into scenarios where a variant that avoids bounds checking is acceptable and appropriate, but in my experience, those cases tend to need private access, not internal - and they're not the norm. If things are helpful for you, they're almost certainly going to be helpful for everyone. Design them that way.

Title: What is a good way to share internal helpers?

Body:
All my projects share the same base library that I have build up over quite some time. It contains utilities and static helper classes to assist them where .NET doesn't exactly offer what I want. Originally all the helpers were written mainly to serve an internal purpose and it has to stay that way, but sometimes they prove very useful to other assemblies. Now making them public in a reliable way is more complicated than most would think, for example all methods that assume nullable types must now contain argument checking while not charging internal utilities with the price of doing so. The price might be negligible, but it is far from right.

While refactoring, I have revised this case multiple times and I've come up with the following solutions so far:

Have an internal and public class for each helper

The internal class contains the actual code while the public class serves as an access point which does argument checking.

Cons:

The internal class requires a prefix to avoid ambiguity (the best presentation should be reserved for public types)

It isn't possible to discriminate methods that don't need argument checking

Have one class that contains both internal and public members (as conventionally implemented in .NET framework).

At first, this might sound like the best possible solution, but it has the same first unpleasant con as solution 1.

Cons:

Internal methods require a prefix to avoid ambiguity

Have an internal class which is implemented by the public class that overrides any members that require argument checking.

Cons:

Is non-static, atleast one instantiation is required. This doesn't really fit into the helper class idea, since it generally consists of independent fragments of code, it should not require instantiation.

Non-static methods are also slower by a negligible degree, which doesn't really justify this option either.

There is one general and unavoidable consequence, alot of maintenance is necessary because every internal member will require a public counterpart.

A note on solution 1:
The first consequence can be avoided by putting both classes in different namespaces, for example you can have the real helper in the root namespace and the public helper in a namespace called "Helpers".


答: I always order methods based on their role, critical (usually small) methods on the bottom, methods that apply the prior methods on top. Don't order them alphabetically, that will you will fade clues that reveal the consistency of the code, this is necessary when you need to refactor the code.</p>

Title: Should our team order Javascript class methods/properties consistently? If so, how?

Body:
As our team is growing I've noticed that different developers put their class methods in different orders.  For instance:

```<code>var Foo = Backbone.Model.extend({
    someVar: {},

    initialize: function() {...},

    fetch: function() {...},
    handleFetchRepsonse: function() {...},

    getFoo: function() {...},

    render: function() {...},
    renderFoo: function() {...},
});
</code>```

vs.

```<code>var Foo = Backbone.Model.extend({
    fetch: function() {...},
    getFoo: function() {...},
    handleFetchResponse: function() {...},
    initialize: function() {...},
    render: function() {...},
    renderFoo: function() {...},
    someVar: {},
});
</code>```

It seems like it'd be more convenient if everyone used roughly the same criteria when they order their methods (if for no other reason than to make it easier to find stuff).  However, I'm wondering if:

A) that is even possible/realistic (or should I simply accept the fact that everyone is going to have a different order)?

B) if so, what sort of ordering should that be (the only really consistent one I can think of is alphabetical, but that seems less than ideal)?


问:
Are short identifiers bad?
Are short identifiers bad? How does identifier length correlate with code comprehension? What other factors (besides code comprehension) might be of consideration when it comes to naming identifiers?

Just to try to keep the quality of the answers up, please note that there is some research on the subject already!

Edit

Curious that everyone either doesn't think length is relevant or tend to prefer larger identifiers, when both links I provided indicate large identifiers are harmful!

Broken Link

The link below pointed to a research on the subject, but it's now broken, I don't seem to have a copy of the paper with me, and I don't recall what it was. I'm leaving it here in case someone else figure it out.

http://evergreen.loyola.edu/chm/www/Papers/SCP2009.pdf

答:
An observation that I have had over the years and it's less so today than it was 10 or 15 years ago.  Programmers that can't type are the one that will fight you tooth and nail over variable naming.  They are the ones with all the 1-3 letter variable names.

So my advice is use a meaningful name as many commenters have said and then learn to type.  I have been considering adding a typing test to interviews, just to see where people are, but I am starting to see a lot less of the non-typers as computers become a bigger part of society.

Title: Are short identifiers bad?

ContentLicense: CC BY-SA 2.5


问:
Does this Decorator implementation violate the Liskov Substitution Principle?
Please consider the following implementation of the Decorator design pattern:

WordBank objects store strings and return them to the client through the method getWords().

The decorator class, WordSorter, is a subclass of WordBank (as in the Decorator pattern). However it's implementation of getWords() sorts some of the strings and removes them, before returning the array to the client.

For example a WordSorter might delete all of the strings in the bank that start with letter 'a', and only after that return the array to the client.

Does this violate the Liskov Substitution Principle? Since some implementations of WordBank return strings while others first sort through the strings and only return some of them, I'm not sure if it's safe to say that a WordSorter can be used anywhere any other WordBank is used. Or am I understanding this principle wrong?

答:
A WordSorter is-a WordBank, so code that works with a WordBank should also work when a WordSorter is used instead of a WorkBank. On the other hand, a WordSorter is-not-a SomeWordBank. The compiler won't even let you use a WordSorter in place of a SomeWordBank, so the issue does not even begin to arise.

There might be a LSP violation, but doesn't appear to be from the minimal specification you've given. Does WordSorter guarantee, for example, that one can add arbitrary strings to it and retrieve them all in the same order later? Then sorting the words would indeed break the that contract, and code that works for "correct" WordBanks can be broken by substituting a WordSorter. Whether there is such a guarantee is impossible to tell from the minimal UML diagram you've shown. If, for example, WordBank's contract says all words which are added are included in the result of getWords, then:

```<code>bank.add(w);
AssertContains(bank.getWords(), w);
</code>```

should always work. That code would break if bank was a WordSorter, and it's WordSorter's fault for breaking the contract and hence violating the LSP. But if WordBank offers no such guarantee, then the above code is in the wrong (in the same way asser x*y == 42 will usually fail) and WordSorter is a perfectly well-behaved subclass.

Body:
A WordSorter is-a WordBank, so code that works with a WordBank should also work when a WordSorter is used instead of a WorkBank. On the other hand, a WordSorter is-not-a SomeWordBank. The compiler won't even let you use a WordSorter in place of a SomeWordBank, so the issue does not even begin to arise.

There might be a LSP violation, but doesn't appear to be from the minimal specification you've given. Does WordSorter guarantee, for example, that one can add arbitrary strings to it and retrieve them all in the same order later? Then sorting the words would indeed break the that contract, and code that works for "correct" WordBanks can be broken by substituting a WordSorter. Whether there is such a guarantee is impossible to tell from the minimal UML diagram you've shown. If, for example, WordBank's contract says all words which are added are included in the result of getWords, then:

bank.add(w);
AssertContains(bank.getWords(), w);

should always work. That code would break if bank was a WordSorter, and it's WordSorter's fault for breaking the contract and hence violating the LSP. But if WordBank offers no such guarantee, then the above code is in the wrong (in the same way asser x*y == 42 will usually fail) and WordSorter is a perfectly well-behaved subclass.


答:
When your problem doesn't have a good solution, solve a different problem.

Instead of iterating over the collection, wrap that collection in another class that tracks the information you want whenever elements are added or removed. Don't make the mistake of assuming that Java's provided collection interfaces satisfy all the needs that you'll meet.

For the basic case, your new class will have two objects: the original List and a new Set field for the property you care about. This, of course, assumes that you are only querying a small number of properties.

This means that you must never allow mutating operations on the inner containers. There are some utility functions in java.util.Collections to return an unmodifiable view of various collections, to ease porting your callers, but if mutating e.g. through an Iterator is a feature that some of your callers use, you'll need to implement that.


问:
Is there any point in writing a random tester for code that deals with inductive data structures?
Let's say we're writing a simple JSON parser and we've fully covered the code with unit tests:

it can parse primitives "0", "123", "-456", '""', '"asd"', true, false

it can parse arrays "[]", "[1, 2, 3]"

it can parse nested arrays "[[]]"

it can parse objects "{}", '{ "a": 1, "b": 2 }'

it can parse nested objects '{ "a": {} }'

Every possible JSON can be either a primitive or an array/object holding other primitives/arrays/objects - this is what I mean by inductive data structure (is 'recursive' a better term?). It seems to me that any JSON parsing can be reduced to these few cases and if the parser passes these tests then it is fully correct (unless it was explicitly hard-wired to break when you try to parse special numbers).

Is there still any point in creating a random tester that generates random stringified JSON in hope that one of them will break this parser? Would this random tester find anything interesting?

P.S. I chose JSON just as an example of an inductive data structure; I'm not interested in writing a JSON parser.

答:
One thing I do when testing parsers is to write separate tests for the just the lexer. This means that there are a lot fewer novel cases that will need to be tested by the parser stage.

Many of the testcases for the lexer might not even be valid to the parser. For example, the input "]:[," should successfully lex to [EndArray, KeyValueSeparator, StartArray, ElementSeparator, EOF], whereas '"\"' would fail to lex with Error("expected closing quote").

I wouldn't use a random tester, but I would generate each sequence of valid tokens and check whether the parser agrees with me on whether it should be parseable. Ensuring that your parser fails when appropriate is just as important as ensuring that it succeeds.

Json has 8 token types (String, Number, BeginList, EndList, BeginObject, EndObject, KeyValueSeparator, ElementSeparator), plus EOF (and occasionally Error, if you're not using exceptions). 4 of them error in the first position, so they'll need no testing with strings with more than one token. Two others (number and string) cannot legally be followed by anything else, so they need no testing with strings with more than two tokens. If the first token is BeginList or BeginObject, 3 of the tokens will error immediately.

Repeat with longer token sequences, until every one of them becomes invalid or repeats a previous testcase just with a longer list or something. But every positive testcase must be a prefix of at least 8 negative testcases.


答:
Speaking on a higher level than JvR, I would use an existing library that uses broadcast/multicast internally.

I'm not as familiar with the Windows ecosystem, but this would be solved by a zeroconf implementation: either Bonjour (Mac OS X) or Avahi (Linux/BSD). The only thing I've ever used Avahi for myself is mDNS, but I know it supports service discovery as well.

Title: Client auto-detect required server

Body:
I have a project that requires a client app to communicate with a server. I was wondering if there is a way for the client app to detect available servers and "know" by some method or another which server is the one it needs.

The client is built with .net and c#, the server is a simple SQL database.They are on the same network.

Is there a built in mechanism to do this or is the task more complex then it seems at first?

I don't have more details ATM, it's still just an idea. The reason behind it is that when a user uses the client app, we don't want him to enter connection strings manually if he doesn't have to.


答:
Everyone will have their own different preferred standard, but it's important for everyone to put their ego aside for the betterment of the team and stick with a consistent standard.

Code reviews are a good way to enforce a coding standard.

What the specifics of the coding standard are up to you and your team. Different teams have different requirements and will be optimized with different standards.

It's important to focus on what you're trying to achieve before deciding on a coding standard.

My team needs to be able to write code quickly and integrate with many large inherited code bases of varying degrees of quality. Our job is usually about implementing new features or extending existing ones. This means we need to write code quickly and have it be easy for anyone else on the team be able to pick it up and run with it.

Because of those requirements our code standard focuses on readability on the small scale. Code we write should generally be short and to the point, and organized in a way that can easily be searched. As we tend to have a moderate number of interns, it's also important that we can train them quickly.

This means we've picked alphabetical ordering because it's faster to teach and reasonably fast to write.

If your requirements are different, such as long-term maintenance with a team of more experienced developers, I'd recommend a structure that's comfortable to work in. An example might be:

For function bodies:

directives

var declarations

function declarations

variable initialization

main execution

For prototypes:

initialization methods

API methods

event handlers

pseudo-private methods

etc...

Again, the specifics of the order should be determined by your team with emphasis on improving the performance of the team overall. Some teams work great when they don't have to work with any formal standard, and others can't work without a well-documented rigorously enforced standard.


问:
Why isn't Haskell able to optimize infinite lists?
Lets say you've got a list
l = [0, 2..]
and you want to get the nth number when n is pretty large, say n=123456789.
So you call l !! 123456789.
On my machine, this results in out of memory.

So why aren't Haskell capable of realizing that the number at index n is 2n, and making a call such as l !! 1230981237 trivial? Or a more extreme example, [1..] !! 123456789. Shouldn't Haskell be able to realize that every number in [1,1..] is 1?

答: A sufficiently smart compiler could notice that in those cases. But for nontrivial cases, finding a closed form ranges from hard to open problem to undecidable. A compiler is a compiler, not a mathematician. There is no general procedure for turning the nth element of a sequence into a simple form that doesn't compute the preceding elements, so at best the optimizations would be a bunch of special cases (e.g. for enumFromThen, which is what [0, 2, ..] desugars to). But there is zero motivation to do that: It's trivial to do by hand, rare in real code, and it's not the sort of pattern that emerges as a result of other optimizations. If you want the nth even number fast, write 2 * n. evens !! n might be cute but it's not worth a rewrite rule to make fast.


答:
The question I intend to answer is one about the value of random testing in general, and of inductive/recursive data structures in particular, not about JSON.

Random testing has value in several different settings. The primary purpose of random testing is to tackle cases where the test space is immensely large so that it cannot be tested exhaustively. I can think of 3 such spaces.

Survivability. Does the system under test survive being fed large quantities of bizarre input data? Yes, you should test that.

Limits. Does the SUT behave correctly when fed input that exceeds its limits, such as token length, recursion depth, backtracking or whatever, either alone or in combination? You can do most of that with planned testing, but a bit of random might be worthwhile.

Test flaws. There is always a risk that your other tests missed something interesting, and that feeding a sufficient quantity of data around the margins (which you will know from white box inspection) will find it. Worth considering.

The problem with random testing is (a) how to adequately explore a near infinite input space (b) how to predict the test outcome for each input case.

If you have solutions for that, then random testing for these three reasons is at least worth considering.

Title: Is there any point in writing a random tester for code that deals with inductive data structures?

Body:
Let's say we're writing a simple JSON parser and we've fully covered the code with unit tests:

it can parse primitives "0", "123", "-456", '""', '"asd"', true, false

it can parse arrays "[]", "[1, 2, 3]"

it can parse nested arrays "[[]]"

it can parse objects "{}", '{ "a": 1, "b": 2 }'

it can parse nested objects '{ "a": {} }'

Every possible JSON can be either a primitive or an array/object holding other primitives/arrays/objects - this is what I mean by inductive data structure (is 'recursive' a better term?). It seems to me that any JSON parsing can be reduced to these few cases and if the parser passes these tests then it is fully correct (unless it was explicitly hard-wired to break when you try to parse special numbers).

Is there still any point in creating a random tester that generates random stringified JSON in hope that one of them will break this parser? Would this random tester find anything interesting?

P.S. I chose JSON just as an example of an inductive data structure; I'm not interested in writing a JSON parser.


问:
Can JSP Expression Language provide type safety like scriptlets in Eclipse IDE?
Almost everywhere you can read that you should use EL instead of scriptles in JSP. And I agree that you should not use any JAVA code in JSP except for calling getter methods on model objects. This is quite obvious for me and I don't need any clarification here. But there is this one thing that I really cannot understand is the lack of support for EL in Eclipse IDE.

Let's start with comparing some code. First EL example:

```<code>${user.name}
${user.surname}
</code>```

And now some scriptlet/JSP expression example:

```<code><jsp:useBean id="user" class="com.mycompany.User">
    <%= user.getName() %>
    <%= user.getSurname() %>
</jsp:useBean>
</code>```

It clearly visible that EL is more elegant. However, Eclipse doesn't provide any autocompletion nor refactoring support for EL. And for JSP expressions it works like a charm. If you delete getName() method from Java class, JSP validator will show you an error during compilation. If you rename the method, all the connected JSP files will update automatically. Moreover, even when you are looking for references to method getName(), Eclipse will show you all calls across Java/JSP files (provided you used JSP expressions/scriptlets). And none of these features are available for EL.

Some of the programmers might say that they don't really care and EL syntax is much better for them, period. But I work with a quite complex legacy code (that I didn't write) in my current project and believe me that the refactoring of EL/model objects is a nightmare. There are a lot of DTO objects extending and composing other DTO objects that are being used on multiple JSP views. Every change is difficult, because I cannot tell at compile time if I didn't break anything.

Based on that experience I just cannot understand how anybody could suggest using EL instead of JSP expressions. Please tell me that I'm missing something and that either using JSP expressions is correct (in my example) or that there is a way to enable all the advantages of using type safety with EL.

EDIT:

I know that IntelliJ has better support for JSP, but I would like to focus on Eclipse first. I hope that there are still some people working on JSP projects on Eclipse/Spring Tool Suite.

答:
Every IDE has its good points and bad points.  A primary good point of Eclipse is its price.  There are other IDEs (such as Intellij) that have comprehensive jsp aware features.  Though there are ways around this by adding additional type information to the beans that should help in all IDEs.

That said, the real question here:

Based on that experience I just cannot understand how anybody could suggest using EL instead of JSP expressions. Please tell me that I'm missing something and that either using JSP expressions is correct (in my example) or that there is a way to enable all the advantages of using type safety with EL.

Here's the real answer... you've got some Java code mixed in there.

How do you test the code you wroteit? You can't unit test a scriptlet or a jsp page.  You can unit test a taglib.

You can't reuse scriptlets, so you are violating DRY

You can't debug an exception part way through (you get a blank page)

As the JSP is compiled at runtime, it is possible/likely to get a compile time exception with a scriptlets that is exceedingly difficult to track down... at run time.

You can't make use of inheritance for them (they can't be extended or encapsulated)

You do get name space collisions, and ${diety} help you if you <%@ include ... %> something that has a collision between names in different files

You are mixing view logic and business logic together

Automatic refactoring tools do not recognize them

While they are not inherently evil and there are sometimes necessary tasks to do with them, they are often a significant and ugly thing that causes problems down the road.

Related reading:

How to avoid Java Code in JSP-Files?


答:
Part of the job of programming is recognizing when you have added a complication that doesn't need to exist, and removing it.

In this case, what you're doing is finding the 123456789th entry in a list where the nth entry is 2*n.  Constructing the list in the first place is extra work, which we should decline to do.

It wouldn't be hard for Haskell compiler writers to add an optimization that would detect such a potential improvement, but if it were added, would it ever get used on code not written specifically to point it out?  I doubt it.  The cases you point out would all be obvious to the programmer -- so obvious that they wouldn't ever get written in the first place.

Compilers are computer programs, they don't "realize" anything.  Realizing is something humans do.

(Nitpick: not every element in [1..] is 1)

Title: Why isn't Haskell able to optimize infinite lists?

Body:
Lets say you've got a list
l = [0, 2..]
and you want to get the nth number when n is pretty large, say n=123456789.
So you call l !! 123456789.
On my machine, this results in out of memory.

So why aren't Haskell capable of realizing that the number at index n is 2n, and making a call such as l !! 1230981237 trivial? Or a more extreme example, [1..] !! 123456789. Shouldn't Haskell be able to realize that every number in [1,1..] is 1?


答:
I don't think it would work. You'd have to define was the order was, and that definition would have to be unambiguous, and it would also have to include a naming standard that defines the name for every possible function because maybe "relaxGraphNodes()" shouldn't go in the same place as "evenOutPointSet()".

It'd be an immense investment... the one group I've seen do something similar was the Microsoft Office dev team, and it took them years to work it all out and they ended up with a hundred-some-page-long standards document.


问:
Wrapping a map with instance or static method
I have a java.util.Map<String, Object> object which different types of values in it. I don't want to cast whereever I do a get operation over this. To do this, I created different classes wrapping this map and these classes provide different get methods which return values for different keys.

There are two options for this:

```<code>public class Wrapper1 {
    private final Map<String, Object> map;

    public Wrapper1(Map<String, Object> map) {
        this.map=map;
    }

    public MyObject getMyObject() {
        return (MyObject)this.map.get("someKey");
    }
}
</code>```

```<code>public class Wrapper2 {
    private Wrapper2() {
    }

    public static MyObject getMyObject(Map<String, Object> map) {
        return (MyObject)map.get("someKey");
    }
}
</code>```

As you see, in first one I'm creating an instance of Wrapper1 and access MyObject instance by instance method. In second, I give the map to a static method and access same MyObject instance.

Which one will you prefer more and why?
Also if this is a bad practice, please let me know.
Thank you.

答:
Personally I would prefer the first option, mainly because it would give you the option to override the wrapper's methods or add additional "getMyObject" methods with an inherited class if need be. And strictly speaking, the second option would not really be a "wrapper". It's just a class with static utility methods.

But whichever option you decide to go with, definitely do type checking in the "getMyObject" methods before casting.


答:
It really depends if you plan to have object types MyObject, MyObject2,... MyObjectN stored in a single map instance or multiple maps that store MyObject.

In the former case with multiple object types, it would make sense to choose Wrapper1 because you can hold the map in the Wrapper1, and you do not need parameters to the method retrieving it. In the latter case with multiple map instances, Wrapper2 makes sense; otherwise you would also need multiple instance of Wrapper1.

Title: Wrapping a map with instance or static method

Body:
I have a java.util.Map<String, Object> object which different types of values in it. I don't want to cast whereever I do a get operation over this. To do this, I created different classes wrapping this map and these classes provide different get methods which return values for different keys.

There are two options for this:

```<code>public class Wrapper1 {
    private final Map<String, Object> map;

    public Wrapper1(Map<String, Object> map) {
        this.map=map;
    }

    public MyObject getMyObject() {
        return (MyObject)this.map.get("someKey");
    }
}
</code>```

```<code>public class Wrapper2 {
    private Wrapper2() {
    }

    public static MyObject getMyObject(Map<String, Object> map) {
        return (MyObject)map.get("someKey");
    }
}
</code>```

As you see, in first one I'm creating an instance of Wrapper1 and access MyObject instance by instance method. In second, I give the map to a static method and access same MyObject instance.

Which one will you prefer more and why?
Also if this is a bad practice, please let me know.
Thank you.


问:
tracking time for personal projects
Does everyone track time spent on personal projects? I feel that it is valuable to know how much time (and potential money) has been put into a hobby.

I am currently using harvest to track time.

答:
Time tracking is useful for determining your capacity as a programmer.  It tells you how accurate your estimating is. It is useful for forecasting future work.

So this would be important if your fun programming is going to turn into something you start bidding projects based on.  If it's truly just for fun don't muck up something fun by putting in extra work you don't need.  Spend that extra 5 to 10 minutes a day writing in your blog/journal about what you did today and why it was cool.  That will have a much better payoff both personally and professionally.

Title: tracking time for personal projects


问:
Help me catch up on what I've missed since Java 1.4.2
I am about to start my first professional career position as a software developer, and I'm likely going to be writing a lot of Java code.  I don't know that much about what specifically I'll be writing, and besides, I have fairly broad interests when it comes to code anyway.

For reasons not worth discussing, my last internship had me coding only for the Java 1.3 and 1.4 SDK's.  Also, my university education has focused mainly on algorithms, data structures, and other theory, not language features or libraries.

So, with the above in mind, what features, classes, etc. in the current version of Java (what number are we on now, anyway?) would be worth my time to read up on and why?  What have I missed since 1.4.2 that makes your life as a programmer easier?

Examples and stories of how you discovered a particular package or some such and put it to use would also be great.

答:
I'll help by categorising the helpful answer from @ykombinator. His list is a list of the elements that you will use on a daily basis while doing "general" java development.

Low impact and low difficulty:

Enhanced for loop (for (String s : set) {...})

Autoboxing/unboxing (automatically convert between types like Integer to int and vice versa)

Varargs (for printf() function, allows variable number of arguments)

Static import (can now import static methods of a class, such as java.lang.Math)

High Impact and medium difficulty:

Typesafe enums (enum is now a keyword, types can be created out of enums)

High Impact and high difficulty:

Annotations

Generics

Low impact and high difficult (will only use unless you do advanced threading)

java.util.concurrent (Demonstrates java's concurrency)

I would suggest therefore that you read through the docs/help on low impact low difficult pieces - they're easy to pick up.
Spend a lo tof time on Annotations and Generics - annotations are very useful, and generics can get rather complicated.

Only look at the new concurrency content if you need to do threading.


问:
What is software maintenance?
I'm a hobbyist programmer, so no professional experience.

People here often talk about doing maintenance of software at work. The author of this question talks about doing 90% maintenance and 10% development at his job.

My question is: what is 'software maintenance' anyway?

Is it mainly about fixing bugs? If so, does that mean that people spend most of their time at work fixing bugs?

Or does 'maintenance' include other things, other than bug fixing?

答:
Fixing bugs is definitely a big part

Small modifications to existing features: add a field here, change the dialog layout there, remove some outdated functionality there... The difference between maintenance and development is fluid here.

changes can even be required by new laws!

Improve performance

Make the system work in a new environment (because the old one is not available anymore or has had its own bugfixes or new features):

new hardware

new version of the operating system

new version of the programming language / runtime

new version of libraries you're using

changes in other systems that your system communicates with

Some concrete examples that I have personally worked on:

When Facebook switched to local currency payments in mid 2013, all Facebook apps that took user payments had to completely rework their payment logic (the new system works fundamentally different on many levels) within 90 days.

If you take direct debit payments in a SEPA country, then in early 2014 you had to switch account numbers to the IBAN scheme (from the form where users enter their data through to where your backend communicates with the payment provider), and if you take recurring payments you had to implement email notifications.

Title: What is software maintenance?


问:
What is Atomicity?
I'm really struggling to find a concrete, easy to grasp, explanation of Atomicity.

My understanding thus far is that to ensure an operation is atomic you wrap the critical code in a locker. But that's about as much as I actually understand. Definitions such as the one below make no sense to me at all.

An operation during which a processor can simultaneously read a location and write it in
      the same bus operation. This prevents any other processor or I/O device from writing or
      reading memory until the operation is complete.
      Atomic implies indivisibility and irreducibility, so an atomic operation must be
      performed entirely or not performed at all.

What does the last sentence mean? Is the term indivisibility relating to mathematics or something else?

Sometimes the jargon with these topics confuse more than they teach.

答:
Atomicity is a trait that defines wether an operation can be interrupted or not. In general, it does not refer to a bunch of operations in a lock. A lock doesn't guarantee that nothing else can run during the lock, just nothing else can run that code, on that instance during the lock.

Let's look at an example: int x = 4 * sin(pi)

Without optimization, this statement is not atomic.

Fetching pi will usually be atomic, assuming it is a double and your processor can read a double in one clock cycle.

Calling sin and returning its result (assuming sin is some function and not something like a macro) is not atomic since something can run between the code running and returning the value.

Granted, this probably doesn't matter. pi will be copied going into the function and sin is unlikely to be a mutable function. So while this is threadsafe (in common usage) it is not atomic.

On most all processors multiplying two doubles and assigning the result will be an atomic operation since it will be done in one operation by the processor.

So, key things to note:

Having two atomic operations does not yield another one, since the processor can switch to another thread in between them.

An operation that is atomic on one machine may not be on another.

Optimization can make an operation that isn't atomic into one that is (and occasionally vice versa!)

Atomicity matters because if something can't be interrupted, it's intrinsically thread safe. Locks are expensive, so atomic operations in key spots can vastly improve concurrent performance and correctness.

Title: What is Atomicity?


答:
As an example, you go to the bathroom, lock the door, do your toilet, wash and dry your hands and then unlock the door.

Absent an emergency (such as a fire alarm) you expect to complete the whole process uninterrupted. It is as single "black box" event from the perspective of some one on the outside who sees A) you go in; B) you come out.

(The equivalent of a fire alarm would be a higher level interrupt).

Title: What is Atomicity?

Body:
I'm really struggling to find a concrete, easy to grasp, explanation of Atomicity.

My understanding thus far is that to ensure an operation is atomic you wrap the critical code in a locker. But that's about as much as I actually understand. Definitions such as the one below make no sense to me at all.

An operation during which a processor can simultaneously read a location and write it in
      the same bus operation. This prevents any other processor or I/O device from writing or
      reading memory until the operation is complete.
      Atomic implies indivisibility and irreducibility, so an atomic operation must be
      performed entirely or not performed at all.

What does the last sentence mean? Is the term indivisibility relating to mathematics or something else?

Sometimes the jargon with these topics confuse more than they teach.


问:
Refactoring a 1500 LOC method that only builds the graphical UI
I'm currently scratching my head over how to refactor a method that basically only builds the UI.

The method is more than 1500 lines of code (LOC) long - and counting. It has grown, there was no plan how to approach this. You might find this familiar.

Anyway, it's basically just one large method that goes a little something like this:

```<code>    .
    .
    .

    # null checks
    null_checks_bx = Box(True)

    null_checks_ck = CheckBox()
    null_checks_ck.set_text('Null checks throwing exceptions of type:')

    if 'doNullChecks' in options:
        null_checks_ck.set_active(options['doNullChecks'])
    else:
        null_checks_ck.set_active(True)

    # dict to sorted list: extract values from dict by list comprehension
    exceptions = sorted([exception.get_full_name() for exception in JavaTypes.exception_types])

    null_checks_se = Selector()
    null_checks_se.add_items(exceptions)
    null_checks_se.set_enabled(null_checks_ck.get_active())

    if 'nullChecksExceptionFullClassName' in options:
        null_checks_se.set_value(options['nullChecksExceptionFullClassName'])
    else:
        # default to first entry
        #(defaulting to doEquals = True and doHashCode = True by using hardcoded Commons Lang implies availability of Commons Lang NullArgumentException)
        null_checks_se.set_value(JavaTypes.exception_types[0].get_full_name())

    # callback
    Callbacks.sync_model_active_status(null_checks_ck, null_checks_se)

    null_checks_ck.add_clicked_callback(lambda: Callbacks.sync_model_active_status(null_checks_ck, null_checks_se))

    null_checks_bx.add(Label(indent), False, True)  # dummy indent label
    null_checks_bx.add(null_checks_ck, False, True)
    null_checks_bx.add(null_checks_se, False, True)

    # relationship entity class constructor calls
    relationship_constructor_calls_bx = Box(True)
    #relationship_constructor_calls_bx.set_spacing(5)
    #relationship_constructor_calls_bx.set_padding(3)

    relationship_constructor_calls_ck = CheckBox()
    relationship_constructor_calls_ck.set_text('Instantiate relationship entities (if all necessary columns present)')

    if 'doRelationshipConCalls' in options:
        relationship_constructor_calls_ck.set_active(options['doRelationshipConCalls'])
    else:
        relationship_constructor_calls_ck.set_active(False)

    relationship_constructor_calls_bx.add(Label(indent), False, True)  # dummy indent label
    relationship_constructor_calls_bx.add(relationship_constructor_calls_ck, False, True)

    # relationship not-null checks: this is an option independent of the null checks!
    relationship_not_null_checks = Box(True)
    #relationship_not_null_checks.set_spacing(5)
    #relationship_not_null_checks.set_padding(3)

    relationship_not_null_checks_ck = CheckBox()
    relationship_not_null_checks_ck.set_text('Not-null checks before relationship instantiation')

    relationship_not_null_checks_ck.set_enabled(relationship_constructor_calls_ck.get_active() and not null_checks_ck.get_active())

    if 'doRelationshipNotNullChecks' in options:
        relationship_not_null_checks_ck.set_active(options['doRelationshipNotNullChecks'])
    else:
        relationship_not_null_checks_ck.set_active(True)

    # callback
    Callbacks.sync_convenience_constructor_options(null_checks_ck, relationship_constructor_calls_ck, relationship_not_null_checks_ck)

    null_checks_ck.add_clicked_callback(lambda: Callbacks.sync_convenience_constructor_options(null_checks_ck, relationship_constructor_calls_ck, relationship_not_null_checks_ck))
    relationship_constructor_calls_ck.add_clicked_callback(lambda: Callbacks.sync_convenience_constructor_options(null_checks_ck, relationship_constructor_calls_ck, relationship_not_null_checks_ck))

    relationship_not_null_checks.add(Label(indent), False, True)  # dummy indent label
    relationship_not_null_checks.add(Label(indent), False, True)  # dummy indent label
    relationship_not_null_checks.add(relationship_not_null_checks_ck, False, True)

    # build final box
    checks_bx = Box(False)
    checks_bx.set_spacing(5)
    #checks_bx.set_padding(3)
    checks_bx.set_homogeneous(True)
    checks_bx.add(omit_auto_increment_columns_bx, False, True)
    checks_bx.add(omit_auto_timestamp_columns_bx, False, True)
    checks_bx.add(null_checks_bx, False, True)
    checks_bx.add(relationship_constructor_calls_bx, False, True)
    checks_bx.add(relationship_not_null_checks, False, True)

    # callback
    Callbacks.sync_model_active_status(convenience_constructors_ck, checks_bx)

    convenience_constructors_ck.add_clicked_callback(lambda: Callbacks.sync_model_active_status(convenience_constructors_ck, checks_bx))

    # need wrapped box for Panel class
    constructors_bx = Box(False)
    constructors_bx.set_spacing(5)
    constructors_bx.set_padding(3)
    #constructors_bx.set_homogeneous(True)
    constructors_bx.add(convenience_constructors_bx, False, True)
    constructors_bx.add(checks_bx, False, True)

    constructors_pn = Panel(TitledGroupPanel)
    constructors_pn.set_title('Constructors')
    constructors_pn.add(constructors_bx)

    # getters and setters
    is_conversion_bx = Box(True)
    #is_conversion_bx.set_spacing(3)
    #is_conversion_bx.set_padding(3)

    is_conversion_ck = CheckBox()
    is_conversion_ck.set_text('Convert respective column names starting with "is_"')
    is_conversion_ck.set_tooltip("Column is_incognito => getter isIncognito() (not getIsIncognito()) and setter setIncognito()")

    if 'doIsConversion' in options:
        is_conversion_ck.set_active(options['doIsConversion'])
    else:
        is_conversion_ck.set_active(True)

    is_conversion_bx.add(is_conversion_ck, False, True)

    # generate code for relationship getters and setters to synchronize with column fields
    sync_relationship_pk_fields_bx = Box(True)
    #sync_relationship_pk_fields_bx.set_spacing(3)
    #sync_relationship_pk_fields_bx.set_padding(3)

    sync_relationship_pk_fields = CheckBox()

    .
    .
    .
</code>```

You get the point.

What I don't see is what the criteria might be to split this method up so the code will become more managable, more understandable etc pp.

What are the best practices here?

I could create some methods that would create recurring types of panels and widgets, but this would become a rather tedious effort for what I fail to see the real gain.

Again, what are some useful, practical approaches to large, clumsy methods that only build the graphical UI?

Thanks

PS: oh and BTW the UI is a single Dialog in a standard, windowed application (no web), and this dialog has 6 tabs which contain mostly check boxes, radio buttons, and text boxes. It is a code generation plugin that the user can choose a lot of options from. I might post an image as soon as I get the plugin running again...

答:
Your code appears to have one feature you can use to your advantage here: all those grouping comments. You can use those comments as the basis for breaking up the method into chunks by extracting smaller methods. You pull out each chunk into its own method, then call that method from the code's original location.

As you start to pull these pieces out, you will either naturally find duplication or you will naturally find strong relationships between some of the methods. As you find duplication, you extract that into helper methods to DRY out your code. As you find natural relationship boundaries, you can break those off into separate classes of more closely related functionality.

Below, for example, I've started to pull out the logic for building the null checks portion. I've extracted it as a method, broken out a few pieces that needed a better name, and de-namespaced all the variables within the method. There's a lot more that can be done, but that is left as an exercise for the reader.

```<code>def add_indent_label(self, box):
    box.add(Label(indent), False, True)

def get_null_checks(self, options):
    box = Box(True)

    checkbox = CheckBox()
    checkbox.set_text('Null checks throwing exceptions of type:')

    if 'doNullChecks' in options:
        checkbox.set_active(options['doNullChecks'])
    else:
        checkbox.set_active(True)

    exceptions = self.get_exceptions()

    selector = Selector()
    selector.add_items(exceptions)
    selector.set_enabled(checkbox.get_active())

    if 'nullChecksExceptionFullClassName' in options:
        selector.set_value(options['nullChecksExceptionFullClassName'])
    else:
        selector.set_value(self.get_first_exception())

    # callback
    Callbacks.sync_model_active_status(checkbox, selector)
    checkbox.add_clicked_callback(lambda: Callbacks.sync_model_active_status(checkbox, selector))

    self.add_indent_label(box);
    box.add(checkbox, False, True)
    box.add(selector, False, True)

    return box

def get_exceptions(self):
    return sorted([exception.get_full_name() for exception in JavaTypes.exception_types])

# This could probably have a better name
def get_first_exception(self):
    #(defaulting to doEquals = True and doHashCode = True by using hardcoded Commons Lang implies availability of Commons Lang NullArgumentException)
    return JavaTypes.exception_types[0].get_full_name()
</code>```

And in your original code, it becomes:

```<code>null_checks_bx = self.get_null_checks(options)
</code>```

Body:
Your code appears to have one feature you can use to your advantage here: all those grouping comments. You can use those comments as the basis for breaking up the method into chunks by extracting smaller methods. You pull out each chunk into its own method, then call that method from the code's original location.

As you start to pull these pieces out, you will either naturally find duplication or you will naturally find strong relationships between some of the methods. As you find duplication, you extract that into helper methods to DRY out your code. As you find natural relationship boundaries, you can break those off into separate classes of more closely related functionality.

Below, for example, I've started to pull out the logic for building the null checks portion. I've extracted it as a method, broken out a few pieces that needed a better name, and de-namespaced all the variables within the method. There's a lot more that can be done, but that is left as an exercise for the reader.

def add_indent_label(self, box):
    box.add(Label(indent), False, True)

def get_null_checks(self, options):
    box = Box(True)

    checkbox = CheckBox()
    checkbox.set_text('Null checks throwing exceptions of type:')

    if 'doNullChecks' in options:
        checkbox.set_active(options['doNullChecks'])
    else:
        checkbox.set_active(True)

    exceptions = self.get_exceptions()

    selector = Selector()
    selector.add_items(exceptions)
    selector.set_enabled(checkbox.get_active())

    if 'nullChecksExceptionFullClassName' in options:
        selector.set_value(options['nullChecksExceptionFullClassName'])
    else:
        selector.set_value(self.get_first_exception())

    # callback
    Callbacks.sync_model_active_status(checkbox, selector)
    checkbox.add_clicked_callback(lambda: Callbacks.sync_model_active_status(checkbox, selector))

    self.add_indent_label(box);
    box.add(checkbox, False, True)
    box.add(selector, False, True)

    return box

def get_exceptions(self):
    return sorted([exception.get_full_name() for exception in JavaTypes.exception_types])

# This could probably have a better name
def get_first_exception(self):
    #(defaulting to doEquals = True and doHashCode = True by using hardcoded Commons Lang implies availability of Commons Lang NullArgumentException)
    return JavaTypes.exception_types[0].get_full_name()

And in your original code, it becomes:

null_checks_bx = self.get_null_checks(options)


问:
MVC design pattern. Overloading controller responsibilities
I'm developing a desktop application with a GUI. To do so, I'm using the MVC design pattern for the GUI part.  For now the application consists of a single window (view) with one controller interacting with the backend (model).

The interaction is becoming more complex day by day with the controller getting more and more methods to handle inputs and adding more dependencies with model objects.  Since it's a best practice to keep the classes and methods small I feel like delegating some tasks, is it right? Is there any clean way to do so?

Regarding the dependencies with the model, I'm using a facade object, but again I feel like it's getting too overloaded.

答:
I suggest you google up the View Helper pattern, it's one I prefer (I am using Spring WebMVC).

Controller methods only receive the parameters, construct a parameter Data Transfer Object and pass this into a ViewHelper class. The ViewHelper class returns a result DTO ready for the consuming view.

The ViewHelper can call the necessary Service classes using the inbound param DTO and construct/ augment the return DTO.

Encapsulating the inbound and outbound parameters/ results into DTO objects help reduce the effort to maintain your code. For example, when a new requirement introduces an additional parameter to the controller method signature, then only the controller, the DTO and the affected service are affected. You do not have to "pass through" this new parameter all the way from the controller to the DAO.

In summary, keep your controller classes light. Encapsulate in/out data with DTO's. Introduce ViewHelpers to offload the complexity of gathering data from your service(s).


答:
Turn your question upside down.
When is it a good idea not to delegate large pieces of functionality to an other class?
....

Bit of a no-brainer isn't it? I can only think of a few scenarios where I wouldn't want to delegate, and I'd view it being difficult / impractical to do so as a major design flaw.

How to do it, is a far more subjective question.

Based on your question, I'd also be reviewing whether one form was good idea as well. User defined controls maybe.

Title: MVC design pattern. Overloading controller responsibilities

Body:
I'm developing a desktop application with a GUI. To do so, I'm using the MVC design pattern for the GUI part.  For now the application consists of a single window (view) with one controller interacting with the backend (model).

The interaction is becoming more complex day by day with the controller getting more and more methods to handle inputs and adding more dependencies with model objects.  Since it's a best practice to keep the classes and methods small I feel like delegating some tasks, is it right? Is there any clean way to do so?

Regarding the dependencies with the model, I'm using a facade object, but again I feel like it's getting too overloaded.


问:
How to represent a tree structure in NoSQL
I'm new to NoSQL and have been playing around with a personal project on the MEAN stack (Mongo ExpressJs AngularJs NodeJs). I'm building a document editor of sorts that manages nodes of data. Each document is actually a tree.

I have a CRUD api for documents, to create new trees and a CRUD api for nodes in a given document.

Right now the documents are represented as a collection that holds everything, including nodes. The children parent relationship is done by ids. So the nodes are an map by id, and each node has references to what nodes are their children. I chose this "flat" approach because it is easier to get a node by id from a document.

Being used to having a relation table between nodes and documents, a relation table between nodes and children nodes I find it a bit weird that I have to save the entire "nodes" map each time I update a node.

Is there a better way to represent such a data type in NoSQL?

答:
One of the tenets of NoSQL is to use the type of database best suited to the task at hand. Do you have the option to use something other than MongoDB?

For a document hierarchy, you can try something like the Java Content Repository standard. It is implemented by most major CM systems, and also has a fully conforming reference implementation: Apache Jackrabbit.


问:
How to avoid overhead while still implementing null object pattern?
I am implementing a binary search tree in java. Inside the BST class I have a protected class Node (in case I want to extend to an AVL tree). The code is below. I had a problem, both conceptually and aesthetically, implementing empty nodes as null pointers. So instead I opted for the null object pattern and created an EmptyNode object, the code for which is also below. However, even though this gives me prettier code and something more conceptually pleasing (to me), I now have the problem that when I'm working with a tree of height n, I can have as many as 2^{n+1} - 2^{n} instances of this EmptyNode class floating around, which takes up space for no good reason.

How should I fix this code to avoid this overhead while still implementing the null object pattern? I feel like the EmptyNode should be something conceptually similar to a constant field of Node, but I can't implement that. I also feel like there should be only one copy of EmptyNode being referenced anywhere, but I can't figure out how to implement that either. Any help or recommendations are appreciated.

```<code>protected class Node<Key,E>{
    protected Key key;
    protected E value;
    protected Node<Key,E> left;
    protected Node<Key,E> right;
    protected int height;
    protected int balanceFactor;
    public Node(){}
    public Node(Key k, E v){
        key = k;
        value = v;
        left = new EmptyNode<Key,E>();
        right = new EmptyNode<Key,E>();
        height = 0;
        balanceFactor = 0;
    }
    public Node(Key k, E v, Node<Key,E> l, Node<Key,E> r){
        key = k;
        value = v;
        left = l;
        right = r;
        height = Math.max(l.height(), r.height())+1;
        balanceFactor = l.height() - r.height();
    }
    public Key getKey(){return key;}
    public E getValue(){return value;}
    public Node<Key,E> getLeft(){return left;}
    public Node<Key,E> getRight(){return right;}
    public int height(){return height;}
    public int balanceFactor(){return balanceFactor;}
    public void setKey(Key k){key = k;}
    public void setValue(E v){value = v;}
    public void setLeft(Node<Key,E> l){
        left = l;
        height = Math.max(l.height(), this.right.height())+1;
        balanceFactor = left.height() - this.right.height();
    }
    public void setRight(Node<Key,E> r){
        right = r;
        height = Math.max(this.left.height(), r.height())+1;
        balanceFactor = this.left.height() - right.height();
    }
    public boolean isEmpty(){return false;}
    public boolean isLeaf(){
        return (left.isEmpty()) && (right.isEmpty());
    }
    public boolean hasLeft(){
        return !left.isEmpty();
    }
    public boolean hasRight(){
        return !right.isEmpty();
    }
}
protected final class EmptyNode<Key,E> extends Node<Key,E>{
    public EmptyNode(){
        key = null;
        value = null;
        left = right = null;
        height = -1;
        balanceFactor = 0;
    }
    @Override
    public void setKey(Key k){}
    @Override
    public void setValue(E v){}
    @Override
    public void setLeft(Node<Key,E> l){}
    @Override
    public void setRight(Node<Key,E> r){}
    @Override
    public boolean isEmpty(){return true;}
    @Override
    public boolean isLeaf(){return false;}
    @Override
    public boolean hasLeft(){return false;}
    @Override
    public boolean hasRight(){return false;}
}
</code>```

答:
Create a single instance of EmptyNode<Object, Object>, and cast it to Node<Key, E> when you need an empty node for a specific key and value type. This will work because an empty node has null key and value, and null reference can be casted to any reference type. See the source code for Collections.emptyList() for an example of this approach.

A fully working code example:

```<code>public class NodeTest {
    protected static class Node<Key,E>{
        private static final Node<?, ?> EMPTY_NODE = new EmptyNode<>();

        protected Key key;
        protected E value;
        protected Node<Key,E> left;
        protected Node<Key,E> right;
        protected int height;
        protected int balanceFactor;
        public Node() {
            this(null, null);
        }
        public Node(Key k, E v){
            this(k, v, Node.<Key, E>emptyNode(), Node.<Key, E>emptyNode());
        }
        public Node(Key k, E v, Node<Key,E> l, Node<Key,E> r){
            this(k, v, l, r, Math.max(l.height(), r.height())+1, l.height() - r.height());
        }
        private Node(Key k, E v, Node<Key, E> l, Node<Key, E> r, int h, int bf) {
            key = k;
            value = v;
            left = l;
            right = r;
            height = h;
            balanceFactor = bf;
        }
        public Key getKey(){return key;}
        public E getValue(){return value;}
        public Node<Key,E> getLeft(){return left;}
        public Node<Key,E> getRight(){return right;}
        public int height(){return height;}
        public int balanceFactor(){return balanceFactor;}
        public void setKey(Key k){key = k;}
        public void setValue(E v){value = v;}
        public void setLeft(Node<Key,E> l){
            left = l;
            height = Math.max(l.height(), this.right.height())+1;
            balanceFactor = left.height() - this.right.height();
        }
        public void setRight(Node<Key,E> r){
            right = r;
            height = Math.max(this.left.height(), r.height())+1;
            balanceFactor = this.left.height() - right.height();
        }
        public boolean isEmpty(){return false;}
        public boolean isLeaf(){
            return (left.isEmpty()) && (right.isEmpty());
        }
        public boolean hasLeft(){
            return !left.isEmpty();
        }
        public boolean hasRight(){
            return !right.isEmpty();
        }

        /**
         * @return empty node. This method can be useful for subclasses
         */
        @SuppressWarnings("unchecked")
        protected static final <Key, E> Node<Key, E> emptyNode() {
            return (Node<Key, E>) EMPTY_NODE;
        }
    }

    private static final class EmptyNode<Key, E> extends Node<Key, E> {
        private EmptyNode() {
            super(null, null, null, null, -1, 0);
        }
        @Override
        public void setKey(Key k){throw new UnsupportedOperationException();}
        @Override
        public void setValue(E v){throw new UnsupportedOperationException();}
        @Override
        public void setLeft(Node<Key,E> l){throw new UnsupportedOperationException();}
        @Override
        public void setRight(Node<Key,E> r){throw new UnsupportedOperationException();}
        @Override
        public boolean isEmpty(){return true;}
        @Override
        public boolean isLeaf(){return false;}
        @Override
        public boolean hasLeft(){return false;}
        @Override
        public boolean hasRight(){return false;}
    }

    public static void main(String[] args) {
        Node<String, Integer> node = new Node<>("hello", 5);
        System.out.println(node.isEmpty()); // prints false
        System.out.println(node.isLeaf());  // prints true
        System.out.println(node.getLeft().isEmpty()); // prints true
        System.out.println(node.getRight().isEmpty()); // prints true
    }
}
</code>```

My previous solution was bad. The new solution is better: shorter, and re-using more of your code. My modifications of your code were the following.

Routed all constructor calls to the private constructor which initializes all the fields (key, value, left, right, balanceFactor). This way, if you want to expand the fields a Node holds, you have to alter the assignment statements in only one constructor, reducing the potential for error.

Implemented public no-arguments constructor for a Node (yours did not initialize the left and right subtrees to be empty, they were null). Now it actually creates a changeable node with initial null key and value.

Extended Node to get EmptyNode. The EmptyNode constructor just calls super to create a node with null key, value, left and right subtrees, height of -1 and balanceFactor of 0.

Added emptyNode() method, which returns an appropriately casted EmptyNode instance (see the description of this technique at the beginning of my answer). This method can be used by subclasses of Node to obtain the shared EmptyNode instance instead of creating their own.

Made setKey(), setValue(), setLeft() and setRight() of EmptyNode throw UnsupportedOperationException, signaling that the empty node is immutable.

Made Node and EmptyNode static classes. I believe most inner classes should be static unless you absolutely have to use their containing class's fields and methods.

Body:
Create a single instance of EmptyNode<Object, Object>, and cast it to Node<Key, E> when you need an empty node for a specific key and value type. This will work because an empty node has null key and value, and null reference can be casted to any reference type. See the source code for Collections.emptyList() for an example of this approach.

A fully working code example:

public class NodeTest {
    protected static class Node<Key,E>{
        private static final Node<?, ?> EMPTY_NODE = new EmptyNode<>();

        protected Key key;
        protected E value;
        protected Node<Key,E> left;
        protected Node<Key,E> right;
        protected int height;
        protected int balanceFactor;
        public Node() {
            this(null, null);
        }
        public Node(Key k, E v){
            this(k, v, Node.<Key, E>emptyNode(), Node.<Key, E>emptyNode());
        }
        public Node(Key k, E v, Node<Key,E> l, Node<Key,E> r){
            this(k, v, l, r, Math.max(l.height(), r.height())+1, l.height() - r.height());
        }
        private Node(Key k, E v, Node<Key, E> l, Node<Key, E> r, int h, int bf) {
            key = k;
            value = v;
            left = l;
            right = r;
            height = h;
            balanceFactor = bf;
        }
        public Key getKey(){return key;}
        public E getValue(){return value;}
        public Node<Key,E> getLeft(){return left;}
        public Node<Key,E> getRight(){return right;}
        public int height(){return height;}
        public int balanceFactor(){return balanceFactor;}
        public void setKey(Key k){key = k;}
        public void setValue(E v){value = v;}
        public void setLeft(Node<Key,E> l){
            left = l;
            height = Math.max(l.height(), this.right.height())+1;
            balanceFactor = left.height() - this.right.height();
        }
        public void setRight(Node<Key,E> r){
            right = r;
            height = Math.max(this.left.height(), r.height())+1;
            balanceFactor = this.left.height() - right.height();
        }
        public boolean isEmpty(){return false;}
        public boolean isLeaf(){
            return (left.isEmpty()) && (right.isEmpty());
        }
        public boolean hasLeft(){
            return !left.isEmpty();
        }
        public boolean hasRight(){
            return !right.isEmpty();
        }

        /**
         * @return empty node. This method can be useful for subclasses
         */
        @SuppressWarnings("unchecked")
        protected static final <Key, E> Node<Key, E> emptyNode() {
            return (Node<Key, E>) EMPTY_NODE;
        }
    }

    private static final class EmptyNode<Key, E> extends Node<Key, E> {
        private EmptyNode() {
            super(null, null, null, null, -1, 0);
        }
        @Override
        public void setKey(Key k){throw new UnsupportedOperationException();}
        @Override
        public void setValue(E v){throw new UnsupportedOperationException();}
        @Override
        public void setLeft(Node<Key,E> l){throw new UnsupportedOperationException();}
        @Override
        public void setRight(Node<Key,E> r){throw new UnsupportedOperationException();}
        @Override
        public boolean isEmpty(){return true;}
        @Override
        public boolean isLeaf(){return false;}
        @Override
        public boolean hasLeft(){return false;}
        @Override
        public boolean hasRight(){return false;}
    }

    public static void main(String[] args) {
        Node<String, Integer> node = new Node<>("hello", 5);
        System.out.println(node.isEmpty()); // prints false
        System.out.println(node.isLeaf());  // prints true
        System.out.println(node.getLeft().isEmpty()); // prints true
        System.out.println(node.getRight().isEmpty()); // prints true
    }
}

My previous solution was bad. The new solution is better: shorter, and re-using more of your code. My modifications of your code were the following.

Routed all constructor calls to the private constructor which initializes all the fields (key, value, left, right, balanceFactor). This way, if you want to expand the fields a Node holds, you have to alter the assignment statements in only one constructor, reducing the potential for error.

Implemented public no-arguments constructor for a Node (yours did not initialize the left and right subtrees to be empty, they were null). Now it actually creates a changeable node with initial null key and value.

Extended Node to get EmptyNode. The EmptyNode constructor just calls super to create a node with null key, value, left and right subtrees, height of -1 and balanceFactor of 0.

Added emptyNode() method, which returns an appropriately casted EmptyNode instance (see the description of this technique at the beginning of my answer). This method can be used by subclasses of Node to obtain the shared EmptyNode instance instead of creating their own.

Made setKey(), setValue(), setLeft() and setRight() of EmptyNode throw UnsupportedOperationException, signaling that the empty node is immutable.

Made Node and EmptyNode static classes. I believe most inner classes should be static unless you absolutely have to use their containing class's fields and methods.


问:
Should I follow the normal path or fail early?
From the Code Complete book comes the following quote:

"Put the normal case after the if rather than after the else"

Which means that exceptions/deviations from the standard path should be put in the else case.

But The Pragmatic Programmer teaches us to "crash early" (p. 120).

Which rule should I follow?

答:
(@mirabilos' answer is excellent, but here's how I think about the question to reach the same conclusion:)

I'm thinking about myself (or someone else) reading the code of my function later on. When I read the first line, I can't make any assumptions about my input (except those which I won't be checking anyway). So my thought is "Ok, I know I'm going to be doing things with my arguments. but first let's 'clean them up" - i.e. kill control paths in which they're not to my liking." But at the same time, I don't see the normal case as something that's conditioned; I want to emphasize its being normal. Thus,

```<code>int foo(int* bar, int baz) {

   if (bar == NULL) /* I don't like you, leave me alone */;
   if (baz < 0) /* go away */;

   /* there, now I can do the work I came into this function to do,
      and I can safely forget about those if's above and make all
      the assumptions I like. */

   /* etc. */
}
</code>```

Body:
(@mirabilos' answer is excellent, but here's how I think about the question to reach the same conclusion:)

I'm thinking about myself (or someone else) reading the code of my function later on. When I read the first line, I can't make any assumptions about my input (except those which I won't be checking anyway). So my thought is "Ok, I know I'm going to be doing things with my arguments. but first let's 'clean them up" - i.e. kill control paths in which they're not to my liking." But at the same time, I don't see the normal case as something that's conditioned; I want to emphasize its being normal. Thus,

int foo(int* bar, int baz) {

   if (bar == NULL) /* I don't like you, leave me alone */;
   if (baz < 0) /* go away */;

   /* there, now I can do the work I came into this function to do,
      and I can safely forget about those if's above and make all
      the assumptions I like. */

   /* etc. */
}


答:
Personally I wouldn't call an atomic operation uninteruptible, after all you could blow the machine up. :)
I'd say it was one that could not be, through all sorts of mechanisms of varying effectiveness and cost, partially complete.

It either all happened (no matter how big or small is) or it didn't happen at all.

Title: What is Atomicity?