问:
How to programmatically construct textual query
Here is a query language, more specifically, it's JQL, you can use it in Jira, to search for issues, it's something like SQL, but quite simpler.

My case is that, I need to construct such queries programmatically, in my application.
Something like:

```<code>JQLMachine jqlMachine = new JQLMachine()
jqlMachine.setStatuses("Open", "In Progress")
jqlMachine.setReporter("foouser", "baruser")
jqlMachine.setDateRange(...)
jqlMachine.getQuery() --> String with corresponding JQL query is returned
</code>```

You get my point I hope. I can imagine the code for this, but it's not nice, using my current knowledge how I'd do that.

That's why I'm asking. What you'd advice to use to create such thing. I believe some patterns for creating something like this already exist and there is already best practices, how to do that in good way.

答:
You should look into the concept of Object-relational Mapping.

Unfortunately, I doubt an ORM solution has been developed for JQL. It is possible that you can extend an existing ORM package to support JQL.


问:
Keeping an enum and a table in sync
I'm making a program that will post data to a database, and I've run into a pattern that I'm sure is familiar: A short table of most-likely (very strongly likely) fixed values that serve as an enum. So suppose the following table called Status:

```
  Status
  Id Description
  --------------
   0 Unprocessed
   1 Pending
   2 Processed
   3 Error
```

In my program I need to determine a status Id for another table, or possibly update a record with a new status Id.

I could hardcode the status Id's in an enum and hope no one ever changes the database. Or I could pre-fetch the values based on the description (thus hardcoding that instead).

What would be the correct approach to keep these two, enum and table, synced?

答: I would normally load this data into a static cache (usually in a HashMap or something like that) when the application starts up. It avoids having to recompile just because the enum has been modified in some way.</p>

ContentLicense: CC BY-SA 3.0

Title: Keeping an enum and a table in sync


答:
I would hard-code the enum within your program, as I suspect these different statuses affect your programs logic.  If you have a new status, how is your program supposed to react to this new status?

Because the database is part of your application, I don't think it would make sense to affect one without consulting other, sort of speak.

Title: Keeping an enum and a table in sync

Body:
I'm making a program that will post data to a database, and I've run into a pattern that I'm sure is familiar: A short table of most-likely (very strongly likely) fixed values that serve as an enum. So suppose the following table called Status:

```
  Status
  Id Description
  --------------
   0 Unprocessed
   1 Pending
   2 Processed
   3 Error
```

In my program I need to determine a status Id for another table, or possibly update a record with a new status Id.

I could hardcode the status Id's in an enum and hope no one ever changes the database. Or I could pre-fetch the values based on the description (thus hardcoding that instead).

What would be the correct approach to keep these two, enum and table, synced?


问:
What are the advantages of Maven when it comes to single man, educational projects
I've spend a few hours playing around with Maven + reading some stuff on the apache official site and also a few random googled articles. By this I mean that I really tried to find the answers myself - both by reading and by doing things on my own. Also maybe worth to mention that I installed the m2e plugin so most of the time I've tried things out from Eclipse and not using the command line too much.

However aside from the generated project that for example prevent me from using the default package I didn't see that much of a difference with the standard way I've created my projects before try Maven. In fact I've almost decided to skip Maven for now and move on to the other technology I wanted to learn more in-depth - Hibernate, but when I start with opening the official page the first thing I've read was the recommendation to use Hibernate with Maven.

That get me confused and made me taking a step back and trying once more to find what I'm obviously missing right now.

As it's said in the maven.apache.. site, the true strength of Maven is shown when you work on large projects with other people, but I lack the option to see how Maven is really used in this scenario, still i think that there are maybe advantages even when it comes to working with small projects alone, but I really have difficulties to point them out.

So what do you think are the advantages of Maven when it's used for small projects writing from a single person. What are the things that I should be aware of and try to exploit (I mean features offered by Maven) that can come in handy in this situations?

