问:
Write data to SQL Server directly from BizTalk or use external service?
An external source will be sending us XML data that BizTalk will pick up and transform into an internal schema.  We need this data to be loaded into a SQL Server database as we're going to expose some of the data to our web front-end via a custom WCF service.

The question is: what is the recommended approach for doing something like this?  Options we're considering are having BizTalk write to the database directly or having BizTalk call a custom WCF service which would handle the save operation.  Another briefly considered idea was having BizTalk write to an MSMQ and have a custom service pull from there and store it in the database.

What are some of the guidelines or questions that should be asked in assessing these options?   There are concerns related to overhead from calling the extra service, duplication of efforts if the schema is modified in the future (which it will be to some extent), and simply the best way to design within a service-oriented architecture that we're struggling with.

答:
A lot depends on your environment and requirements. If BizTalk can keep up with the traffic, then I'd just have it write the data to the database. Simple, easy to understand and implement.

If it has problems keeping up, though, then I'd go with the MSMQ solution. This will provide you some buffering, as well as a convenient point to add things like load balancing or sharding, if those become important. It also permits a clean architecture if you need to introduce a filter chain between the source and the database. In fact, if BizTalk becomes the bottleneck, you could simply write a simple service to take the XML and dump it onto the queue, then have BizTalk read it from there. That way you won't risk losing messages because your BizTalk service can't respond quickly enough, and would also permit you to add additional instances of the service to handle heavy data loads.


问:
Open Source-Only license
I want to know if a license exists that is similar to GPL but allows only source distribution (that is no binary distribution).

Why do I want this? The idea is that I want fellow programmers to be able to have the benefits of open source software BUT also retain control over the consumer binary distribution. Specifically I want to prevent my software to be picked by organazations like the linux distributors. I want the users of my software to dowlnload binaries only from my site.

Is this possible?

Thanks

答:
You commented on your question to add:

I wouldn't mind binary distributions of derivatives, however under a
  different name.

That adds the possibility of a free software (that is open source) answer to the original 'shared source' or 'shareware' question.

There are free software licenses that seem to require the name to be changed.

I may be wrong. Ask your lawyer about the Mozilla Public License

```<code> This License does not grant any rights in the trademarks, service marks,
 or logos of any Contributor (except as may be necessary to comply with
 the notice requirements in Section 3.4).
</code>```

Sometimes, redistributors might not read your license, or make a very small change to your trademark. You might want to consider how difficult your restrictions may be to enforce, especially outside your home country.

ContentLicense: CC BY-SA 3.0

Title: Open Source-Only license

Body:
You commented on your question to add:

I wouldn't mind binary distributions of derivatives, however under a
  different name.

That adds the possibility of a free software (that is open source) answer to the original 'shared source' or 'shareware' question.

There are free software licenses that seem to require the name to be changed.

I may be wrong. Ask your lawyer about the Mozilla Public License

 This License does not grant any rights in the trademarks, service marks,
 or logos of any Contributor (except as may be necessary to comply with
 the notice requirements in Section 3.4).

Sometimes, redistributors might not read your license, or make a very small change to your trademark. You might want to consider how difficult your restrictions may be to enforce, especially outside your home country.


问:
How do I ensure my site will be crawled when articles are generated by the database?
I wasn't sure how to ask the question. But basically, it's a textbook scenario. I'm working on a site that's article based, but the article information is stored in a database. Then the page is rendered with the information in the database based on the requested article id:

For example: http://www.mysite.com/articles/9851

I'm new to SEO, so I'm wondering how engines are able to crawl the contents of pages like this and/or what I need to do in order to ensure that it will be crawled.

So for instance, this site. All of the articles/posts on this site appear to live in a database somewhere. The URL has an ID which looks like it is used to tell the server which data to use to generate the page -- so the page doesn't actually exist somewhere, but it's template does. When I search google, I might find one of these posts based on the content of the post.

I understand that crawlers normally just find a page and follow it's links and follow its links' links and so on, but how does that work when the site is search based like this? Do have to create a page that randomly picks articles out of the database so that the crawler can see it or something?

答:
At its very simplest, search engines are just reading HTML. The web page at a certain URL is just an HTML file to a search engine, so it doesn't know a database query is involved. It only knows that the HTML file contains text and links -- which is an overly simplified explanation, but accurate enough for this scenario.

@RomanMik has the right idea. You need to review Google's documentation, but regardless of the search engine, the process is the same:

Submit your site to the search engine

Your site needs links -- lots of links, and links with descriptive text -- to the rest of the pages on your site

A robots.txt file in the root of your domain can help tweak the search indexers, usually by telling them to ignore certain directories or file types

Create fresh content and update the home page and section pages of your site to link to the new content

A search indexer will start at your home page, index it, then it will move on to child pages in your site based on the links it finds in the document it is currently indexing.

Forget about thinking of search engines and your site in terms of your database. It's all HTML to a search engine, and they need fresh content, descriptive content, and links to other pages. Do that and you've cleared the first major hurdle.


问:
how to write unit test for AND logic gate
I'm learning about unit tests, and have a doubt for a test i want to do,

to implement an "AND" logic gate

```<code>A   B   A^B
0   0   0
0   1   0
1   0   0
1   1   1
</code>```

how can i test for a method that works like AND gate?, is this what a mock object is?
or stub?
Thanks,

Please provide pseudo code,

答:
I assume you're just looking for an example of how to write a unit test for something like an AND gate.

Depending on your unit test framework, you can use parameterized unit tests, like in NUnit:

```<code>[RowTest]
[Row(0,0,0)]
[Row(0,1,0)]
[Row(1,0,0)]
[Row(1,1,1)]
public void TestAndGate(int a, int b, int expected)
{
    var test = new AndGateImplementation();
    Assert.AreEqual(expected, test.And(a,b));
}
</code>```

Body:
I assume you're just looking for an example of how to write a unit test for something like an AND gate.

Depending on your unit test framework, you can use parameterized unit tests, like in NUnit:

[RowTest]
[Row(0,0,0)]
[Row(0,1,0)]
[Row(1,0,0)]
[Row(1,1,1)]
public void TestAndGate(int a, int b, int expected)
{
    var test = new AndGateImplementation();
    Assert.AreEqual(expected, test.And(a,b));
}


答:
Unit tests verify that a function returns properly for a handful of inputs and known outputs. In the case of a simple logic function, you actually have the advantage of testing every input/output:

```<code>// this is what you're testing:
public Boolean And(Boolean p1, Boolean p2);

// depending on your testing framework, your test might look like this
public void TestAnd() {
  TestAnd(true,  true,  true);
  TestAnd(true,  false, false);
  TestAnd(false, true,  false);
  TestAnd(false, false, false);
}

public void TestAnd(Boolean p1, Boolean p2, Boolean r) {
  Assert.Equal(And(p1, p2), r);
}
</code>```

Title: how to write unit test for AND logic gate

Body:
I'm learning about unit tests, and have a doubt for a test i want to do,

to implement an "AND" logic gate

```<code>A   B   A^B
0   0   0
0   1   0
1   0   0
1   1   1
</code>```

how can i test for a method that works like AND gate?, is this what a mock object is?
or stub?
Thanks,

Please provide pseudo code,

Body:
Unit tests verify that a function returns properly for a handful of inputs and known outputs. In the case of a simple logic function, you actually have the advantage of testing every input/output:

// this is what you're testing:
public Boolean And(Boolean p1, Boolean p2);

// depending on your testing framework, your test might look like this
public void TestAnd() {
  TestAnd(true,  true,  true);
  TestAnd(true,  false, false);
  TestAnd(false, true,  false);
  TestAnd(false, false, false);
}

public void TestAnd(Boolean p1, Boolean p2, Boolean r) {
  Assert.Equal(And(p1, p2), r);
}


问:
Is making a small change, testing it, then "rinse and repeat", a bad habit?
I am a programmer with a number of years of experience. I realized I got a certain habit. I'm not sure whether it's really a bad habit or not.

I get a list of tasks to perform for a solution, even small small tasks, for example,

Change resources of this user control

Change size of another one

Add some HTML and coding on another user control

All of these tasks are small. I mean they can be done within 10 minutes, but I got a bad habit of making small changes and then test them again and again in a web browser. Is this a good practice?

Or should I perform them all at once and then test them together?

If it is really a bad habit then how do I rectify it, since it feels like wasting time testing small changes over and over?

答:
This depends on the domain.  For laying out a web page it will work fine and you can get immediate feedback (you can even do it in the browser directly!).  Similarly it would work well for anything that doesn't require a long time to initialize.  This is preferred since it keeps your mental workload low and reduces the possibility of mistakes.

However, for really big projects where you have to compile the code and the time taken is non-trivial (several minutes), this can result in a lot of down time so you often have to resort to:

"parallelizing" your work flow (e.g. work on multiple builds simultaneously), or

do as many things as possible in one go, or

create a small independent part to work on and integrate into the larger project later.

(There are probably other ways too.)


问:
What's a nice explanation for pointers?
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.

答: When I was in university, my professor had some really neat powerpoint slides depicting a point as a separate variable on it's own with an arrow to a memory location (represented like an array) and when we were doing Linked Lists, he would do it step-by-step, showing when the arrow changes, when the pointer is dereferenced etc..., there was no way one could not understand it within a couple of minutes. The concept itself is really easy, but doing it right or applying it in practical programs requires more practice.</p>

ContentLicense: CC BY-SA 2.5

Title: What's a nice explanation for pointers?


问:
Implementation of strategy design pattern
Here is my code:

```<code>public class StrategyDemo {

        public static void main(String[] args) {

            Phone ipPhone = new IPPhone("1234", "ProviderA");
            Phone tdmPhone = new TDMPhone("4567", "ProviderB");

            ipPhone.getRecordingResource();
            tdmPhone.getRecordingResource();

            ipPhone.setRecordingResource(Resource.IPRecorderIP2);
            ipPhone.getRecordingResource();

        }

    }
</code>```

As I understood, a strategy pattern made that I would be able to change dynamically objects.

I always have hard time to actuality think of something to implement to practice on them.

This implementation is actually a strategy implementation ? How should I improve it?

Regarding comments asking to clarify my needs, I will try to explain the problem that I created that it will be more clear to determine if I used strategy correctly.

A phone should have an ability to be recorded.

A phone can be one of 2 types - IPPhone or TDMPhone.

A recording resource can be one of 2 types -  TDMRecorder or IPRecorder.

IPRecorder should but not must to record an IPPhone.

TDMRecorder should but not must to record an TDMPhone.

An actual recorder is a host in that case that is represented with an IP.

I was trying to implement it that way, that I would be able to change dynamically during  runtime  the resource the a phone is been recorded on (an IP address).

As I understood the part that is missing for me is to have under Record class an abstract method startRecording and the ability to change the recording resource from IPRecorder to an TDMRecorder and vice versa?

Is the problem that I defined suitable for a strategy design pattern?

答:
You're question is a bit unclear, but I'll explain what the Strategy pattern is in case you don't have a good understanding.

Strategy allows you to swap part of the functionality of an object dynamically during runtime. This is done by encapsulating the different functionalities in classes that all share a common supertype, and having the object in question (the 'context') own a reference of this supertype.

Than, when the object wants to perform some functionality, it actually delegates to the Strategy object it owns. We can swap the current Strategy object for a different one dynamically via e.g. a public setter method.
Thus swapping the functionality owned by the object.

Note that the Strategy pattern is called that because it allows you to choose different 'strategies' for performing generally the same operation.

For example, in a game you might have a Soldier class. Objects of this class are able to attack bad guys via their attack() method.

But what if you wanted attack() to do something different based on the current weapon the soldier holds? For example if currently the weapon is a gun, attack() will shoot bullets. If it's a knife, attack() will make the soldier stab people.

A naive way to approach this, would be for Soldier to hold a String variable that signifies what the current weapon is. attack() will than have a long else if chain to determine the correct logic according to the current weapon. Something like this:

```<code>class Soldier{
    String weapon;
    void setWeapon(String w){ weapon = w; }
    void attack(){
        if(weapon.equals("gun")) // shoot bullets
        else if(weapon.equals("knife")) // slash people
        // else if ...
    }
}
</code>```

But this approach is bad and definitely not very Object Oriented. What's so bad about it?

Well, suppose you already had 5 different kinds of weapons, and wanted to add another one to the game. You'd have to go into Soldier and add another else if to match.

That's not so bad, but what if more classes in your game needed to use weapons? For example, a DefenseTurret could also hold a specific kind of weapon that would govern the way it attack()s.

That would mean a lot of code duplication between Soldier and DefenseTurret. And again, if you want to add a new weapon - you need to go to both these classes and add logic to them, resulting in classes that keep growing and more and more code duplication. Probably resulting in nasty bugs.

The Strategy pattern is there exactly to provide a more elegant and OO solution to these situations.

With Strategy, each kind of weapon will be implemented in it's own Weapon subclass. Weapon would be an abstract class (or interface) that defines an abstract attack() method. Each of it's subclasses implements this method differently.

Soldier, instead of holding a String weapon member, will have a Weapon weapon member. And it's attack() method, instead of containing a long else if chain, will simply delegate to the weapon: weapon.attack(). Code to clarify:

```<code>class Soldier{
    // .. stuff omitted
    Weapon weapon;
    void attack(){
        weapon.attack();
    }
    void setWeapon(Weapon newWeapon){
        weapon = newWeapon;
    }
}
abstract class Weapon{
    public abstract void attack();
}
class Gun extends Weapon{
    public void attack{ /* shoot some bullets */ }
}
class Knife extends Weapon{
    public void attack{ /* stab some bad guys */ }
}
</code>```

Much more elegant.

Here's a UML diagram to clarify even more:

And now, what if you wanted to give DefenseTurret some gun shooting capabilities? Just give it a Weapon reference and have it delegate to it, like you did with Soldier. You can reuse the code you already wrote without copy-pasting it all the time.

I hope this clarifies what Strategy is. Regarding your question, I couldn't really understand it, but it seems to me what you're doing doesn't clarify as a Strategy implementation since your swapping data (i.e. with a simple setter that sets a String value), but not swapping functionality and logic.

I'll be happy to help if you explain more clearly what your problem is.

Body:
You're question is a bit unclear, but I'll explain what the Strategy pattern is in case you don't have a good understanding.

Strategy allows you to swap part of the functionality of an object dynamically during runtime. This is done by encapsulating the different functionalities in classes that all share a common supertype, and having the object in question (the 'context') own a reference of this supertype.

Than, when the object wants to perform some functionality, it actually delegates to the Strategy object it owns. We can swap the current Strategy object for a different one dynamically via e.g. a public setter method.
Thus swapping the functionality owned by the object.

Note that the Strategy pattern is called that because it allows you to choose different 'strategies' for performing generally the same operation.

For example, in a game you might have a Soldier class. Objects of this class are able to attack bad guys via their attack() method.

But what if you wanted attack() to do something different based on the current weapon the soldier holds? For example if currently the weapon is a gun, attack() will shoot bullets. If it's a knife, attack() will make the soldier stab people.

A naive way to approach this, would be for Soldier to hold a String variable that signifies what the current weapon is. attack() will than have a long else if chain to determine the correct logic according to the current weapon. Something like this:

class Soldier{
    String weapon;
    void setWeapon(String w){ weapon = w; }
    void attack(){
        if(weapon.equals("gun")) // shoot bullets
        else if(weapon.equals("knife")) // slash people
        // else if ...
    }
}

But this approach is bad and definitely not very Object Oriented. What's so bad about it?

Well, suppose you already had 5 different kinds of weapons, and wanted to add another one to the game. You'd have to go into Soldier and add another else if to match.

That's not so bad, but what if more classes in your game needed to use weapons? For example, a DefenseTurret could also hold a specific kind of weapon that would govern the way it attack()s.

That would mean a lot of code duplication between Soldier and DefenseTurret. And again, if you want to add a new weapon - you need to go to both these classes and add logic to them, resulting in classes that keep growing and more and more code duplication. Probably resulting in nasty bugs.

The Strategy pattern is there exactly to provide a more elegant and OO solution to these situations.

With Strategy, each kind of weapon will be implemented in it's own Weapon subclass. Weapon would be an abstract class (or interface) that defines an abstract attack() method. Each of it's subclasses implements this method differently.

Soldier, instead of holding a String weapon member, will have a Weapon weapon member. And it's attack() method, instead of containing a long else if chain, will simply delegate to the weapon: weapon.attack(). Code to clarify:

class Soldier{
    // .. stuff omitted
    Weapon weapon;
    void attack(){
        weapon.attack();
    }
    void setWeapon(Weapon newWeapon){
        weapon = newWeapon;
    }
}
abstract class Weapon{
    public abstract void attack();
}
class Gun extends Weapon{
    public void attack{ /* shoot some bullets */ }
}
class Knife extends Weapon{
    public void attack{ /* stab some bad guys */ }
}

Much more elegant.

Here's a UML diagram to clarify even more:

And now, what if you wanted to give DefenseTurret some gun shooting capabilities? Just give it a Weapon reference and have it delegate to it, like you did with Soldier. You can reuse the code you already wrote without copy-pasting it all the time.

I hope this clarifies what Strategy is. Regarding your question, I couldn't really understand it, but it seems to me what you're doing doesn't clarify as a Strategy implementation since your swapping data (i.e. with a simple setter that sets a String value), but not swapping functionality and logic.

I'll be happy to help if you explain more clearly what your problem is.


问:
A container only assets in Rails
I have multiple segmented Rails apps that are connected to each other:

App A

App B

App C

While I try to keep the design, such as header and footer, to look similar, but each app has its own stylesheet, javascript and images in the asset folder. Some of these assets are duplicate, like CSS for footer. It makes maintenance difficult.

I'm wondering if I could do something like having App D, where App A, B, and C will just retrieve the assets from App D. So if I need to change anything, I can just change the assets in App D.

How do I achieve this?

答:
There is not much detail in the question but that gives some flexibility in the answers. These would work for almost any web app, not just Rails.

You could store the duplicate items in a git submodule.

Or you could write a script that copies the assets to each app each time you update them.

Or (if the apps are on the same filesystem) you could hard link or symbolically link all the asset files together.

Or you could could link the assets with the full urls (including the domain names) so that the browser always gets them from the same server (in much the same way as the browser might get jQuery from the Google Content Delivery Network.)