答:
Maven and similar tools automate a whole load of tedious tasks. Eclipse automates some of the same tasks - compiling, packaging, running tests, starting a webapp container (if you're using WTP). So, if you're comparing Eclipse with a build tool to Eclipse without a build tool, the difference will not be so big, at least for a small project.

As Eric points out, one big win is dependency management. If your project has few dependencies outside the JDK, then this you may not perceive how useful this is. Wait until it's grown to having a couple of dozen dependencies, then try removing the build tool and see how much pain you feel!

I should add that although Maven is the most widely-used sophisticated build tool, it isn't the only one, and in my opinion, not the best. Maven is rather inflexible and overcomplicated; its successors, chiefly Gradle and Buildr, are hugely more flexible, and much simpler to use, making easy things easy and difficult things possible. I would strongly encourage you to not use Maven at all, and to either use Gradle, or to try Gradle and Buildr,and use the one you prefer.


问:
Why does XCode convert PNGs to CgBI format?
According to the research done here http://imageoptim.com/tweetbot.html, Xcode's conversion of PNGs to the proprietary Apple CgBI format does not create a noticeable performance improvement. Their claim is that the conversion only reduces PNG loading speed by 1 nanosecond.

If this is true, why does apple bother with the CgBI format at all? Has anyone else benchmarked loading CgBI images vs regular PNG images on iOS devices to see if they perform differently?

答:
This blog post describing the patent that Apple filed for the CgBI format implies that Apple thought there were some technical benefits from the conversion.  Specifically:

If the file has the CgBI header, then CRCs can be ignored

The RGBA pixels are written in a different order (BGRA)

The data is pre-multiplied if there is an alpha channel

The first and last benefit are more likely to be of value, but I'm not a graphics expert.

With the post you displayed in your question, there is a subtle shift of attention in the results comparison.

The list 4 sets of images and their sizes.

Unoptimized (aka PNG) at 49.63MB

Xcode converted to CgBI at 26.46MB

ImageOptim optimization of the PNG images at 16.81MB

ImageAlpha + ImageOptim optimization at 9.37MB

And there are two additional things to note.  First, the second two sets of images are the results of their compression routines.  Second, they note that they ran repeated compressions (optimizations) of the images until they didn't get any additional benefit.  Despite their wanting you to believe otherwise, those sets of numbers are not apples to apples comparisons.

Discussing load speed, they state: Although Xcode optimisation is assumed to improve decoding speed of PNG images, testing on an actual device disproves that.  Xcode-optimized images were significantly slower to display.

And they provide three, not four, sets of results to review.  They do not provide loading times for the unoptimized PNG images, they only provide results for the CgBI and ImageOptim optimized images.  Not so surprisingly, their product's optimizations outperform what Xcode will provide.

They even go so far as to state that Decoding speed appears to be correlated to image file size more than anything else.  Later in the article, they provide another link that confirms their observation regarding file size.  Using a bit of logic we can safely conclude that if they had provided loading times for the unoptimized PNG images, then that would have been the slowest performing set since it was also the largest image set.

So the basis of your question is a bit off - Xcode's conversion to CgBI does provide performance enhancement because of the smaller image file size.  We can tell by the image file sizes alone.  While the ImageOptim folk were able to get to 1/3rd or 1/5th of the original file size with multiple passes, Xcode's conversion got to roughly 1/2th the original file size on a single pass.

So Xcode gives you "out-of-the-box" performance improvements by a factor of two from a single optimization path.

Add-on alternatives like ImageOptim exist to get greater improvements but at a cost of additional rounds of optimization.


问:
Are all View Models supposed to be accessed through the Main View Model in MVVM?
I am currently working on a WP8 application. My current design is to have each view bind against a specific view model directly.

Looking through the samples though, it seems that another way is to have all the view models accessed through the Main View Model and then have all the views to their view models through the MVM.

Is this the correct way to do it (So that it doesn't cause flexibility and other issues in the future)?

答:
Generally, yes, MVVM leads to a 1:1 binding between Views and ViewModels.  It's not a requirement, but seems to be a side-effect of how most people are writing MVVM structured applications.

It is possible to have one or more Views pointing to the same ViewModel.  The VM merely needs to provide the properties that the specific View requires for the VM to be useful.

I would shy away from a hub-spoke pattern using a "main" VM that provides access to the other VMs.  Sounds like more overhead than necessary without adding much benefit.

There's an alternative pattern called MVPVM that's a pretty useful read even if you're going to stick with the MVVM pattern.  MVPVM separates out the business logic from the VM and places it within the Presenter.

What I really liked about the article is it gives the progression of MVC -> MVP in the smalltalk days, then explains how MVP remained relevant for a lot of today's UI's and the natural progression into MVVM from MVP.  The author gives a caveat about not discussing web applications, only desktop applications, but I think the article is broad enough to where you can glean the relevant details regardless of your target application.


问:
Developing an iOS app for a single device - licensing issue
I'm developing an iOS app for a museum as a freelancer. It's a very simple video player, to be installed on a single iPad that will be part of a permanent exhibition, basically acting as a kiosk. It turns out the iPad is the ideal device for that if you're looking for a small and affordable touchscreen.

The problem is: as far as I can tell, none of the Apple Developer Program options available will allow me to distribute an app like that. The relevant options are (from the link above):

iOS Developer Program ($99/year)
Select this program if you would like to distribute apps on the App Store as an individual, sole proprietor, company, organization, government entity or educational institution.

iOS Developer Enterprise Program ($299/year)
Select this program if you would like to develop proprietary apps for internal distribution within your company, organization, government entity or educational institution.

The regular program requires distribution through the App Store. The Enterprise version is for internal distribution within my own organization. Neither is the case here! It seems like I'm doomed to violate Apple's terms of service (and I can think of at least two ways of doing that: jailbreaking, or changing the iPad's date so it won't know the provisioning profile expired).

Is that really so, or did I get the descriptions wrong? Has anyone here been in a similar situation?

答:
You can't deploy to hardware without a dev program subscription.

The proper way would be for the museum to buy the iOS dev program and for them to add you as a member to it. Add the iPad as one of your test devices and you can just have xcode build directly to it.

The enterprise program is for entities that need to run an internal app store which you don't here.


问:
Developing workflow for existing silverlight and WCF application
I have an already existing application in Silverlight 4.0 with WCF services. Now what I want is a workflow to be integrated along with the above application. The workflow will be a simple approval workflow i.e sequential workflow. Can any one suggest some links or a solution?</p>

答:
A workflow is simply applying a state to your application's data.

And the type of workflow you described (simple, sequential) is a really good fit with the async model that WCF requires.

When a user submits a request for a resource, they have to wait until their supervisor (and so on up the chain) approves the request.  In the meantime, the user is free to go about other work or simply wait for the resource request to be approved.  Polling or notification mechanisms of some sort are required for the user and the approvers.  The user needs notification for when the resource is available, and the approvers need notification that they have work (grant | deny approval) to do.

One possibility for those mechanisms is to add a polling routine to your View-Models.  Another option would be to look at push type notifications.  However, there's nothing within Silverlight or WCF that makes creating a workflow inherently more difficult than with any other framework.


问:
Can someone provide a short code example of compiler bootstrapping?
This Turing award lecture by Ken Thompson on topic "Reflections on Trusting Trust" gives good insight about how C compiler was made in C itself.

Though I understand the crux, it still hasn't sunk in. So ultimately, once the compiler is written to do lexical analysis, parse trees, syntax analysis, byte code generation etc, a separate machine code is again written to do all that on compiler?

Can anyone please explain with a small example of the procedure? Bootstrapping on wiki gives good insights, but only a rough view on it.

PS: I am aware of the duplicates on the site, but found them to be an overview which I am already aware

答:
Unlike some other answers that suggest writing the compiler in some other language (presumable one that runs on the same machine you are targeting), it is also possible (actually preferable) to write the compiler in the target language from the beginning.

Say you want to write a compiler for C for an ARM processor.  You already have a C compiler that runs on Windows (Intel architecture).  You write your new compiler in C, both the front end (lexical analysis and parsing), and back end (code generation).  The back end of course is written to generate code for the ARM, not Intel.

You then compile the source for the new compiler with the existing compiler.  Once you are satisfied the compiler is generating valid code for the ARM, you take the compiled ARM code and run it on the target ARM architecture.  You now have the source for the new compiler, that can be modified and fed into it's executable and generate a new version.

This is process is called cross-compiling.  The advantage is that you only have to write the compiler once.


答:
I would recommend Builder/Method chaining like Guava uses for it's HashCode and HashFunction classes.
Hashing Explained

```<code>HashCode hc = hf.newHasher()
   .putLong(id)
   .putString(name)
   .putObject(person, personFunnel)
   .hash();
</code>```

Title: How to programmatically construct textual query

Body:
Here is a query language, more specifically, it's JQL, you can use it in Jira, to search for issues, it's something like SQL, but quite simpler.

My case is that, I need to construct such queries programmatically, in my application.
Something like:

```<code>JQLMachine jqlMachine = new JQLMachine()
jqlMachine.setStatuses("Open", "In Progress")
jqlMachine.setReporter("foouser", "baruser")
jqlMachine.setDateRange(...)
jqlMachine.getQuery() --> String with corresponding JQL query is returned
</code>```

You get my point I hope. I can imagine the code for this, but it's not nice, using my current knowledge how I'd do that.

That's why I'm asking. What you'd advice to use to create such thing. I believe some patterns for creating something like this already exist and there is already best practices, how to do that in good way.

Body:
I would recommend Builder/Method chaining like Guava uses for it's HashCode and HashFunction classes.
Hashing Explained

HashCode hc = hf.newHasher()
   .putLong(id)
   .putString(name)
   .putObject(person, personFunnel)
   .hash();


问:
How to enter flow experience for SW development?
What are your strategies to improve the flow experience when doing work?</p>

答:
I need a clear understanding of what I'm trying to accomplish.  It's hard to achieve flow when I'm testing something because I'm searching around, trying to find stuff and figure out what to do next.

I need sensory isolation. By this I mean no distractions in any of my senses.  If people are wandering through my field of view, or people are making noise around me, forget it (touch, taste and smell usually aren't too much of an issue in an office).  A good set of noise-isolating earbuds and either some white noise (waves crashing on the beach, or a campfire burning and popping) or some music works for me.  Any music needs to be devoid of lyrics; otherwise, my mind will be parsing the words, unconsciously, which will disrupt the flow.  Ditto for people in my vicinity carrying on conversations; I try to "tune them out," but my mind will, unconsciously, lock on to the speakers and the conversation and distract.

Finally, I need an editor which doesn't force me to "pause."  I can code for hours using vim; I use the control-n and control-p to auto-complete stuff, but that's really quick and I can usually get to where I can predict how many of those I will need to get the variable name or method name I'm seeking.  Using Eclipse is largely devoid of flow because it is always pausing the input while it reformats stuff, checks to see if my syntax is valid, etc.  The auto-completion for object-oriented stuff is too slow and unpredictable to achieve a state of flow.

In case you haven't guessed, flow involves a rhythm.  Anything which disrupts that rhythm, disrupts the flow.

Turn off the email notifiers.  Turn off the social networking notifiers.  Turn off the alarms.  Make sure you have a nice, long, uninterrupted block of time in which you can work.

Finally, copious amounts of caffeine seems to help.

Some of the most productive coding I've ever done involved writing HTML, CSS, Javascript and Perl, using vim, with Eric Johnson, Blues Saraceno and Joe Satriani blaring in my earbuds, amped up on Mountain Dew.

Some of my least productive time involves sitting in a cubicle farm, trying to write Java, using Eclipse, when I forgot my smartphone and earbuds at home and the guy across the cubicle wall feels the need to use his speakerphone on a conference call.

ContentLicense: CC BY-SA 2.5


问:
Did a bunch of wrong work, should I keep it?
I have forked a repo and branched that clone to code a story, and because I didn't understand the problem, wrote code that isn't solving my task at hand, but may prove useful later.

Should I:

Delete it, and don't worry about it. Then commit without the extra code.

Make yet another branch for just that work, commit it, but don't post a pull request on it.

Just commit it with the existing code, and worry about the extra "fluff" later.

I was thinking #2. If I understand correctly, I could just keep the extra code on a branch I never use on my clone, and dig it up later if something comes up that may benefit from using it.

答:
Option #2 is legitimate if the code really could be useful later on. #3 is not the right answer.

Option #1 is probably the right answer. More often than not, the code should just be scrapped. As programmers, we don't like to delete code--if feels like throwing out our babies. One of the biggest rules of programming is "do not be afraid to delete code" (I think Jeff Atwood had a post to this effect, but I don't have the link handy). Unused code that gets squirreled away seldom finds its way into a working project. It just sort of molders there until someone finally deletes it (even in another branch) because it's been laying around forever and no one knows why it's there.


答:
You should have included option number 4....

```<code>4.  Commit it with the extra code, and then delete it and commit it again.
</code>```

If you don't commit it, it is lost.  If you commit it and leave it in, then you have an extra source of confusion -- you should try to avoid having other people scratching their heads and wondering WTF is going on here...

Commit it, delete it, commit it again -- add a couple of good commit comments and you're golden.

Title: Did a bunch of wrong work, should I keep it?

Body:
I have forked a repo and branched that clone to code a story, and because I didn't understand the problem, wrote code that isn't solving my task at hand, but may prove useful later.

Should I:

Delete it, and don't worry about it. Then commit without the extra code.

Make yet another branch for just that work, commit it, but don't post a pull request on it.

Just commit it with the existing code, and worry about the extra "fluff" later.

I was thinking #2. If I understand correctly, I could just keep the extra code on a branch I never use on my clone, and dig it up later if something comes up that may benefit from using it.

Body:
You should have included option number 4....

4.  Commit it with the extra code, and then delete it and commit it again.

If you don't commit it, it is lost.  If you commit it and leave it in, then you have an extra source of confusion -- you should try to avoid having other people scratching their heads and wondering WTF is going on here...

Commit it, delete it, commit it again -- add a couple of good commit comments and you're golden.


答:
You need to make an assessment of whether it is likely that the code will be used in the future:

If it is (realistically) unlikely, then just get rid of it; i.e. #1

If it is likely #3 followed by some refactoring to make sure that the "fluff" code doesn't impact on your actual builds, test coverage, etc.

My reason for preferring #3 over #2 (or #4) is that code on old development branches or in the revision history is hard to find ... unless you know to look for it.  When I look at a codebase to see if some bit of functionality is there to be reused, I look at HEAD:master.  I don't trawl through the old branches, or through the commit logs.

Now in your case, there is a reasonable chance that you will remember that you implemented the functionality and then removed it from "master".  But your co-workers are unlikely to know this, and even if you mention it to them they likely to forget it.  However, if the code is still in HEAD:master, then there is a much better chance that they will find using IDE search.


问:
Code review process when using GIT as a repository?
What is the best process for code review when using GIT? We have an external GIT provider (Unfuddle) and have caps on resource usage - so we can't have dedicated remote repositories for every dev.

Current process:

We have a GIT server with a master branch to which everyone commits

Devs work off the local master mirror or a local feature branch

Devs push to server's master branch

Devs request code review on last commit

Problem:

Any bug in code review are already in master by the time it's caught.

Worse, usually someone has burnt a few hours trying to figure out what happened...

So, we would like

To do code review BEFORE delivery into the 'master'.

Have a process that works with a global team (no over the shoulder reviews!)

something that doesn't require an individual dev to be at his desk/machine to be powered up so someone else can remote in (remove human dependency, devs go home at different timezones)

We use TortoiseGIT for a visual representation of a list of files changed, diff'ing files etc. Some of us drop into a GIT shell when the GUI isn't enough, but ideally we'd like the workflow to be simple and GUI based (I want the tool to lift any burden, not my devs).

答: A simple but effective model is the GitHub pull request model, where contributors file "please merge in my code" requests.  A maintainer reviews the changesets and decides if they need more work or if they are suitable for merging.  He then may merge into the master branch.  Committers are generally not allowed to push directly to the master branch (this can be customized to your tastes, we allow "minor" commits to go directly in).</p>


问:
How to check if 4 points form a square?
Assume I have 4 points (they are 2-dimension), which are different from each other, and I want to know whether they form a square. How to do it? (let the process be as simple as possible.)</p>

答:
Similar to the answer by starblue

Pick any three of the four points.

Look for a right angled vertex among them: By checking if the dot product of any two of the three vectors is zero. If not found, not a square.

Check whether the vertices adjacent to this angle are right angled too. If not, not a square.

Check whether diagonals are perpendicular: If the dot product of the vectors between the first and fourth vertex and the other two vertices (diagonals) is zero, then its a square.

Title: How to check if 4 points form a square?


答:
Git is a distributed version control system: don't have only one repo with one branch!

You can set up multiple repositories - one for each developer - and another which is the master repo. When one of their branches is ready to be merged, the developer requests a merge and their changes are pulled from their branch/repo into the master.

Before that merge actually happens, the reviewer can pull the changes into their environment, and review them before pushing them to master.

Added advantages are that this way a developer can have as many branches as they want, named whatever say they want, without interfering with each other or even having to see each other's dirty laundry that much.

Also, learn the lingo: by "Devs commit to server's master branch" do you mean that they push their changes to master?

Title: Code review process when using GIT as a repository?

Body:
What is the best process for code review when using GIT? We have an external GIT provider (Unfuddle) and have caps on resource usage - so we can't have dedicated remote repositories for every dev.

Current process:

We have a GIT server with a master branch to which everyone commits

Devs work off the local master mirror or a local feature branch

Devs push to server's master branch

Devs request code review on last commit

Problem:

Any bug in code review are already in master by the time it's caught.

Worse, usually someone has burnt a few hours trying to figure out what happened...

So, we would like

To do code review BEFORE delivery into the 'master'.

Have a process that works with a global team (no over the shoulder reviews!)

something that doesn't require an individual dev to be at his desk/machine to be powered up so someone else can remote in (remove human dependency, devs go home at different timezones)

We use TortoiseGIT for a visual representation of a list of files changed, diff'ing files etc. Some of us drop into a GIT shell when the GUI isn't enough, but ideally we'd like the workflow to be simple and GUI based (I want the tool to lift any burden, not my devs).


问:
Is it reasonable to require passwords when users sign into my application through social media accounts?
I've built an application that requires users to authenticate with one or more social media accounts from either Facebook, Twitter, or LinkedIn.

Edit
Once the user has signed in, an 'identity' for them is maintained in the system, to which all content they create is associated. A user can associate one account from each of the supported providers with this identity.

I'm concerned about how to protect potential users from connecting the wrong account to their identity in our application.

/Edit

There are two main scenarios that could happen:

User has multiple accounts on one of the three providers, and is not logged into the one s/he desires.

User comes to a public or shared computer, in which the previous user left themselves logged into one of the three providers.

While I haven't encountered many examples of this myself, I'm considering requiring users to password authenticate with Facebook, Twitter, and LinkedIn whenever they are signing into our application.

Is that a reasonable approach, or are there reasons why many other sites and applications don't challenge users to provide a user name and password when authorizing applications to access their social media accounts?

Thanks in advance!

Edit

A clarification, I'm not intending to store anyone's user name and password. Rather, when a user clicks the button to sign in, with Facebook as an example, I'm considering showing an "Is this you?" type window.

The idea is that a user would respond to the challenge by either signing into Facebook on the account fetched from the oauth hash, or would sign into the correct account and the oauth callback would run with the new oauth hash data.

答:
One of the reasons that they don't usually ask for a password is the fact that people don't trust giving passwords out.

Passwords are often reused on sites. Therefore each time someone enters a password for a new site they are potentially giving away their sensitive information.

Another reason that passwords aren't used is you are trusting the site that you have done OAuth with to be your authentication provider.

Unless you are intending to adequately hash and salt the passwords you are actually removing security from the users. Doubly so if your site isn't running over SSL.

Its not impossible its not necesarily a bad thing but it may put people off.

Finaly reason is it removes a lot of the convenience of single sign in.

Comments
Generally its a good idea to time out someones active session. That stops the shared computer thing mostly. However for some reason this usually isn't done with OAuth/ OpenId


答:
Answering the updated question

I would avoid any scheme that requires the user to type their social media password anywhere in your application. It will put many users off even if you put a big explanation next to it that you are not storing this password or using it for anything else than one-time verification. After all, how are they sure they can trust you?

A simple confirmation page should be enough to address your concerns in your first scenario (multiple accounts). Just show it to the user before you start using the social media account as their identity.

The best approach to address your second scenario might be to let the user update their identity. So if they realize they are signed up with someone else's account (they clicked through the confirmation page without looking), they can always go back and update it.

You could also check the OAuth credentials periodically to see if your application still has access to their social media account, and stop using it for identity if not. This will let the third party revoke the access in your second scenario.

Original answer

It seems to me that users can be concerned about your application asking them about the password to their accounts. By now they have been trained to expect the OAuth based authentication for your application.

Title: Is it reasonable to require passwords when users sign into my application through social media accounts?

Body:
I've built an application that requires users to authenticate with one or more social media accounts from either Facebook, Twitter, or LinkedIn.

Edit
Once the user has signed in, an 'identity' for them is maintained in the system, to which all content they create is associated. A user can associate one account from each of the supported providers with this identity.

I'm concerned about how to protect potential users from connecting the wrong account to their identity in our application.

/Edit

There are two main scenarios that could happen:

User has multiple accounts on one of the three providers, and is not logged into the one s/he desires.

User comes to a public or shared computer, in which the previous user left themselves logged into one of the three providers.

While I haven't encountered many examples of this myself, I'm considering requiring users to password authenticate with Facebook, Twitter, and LinkedIn whenever they are signing into our application.

Is that a reasonable approach, or are there reasons why many other sites and applications don't challenge users to provide a user name and password when authorizing applications to access their social media accounts?

Thanks in advance!

Edit

A clarification, I'm not intending to store anyone's user name and password. Rather, when a user clicks the button to sign in, with Facebook as an example, I'm considering showing an "Is this you?" type window.

The idea is that a user would respond to the challenge by either signing into Facebook on the account fetched from the oauth hash, or would sign into the correct account and the oauth callback would run with the new oauth hash data.


答:
It defeats the benefits of open authentication if you still require the user to create a new password. The idea of oAuth is that the user manages their password on another network, and they never disclose that password to the website they are logging into. That improves your sign up rates since they trust their social network, but may not know your website very well.

An alternative approach is to use oAuth to assist in user sign up. Rather then use Facebook to log in. You can use Facebook to populate common fields in the user's profile on your website, and then have them sign in without Facebook later.

The problem you are describing is a common concern with oAuth approaches, but it's an issue between the user and Facebook. Since they are using Facebook to sign in, then it's the user's responsibility to sign out on public terminals. If they fail, it's no different then that user walking away with their bank account open on the web page or other important personal information.


答:
Answering the Edit not the origional question. Yes its perfectly acceptable to show the user some of their own non sensitive information in order to prove:

That your the site you say you are.

That their account is already associated.

Yahoo do something similar where by the user uploads an image which they call a security seal. The idea being that this image proves that it is yahoo that they are communicating with.

Lots of blogs post the image of the currently logged in facebook account and say answering as "Athas" when you try to comment.

On a useability scale though it may just be better to show this in whatever area of the page you associate with the user. i.e. in stackexchange you can see your username at the top.

Otherwise its just an extra hoop for someone to jump through.

Or do it on a time basis.


答:
There are some good answers here, but the question asked for the simplest approach. I gave this some quick thought and this is how I would do it.

You can tell if four points represent a square (even if rotated), but finding the average of the four points.

```<code>R = (A+B+C+D)/4
</code>```

Once you have the average, the distance between each point and the average would have to be the same for all four points.

```<code>if(dist(R,A) == dist(R,B) == dist(R,C) == dist(R,D) then
   print "Is Square"
else
   print "Is Not Square"
</code>```

EDIT:

My mistake. That would only tell you if the form points were on a circle. If you also check the distance between points, then it must be a square.

```<code>if(dist(R,A) == dist(R,B) == dist(R,C) == dist(R,D) AND
  (dist(A,B) == dist(B,C) == dist(C,D) == dist(A,D) then
   print "Is Square"
else
   print "Is Not Square"
</code>```

This assumes that points A,B,C,D do not cross (as in have a valid winding order).

Title: How to check if 4 points form a square?

Body: Assume I have 4 points (they are 2-dimension), which are different from each other, and I want to know whether they form a square. How to do it? (let the process be as simple as possible.)</p>

Body:
There are some good answers here, but the question asked for the simplest approach. I gave this some quick thought and this is how I would do it.

You can tell if four points represent a square (even if rotated), but finding the average of the four points.

R = (A+B+C+D)/4

Once you have the average, the distance between each point and the average would have to be the same for all four points.

if(dist(R,A) == dist(R,B) == dist(R,C) == dist(R,D) then
   print "Is Square"
else
   print "Is Not Square"

EDIT:

My mistake. That would only tell you if the form points were on a circle. If you also check the distance between points, then it must be a square.

if(dist(R,A) == dist(R,B) == dist(R,C) == dist(R,D) AND
  (dist(A,B) == dist(B,C) == dist(C,D) == dist(A,D) then
   print "Is Square"
else
   print "Is Not Square"

This assumes that points A,B,C,D do not cross (as in have a valid winding order).


问:
Would you refactor this and if so, would you charge your client?
I am working on a freelance job at home. The client wants me to write some new functionality for his CMS, but it is taking me a lot of time to figure out what the code is doing, because it is written in a very unreadable style.

Below is just an example of what I mean. The previous programmer made extensive use of anonymous functions, of eval(), he uses deeply nested ternary operators, he didn't indent code, didn't use comments, and he uses funny constructions like misusing the behaviour of logical operators || and && for creating if/else conditions (the second condition of && only gets tested if the first one is true, opening the possibility to use && as an if/else construction). All in all it's insane code and it's costing me a lot of time to find out how the current code works.

```<code>return ($this->main->context != "ajax" || in_array($this->type, $this->definition->ajax)) ? eval('return method_exists($this,"Show'.ucfirst($this->type).'") ? $this->Show'.ucfirst($this->type).'('.(count($args) ? join(",",array_map(create_function('$a','return (is_numeric($a) || preg_match("/^array/",$a)) ? $a : "\"".$a."\"";'),$args)) : "").') : null;') : '';
</code>```

Would you refactor this code and how would you handle this sort of thing with your client, I mean financially?

答:
If it's something easy (in my definition takes less than an hour), then I would just do it to preserve my sanity.

However, anything larger than that needs a bit of thought.

How long will it take you to finish your job (the one you're being paid for) without refactoring? Let's call this A.

How long will it take you to finish your job after refactoring, plus the amount of time of the actual refactoring and testing (to make sure you didn't break anything). Let's call this B.

I would only do it if B is significantly less than A. Otherwise I would ask for compensation from the client.


问:
What build tools do not depend on java (or Ruby)?
I'm wondering what generic build tools out there include their binary run-times and do not depend on another environment not shipped with them.

For example, ANT requires Java, Rake requires Ruby, etc..

would be great if talking about also target-platform-agnostic tools, where I'd just give whatever command for building, whatever command for testing, etc.. and can then define my artifacts in CI or so.

Would see something like that useful for building .NET projects (say, on both Windows .NET and  Mono), and Node JS projects especially. I do not want to install Java and / or Ruby if what I want is a .NET build or a Node JS build.

This is a bit of general awareness question not an exact problem I'm facing, that's why it's here not on StackOverflow.

Update:

To explain a bit more,  what I'm after is the build script that would run MSBuild for compiling for example ( in .NET, and then maybe several Node/NPM commands in Node, etc..), and then have the rest build/test steps, instead of setting these all in MSBuild (again, in .NET case, also, wondering if there is equivalent story in Node).

Update2:

My target is being able to have a developer on a vanilla machine to just clone the code without installing any dependencies except the platform the code targets be it .NET/Mono or Node (not even Java, Ruby, or Python) and still be able to build and run tests.

答:
Well for .NET projects typically one uses Team Foundation Server - Build Server setup on the Windows platform.

I want to make sure I understand your questions correctly, but it would help if you also gave your base O/S your developing in too.


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答: The fact that marketing seems to think that adding a ton of small features is less work than adding a single, but rather heavy, feature.  Which probably is a more specific case of the misconception that "task-switching has no overhead".</p>


问:
Writing a Software Requirement Specification
I have a few questions about writing a specification and they are:

When we write a software specification, under the topic "User requirements definition" we have to specify the "Functions" and "Constraints" only ?

Does "User Interface" fall into "functions" or "constraints" ?

What are the major key areas (requirements) a software can be broken into (e.g. UI ) ?

答:
The main requirement for a requirement is that it is testable.  If you can't figure out how to test a requirement, the odds are that it won't be implemented the way the writer intended.

I've never seen a requirements document limited to Functions and Constraints only, but I can see some value in having a structure like this - it forces the writer to categorize the requirements into "things the software needs to do", and "rules the software needs to follow."

I think a user interface has requirements in both categories

Constraints:

"the startup screen shall display two buttons: "Start", and "Stop"

"The display font shall be no smaller than 10 point."

Functions:

"When the Start key is pressed, the software shall establish a TCP/IP connection to WOPR"


答:
You don't want platform agnostic so much as the native build tool for .NET. To be precise you should look into MSBuild (.NET) and xbuild (mono). They are functionally equivalent and moreover use the same XML-based build files so you can theoretically handle both .NET and mono without any modifications. In fact, rake or ANT have to call out to MSBuild to actually build any .NET stuff so you are already using it -- the most common MSBuild file ends in .csproj.

I will note that having done a pretty massive amount of MSBuild scripting I would really prefer ruby-based build scripts over XML-based build scripts. Turing-complete languages in XML are verbose.

I'm only tangentially familiar with node.js so I could be wrong but my impression is there isn't really a build there -- it is all interperted javascript. Now, you might have a script to call NPM to load your packages.

Another thing you might want to look at is psake -- it is a powershell-based build system based on ruby's sake. I've heard good things about it though I haven't used it in anger as I can make MSBuild do what I need it to do.

Title: What build tools do not depend on java (or Ruby)?

Body:
I'm wondering what generic build tools out there include their binary run-times and do not depend on another environment not shipped with them.

For example, ANT requires Java, Rake requires Ruby, etc..

would be great if talking about also target-platform-agnostic tools, where I'd just give whatever command for building, whatever command for testing, etc.. and can then define my artifacts in CI or so.

Would see something like that useful for building .NET projects (say, on both Windows .NET and  Mono), and Node JS projects especially. I do not want to install Java and / or Ruby if what I want is a .NET build or a Node JS build.

This is a bit of general awareness question not an exact problem I'm facing, that's why it's here not on StackOverflow.

Update:

To explain a bit more,  what I'm after is the build script that would run MSBuild for compiling for example ( in .NET, and then maybe several Node/NPM commands in Node, etc..), and then have the rest build/test steps, instead of setting these all in MSBuild (again, in .NET case, also, wondering if there is equivalent story in Node).

Update2:

My target is being able to have a developer on a vanilla machine to just clone the code without installing any dependencies except the platform the code targets be it .NET/Mono or Node (not even Java, Ruby, or Python) and still be able to build and run tests.


答:
You "own" what you change with respect to liability for fixing defects and undesirable behavior.... maybe you can get out of it sometimes, but the customer will say "You changed it, it's broken, you fix it. Too many of these, and he won't be a happy customer.

If you refactor, and break it, it's yours.

If you refactor, and it was broken before, and is afterwards, it's yours.

If you refactor and fix a "defect", but change the behavior, when the "broken" behavior was being used, it's yours.

Unless you have great unit tests, refactoring will change behavior - and you now own the responsibility for fixing it if it's broken.

Up to you if you are prepared to take on that risk for free. I don't. So you need to discuss this with your client, and ask them how much they are prepared to pay for it. Ensure they understand the risk that you break something, and have an agreement on how that is paid for.

I have purposely not addressed the issue of direct time/costs to refactor, as already commented, most clients will say "What value do I get for paying you that much money", that is the easy part of the discussion.

Title: Would you refactor this and if so, would you charge your client?

Body:
I am working on a freelance job at home. The client wants me to write some new functionality for his CMS, but it is taking me a lot of time to figure out what the code is doing, because it is written in a very unreadable style.

Below is just an example of what I mean. The previous programmer made extensive use of anonymous functions, of eval(), he uses deeply nested ternary operators, he didn't indent code, didn't use comments, and he uses funny constructions like misusing the behaviour of logical operators || and && for creating if/else conditions (the second condition of && only gets tested if the first one is true, opening the possibility to use && as an if/else construction). All in all it's insane code and it's costing me a lot of time to find out how the current code works.

```<code>return ($this->main->context != "ajax" || in_array($this->type, $this->definition->ajax)) ? eval('return method_exists($this,"Show'.ucfirst($this->type).'") ? $this->Show'.ucfirst($this->type).'('.(count($args) ? join(",",array_map(create_function('$a','return (is_numeric($a) || preg_match("/^array/",$a)) ? $a : "\"".$a."\"";'),$args)) : "").') : null;') : '';
</code>```

Would you refactor this code and how would you handle this sort of thing with your client, I mean financially?


问:
Should I leave href empty when implementing click events via jQuery?
Is it preferable to have # in a link's href attribute when I am implementing the click event via jQuery, or is it ok to leave href empty?

i.e.

```<code>id="myLink" href="#" />
</code>```

vs

```<code>id="myLink" href="" />
</code>```

When I'm doing

```<code>$("#myLink").on('click', function() {
   // do ajaxy stuff
});
</code>```

Although I understand the click event could be on a span or other such element I'm interested in this case for particular best practices when using an a tag.

答:
I don't think it'll make a huge difference most of the time. If there's no real link, you might also consider using a span instead of an a tag.

I've seen something like this as well:

```<code><a id="myLink" href="javascript:void(0)" />
</code>```

See this page for examples: http://weblogs.asp.net/joelvarty/archive/2008/09/30/javascript-in-lt-a-gt-tags-vs-javascript-void-0.aspx

Additionally, it would be a good idea to run the html through a validator to check for any potential problems.

Body:
Is it preferable to have # in a link's href attribute when I am implementing the click event via jQuery, or is it ok to leave href empty?

i.e.

```<code><a id="myLink" href="#" />
</code>```

vs

```<code><a id="myLink" href="" />
</code>```

When I'm doing

```<code>$("#myLink").on('click', function() {
   // do ajaxy stuff
});
</code>```

Although I understand the click event could be on a span or other such element I'm interested in this case for particular best practices when using an a tag.

Body:
I don't think it'll make a huge difference most of the time. If there's no real link, you might also consider using a span instead of an a tag.

I've seen something like this as well:

<a id="myLink" href="javascript:void(0)" />

See this page for examples: http://weblogs.asp.net/joelvarty/archive/2008/09/30/javascript-in-lt-a-gt-tags-vs-javascript-void-0.aspx

Additionally, it would be a good idea to run the html through a validator to check for any potential problems.


答:
Links with an empty href attribute are valid, as explained in RFC2396:

4.2. Same-document References

A URI reference that does not contain a URI is a reference to the current document.  In other words, an empty URI reference within a document is interpreted as a reference to the start of that document, and a reference containing only a fragment identifier is a reference to the identified fragment of that document. Traversal of such a reference should not result in an additional retrieval action. However, if the URI reference occurs in a context that is always intended to result in a new request, as in the case of HTML's FORM element, then an empty URI reference represents the base URI of the current document and should be replaced by that URI when transformed into a request.

It's not really an issue significant enough to be anything more than personal preference. Personally, I'd go with a third option:

```<code><a id="myLink" href="<url>" />
</code>```

...where <url> is the url of my ajax request. Obviously that introduces a step in jQuery:

```<code>$("#myLink").click(function(event) {
    event.preventDefault();
   url = $(this).attr("href");

   // do ajaxy stuff
});
</code>```

...but I find it a bit more convenient than hardcoding the url in Javascript, it makes sense semantically (checking your code couple of years after you wrote it, the url will be were you'll first look for it - probably). It's also a neat trick if you have a few simplistic ajax-y links that do more or less the same thing. Consider this example:

```<code><a class="ajax" href="<url1>">
<a class="ajax" href="<url2>">
<a class="ajax" href="<url3>">

$("a.ajax").click(function(event) {
    event.preventDefault();
    var url = $(this).attr("href");

    $.get(url, function(data) {
        console.log(data);
    });
});
</code>```

Title: Should I leave href empty when implementing click events via jQuery?

Body:
Links with an empty href attribute are valid, as explained in RFC2396:

4.2. Same-document References

A URI reference that does not contain a URI is a reference to the current document.  In other words, an empty URI reference within a document is interpreted as a reference to the start of that document, and a reference containing only a fragment identifier is a reference to the identified fragment of that document. Traversal of such a reference should not result in an additional retrieval action. However, if the URI reference occurs in a context that is always intended to result in a new request, as in the case of HTML's FORM element, then an empty URI reference represents the base URI of the current document and should be replaced by that URI when transformed into a request.

It's not really an issue significant enough to be anything more than personal preference. Personally, I'd go with a third option:

<a id="myLink" href="<url>" />

...where <url> is the url of my ajax request. Obviously that introduces a step in jQuery:

$("#myLink").click(function(event) {
    event.preventDefault();
   url = $(this).attr("href");

   // do ajaxy stuff
});

...but I find it a bit more convenient than hardcoding the url in Javascript, it makes sense semantically (checking your code couple of years after you wrote it, the url will be were you'll first look for it - probably). It's also a neat trick if you have a few simplistic ajax-y links that do more or less the same thing. Consider this example:

<a class="ajax" href="<url1>">
<a class="ajax" href="<url2>">
<a class="ajax" href="<url3>">

$("a.ajax").click(function(event) {
    event.preventDefault();
    var url = $(this).attr("href");

    $.get(url, function(data) {
        console.log(data);
    });
});


答:
Refactoring tricksy code is always dangerous.  The risk of missing some assumption that was present in the original is just way too high, and you may well end up doing more harm than good, however well-intentioned you may be at the outset.

If you don't need to do it as part of this job, then don't touch it with a 10-foot pole.  However awful this may sound, once you've delivered the requirement you can walk away when done and the problem is not yours anymore.

On the other hand, if you do need to do it, then maybe it's time to renegotiate terms with the client.  After all, you've been dumped with a lot of crap that wasn't in the original agreement, so it's unrealistic to expect you to deliver within the originally agreed terms given the circumstances (which you couldn't be reasonably expected to have been aware of when you took the job).  The client may also be in a position to get hold of the original developer and at least clarify things a little better than you could figure out on your own, so it's in your own best interest.


答:
I might do some cleanup to maintain my own sanity, but I wouldn't include my cleanup in the final changeset I test and submit to the client. The other responses are right on that point. You don't want to risk breaking something because you did something that wasn't requested.

If you believe that the code in its current form will be difficult to modify and maintain, let the client know as soon as possible. If I take my car to a mechanic to have the oil changed, I don't expect him to pretend not to see that my brake lines are damaged just because it's not what I hired him to fix. I expect him to suggest reasonable repairs and maintenance.

It may be very useful for your client to know the code is bad. They may decide they don't want work with the author again. They may decide it's not worth fixing. Or they might have you fix it. They are paying you for your expertise. Supply it!


答:
Whenever you see an opportunity to NOT require the user to do something, you should take it.  And NOT requiring them to either make up or reuse a password is a win-win situation - you don't make them do work and you don't have to worry about the huge expense of dealing with a breach that leaks passwords.

The whole purpose of letting someone else do the authentication, is that you don't have to deal with all of the baggage that comes with it.


问:
What are the downsides of leaving automation tags in production code?
I've been setting up debug tags for automated testing of a GWT-based web application. This involves turning on custom debug id tags/attributes for elements in the source of the app. It's a non-trivial task, particularly for larger, more complex web applications. Recently there's been some discussion of whether enabling such debug ids is a good idea to do across the board.

Currently the debug ids are only turned on in development and testing servers, not in production. There have been points raised that enabling debug ids does cause performance to take a hit, and that debug ids in production may lead to security issues.

What are benefits of doing this? Are there any significant risks for turning on debug tags in production code?

答:
The performance penalty is not in the observable range. Enabling debug ids in GWT is as simple as turning on a inherits tag in GWT. It only is non trivial for some composed widgets or in case of custom logic for grids or tree.

Build with debug ids and run selenium based automation.

Build without debug ids and run manual sanity tests.


问:
Keeping an enum and a table in sync
I'm making a program that will post data to a database, and I've run into a pattern that I'm sure is familiar: A short table of most-likely (very strongly likely) fixed values that serve as an enum. So suppose the following table called Status:

```
  Status
  Id Description
  --------------
   0 Unprocessed
   1 Pending
   2 Processed
   3 Error
```

In my program I need to determine a status Id for another table, or possibly update a record with a new status Id.

I could hardcode the status Id's in an enum and hope no one ever changes the database. Or I could pre-fetch the values based on the description (thus hardcoding that instead).

What would be the correct approach to keep these two, enum and table, synced?

答:
Because those are statuses they should be hard-coded into the application to ensure no DB change will corrupt your program (at least not easily). This is important because every status that must be added has to be coded against first and not simply added to the DB.

You should still have those status values written to the DB with their correct descriptions in case you need to pull a report for example.

Usually I have a small code snippet that will connect to the DB and verify that the statuses listed in a specific table all have the same id/name values that I have hard-coded in memory. If they don't match I will abort the execution of the software.

Depending on your needs you might want to implement slightly different behaviors but overall it's a good idea to have those statuses hard-coded anyway.

Title: Keeping an enum and a table in sync


问:
Why does Java allow to implement different interfaces, each containing a method with the same signature?
I recently found out that I can have two interfaces, one containing a method with the same signature as a method in the other interface. And I can have an interface or class that implements both of afore-mentioned interfaces. So the descendant class/interface implicitly implements two different methods as one method.

Why is this allowed in Java?

I can see numerous problems arising from this. Eclipse, for example, can only find out about implementations for one interface method, but for the second one it doesn't show any implementations at all. Also, I believe that there would be problems with automatic refactoring, like when you want to change the signature of the method in one of the interfaces and the IDE will be unable to correctly change that signature in all implementations (since they implement two different interfaces, and the IDE cannot tell which interface method the implementation is referring to.)

Why don't just make a compiler error like 'interfaces method names clashes' or something like that?

答:
Well, I'm more of a .Net guy but I though of chipping in.

So, forgive me if the syntax is incorrect.

Suppose you have to talk to different two DBs in your class. Each DB has a different interface.

```<code>interface IOldDB
{
   string GetConnectionString()
   void OpenConnection()
   void OpenSession()
   ...
}

interface IOldDB
{
   string GetConnectionString()
   bool Connect()
   void NewSession()
   ...
}
</code>```

Making it illegal would mean that I'd have to have two classes, one per Interface. All because one "apparently" conflicting method.

And if the methods of some interfaces have the same signature and you are implementing both, they are probably there for the same reason, right? If not, you're probably violating the SRP. Even if you are violating it, there's no reason for the compiler to stop you.

By the way, if I'm not mistaken, the compiler will throw an error if the signature of any of the methods conflict. Trying to implement those two interfaces

```<code>interface IAnotherDB
{
   void GetConnectionString(string cs)
}

interface IYetAnotherDB
{
   void GetConnectionString(string ConnectionString)
}
</code>```

Will throw an error.

In .Net you could do that, by Implementing the Interface explicitly.

Instead of:

```<code>public void GetConnectionString(string ConnectionString)
</code>```

You could do

```<code>IAnotherDB.GetConnectionString(string cs)
IYetAnotherDB.GetConnectionString(string ConnectionString)
</code>```

And go on.

Hope it helps.

Body:
Well, I'm more of a .Net guy but I though of chipping in.

So, forgive me if the syntax is incorrect.

Suppose you have to talk to different two DBs in your class. Each DB has a different interface.

interface IOldDB
{
   string GetConnectionString()
   void OpenConnection()
   void OpenSession()
   ...
}

interface IOldDB
{
   string GetConnectionString()
   bool Connect()
   void NewSession()
   ...
}

Making it illegal would mean that I'd have to have two classes, one per Interface. All because one "apparently" conflicting method.

And if the methods of some interfaces have the same signature and you are implementing both, they are probably there for the same reason, right? If not, you're probably violating the SRP. Even if you are violating it, there's no reason for the compiler to stop you.

By the way, if I'm not mistaken, the compiler will throw an error if the signature of any of the methods conflict. Trying to implement those two interfaces

interface IAnotherDB
{
   void GetConnectionString(string cs)
}

interface IYetAnotherDB
{
   void GetConnectionString(string ConnectionString)
}

Will throw an error.

In .Net you could do that, by Implementing the Interface explicitly.

Instead of:

public void GetConnectionString(string ConnectionString)

You could do

IAnotherDB.GetConnectionString(string cs)
IYetAnotherDB.GetConnectionString(string ConnectionString)

And go on.

Hope it helps.


问:
Hierarchical View/ViewModel/Presenters in MVPVM
I've been working with MVVM for a while, but I've recently started using MVPVM and I want to know how to create hierarchial View/ViewModel/Presenter app using this pattern.

In MVVM I would typically build my application using a hierarchy of Views and corresponding ViewModels e.g. I might define 3 views as follows:

The View Models for these views would be as follows:

```<code>public class AViewModel
{
    public string Text
    {
        get { return "This is A!"; }
    }

    public object Child1 { get; set; }
    public object Child2 { get; set; }
}

public class BViewModel
{
    public string Text
    {
        get { return "This is B!"; }
    }
}

public class CViewModel
{
    public string Text
    {
        get { return "This is C!"; }
    }
}
</code>```

In would then have some data templates to say that BViewModel and CViewModel should be presented using View B and View C:

```<code><DataTemplate DataType="{StaticResource local:BViewModel}">
    <local:BView/>
</DataTemplate>
<DataTemplate DataType="{StaticResource local:CViewModel}">
    <local:CView/>
</DataTemplate>
</code>```

The final step would be to put some code in AViewModel that would assign values to Child1 and Child2:

```<code>public AViewModel()
{
    this.Child1 = new AViewModel();
    this.Child2 = new BViewModel();
}
</code>```

The result of all this would be a screen that looks something like:

Doing this in MVPVM would be fairly simple - simply moving the code in AViewModel's constructor to APresenter:

```<code>public class APresenter
{
    ....
    public void WireUp()
    {
        ViewModel.Child1 = new BViewModel();
        ViewModel.Child2 = new CViewModel();
     }
}
</code>```

But If I want to have business logic for BViewModel and CViewModel I would need to have a BPresenter and a CPresenter - the problem is, Im not sure where the best place to put these are.

I could store references to the presenter for AViewModel.Child1 and AViewModel.Child2 in APresenter i.e.:

```<code>public class APresenter : IPresenter
{
    private IPresenter child1Presenter;
    private IPresenter child2Presenter;

    public void WireUp()
    {
        child1Presenter = new BPresenter();
        child1Presenter.WireUp();
        child2Presenter = new CPresenter();
        child2Presenter.WireUp();

        ViewModel.Child1 = child1Presenter.ViewModel;
        ViewModel.Child2 = child2Presenter.ViewModel;
    }
}
</code>```

But this solution seems inelegant compared to the MVVM approach. I have to keep track of both the presenter and the view model and ensure they stay in sync. If, for example, I wanted a button on View A, which, when clicked swapped the View's in Child1 and Child2, I might have a command that did the following:

```<code>var temp = ViewModel.Child1;
ViewModel.Child1 = ViewModel.Child2;
ViewModel.Child2 = temp;
</code>```

This would work as far as swapping the view's on screen (assuming the correct Property Change notification code is in place), but now my APresenter.child1Presenter is pointing to the presenter for AViewModel.Child2, and APresenter.child2Presenter is pointing to the presenter for AViewModel.Child1. If something accesses APresenter.child1Presenter, any changes will actually happen to AViewModel.Child2. I can imagine this leading to all sorts of debugging fun.

I know that I may be misunderstanding the pattern, and if this is the case a clarification of what Im doing wrong would be appreciated.

EDIT - this question is about WPF and the MVPVM design pattern, not ASP.NET and MVP.

答:
If you are swapping the ViewModel, shouldn't you swap the presenter too?

Anyway, I've been researching the MVP pattern. I'm far from understanding. But I can you give you some links that are helping me:

http://lostechies.com/derekgreer/2008/11/23/model-view-presenter-styles/

http://webclientguidance.codeplex.com/wikipage?title=HowToImplementModelViewPresenterPattern&referringTitle=HowToUnitTestPresenter

In the end, there's no right way of implementing it. I've read somewhere that if you put 10 programmers in a room discussing MVP, you'll get 11 different implementations. You should do whatever works best for you.

If I'm not the mistaken this patterns are there to help separate the concerns, and also help you test your code. Try variations and see what works better for you.


问:
At which architecture level are you running BDD tests (e.g. Cucumber)
I have in the last year gotten quite fond of using SpecFlow (which is a .NET port of Cucumber)

I have used it both to test a ASP.NET MVC application at the web layer, i.e. using browser automation, but also at the controller layer.
The first gives me a higher confidence in the correctness of the application, because JavaScript is tested, and improper controller configuration is also caught.

But those tests are slower to execute, and more complex to implement, than those just testing on the controller layer.

My tests are full functional tests, i.e. they exercise all layers of the application, all the way down to the database. So the first thing before any scenario is that the database is cleared of data, allowing the test to assume that only data specified in the "Given" block exists.

Then I see example on how to use it, where they test just exercise the model layer.

So what are your experiences with these tools? Which layer of the application do you test?

答:
Our company is embarking on implementing BDD with our .NET application. Our application is structured with:

.NET UI + Middleware

OpenEdge AppServer+Database

Our thinking is to replace the UI with the BDD scenarios, and the scenarios interact directly with the middleware.

We are leaving any UI testing as manual (for the moment).


答:
We have similar issues on my project (legacy code, hooray!)  The major problem is that "the enum tables never change" until they do and code breaks.  I have two strategies to mitigate that I've been slowly migrating towards.

First, and best, is to eliminate direct references to these values whenever possible.  Always ask, "why do I need to directly use the enum value?"  In many cases, this is a sign that the code has too many hard coded assumptions or is trying to do too much manipulation on the data.  See if you can't make better relationships in the database or more flexible code to handle what is being manipulated.

When that doesn't work, I go to plan B:  code generation.  Since the tables change infrequently and we publish new builds regularly, a code generator can read the enum tables and write the enum code.  This dynamically generated library is then used in the project.  If the DB changes, the next build will not compile, which is a lot better than getting mysterious runtime errors.

Title: Keeping an enum and a table in sync


问:
Abstract Data Type and Data Structure
It's quite difficult for me to understand these terms. I searched on google and read a little on Wikipedia but I'm still not sure. I've determined so far that:

Abstract Data Type is a definition of new type, describes its properties and operations.

Data Structure is an implementation of ADT. Many ADT can be implemented as the same Data Structure.

If I think right, array as ADT means a collection of elements and as Data Structure, how it's stored in a memory. Stack is ADT with push, pop operations, but can we say about stack data structure if I mean I used stack implemented as an array in my algorithm? And why heap isn't ADT? It can be implemented as tree or an array.

答:
Abstract Data Type: ADT may be defined as a set of data values and associated operations that are precisely specified independent of any particular implementation.  Thus an Abstract Data Type is an organized collection of information and a set of operations used to manage that information.  The set of operations defines the interface of the ADT.  As long as the ADT fulfills the conditions of the interface, it doesn’t really matter how the ADT is implemented.  Since, in ADT, the data values and operations are defined with mathematical precision, rather than as an implementation in a computer language, we may reason about effects of the operations, relations to other abstract data types whether a program implements the data type etc.  One of the simplest abstract data type is the stack data type for which functions might be provided to create an empty stack, to push values onto a stack and to pop values from a stack.

The basic difference between abstract data type (ADT) and concrete data type is that the latter allow us to look at the concrete representation, whereas the former hide the representation from us.  An ADT may be pure ADT or Updatable ADT.  A pure ADT is one where all operations are pure functions.  This means that operations have no side effects.  In particular, they do not modify or update there input arguments.  They just use these arguments to generate output, which are fresh values of ADT (or of other types).  Most concrete types are pure.  For example, no operation on integers actually modifies an integer.  Instead, all the operations like ‘+’ produce fresh outputs.

An updatable ADT is one where some operations actually change values of the ADT.  For example, suppose we had an operation called ‘pop’ that took a stack as an argument and modified it.  (“in place”, “destructively”) by removing the highest priority item.  This operation would be considered impure and the whole ADT would then be impure also.  An ADT may be user defined ADT.

We know that an Abstract Data Type is a data type that satisfies the following two conditions:

The representation, or definition, of the type and the operations are contained in a single syntactic unit.

The representation of objects of the type is hidden from the program units that use the type, so only direct operations possible on those objects are those provided in the type’s definition.

A user defined Abstract Data Type should provide:

A type definition that allows program units to declare variables of the type, but hides the representation of these variables.

A set of operations for manipulating objects of the type.

An example of a user defined abstract data type is structure.  ’C’ provides four basic types: int, char, float and double.  However, ‘C’ also provides the programmer with the ability to define his/her own types.  Structure is one such example.  A structure is an aggregate of different parts, where each part is of some existing type.

```<code>struct abc

{int x;

float y;

};
</code>```

The above structure definition does not create any variables, rather it creates a new type.  Variables of this type may be created in a similar way to variables of a built in type.

```<code>struct abc a;
</code>```

The typedef keyword allows us to create new type names for our new types.

For example:

```<code>typedef struct abc AB;
</code>```

where AB is a new type name that can now be used to create new types.

```<code>AB b;
</code>```

Data Structures:  The following are the characteristic features of data structures:

It contains component data items, which may be atomic or another data structure (still a domain).

A set of operations on one or more of the component items.

Defines rules as to how components relates to each other and to the structure as a whole (assertions).

Data Structures:

A data structure may be static or dynamic.  A static data structure has a fixed size.  This meaning is different from the meaning of static modifier.  Arrays are static; once we define the number of elements it can hold, the number doesn’t change.  A dynamic data structure grows and shrinks at execution time as required by its contents.  A dynamic data structure is implemented using links.

Data structures may further be categorized into linear data structures and non-linear data structures.  In linear data structures every component has a unique predecessor and successor, except first and last elements, whereas in case of non-linear data structures, no such restriction is there as elements may be arranged in any desired fashion restricted by the way we use to represent such types.

Title: Abstract Data Type and Data Structure

Body:
Abstract Data Type: ADT may be defined as a set of data values and associated operations that are precisely specified independent of any particular implementation.  Thus an Abstract Data Type is an organized collection of information and a set of operations used to manage that information.  The set of operations defines the interface of the ADT.  As long as the ADT fulfills the conditions of the interface, it doesn’t really matter how the ADT is implemented.  Since, in ADT, the data values and operations are defined with mathematical precision, rather than as an implementation in a computer language, we may reason about effects of the operations, relations to other abstract data types whether a program implements the data type etc.  One of the simplest abstract data type is the stack data type for which functions might be provided to create an empty stack, to push values onto a stack and to pop values from a stack.

The basic difference between abstract data type (ADT) and concrete data type is that the latter allow us to look at the concrete representation, whereas the former hide the representation from us.  An ADT may be pure ADT or Updatable ADT.  A pure ADT is one where all operations are pure functions.  This means that operations have no side effects.  In particular, they do not modify or update there input arguments.  They just use these arguments to generate output, which are fresh values of ADT (or of other types).  Most concrete types are pure.  For example, no operation on integers actually modifies an integer.  Instead, all the operations like ‘+’ produce fresh outputs.

An updatable ADT is one where some operations actually change values of the ADT.  For example, suppose we had an operation called ‘pop’ that took a stack as an argument and modified it.  (“in place”, “destructively”) by removing the highest priority item.  This operation would be considered impure and the whole ADT would then be impure also.  An ADT may be user defined ADT.

We know that an Abstract Data Type is a data type that satisfies the following two conditions:

The representation, or definition, of the type and the operations are contained in a single syntactic unit.

The representation of objects of the type is hidden from the program units that use the type, so only direct operations possible on those objects are those provided in the type’s definition.

A user defined Abstract Data Type should provide:

A type definition that allows program units to declare variables of the type, but hides the representation of these variables.

A set of operations for manipulating objects of the type.

An example of a user defined abstract data type is structure.  ’C’ provides four basic types: int, char, float and double.  However, ‘C’ also provides the programmer with the ability to define his/her own types.  Structure is one such example.  A structure is an aggregate of different parts, where each part is of some existing type.

struct abc

{int x;

float y;

};

The above structure definition does not create any variables, rather it creates a new type.  Variables of this type may be created in a similar way to variables of a built in type.

struct abc a;

The typedef keyword allows us to create new type names for our new types.

For example:

typedef struct abc AB;

where AB is a new type name that can now be used to create new types.

AB b;

Data Structures:  The following are the characteristic features of data structures:

It contains component data items, which may be atomic or another data structure (still a domain).

A set of operations on one or more of the component items.

Defines rules as to how components relates to each other and to the structure as a whole (assertions).

Data Structures:

A data structure may be static or dynamic.  A static data structure has a fixed size.  This meaning is different from the meaning of static modifier.  Arrays are static; once we define the number of elements it can hold, the number doesn’t change.  A dynamic data structure grows and shrinks at execution time as required by its contents.  A dynamic data structure is implemented using links.

Data structures may further be categorized into linear data structures and non-linear data structures.  In linear data structures every component has a unique predecessor and successor, except first and last elements, whereas in case of non-linear data structures, no such restriction is there as elements may be arranged in any desired fashion restricted by the way we use to represent such types.


答:
Although not completely independent, SCons is a Python based build tool that I've had very good experiences with.  Python is pretty commonly available (more so than Ruby?) and the "build scripts" are simple Python files that are very easy to write and maintain.

In a .NET environment, however, I'd still recommend learning some of MSBuild's syntax, as you will ultimately have to use it for some part of the process.  (Theoretically you could go without it, but very few . NET devs are going to not be using VS, MonoDev, or something like SharpDevelop, and I think they all generate MSBuild project files.)


问:
C Language - K&R 1st vs 2nd Edition?
I'm planning to buy a book to learn C Language. Many say K&R is a must-have book for C programmers so I chose it. I see that there are two editions. What are the differences between them?</p>

答:
If memory serves me right, K&R 2nd Edition was published in 1988, to comply with the imminent release of ANSI-C (aka C89)

A lot has happened in the C world since then...

1990 - adoption of C by ISO as ISO/IEC 9899:1990 (aka C90)

1999 - new revised standard as ISO/IEC 9899:1999 (aka C99)

2011 - further major revision as ISO/IEC 9899:2011 (aka C11)

Not to mention the work of MISRA and CERT-C (etc) to produce safer subsets.

I have a copy of both editions, but seldom refer to either...

Title: C Language - K&R 1st vs 2nd Edition?


答:
what generic build tools out there include their binary run-times... target-platform-agnostic tools

Above would violate principle of separation of concerns, and quite in a blatant way.

Think of consequences. Such a tool would also need to have a set of binaries for respective target platforms, for all of them and for everyone of them.

This would mean that besides providing build tool functionality, its developers would also have to invest their efforts into platform-specific binaries - design, programming, testing, maintenance, doing new features, bugfixes and testing them again and again and again, over and over again.

Now take a minute to think of long-term perspectives for such a tool. "It's a competitive worls, everything counts in large amounts."

While developers of our monster tool would struggle with specific glitches and pecularities of each and every target platform, over and over and over again, their competitors would have a great time providing extensions, enhancements and new features to build functionality, leveraging on the fact that cumbersome platform specific is covered by underlying third-part runtime.


问:
Why is a small fixed vocabulary seen as an advantage to RESTful services?
So, a RESTful service has a fixed set of verbs in its vocabulary. A RESTful web service takes these from the HTTP methods. There are some supposed advantages to defining a fixed vocabulary, but I don't really grasp the point. Maybe someone can explain it.

Why is a fixed vocabulary as outlined by REST better than dynamically defining a vocabulary for each state? For example, object oriented programming is a popular paradigm. RPC is described to define fixed interfaces, but I don't know why people assume that RPC is limited by these contraints. We could dynamically specify the interface just as a RESTful service dynamically describes its content structure.

REST is supposed to be advantageous in that it can grow without extending the vocabulary. RESTful services grow dynamically by adding more resources. What's so wrong about extending a service by dynamically specifying a per-object vocabulary? Why don't we just use the methods that are defined on our objects as the vocabulary and have our services describe to the client what these methods are and whether or not they have side effects?

Essentially I get the feeling that the description of a server side resource structure is equivalent to the definition of a vocabulary, but we are then forced to use the limited vocabulary in which to interact with these resources.

Does a fixed vocabulary really decouple the concerns of the client from the concerns of the server? I surely have to be concerned with some configuration of the server, this is normally resource location in RESTful services. To complain at the use of a dynamic vocabulary seems unfair because we have to dynamically reason how to understand this configuration in some way anyway. A RESTful service describes the transitions you are able to make by identifying object structure through hypermedia.

I just don't understand what makes a fixed vocabulary any better than any self-describing dynamic vocabulary, which could easily work very well in an RPC-like service. Is this just a poor reasoning for the limiting vocabulary of the HTTP protocol?

Reflection

Just to clarify my thoughts a little better than I have done. Suppose you are designing any general purpose API, maybe not even web facing. Would you be happy if someone said you can only use these method names on your objects? REST isn't restricted to HTTP, but consider the situation where every API you write, web facing or otherwise simply consisted of objects containing GET POST PUT and DELETE methods. So that object.foo method you wanted to define isn't possible. You have to define a new object called foo, and call its GET method. That's essentially how REST works, and it makes me a little uncomfortable to think about it. You don't have any better generic understanding of what foo does, you were just forced to create a new object for what is essentially a method on a parent object. Furthermore your API is no less complex, you have just hidden interface complexity by creating more objects. RESTful web services force us to adopt an interface which may or may not be sufficient in the context of the API we are exposing. Perhaps there is a good reason for doing this with web facing APIs, but a good reason to not adopt standard interfaces for every object in every general purpose API. A practical example would be appreciated.

答:
The alternative is something horrible: WSDL (aka Web Service Definition Language), which is a (clumsy) way to programmatically describe (somewhat) arbitrary APIS.

REST severely limits the verbs, pushing almost all application-specific variation into the payload of the document. The benefit of doing that is that many client implementations can communicate with many heterogeneous services. The clients and servers may be completely unknown to each other, some not being written yet.

There's a podcast in which Stefan Tilkov explains REST nicely.


问:
Is code that terminates on a random condition guaranteed to terminate?
If I had a code which terminated based on if a random number generator returned a result (as follows), would it be 100% certain that the code would terminate if it was allowed to run forever.

```<code>while (random(MAX_NUMBER) != 0): // random returns a random number between 0 and MAX_NUMBER
   print('Hello World')
</code>```

I am also interested in any distinctions between purely random and the deterministic random that computers generally use. Assume the seed is not able to be known in the case of the deterministic random.

Naively it could be suggested that the code will exit, after all every number has some possibility and all of time for that possibility to be exercised. On the other hand it could be argued that there is the random chance it may not ever meet the exit condition-- the generator could generate 1 'randomly' until infinity.

(I suppose one would question the validity of the random number generator if it was a deterministic generator returning only 1's 'randomly' though)

答:
By definition, it must be possible to get an infinite sequence of 0 in a really casual ("random") sequence so this program must be able to run forever. Otherwise, this could not be considered a random sequence from a mathematical/statistical point of view. You cannot rule out a specific, legitimate sequence and still consider your system a really random one.

An infinite sequence of 0 would fail to be recognized as a legitimate random sequence by most if not all the standard statistical methods of analysis we use in practice but, despite this, it actually is a perfectly legitimate random sequence for the theory.

This in theory.

In practice, we all know that, given enough time, we will get a number different from 0 and the program will terminate.

The random generator used by computers are considered to be random when a reasonably long sequence of number they generate (say, some million numbers...) cannot be distinguished from a really casual one when analyzed whith standard statistical tools. That is: we do not really know if the sequence of number they generate is really random but we cannot tell it apart from a genuine random sequence when we analyze a finite-length sample.

This is a big difference because... given a longer sequence you can discover that your sequence is not really random and can be reproduced. In cryptography, this would be a very bad discovery.

As I said above, the statistical methods of analysis we use would not recognize an infinite sequence of 0 as a legitimate random sequence. Nevertheless, this is a failure of the analytical methods, not of the random generator. Mathematically speaking, you cannot rule out such a sequence just because it does not satisfy your analytical system or your personal taste. If you do not have a real, mathematical reason to rule it out, it is legitimate.


问:
Render Ruby object to interactive html
I am developing a tool that discovers network services enabled on host and writes short summary on them like this:
```
init,1
└── login,1560 --
    └── bash,1629
        └── nc,12137 -lup 50505
{
    :net => [
        [0] "*:50505 IPv4 UDP "
    ],
    :fds => [
        [0] "/root (cwd)",
        [1] "/",
        [2] "/bin/nc.traditional",
        [3] "/xochikit/ld_poison.so (stat: No such file or directory)",
        [4] "/dev/tty2",
        [5] "*:50505"
    ]
}
```

It proved to be very nice formatted and useful for quick discovery thanks to colors provided by the awesome_print gem. However, its output is just a text. One issue is that if I want to share it, I lose colors. I'd also like to fold and unfold parts of objects, quickly jump to specific processes and what not? Adding comments, for example. Thus I want something web-based.

What is the best approach to implement features like these? I haven't worked with web interfaces before and I don't have much experience with Ruby.

Update:

Maybe I didn't write my willings clear enough.

I think I want something that behaves like Chromium's chrome://chrome/settings/ (or better, of course). Is there maybe an erb template or manual showing how to implement that? I thought this is a thing needed often enough.

答:
This is the kind of processing you usually perform on the client-side (that is: inside the web browser) with AJAX (HTML, Javascript and CSS). There are many libraries that can do this job out there. Search for AJAX foldable tree, AJAX table and so on. JQuery and other well-known libraries have table/tree widgets you can use for this.

Have a look at these AJAX table/grid widgets, for example:

https://stackoverflow.com/questions/1503810/what-javascript-table-widgets-are-available

Most likely, you will have to package your data as a JSON or a XML hierarchycal structure before sending it to your AJAX viewer. JSON and XML will allow you to easily share your data with other people, as well. They are both largely recognized as standard data exchange formats.

Title: Render Ruby object to interactive html


问:
SpecFlow/Cucumber - Documenting available steps
Our company is looking at implementing BDD in our .NET application. Specifically, SpecFlow.

We can foresee a large number of common steps being created ('Given a customer', etc), so what methods have been used to document these, so that the business can reference them? Is XmlDoc on the step definition classes sufficient, or have others found better methods of documentation?

答: The step definition report of SpecFlow provides the information, which steps have been defined, and whether and how often they are actually used, as well as which steps have no step definition yet. You can read more about it on the Reporting page of the SpecFlow wiki.</p>


答:
The "verb" and "noun" terminology is somewhat unfortunate here. As you already mentioned, you can easily create object for function. All object oriented languages except Java have that transformation built-in and in Java you end up doing it all the time anyway ending up with lots of objects with single method and often one called "invoke", "execute", "apply" or somesuch (so it's the programming languages where the "verb"/"noun" distinction actually doesn't make sense).

The "verbs" of REST is more like classifying your methods to getters, setters (deleters; can be considered kind of setters) and other. And trying to do everything with getters and setters. The reason for this is:

Easier semantics in face of communication failure, since both getters and setters are idempotent. Getting the resource twice has no additional effect and nor does setting it to the value it already has.

Defining some semantics that can be used by possibly caching proxy that does not understand the specific interface. Getters are cached and setters are known to invalidate the cache.

HTTP was designed from the beginning with both caches and fault-tolerance in mind, so these two points lead to it's four basic methods:

GET is a getter. It's assumed not to modify server state and return the same value each time with possibility to specify expiration and revalidation policy.

PUT and DELETE are the setter and deleter (= setter with nil). They are not normally used in context of normal web, but make sense for REST.

POST is a generic "invoke" kitchen sink for which caches can assume nothing.

REST is a design pattern describing how to use raw HTTP or similar network protocols to implement interface that allows easy handling of failures by simple retrying and works nicely with caching proxies.

It doesn't correspond easily to regular object-oriented programming API. I think it is actually a good thing. The challenges of interfacing over network, which is inherently unreliable and where round-trips are much slower than transferring even moderate amount of data call for different design approach than in-process API, so when it looks different, people don't try to apply invalid experience from the other domain that much (that's the bane of SOAP, XML-RPC and such; it looks like procedure calls, but doesn't work like it and ends up being pain to work with).

Title: Why is a small fixed vocabulary seen as an advantage to RESTful services?

Body:
So, a RESTful service has a fixed set of verbs in its vocabulary. A RESTful web service takes these from the HTTP methods. There are some supposed advantages to defining a fixed vocabulary, but I don't really grasp the point. Maybe someone can explain it.

Why is a fixed vocabulary as outlined by REST better than dynamically defining a vocabulary for each state? For example, object oriented programming is a popular paradigm. RPC is described to define fixed interfaces, but I don't know why people assume that RPC is limited by these contraints. We could dynamically specify the interface just as a RESTful service dynamically describes its content structure.

REST is supposed to be advantageous in that it can grow without extending the vocabulary. RESTful services grow dynamically by adding more resources. What's so wrong about extending a service by dynamically specifying a per-object vocabulary? Why don't we just use the methods that are defined on our objects as the vocabulary and have our services describe to the client what these methods are and whether or not they have side effects?

Essentially I get the feeling that the description of a server side resource structure is equivalent to the definition of a vocabulary, but we are then forced to use the limited vocabulary in which to interact with these resources.

Does a fixed vocabulary really decouple the concerns of the client from the concerns of the server? I surely have to be concerned with some configuration of the server, this is normally resource location in RESTful services. To complain at the use of a dynamic vocabulary seems unfair because we have to dynamically reason how to understand this configuration in some way anyway. A RESTful service describes the transitions you are able to make by identifying object structure through hypermedia.

I just don't understand what makes a fixed vocabulary any better than any self-describing dynamic vocabulary, which could easily work very well in an RPC-like service. Is this just a poor reasoning for the limiting vocabulary of the HTTP protocol?

Reflection

Just to clarify my thoughts a little better than I have done. Suppose you are designing any general purpose API, maybe not even web facing. Would you be happy if someone said you can only use these method names on your objects? REST isn't restricted to HTTP, but consider the situation where every API you write, web facing or otherwise simply consisted of objects containing GET POST PUT and DELETE methods. So that object.foo method you wanted to define isn't possible. You have to define a new object called foo, and call its GET method. That's essentially how REST works, and it makes me a little uncomfortable to think about it. You don't have any better generic understanding of what foo does, you were just forced to create a new object for what is essentially a method on a parent object. Furthermore your API is no less complex, you have just hidden interface complexity by creating more objects. RESTful web services force us to adopt an interface which may or may not be sufficient in the context of the API we are exposing. Perhaps there is a good reason for doing this with web facing APIs, but a good reason to not adopt standard interfaces for every object in every general purpose API. A practical example would be appreciated.


答:
Yes, given infinite time the code would surely terminate. See infinite monkey theorem. The probability of it running forever is 0, there's a mathematical proof for that.

That's if the numbers were truly random. I don't know enough about random number generators to tell you more than that.

Title: Is code that terminates on a random condition guaranteed to terminate?

Body:
If I had a code which terminated based on if a random number generator returned a result (as follows), would it be 100% certain that the code would terminate if it was allowed to run forever.

```<code>while (random(MAX_NUMBER) != 0): // random returns a random number between 0 and MAX_NUMBER
   print('Hello World')
</code>```

I am also interested in any distinctions between purely random and the deterministic random that computers generally use. Assume the seed is not able to be known in the case of the deterministic random.

Naively it could be suggested that the code will exit, after all every number has some possibility and all of time for that possibility to be exercised. On the other hand it could be argued that there is the random chance it may not ever meet the exit condition-- the generator could generate 1 'randomly' until infinity.

(I suppose one would question the validity of the random number generator if it was a deterministic generator returning only 1's 'randomly' though)