Title: A container only assets in Rails


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答: Among another signals, there is one important warning for me (maybe I'm wrong, and it is not common): double-digits in the minor version like "superproject version 3.16"


问:
Is Chef an appropriate tool to use for application deployment?
We use Chef for both config management (making sure a "DB Node" has the right version of the right DB on it; that an "App Server" has the right version of Java and env vars on it, etc.). as well as deployment (chef-client --once) of our apps to the appropriate app server nodes.

To me, personally, I feel like deployment belongs in the realm of the CI server. Everything besides the app (the container, the OS, system tools, system config, etc.) belongs to config management, and is therefore best managed by tools like Chef, Puppet, etc.

Currently, our CI builds produce an artifact (an executable JAR with an embedded Tomcat container), and then executes the Chef-Client on all the nodes where the JAR needs to be deployed. The Chef-Client is configured to pull the JAR from the CI server. This feels hacky to me, and I'm trying to research a better, more cogent solution.

So I ask:

Does deployment belong to the CI server, or to the CM tool? Why?

If it belongs to the CI server, what mechanisms (SSH, SCP, etc.) should the CI server be using to actually perform the deploy? We use Bamboo but could just as easily be talking about Jenkins, Hudson, etc.

There is a difference between deploying (placing the app on the node) and running. Does running belong to the CI server as well, the CM tool, or some other process? In other words, what should actually stop the "old" version of the app, replace it with the "new" version, and then start the new version? Is this a candidate for something like Run Deck?

答:
I suspect the answers are going to be largely opinion based, and reflect the political atmosphere of the companies people work for, but here goes...

I would say everything starts with "why?"  Why do we build apps?  To fulfill business goals.  Why do we build infrastructure?  To run apps that fulfill business goals.  So it seems that there's a natural hierarchy here.  CI servers build apps and test them on something.  CM tools build servers.  So, a properly configured DevOps chain probably uses CI servers to invoke CM tools to make sure that the place they're about to deploy to is configured properly.  Then, once tests pass, those same CI servers invoke deployment tools (if necessary) to push code to production servers that could be built with CM scripts on a moment's notice if necessary.  In other words, the scripts become the definition of what's there -- no changes are made to the servers that aren't scripted first.  As far as bouncing the existing app, that's going to depend on the configuration of your infrastructure.  If you can smoothly take an app server offline (without affecting users), deploy new code, run a smoke test, and bring it all back online in a rolling script across a farm of servers, that's what you're shooting for -- continuous delivery capabilities that don't affect end users.


问:
Uses for System.gc() in Java
In Java, there is a method called System.gc(), which calls the garbage collector (or rather, "suggests" to the JVM to run the GC).

Are there valid reasons to call this method? I'm thinking that it would be evident of bad software design.

答: How about a benchmarking suite? Rather than letting the GC run at any random time, you might want to make it run between sets of tests, to (possibly) create more consistent conditions for each set.</p>

Title: Uses for System.gc() in Java


问:
Which approach would be better for persisting these overridable configuration keys and values? A simple key-value store, or a graph database?
I'm creating a system where there are config keys and values. So for example:

```<code>config.key = 10
</code>```

Is an example of a configuration key and a value. These keys can also have overrides based on "dimensions". So for example, if we wanted to apply config.key to applications with the dimension foo, the overridden key would essentially be:

```<code>config.key.foo = 20
</code>```

In future we may have multiple dimensions in arbitrary order, so this could be a possibility in future:

```<code>config.key.foo.bar = 30
</code>```

A more concrete example would be if we had a key/toggle called display.pintrest.feed that has a boolean value. So the default value would be false, but you could have overrides like so:

```<code>display.pintrest.feed = false
display.pintrest.feed.femaleUser = true
</code>```

Here femaleUser is a dimension (so we want to set the value of this config to true for only female users).

This is essentially what I am trying to do. My question is regarding persistence. What would be the best way to persist this kind of data? This is data that will be queried somewhat frequently but written to less often. The naive solution would be to use MySQL or PostgreSQL and create a table like this:

```<code>+----------------------------------+-------+
|                Key               | Value |
+----------------------------------+-------+
| config.key                       | 10    |
| config.key.foo                   | 20    |
| display.pintrest.feed            | true  |
| display.pintrest.feed.femaleUser | false |
+----------------------------------+-------+
</code>```

But we lose the type safety of Value and also have a single point of failure. We also have a lot of redundancy (the base part of the configuration key is repeated each time). So I wondered about perhaps representing it as a graph so that I could write it to a graph database. I was thinking of modeling it like so:

Is this viable or overkill?

I don't mind using a simple key-value store either but it should be fault-tolerant and should be able to be clustered. Also we only really care about eventual consistency (i.e., don't mind it taking time to propagate changes to all the nodes).

So my question is what kind of data store should back this kind of data? Is a simple key-value store enough or should I go for a graph database? My rationale for the latter is simply to mitigate the redundancy from keys but I don't know if that's strong rationale.

答:
You could use a slightly difference structure in your table, if you still wanted to go with a table-based solution:

```
key_values
----------
  id
  parent_id
  key
  value
  type_constraint_id

type_contraints
---------------
  id
  name
```

and then populate it like this:

```
key_values
----------
id  | parent_id | key       | value    | type_constraint_id
----+-----------+-----------+----------+-------------------
1   |           | config    |          |
2   | 1         | key       | 10       |
3   | 2         | foo       | 20       |
4   |           | display   |          |
5   | 3         | pinterest |          |
6   | 5         | feed      | true     |
7   | 6         | femaulUsr | false    |

type_constraints
----------------
id  |   name
----+-----------
1   | numeric
2   | boolean
3   | text
```

This schema allows you to store the hierarchy in such a way that you can query it directly, since it sounds like you're interested in in working with it in that way.

I've also added a type_constraint table and FK so that you can associate keys with named types. The database can't actually enforce these so you'd have to use this as a hint for your application to do type validation (or do it in the database with triggers). I'm not sure I'd bother if I was building this for myself, but you seem to want to have some sort of type-safety, this was the simplest way I could think to add it to this schema.

I suppose a graph database could work if these key/value structures get very complex, but I'm not familiar enough with them to know if they offer the type-safety you want and will work the way you need.

Body:
You could use a slightly difference structure in your table, if you still wanted to go with a table-based solution:

key_values
----------
  id
  parent_id
  key
  value
  type_constraint_id

type_contraints
---------------
  id
  name

and then populate it like this:

key_values
----------
id  | parent_id | key       | value    | type_constraint_id
----+-----------+-----------+----------+-------------------
1   |           | config    |          |
2   | 1         | key       | 10       |
3   | 2         | foo       | 20       |
4   |           | display   |          |
5   | 3         | pinterest |          |
6   | 5         | feed      | true     |
7   | 6         | femaulUsr | false    |

type_constraints
----------------
id  |   name
----+-----------
1   | numeric
2   | boolean
3   | text

This schema allows you to store the hierarchy in such a way that you can query it directly, since it sounds like you're interested in in working with it in that way.

I've also added a type_constraint table and FK so that you can associate keys with named types. The database can't actually enforce these so you'd have to use this as a hint for your application to do type validation (or do it in the database with triggers). I'm not sure I'd bother if I was building this for myself, but you seem to want to have some sort of type-safety, this was the simplest way I could think to add it to this schema.

I suppose a graph database could work if these key/value structures get very complex, but I'm not familiar enough with them to know if they offer the type-safety you want and will work the way you need.


答: What about a game where you want to control gc pauses. You could then call gc right before a level starts after assets are loaded.</p>

Title: Uses for System.gc() in Java

Body:
In Java, there is a method called System.gc(), which calls the garbage collector (or rather, "suggests" to the JVM to run the GC).

Are there valid reasons to call this method? I'm thinking that it would be evident of bad software design.


问:
How does Elastic Search approach the problem of distributed membership and consensus?
I already understand that Elastic Search is supposed to be deployed in a distributed topology, in that you can have multiple nodes for a cluster of ES instances.

I like the API, and it looks promising. But I wonder how Elastic Search solves some standard problems in distributed computing. My "architectural" questions are motivated out of trying to understand whether I ought to commit to using the product.

Consider membership problem: If I add a node to the cluster, how does Elastic Search cluster know to add that node wants to join? Or what if a node goes down (or the network to the data center it is in) gets too flaky. Is it using some sort of gossip protocol like Amazon Dynamo does?

Consider the consensus problem: if I POST a document to one node to the cluster, how does the change get propagated to the other nodes? Of course, I understand that the document has to be indexed, so I cannot expect a search query to find it immediately. Does ES use a Paxos algorithm? Raft algorithm?

UPDATE: A nice discussion of the split-brain problem in Elastic Search.

答:
There is not an incredible amount of detail in the online Elasticsearch: The Definitive Guide, but suffice to say, with respect to:

Cluster membership: the oldest node becomes the "master" and it appears some sort of gossip protocol is used when nodes join and leave the cluster.

A leadership election does occur when the master leaves the cluster (which I tried for myself). Elastic Search does not state how they pull this off, and they want to leave this encapsulated for their users.

ContentLicense: CC BY-SA 4.0


问:
Website Internationalisation approaches
I'm currently working on a project that the client wants to deliver to different countries.

The application is a website.

We started out using resource files to change the text the user sees when visiting pages based on their locations. But this isn't enough.

In the English version of the site we have a page that states "page x of y".
In the Chinese version of the site, it's not enough to do " x  y"

The syntax for the language doesn't match the placeholders that were created for the English language.

The only other option I can think of is to have a completely separate site, serving different content.

Are there any other options to solve this issue?

答:
For i18n, you've got several solutions of increasing complexity.

First, store a language specific template in a properties file. E.g. messages.en may store the property. This works for short and simple text.

```<code>pagination.text = [X] of [Y]
</code>```

But messages.zh may store

```<code>pagination.text = [X of Y]
</code>```

Second, at least in the Java world, changing a property file change means a new deployment. String attributes can also be internationalized in the database.

Suppose you had an Products mapped directly to a product table. Let's say we have the following API to support internationalizing the name of a product.

```<code>class Product
   def id: Long
   def name(language: Language): String

class Language
   // e.g. 'en' for English, 'zh' for Chinese
   def isocode: String

   def name: String

   // ordered list of isodcode s.t. if the internationalized attribute
   // does not exist for this language, it tries each language in this list in order.
   def fallbackLanguage: List[String]

   // default language for entire system. Use this language if all else fails
   def isDefault: Boolean
</code>```

The name attribute on product table would need a one-to-many table joined with the language table.

It usually helps to provide an admin interface so that business users can make changes
to these core entities on their own.

Next, you may need to add currency, country and region (e.g. California, Wuhan Province), as first class object just as much as language, so that your system can localize to the particular business rules that apply to a specific region. To continue with my product example, the prices in China won't be the same as in the US, simply because the currency differs. Chinese customers may be expected to pay only in renminbi. And US customers pay only in US dollars.

Lastly, a reason that the same overarching functionality may need to be a separate system is that the business rules in different countries differ. Taxes in the US are not the same as taxes in China. The product catalog can differ because of differing marketing emphases. So It may make sense for your client's China team to have ownership over their own site, as opposed to your client's English-speaking team in an English-speaking country.

Title: Website Internationalisation approaches

Body:
For i18n, you've got several solutions of increasing complexity.

First, store a language specific template in a properties file. E.g. messages.en may store the property. This works for short and simple text.

pagination.text = [X] of [Y]

But messages.zh may store

pagination.text = [X of Y]

Second, at least in the Java world, changing a property file change means a new deployment. String attributes can also be internationalized in the database.

Suppose you had an Products mapped directly to a product table. Let's say we have the following API to support internationalizing the name of a product.

class Product
   def id: Long
   def name(language: Language): String

class Language
   // e.g. 'en' for English, 'zh' for Chinese
   def isocode: String

   def name: String

   // ordered list of isodcode s.t. if the internationalized attribute
   // does not exist for this language, it tries each language in this list in order.
   def fallbackLanguage: List[String]

   // default language for entire system. Use this language if all else fails
   def isDefault: Boolean

The name attribute on product table would need a one-to-many table joined with the language table.

It usually helps to provide an admin interface so that business users can make changes
to these core entities on their own.

Next, you may need to add currency, country and region (e.g. California, Wuhan Province), as first class object just as much as language, so that your system can localize to the particular business rules that apply to a specific region. To continue with my product example, the prices in China won't be the same as in the US, simply because the currency differs. Chinese customers may be expected to pay only in renminbi. And US customers pay only in US dollars.

Lastly, a reason that the same overarching functionality may need to be a separate system is that the business rules in different countries differ. Taxes in the US are not the same as taxes in China. The product catalog can differ because of differing marketing emphases. So It may make sense for your client's China team to have ownership over their own site, as opposed to your client's English-speaking team in an English-speaking country.


问:
Notation/Meta Language To Express An Algorithm
I need to learn a notational language, so I can express and possibly prove the correctness of what I believe to be a complicated algorithm that distributes a credit adjustment across multiple water bills in issue date descending order. But I cannot tell what that notational language should be.

Each bill has three consumption tiers, 1-30, 31-60, and over 60. Each tier is associated with a different water and sewer rate. The higher the tier, the higher is the rate.

Two water bills each have 100ccf consumption, which means each bill is billed like this. That is it's distribution across tiers 1, 2, and 3 is tier1 = -30, tier2 = -30, and tier3 = -40. In case it is not obvious, billing takes place from lowest to highest tier, so crediting takes place from highest to lowest tier.

If I apply a -170 consumption credit, the first bill consumes -100ccfs. It is the remaining -70 ccf credit to be applied to the second bill that gets crazy.

-40 of it has to be credited at tier3 and the remaining -30 at tier2. Nothing is left over for tier1 (second bill). I know this is absolutely correct distribution, because I've consulted the oracles in our municipality. They know what they're talking about.

With -70 left (held in one variable) and the second bill's original consumption (held in a separate variable), I subtract the value of the sum of tier1's and tier2's cutoffs (60ccf) from 100ccf (the consumption when the bill was issued). I want to prove why that is right. I'm not content to say "Hey, I fooled around until I got a nice answer."

Any ideas or help would be appreciated.

答:
As I expressed in another answer, Z-Notation is a common standard method in formal CS for expressing algorithms independent of programming language. The broader category is Pidgin Code.

Z-Notation is used in both Introduction to Algorithms and Artificial Intelligence: A Modern Approach, both standard textbooks in their respective sub-disciplines and containing some very complex examples rendered beautifully in Z-Notation.

You can, of course, use whatever notation you desire but since Z-Notation is widely used and developed by researchers working in theoretical Computer Science and Mathematics, it will allow a wider audience than many of the alternatives.


问:
How do tablespaces differ in DB2 from databases in MySQL or MS SQL Server?
In DB2, it seems there is a strong separation between what a database is and what a tablespace is. Where as in MySQL and MS SQL Server tablespace and database seemed to be used synonymously.

What are the differences, if any?

答:
In DB2 and Oracle, tablespace is roughly the child 'containers' within a database. You can, for example, organize your huge tables to be created on a specific tablespace, for managing the disk storage.

In MS SQL server there is no concept of tablespaces AFAIK. It uses file groups for the purpose of organizing storage and there is no one-to-one correlation with the tablespace concept.


问:
Best approach for a server configuration data collection and reporting solution from a legacy script?
I have a project which involves collecting config data from windows servers in our (very large) server estate. My manager wants me to collect over 150 data items across all configuration areas including network config data, disks, registry values, BIOS version, dll versions, you name it. The server support team currently use a nasty vbScript script which is massive, messy and has been passed around and grown organically over time. The script is currently used to collect the data and produce a very basic flat HTML report with a column for each of the 150+ items it collects data for.  My job is to tranform it into a proper software solution with new bells and whistles, a website, reports etc.

The idea is a sys admin will go to an intranet website, puts the server name in and presses the go button, the solution collects the data and pushes it into the DB for reporting later.

My manager wants the solution to collect the data, some of it referencing known desired values (e.g. RAID card drivers for ABC model servers is at v1.2.5.1) to see if they are correct or up to date, store it in a SQL database, and then use the front end web site for producing reports. In the reports, he wants it to be able to compare two datasets; for example, one for server ABC123 and one for server DEF987 in one report, highlighting any differences between the two.

It gets messy pretty quick as some data will be collected for on some servers but not others (domain controllers wont have data collected about exchange services running status). There are many miscellanous items which don't fit into a data model area and don't really have a home ... it's a mess.

I'm ok with collecting the data (using .Net), but I'm at a loss as to where the best place is to do such things as store and lookup/compare items to good known values (XML, DB?). Should I do it as part of the data collection phase and then push it into the DB. Or should I marry it all up as part of the reporting data?

I'm going with a data warehouse (de-normalised) schema for the DB. There will probably be about 20 tables which the data will need to be pulled from, so I have no real idea what the best way to compare the dataset from one server data collection, with another, with such a massive set of fields to compare.

What do you guys think my best options are for approaching this project and the architecure of the solution?

答:
With the information you have provided , I would recommend using MS SQL server to store and compare the data. No XML or intermediate representations. Collect, transform and dump everything directly to the DB.  If right now it is running on VBscript and MS SQL Server I am assuming it is not super critical.

The reads from the de-normalised schema could be fast, that will serve the reports faster when requested. Better than running join queries with a complex but leaner data model.
Again a lot of depends on the sampling interval, and volume of data. I don't think it can grow more than a few million rows if we are talking about few days of data with 10 second sampling for some 100 servers. With required indexes in place it should be fast enough in MS SQL Server. You might need to define an archival strategy; or aggregate older statistics in a coarser granularity and push to some aggregate tables.


答:
In general, there isn't a good reason to call System.gc().  Especially since the system might ignore it.  But here are some plausible reasons.

As mentioned, in a benchmark

You just freed up a ton of large Objects and otherwise "things are quiet", the queues are empty, etc...  Now is a good time to get the maintenance work done.

You are about to allocate a ton of large Objects and otherwise "things are quiet".

You are about to enter speed sensitive code where low latency is desired.  Get the garbage collection "out of the way" now, before the climactic fight vs. the super-fast 28 Days Later Zombies in 3D and 4K resolution.  :-)

Title: Uses for System.gc() in Java


问:
Why does C use the asterisk for pointers?
I'm just now learning about C.

I find it odd that the creators chose the asterisk (*) as the symbol for pointers rather than a symbol that actually looks like a pointer (->).

Considering how confusing dereferencing and function pointers can be, is there a historical, or even practical, reason for using the asterisk?

答:
Why does C use the asterisk for pointers?

Simply - because B did.

Because memory is a linear array, it is possible to interpret the value in a cell as an index in this array, and BCPL supplies an operator for this purpose. In the original language it was spelled rv, and later !, while B uses the unary *. Thus, if p is a cell containing the index of (or address of), or pointer to) another cell, *p refers to the contents of the pointed-to cell, either as a value in an expression or as the target of an assignment.

From The Development of the C Language

Thats it.  At this point, the question is as uninteresting as "why does python 3 use . to call a method? Why not ->?"  Well... because Python 2 uses . to call a method.

Rarely does a language exist from nothing.  It has influences and is based on something that came before.

So, why didn't B use ! for derefrencing a pointer like its predecessor BCPL did?

Well, BCPL was a bit wordy.  Instead of && or || BCPL used logand and logor.  This was because most keyboards din't have ∧ or ∨ keys and not equal was actually the word NEQV (see The BCPL Reference Manual).

B appears to have been partially inspired to tighten up the syntax rather than have long words for all these logical operators that programmers did fairly frequently.  And thus ! for dereference became * so that ! could be used for logical negation.  Note there's a difference between the unary * operator and the binary * operator (multiplication).

Well, what about other options, like ->?

The -> was taken for syntactic sugar around field derefrences struct_pointer->field which is (*struct_pointer).field

Other options like <- could create ambiguous parsings.  For example:

```<code> foo <- bar
</code>```

Is that to be read as:

```<code>(foo) <- (bar)
</code>```

or

```<code>(foo) < (-bar)
</code>```

Making a unary operator that is composed of a binary operator and another unary operator is quite likely to have problems as the second unary operator may be a prefix for another expression.

Furthermore, it is again important to try to keep the things being typed frequently to a minimum.  I would hate to have to write:

```<code>int main(int argc, char->-> argv, char->-> envp)
</code>```

This also becomes difficult to read.

Other characters might have been possible (the @ wasn't used until Objective C appropriated it).  Though again, this goes to the core of 'C uses * because B did'.  Why didn't B use @?  Well, B didn't use all the characters.  There was no bpp program (compare cpp) and other characters were available in B (such as # which was later used by cpp).

If I may hazard a guess as to why - its because of where the keys are.  From a manual on B:

To facilitate manipulation of addresses when it seems advisable, B provides two unary address operators, * and &. & is the address operator so &x is the address of x, assuming it has one. * is the indirection operator; *x means "use the content of x as an address."

Note that & is shift-7 and * is shift-8.  Their proximity to each other may have been a hint to the programmer as to what they do... but that's only a guess. One would have to ask Ken Thompson about why that choice was made.

So, there you have it.  C is that way because B was.  B is that way because it wanted to change from how BCPL was.

Body:
Why does C use the asterisk for pointers?

Simply - because B did.

Because memory is a linear array, it is possible to interpret the value in a cell as an index in this array, and BCPL supplies an operator for this purpose. In the original language it was spelled rv, and later !, while B uses the unary *. Thus, if p is a cell containing the index of (or address of), or pointer to) another cell, *p refers to the contents of the pointed-to cell, either as a value in an expression or as the target of an assignment.

From The Development of the C Language

Thats it.  At this point, the question is as uninteresting as "why does python 3 use . to call a method? Why not ->?"  Well... because Python 2 uses . to call a method.

Rarely does a language exist from nothing.  It has influences and is based on something that came before.

So, why didn't B use ! for derefrencing a pointer like its predecessor BCPL did?

Well, BCPL was a bit wordy.  Instead of && or || BCPL used logand and logor.  This was because most keyboards din't have ∧ or ∨ keys and not equal was actually the word NEQV (see The BCPL Reference Manual).

B appears to have been partially inspired to tighten up the syntax rather than have long words for all these logical operators that programmers did fairly frequently.  And thus ! for dereference became * so that ! could be used for logical negation.  Note there's a difference between the unary * operator and the binary * operator (multiplication).

Well, what about other options, like ->?

The -> was taken for syntactic sugar around field derefrences struct_pointer->field which is (*struct_pointer).field

Other options like <- could create ambiguous parsings.  For example:

 foo <- bar

Is that to be read as:

(foo) <- (bar)

or

(foo) < (-bar)

Making a unary operator that is composed of a binary operator and another unary operator is quite likely to have problems as the second unary operator may be a prefix for another expression.

Furthermore, it is again important to try to keep the things being typed frequently to a minimum.  I would hate to have to write:

int main(int argc, char->-> argv, char->-> envp)

This also becomes difficult to read.

Other characters might have been possible (the @ wasn't used until Objective C appropriated it).  Though again, this goes to the core of 'C uses * because B did'.  Why didn't B use @?  Well, B didn't use all the characters.  There was no bpp program (compare cpp) and other characters were available in B (such as # which was later used by cpp).

If I may hazard a guess as to why - its because of where the keys are.  From a manual on B:

To facilitate manipulation of addresses when it seems advisable, B provides two unary address operators, * and &. & is the address operator so &x is the address of x, assuming it has one. * is the indirection operator; *x means "use the content of x as an address."

Note that & is shift-7 and * is shift-8.  Their proximity to each other may have been a hint to the programmer as to what they do... but that's only a guess. One would have to ask Ken Thompson about why that choice was made.

So, there you have it.  C is that way because B was.  B is that way because it wanted to change from how BCPL was.


问:
n:m as the only way to store notifications?
I have a user and a notifications table. I want to make sure that every users sees a new notification once and only once. Not more, not less. The intuitive idea is to have a n:m relation table with userId:notificationId. But isn´t it a little too much overhead to create a new table just for that?

What about NoSQL databases? Would it be a good idea to just add an array of notification ids to the individual user in the user table?

答:
@Amberlamps your question is very generic and from one perspective, AakashM did answer it in a comment already.

However let's look at it's basics to illustrate some ideas and techniques and their design considerations..

For a single user, what is the least amount of records (of the smallest size) that will address your need.
On the surface (m) records per user. However more carefully, you can see it is likely to be a sparse set or the opposite of it, i.e. a mostly filled set.

You can, based on your data, come up with more complex representations if space is your concern.. i.e. for each user represent all "seen" records in ranges, i.e. (user1, lowid1, highid1), (user1, lowid2, highid2), (user2, lowid1, highid1) and so on. Separately system wide you'd have a system lowid and system highid to give boundaries to your queries. In essence this is one way to represent a sparse set (I haven't seen this exact structure anywhere else but if someone has seen it formally represented elsewhere please comment)..

You can find other ways to represent sparse sets too.

OTOH, if speed of lookup is more important then a straight n:m takes extra space compared to other representations but gives you very high speed for almost any operation you can think of.

Now switching topics.. In relational DB;s Having a separate table is actually not much more overhead, because the storage is efficient.
In NoSQL DB, adding an array to each user will take less space, however when you're searching for all users who have "read" a particular notification, it forces you into an expensive query, unless you have indexes (which can be the same overhead as having them in a separate table). In this case if you switch the query around and search for all users who have "not" read a notification, it could be even more expensive.

Write a comment or update your question and I'll expand more if as needed.


问:
Design pattern for an automated mechanical test bench
Background

I have a test fixture with a number of communication/data acquisition devices on it that is used as an end of line test for a product.

Because of all the various sensors used in the bench and the need to run the test procedure in near real-time, I'm having a hard time structuring the program to be more friendly to modify later on. For example, a National Instruments USB data acquisition device is used to control an analog output (load) and monitor an analog input (current), a digital scale with a serial data interface measures position, an air pressure gauge with a different serial data interface, and the product is interfaced through a proprietary DLL that handles its own serial communication.

The hard part

The "real-time" aspect of the program is my biggest tripping point. For example, I need to time how long the product needs to go from position 0 to position 10,000 to the tenth of a second. While it's traveling, I need to ramp up an output of the NI DAQ when it reaches position 6,000 and ramp it down when it reaches position 8,000. This sort of control looks easy from browsing NI's LabVIEW docs but I'm stuck with C# for now. All external communication is done by polling which makes for lots of annoying loops.

I've slapped together a loose Producer Consumer model where the Producer thread loops through reading the sensors and sets the outputs. The Consumer thread executes functions containing timed loops that poll the Producer for current data and execute movement commands as required. The UI thread polls both threads for updating some gauges indicating current test progress.

Unsure where to start

Is there a more appropriate pattern for this type of application?

Are there any good resources for writing control loops in software (non-LabVIEW) that interface with external sensors and whatnot?

答:
You have got the hardware that you have got.  However...  Windows OS wasn't designed for precision timing, as you probably know.  The peripheral controllers (in the data acquisition devices) can usually do timing a lot better than Windows.

Ideally, the peripheral controller would have a functionality where it can receive a list of commands, which it would time and execute.  Essentially, you would have real-time thread running on a dedicated controller.

Distributed control.


答:
My opinion is that Deployment belongs to CI server. A CM tool like chef is to build your infrastructure to the desired state. But deployment is more than that. Suppose you have to deploy a system that includes a front-end web application to multiple load balanced servers, some DB change scripts and a few back-end services to another set of servers. There are dependencies and order involved in the deployment. e.g. DB changes before back-end services to all servers and before front-end web app. There may be actions needed to be taken if there is error at any step. Chef as I understand cannot handle this kind of scenarios whereas any competent CI tool would.

The other issue is often times infrastructure is shared among multiple apps and is patched/updated in a different cadence to the apps and indeed one app should not upgrade the infrastructure as it doesn't own it. This is another reason to keep CI and CM separate.

Title: Is Chef an appropriate tool to use for application deployment?

Body:
We use Chef for both config management (making sure a "DB Node" has the right version of the right DB on it; that an "App Server" has the right version of Java and env vars on it, etc.). as well as deployment (chef-client --once) of our apps to the appropriate app server nodes.

To me, personally, I feel like deployment belongs in the realm of the CI server. Everything besides the app (the container, the OS, system tools, system config, etc.) belongs to config management, and is therefore best managed by tools like Chef, Puppet, etc.

Currently, our CI builds produce an artifact (an executable JAR with an embedded Tomcat container), and then executes the Chef-Client on all the nodes where the JAR needs to be deployed. The Chef-Client is configured to pull the JAR from the CI server. This feels hacky to me, and I'm trying to research a better, more cogent solution.

So I ask:

Does deployment belong to the CI server, or to the CM tool? Why?

If it belongs to the CI server, what mechanisms (SSH, SCP, etc.) should the CI server be using to actually perform the deploy? We use Bamboo but could just as easily be talking about Jenkins, Hudson, etc.

There is a difference between deploying (placing the app on the node) and running. Does running belong to the CI server as well, the CM tool, or some other process? In other words, what should actually stop the "old" version of the app, replace it with the "new" version, and then start the new version? Is this a candidate for something like Run Deck?


问:
Avoiding polling with components
Once you create separate components that need to communicate with each other you enter the realm of systems programming where you have to assume that errors could originate at any step in the process.  You throw try-catch blocks out the window and have to develop robust alternatives for error handling yourself.

We have two systems both with REST apis.  Both systems have GUIs that users can use to add/update information.  When information is added to one system it must be propagated to the other.  We have integration software (the middleman) that polls on a minute-by-minute basis, picks up adds/edits and translates them from one system to the other.  Each invokation keeps track of the timestamp of the last successful run--we have one timestamp for communication in either direction.  In this way, if any part of the system fails, we can resume right where we left off when the issues are corrected.

I have heard bad things about poll-based approaches: namely the fact that it runs without regard to whether there is actually work.  I have heard that push-based approaches are more efficient because they are triggered on demand.

I am trying to understand how a push-based approach might have worked.  If either system attempts to push an add/edit, we have to assume that it could fail because the other system is down.  It would seem to me that either system would need to maintain its own outgoing queue in order to resume once the issue with the other system is corrected.

It seems to me that using a push approach eliminates the middleman, but heaps more responsibility on each system to manage its messages to the other system.  This seems to not be a clean way of separating concerns.  Now both systems have to take on middleman responsibilities.

I don't see how you would redesign the middleman for a push-based architecture.  You run the risk that messages are lost if the middleman himself fails.

Is there a fault-tolerant architecture that could be used to manage system interactions without the polling?  I'm trying to understand if we missed a better alternative when we devised/implemented our poll-based middleman.  The software does the job, but there's some latency.

答:
From your question and the comments to other answers already given, I feel like you're working on two things: 1) eliminating the middleman, 2) converting your poll-mechanism to a push-mechanism. I'd say, those can be viewed separately. Let's start with the poll-to-push change.

In general, I'd say yes, pushing is superior to polling. If I understand your infrastructure correctly, you have a middleman that polls in both directions looking for stuff to sync between the systems involved. I'd imagine there's already some kind of queuing in place. If your middleman polled some events from A and B is down, it'll keep those events until B is up again an re-transmits. Not sure if I got this right but assuming so, switching to push-mechanisms would be pretty simple and the benefit clear: Instead of the middleman fetching information (which may or may not be there), A (and B, of course) could just push their events into the middleman. It'll use its existing queues and either pushes to B immediately or whenever it sees fit. Now, if this is better for your situation depends on a lot of things, mainly the amount of events expected and the maximum delay allowed between syncs. Currently, any number of events will be synced with a delay of max. 1 minute. With pushing, the delay may decrease heavily but on the other hand, the load may increase if lots of events (that previously have been handled in a bunch) now result in many singular pushes. All of this can and must be handled by the middleman.

If you now try to eliminate the middleman, all that queuing must reside within the systems A and B. Whether that's feasible depends highly on what A and B currently do. It may be overstepping their responsibilities. Also, the currently very constant overhead of syncing might vary as described before. The middleman may be even good for load-reduction. Its mechanisms to forward incoming events could be set up to transmit them in batches. What you then gain is: Systems A and B that can have events, push them out and immediately forget about them. That nice and simple for them. The middleman could then, depending on various settings like maximum delay, maximum number of events, etc., sync those events into the respective other system.

I'm sure you see what I'm getting at and it may very well not be what you're looking for. But maybe it helps if you think about it this way. Let me know if I can clarify things.

Title: Avoiding polling with components


问:
How do you guys feel about organization specific frameworks?
I know that there should be a kind of standard for developing software but in the organization where I work for (30,000+ employees), we have a very strict framework for Java development.

In my opinion such a framework is prehistoric as we are therefor running at least 10 years behind (Standard is Java 1.5 but with support 'til java 1.2).

Further the framework slows down performance, user satisfaction drops and I'm writing more boilerplate code than is good for my health :-).

Any suggestions on the advantages of such a framework? What are good practices for such a framework for not running behind the facts?

答:
I've seen both, organizations with specific frameworks and others without.

Having a framework and strictly sticking to it means that every programmer can, at least in theory, work on any part of any project. This is a big advantage for a large organisation. There are, obviously, at least two downsides: a) at some point in time, it becomes out-dated, but you have to stick to it for all those millions of LOC that use it; b) you use it for every project, whether or not it is a good fit; so it's a golden hammer (see antipatterns)

On the other hand, organisations without a framework tend to use new tools for every project, thus having a fragmented codebase that becomes hard to maintain. "Oh, the 2003 project needs an update, where is the VB6 programmer? Sh*t, he left in 2007!"

It's no surprise that some organisations manage to implement the worst of both worlds: an outdated in-house framework for some projects, several other tools for the other projects.


问:
What is the Controller in Django MVC?
Learning Django MVC and the way I thought of it is:

Models  are the database tables represented in Django as Python classes.

Views are the HTML returned from function in views.py.

Controllers are the actual functions themselves in views.py invoked from a HTTP request.

However I read on Wikipedia (at the time of writing):

... a regular-expression-based URL dispatcher ("Controller").

I would have thought the mapping of URLs to functions as routing - not the controller. But perhaps I am wrong - I guess I got my ideas because is ASP MVC the functions that handle the requests are contained in classes called Contollers...

答:
Your thoughts are not wrong. In MVC web-frameworks, people often speak of a Base Controller that performs the routing of a request to the actual Controller that handles the request.

This has come about because web frameworks generally have a single point where the request is received by the application and in pure MVC terms, this is where the job of the Controller starts.

The Django framework uses a non-idiomatic way of naming the parts of the MVC triad.

The mapping between Django names and the idiomatic terminology is:

```<code>Idiomatic term | Django term | Meaning
Model          | Model       | Contains all the business logic. At the very least the database access logic
View           | Template    | Responsible for generating the HTML and other UI
Controller     | View        | Contains the logic to tie the other parts together and to generate a response to a user request
</code>```

Title: What is the Controller in Django MVC?

Body:
Your thoughts are not wrong. In MVC web-frameworks, people often speak of a Base Controller that performs the routing of a request to the actual Controller that handles the request.

This has come about because web frameworks generally have a single point where the request is received by the application and in pure MVC terms, this is where the job of the Controller starts.

The Django framework uses a non-idiomatic way of naming the parts of the MVC triad.

The mapping between Django names and the idiomatic terminology is:

Idiomatic term | Django term | Meaning
Model          | Model       | Contains all the business logic. At the very least the database access logic
View           | Template    | Responsible for generating the HTML and other UI
Controller     | View        | Contains the logic to tie the other parts together and to generate a response to a user request


问:
Why does C# allow properties in interfaces?
In C#, the following code is valid

```<code>interface I{
    int property{get;set;}
}
</code>```

Which doesn't make any sense to me. This seems to break one of the most important principles of interfaces: lack of state (in other words, no fields). Doesn't the property create an implicit private field? Wouldn't that be really bad for interfaces?

答:
I think the confusing part is that if you write int Property { get; set; } inside a class, then it's an auto-property with implicit backing field.

But if you write exactly the same thing in an interface, then it's not auto-property, it just declares that the property is part of the interface and that any type that implements the interface has to contain that property (as auto-property or not), but it doesn't create the backing field.

One way to see the difference is to write int Property { get; }: this is valid in an interface and declares a property that has only a getter, but no setter. But it won't compile in a class (unless you're using C# 6.0), because auto-property has to have a setter.


问:
What's in the "contrib" folder?
Often open-source software projects have a folder called "contrib". For example, Django has one. What is it for?</p>

答:
Looking at popular open source projects which come in mind, I see no mention of any “contrib” folder:

jQuery,

Express,

Sass,

LESS,

MongoDB,

Redis,

Puppet,

Chef

NUnit,

Ruby on Rails,

Laravel,

Jenkins,

Clojure,

Ruby.

The only one which has a “contrib” folder is Django. For Django, the role of this folder is already explained in the documentation:

Django aims to follow Python’s “batteries included” philosophy. It ships with a variety of extra, optional tools that solve common Web-development problems.

This code lives in django/contrib in the Django distribution. This document gives a rundown of the packages in contrib, along with any dependencies those packages have.

Chapter 16 of The Django Book contains a more detailed description of the role of this directory and the list of contents.

Another example is Solr. With gitstats, we can get the statistics about the contributors.

```<code>Robert Muir         22.09%
Michael McCandless  13.60%
Mark Robert Miller   9.73%
Uwe Schindler        8.17%
Yonik Seeley         5.56%
Steven Rowe          5.55%
</code>```

Then, we can select only the contrib directory by running:

```<code>git filter-branch --subdirectory-filter solr/contrib --prune-empty
</code>```

and get the statistics one more time:

```<code>Robert Muir         19.62%
Steven Rowe          8.87%
Mark Robert Miller   8.33%
Uwe Schindler        8.06%
James Dyer           7.80%
</code>```

So the top authors are practically the same, which means that those are not contributions from the outsiders. Looking at the directories inside contrib folder, it seems that once again, those are “a variety of extra, optional tools”, exactly as in Django. For instance, you don't need the Data Import Request Handler to make Solr work, but if you want to import data from database or XML, it's nice to have it in contrib folder. Same for map-reduce, you may not necessarily need it, but there are cases where you do.

Are those plugins or add-ons? I wouldn't use this term. Plugins and add-ons have a specific integration with the main application. For instance, a plugin is not expected to run standalone, but hosted within the main application. On the other hand, contrib contains tools which can probably run standalone.

Title: What's in the "contrib" folder?

Body:
Looking at popular open source projects which come in mind, I see no mention of any “contrib” folder:

jQuery,

Express,

Sass,

LESS,

MongoDB,

Redis,

Puppet,

Chef

NUnit,

Ruby on Rails,

Laravel,

Jenkins,

Clojure,

Ruby.

The only one which has a “contrib” folder is Django. For Django, the role of this folder is already explained in the documentation:

Django aims to follow Python’s “batteries included” philosophy. It ships with a variety of extra, optional tools that solve common Web-development problems.

This code lives in django/contrib in the Django distribution. This document gives a rundown of the packages in contrib, along with any dependencies those packages have.

Chapter 16 of The Django Book contains a more detailed description of the role of this directory and the list of contents.

Another example is Solr. With gitstats, we can get the statistics about the contributors.

Robert Muir         22.09%
Michael McCandless  13.60%
Mark Robert Miller   9.73%
Uwe Schindler        8.17%
Yonik Seeley         5.56%
Steven Rowe          5.55%

Then, we can select only the contrib directory by running:

git filter-branch --subdirectory-filter solr/contrib --prune-empty

and get the statistics one more time:

Robert Muir         19.62%
Steven Rowe          8.87%
Mark Robert Miller   8.33%
Uwe Schindler        8.06%
James Dyer           7.80%

So the top authors are practically the same, which means that those are not contributions from the outsiders. Looking at the directories inside contrib folder, it seems that once again, those are “a variety of extra, optional tools”, exactly as in Django. For instance, you don't need the Data Import Request Handler to make Solr work, but if you want to import data from database or XML, it's nice to have it in contrib folder. Same for map-reduce, you may not necessarily need it, but there are cases where you do.

Are those plugins or add-ons? I wouldn't use this term. Plugins and add-ons have a specific integration with the main application. For instance, a plugin is not expected to run standalone, but hosted within the main application. On the other hand, contrib contains tools which can probably run standalone.


问:
What's the difference between an API and an SDK?
I was looking through various APIs and SDKs, when I realized that I couldn't really tell the difference between something called an API and something called an SDK.

Both of them are, conceptually, a way for your program to interface with and control the resources provided by another piece of software, whether that other software is a web service, an end-user app, an OS service or daemon, or a kernel device driver.

So, what is the semantic difference between an SDK and an API?

答:
As applications are developed and enhanced by interfacing them with other applications there is a need
to allow other applications (logic) to interface with the core logic - this is done via a defined set of APIs.
SDK is used to create / craft code that uses APIs to interact with other applications.</p>


问:
How deep is enough to represent an algorithm in UML sequence diagram?
I have three simple classes. LoginController, UsersCatalog and User. UsersCatalog has an array of User. I have to represent a simple process of login.

LoginController has a method login(username, password) that simply  calls a method authenticate(username, password) with the same parameters.

Now, it's obvious that the method authenticate seeks for a matching User object and returns it. The question is: Is it necesary to represent the seek algorithm? Isn't representing the seek algorithm too much low level?

In the other side, the access to User class is inside the seek algorithm, so if i don't represent it, then i don't represent the access to the User class.

This is part of a wider question. There are any criteria for how deep is enough to represent an algorithm in UML squence diagram?

答:
There are 2 things to consider, in general:

The intended audience of your UML documentation

How critical the algorithm is to the success of the project

Are you creating these diagrams as part of a design review for non-technical (or rather, non-software) customers? If yes, then do not bother including the algorithm. Its too low level, and you will lose the audience.

Will the diagrams be used as overall reference for maintenance programmers? Assuming there is nothing special, new, or technically innovative about this seek algorithm, then don't bother. Comments could be enough.

Alternatively, for some reason, it could be vital that the software perform this seek efficiently. Or reliably. Or the algorithm itself is special, new or technically innovative. In that case, document it in whatever form is appropriate - pseudo-code, UML sequence diagrams, etc. If it is important to the success of the project, then the diagram is likely to be referenced in the future.


问:
Where is Smalltalk-80 best used?
I want to know in which applications/programming domain are most suitable for Smalltalk. Could anyone please provide me some useful links that could answer my query?

Through googling I learned that some companies use it for:

logistics and foreign trade application
desktop, server and script development
data processing and logistics, scripts and presentations
but I cant find documents/research papers that can tell me which programming domain Smalltalk-80 (or Smalltalk) is best suited.

Some of the programming domains are: - Artificial intelligence reasoning - General purpose applications - Financial time series analysis - Natural language processing - Relational database querying - Application scripting - Internet - Symbolic mathematics - Numerical mathematics - Statistical applications - Text processing - Matrix algorithms

I hope you guys can help me. I am doing this for my case study. Thanks in advance.

答: Asking the question "where is (programming language X) best used?" is equivalent to asking "which road is (car brand X) best driven on?".  The question cannot be answered.  I've used (and continue to use) Smalltalk for a wide variety of problems.  From your list, I've used Smalltalk for artificial intelligence, general purpose applications, relational database querying, text processing, matrix algorithms, and other uses (although once one has said "general purpose applications" one has probably covered just about everything).  I strongly suspect that Smalltalk (and just about any language out there) has been used for all the categories you mentioned.  Having said that, what has been "proved"?  Nothing, IMHO.  Smalltalk is a Turing-complete language and can thus be used for nearly any purpose.  Same-same for Autocoder, PL/I, COBOL, Java, C, C#, C++, FORTRAN, BASIC, Visual Basic, assembler for any particular processor, Ruby, Forth, Python, PERL, SPL, APL, Pascal, Delphi, B, BCPL, ALGOL, PL/SQL, etc, etc, etc.  And you can probably find someone out there who will argue that each of the above is The Best Language for any particular purpose.  YMMV.

OwnerDisplayName: njay

Title: Where is Smalltalk-80 best used?


问:
Pattern to safely establish a one to one bidirectional relationship
Let suppose we have 2 classes, Pilot and Plane, being in an optional one-to-one relationship. So a Plane might have a pilot when it's flying, but when it's standing in its hangar, it has none. Similar for the Pilot.

It would be just logical to hold a pointer to the Plane in the Pilot and a pointer to the Pilot in the Plane, accessible via getters and setters.

Constructing the setters so that a call on any of them establishes the bidirectional relationship is surprisingly hard. I was even more surprised that I couldn't find a suitable solution on the web as this construct seems to be common to me.

Does anyone know of concepts that would encapsulate such a relationship inside a class? Or an idiom to stick with normal getters/setters and still establish the relationship with one setPilot/setPlane call?

答:
Let's assume that this will always be 1-1 (e.g., you wont get 2 pilots from a plane to represent pilot and co-pilot). Instead of trying to build this relationship into the Plane or Pilot classes, use a third class that provides the mapping. For lack of a better name, let's call it PilotPlaneMap here. This class could have the following public functions:

```<code>class PilotPlaneMap
{
public void RelatePilotAndPlane(Pilot pilot, Plane plane){..} //make the relationship here
public Pilot GetPilot(Plane plane){..} //retrieve the pilot related to given plane
public Plane GetPlane(Pilot pilot){..} //retrieve the plane related to given pilot

}
</code>```

Not sure what language you are using, but internally you would make use of some hashmap to store the relationships. Two dictionaries could be used. One that maps Pilot->Plane, and the other maps Plane->Pilot. These are both set when calling RelatePilotAndPlane(). That's just one option.

Body:
Let's assume that this will always be 1-1 (e.g., you wont get 2 pilots from a plane to represent pilot and co-pilot). Instead of trying to build this relationship into the Plane or Pilot classes, use a third class that provides the mapping. For lack of a better name, let's call it PilotPlaneMap here. This class could have the following public functions:

class PilotPlaneMap
{
public void RelatePilotAndPlane(Pilot pilot, Plane plane){..} //make the relationship here
public Pilot GetPilot(Plane plane){..} //retrieve the pilot related to given plane
public Plane GetPlane(Pilot pilot){..} //retrieve the plane related to given pilot

}

Not sure what language you are using, but internally you would make use of some hashmap to store the relationships. Two dictionaries could be used. One that maps Pilot->Plane, and the other maps Plane->Pilot. These are both set when calling RelatePilotAndPlane(). That's just one option.


问:
Is my 'variable-storing area' basically a 'heap'?
I'm planning to implement a simple VM/interpreter kind of thing for a simple language I'm making. The compiler of the language emits mostly stack-oriented instructions to be executed by the VM.

The structure of the program will be something like this:

The execution part (for lack of a better term): interprets the
opcodes and executes them.

The call stack: to keep track of function calling, and for parameter
passing and return values.

The data stack: for none function-calling-related computation, such as
arithmetic.

The variable-storing area, where variable names are matched with values.

The "variable-storing area" will be implemented basically with a HashTable/dictionary thing. When the programmer creates a variable (assuming for now only numeric variables), a new entry is added to the table. When he/she assigns a value to a variable, the entry with the matching name in the table is assigned this value. When the programmer accesses a variable, again we fetch the value from the table.

I'm pretty sure that's the only data-storing part I need in the application, aside from the data stack and the call stack. I don't see why I'd need anything else.

Now, I looked at what a 'heap' is in Wikipedia and other sources online. I found mostly technical terms that I'm having trouble understanding.

But in simpler non-very-technical terms, if I understand correctly, the heap is where the 'constant' data is saved, things that aren't local computation such as arithmetic.

So if my understanding is correct, is my 'variable-storing area' basically a 'heap'? Why or why not? If my understanding of what a heap is is wrong please explain it.

答:
The term heap is tied to dynamic memory allocation. If your programs dynamically create "variables", your "variable storing area" might be considered a heap. But what one usually calls variables is far from dynamic:

```<code>for (int i = 0; i < N; ++i) {
  int var = i * i;
}
</code>```

Here at most three variables exist at any point in time. You'd have to write additional code to create more variables. The lifetime of all variables is very much statically determined. And so on.

The heap is not "all data, except constants". A common (simplified, of course) model of real computers is: You have registers and the stack (which house not only temporary values but also variables), memory that is statically allocated (i.e. exactly once for the entire time the program is running), and the heap for everything that doesn't fit in those categories. Usually variables and their values are not part of the heap at all, at most the variable values are references/pointers to data that's stored on the heap.

In this context, the stack is called stack because allocations are FIFO: When variables a, b, c were created in that order, c must be removed first before b and then a can be destroyed. But it's still random access memory, so accessing a variable looks like this in pseudo-C: stackpointer[-10] for the tenth value from the top of the stack.

A bytecode instruction dec a does not mean dynamic creation of variables in the sense used above. Obviously the memory management that makes room for the variable has to happen at run time, this is true even in C. But can a program perform a loop that creates a variable number of "variables"? If not, the set of variables is set in stone at the time the program is written and there is nothing dynamic about it.

Body:
The term heap is tied to dynamic memory allocation. If your programs dynamically create "variables", your "variable storing area" might be considered a heap. But what one usually calls variables is far from dynamic:

for (int i = 0; i < N; ++i) {
  int var = i * i;
}

Here at most three variables exist at any point in time. You'd have to write additional code to create more variables. The lifetime of all variables is very much statically determined. And so on.

The heap is not "all data, except constants". A common (simplified, of course) model of real computers is: You have registers and the stack (which house not only temporary values but also variables), memory that is statically allocated (i.e. exactly once for the entire time the program is running), and the heap for everything that doesn't fit in those categories. Usually variables and their values are not part of the heap at all, at most the variable values are references/pointers to data that's stored on the heap.

In this context, the stack is called stack because allocations are FIFO: When variables a, b, c were created in that order, c must be removed first before b and then a can be destroyed. But it's still random access memory, so accessing a variable looks like this in pseudo-C: stackpointer[-10] for the tenth value from the top of the stack.

A bytecode instruction dec a does not mean dynamic creation of variables in the sense used above. Obviously the memory management that makes room for the variable has to happen at run time, this is true even in C. But can a program perform a loop that creates a variable number of "variables"? If not, the set of variables is set in stone at the time the program is written and there is nothing dynamic about it.


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答: One sure sign that I've seen in my career is when management starts talking about bringing in more bodies to make up time in the schedule.  I've never actually seen more bodies on a project help.</p>


答:
I will preface this by saying I think that the mapping suggestion is better. However, I believe the code below will work:

```<code>public final class Pilot {
    private Plane plane;

    public Plane getPlane() {
        return plane;
    }

    public void setPlane(final Plane newPlane) {
        if (this.plane == newPlane)
            return;

        final Plane oldPlane = this.plane;
        this.plane = newPlane;

        if (oldPlane != null)
            oldPlane.setPilot(null);

        if (newPlane != null)
            newPlane.setPilot(this);

        this.plane = newPlane;
    }
}

public final class Plane {
    private Pilot pilot;

    public Pilot getPilot() {
        return pilot;
    }

    public void setPilot(final Pilot newPilot) {
        if (this.pilot == newPilot)
            return;

        final Pilot oldPilot = this.pilot;
        this.pilot = newPilot;

        if (oldPilot != null)
            oldPilot.setPlane(null);

        if (newPilot != null)
            newPilot.setPlane(this);

        this.pilot = newPilot;
    }
}
</code>```

And some cursory testing:

```<code>    Plane plane1 = new Plane();
    Plane plane2 = new Plane();
    Pilot pilot1 = new Pilot();
    Pilot pilot2 = new Pilot();

    pilot1.setPlane(plane1);
    Assert.assertEquals(plane1, pilot1.getPlane());
    Assert.assertNull(pilot2.getPlane());

    pilot2.setPlane(plane1);
    Assert.assertNull(pilot1.getPlane());
    Assert.assertEquals(plane1, pilot2.getPlane());

    pilot1.setPlane(null);
    pilot2.setPlane(null);
    Assert.assertNull(plane1.getPilot());
    Assert.assertNull(pilot1.getPlane());
    Assert.assertNull(pilot2.getPlane());

    plane1.setPilot(pilot1);
    Assert.assertEquals(plane1, pilot1.getPlane());
    Assert.assertNull(pilot2.getPlane());

    plane1.setPilot(pilot2);
    Assert.assertNull(pilot1.getPlane());
    Assert.assertEquals(plane1, pilot2.getPlane());

    plane1.setPilot(null);
    plane2.setPilot(null);

    plane1.setPilot(pilot1);
    plane2.setPilot(pilot2);
    Assert.assertEquals(plane1, pilot1.getPlane());
    Assert.assertEquals(pilot1, plane1.getPilot());
    Assert.assertEquals(plane2, pilot2.getPlane());
    Assert.assertEquals(pilot2, plane2.getPilot());

    plane1.setPilot(pilot2);
    Assert.assertEquals(plane1, pilot2.getPlane());
    Assert.assertEquals(pilot2, plane1.getPilot());
    Assert.assertNull(pilot1.getPlane());
    Assert.assertNull(plane2.getPilot());
</code>```

Title: Pattern to safely establish a one to one bidirectional relationship

Body:
Let suppose we have 2 classes, Pilot and Plane, being in an optional one-to-one relationship. So a Plane might have a pilot when it's flying, but when it's standing in its hangar, it has none. Similar for the Pilot.

It would be just logical to hold a pointer to the Plane in the Pilot and a pointer to the Pilot in the Plane, accessible via getters and setters.

Constructing the setters so that a call on any of them establishes the bidirectional relationship is surprisingly hard. I was even more surprised that I couldn't find a suitable solution on the web as this construct seems to be common to me.

Does anyone know of concepts that would encapsulate such a relationship inside a class? Or an idiom to stick with normal getters/setters and still establish the relationship with one setPilot/setPlane call?

Body:
I will preface this by saying I think that the mapping suggestion is better. However, I believe the code below will work:

public final class Pilot {
    private Plane plane;

    public Plane getPlane() {
        return plane;
    }

    public void setPlane(final Plane newPlane) {
        if (this.plane == newPlane)
            return;

        final Plane oldPlane = this.plane;
        this.plane = newPlane;

        if (oldPlane != null)
            oldPlane.setPilot(null);

        if (newPlane != null)
            newPlane.setPilot(this);

        this.plane = newPlane;
    }
}

public final class Plane {
    private Pilot pilot;

    public Pilot getPilot() {
        return pilot;
    }

    public void setPilot(final Pilot newPilot) {
        if (this.pilot == newPilot)
            return;

        final Pilot oldPilot = this.pilot;
        this.pilot = newPilot;

        if (oldPilot != null)
            oldPilot.setPlane(null);

        if (newPilot != null)
            newPilot.setPlane(this);

        this.pilot = newPilot;
    }
}

And some cursory testing:

    Plane plane1 = new Plane();
    Plane plane2 = new Plane();
    Pilot pilot1 = new Pilot();
    Pilot pilot2 = new Pilot();

    pilot1.setPlane(plane1);
    Assert.assertEquals(plane1, pilot1.getPlane());
    Assert.assertNull(pilot2.getPlane());

    pilot2.setPlane(plane1);
    Assert.assertNull(pilot1.getPlane());
    Assert.assertEquals(plane1, pilot2.getPlane());

    pilot1.setPlane(null);
    pilot2.setPlane(null);
    Assert.assertNull(plane1.getPilot());
    Assert.assertNull(pilot1.getPlane());
    Assert.assertNull(pilot2.getPlane());

    plane1.setPilot(pilot1);
    Assert.assertEquals(plane1, pilot1.getPlane());
    Assert.assertNull(pilot2.getPlane());

    plane1.setPilot(pilot2);
    Assert.assertNull(pilot1.getPlane());
    Assert.assertEquals(plane1, pilot2.getPlane());

    plane1.setPilot(null);
    plane2.setPilot(null);

    plane1.setPilot(pilot1);
    plane2.setPilot(pilot2);
    Assert.assertEquals(plane1, pilot1.getPlane());
    Assert.assertEquals(pilot1, plane1.getPilot());
    Assert.assertEquals(plane2, pilot2.getPlane());
    Assert.assertEquals(pilot2, plane2.getPilot());

    plane1.setPilot(pilot2);
    Assert.assertEquals(plane1, pilot2.getPlane());
    Assert.assertEquals(pilot2, plane1.getPilot());
    Assert.assertNull(pilot1.getPlane());
    Assert.assertNull(plane2.getPilot());