问:
Should we design programs to randomly kill themselves?
In a nutshell, should we design death into our programs, processes, and threads at a low level, for the good of the overall system?

Failures happen. Processes die. We plan for disaster and occasionally recover from it. But we rarely design and implement unpredictable program death. We hope that our services' uptimes are as long as we care to keep them running.

A macro-example of this concept is Netflix's Chaos Monkey, which randomly terminates AWS instances in some scenarios. They claim that this has helped them discover problems and build more redundant systems.

What I'm talking about is lower level. The idea is for traditionally long-running processes to randomly exit. This should force redundancy into the design and ultimately produce more resilient systems.

Does this concept already have a name? Is it already being used in the industry?

EDIT

Based on the comments and answers, I'm afraid I wasn't clear in my question. For clarity:

yes, I do mean randomly,

yes, I do mean in production, and

no, not just for testing.

To explain, I'd like to draw an analogy to multicellular organisms.

In nature, organisms consist of many cells. The cells fork themselves to create redundancy, and they eventually die. But there should always be enough cells of the right kinds for the organism to function. This highly redundant system also facilitates healing when injured. The cells die so the organism lives.

Incorporating random death into a program would force the greater system to adopt redundancy strategies to remain viable. Would these same strategies help the system remain stable in the face of other kinds of unpredictable failure?

And, if anyone has tried this, what is it called? I'd like to read more about it if it already exists.

答:
IIS server has a configurable feature which automatically recycles worker processes either after they have used a certain amount of memory or after servicing a certain number of requests or after they have been alive for a specified timespan. (http://msdn.microsoft.com/en-us/library/ms525803(v=vs.90).aspx) and (http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/1652e79e-21f9-4e89-bc4b-c13f894a0cfe.mspx?mfr=true)

When a CONTAINER like IIS does it, it makes sense to protect the server from rogue processes. However I would prefer to keep this turned off, because it doesn't make sense if you have sufficiently tested your code.

We already work on unreliable layers (hardware, network) so I would never write any code that randomly kill its threads or processes intentionally. Random killing is also a bad idea from an economic perspective- no one would use my API if they figured I've programmed it to randomly crash. Lastly, if I were to consume an API or use a system with randomly crashing threads I would have to spend a lot of money to create a robust enough monitoring mechanism for it so that I could sleep peacefully at night.

Instead If i were developing a system or an API I would write scripts or use a harness that would do this purely to stress test the resilience of the system. And I would make such a test run on all builds to identify bad builds. However, while this would be a necessary test, it could never be a "sufficient" test.


问:
Working for free?
I came across this article Work for Free that got me thinking.

The goal of every employer is to gain
  more value from workers than the firm
  pays out in wages; otherwise, there is
  no growth, no advance, and no
  advantage for the employer.
  Conversely, the goal of every employee
  should be to contribute more to the
  firm than he or she receives in wages,
  and thereby provide a solid rationale
  for receiving raises and advancement
  in the firm.

I don't need to tell you that the
  refusenik didn't last long in this
  job.

In contrast, here is a story from last
  week. My phone rang. It was the
  employment division of a major
  university. The man on the phone was
  inquiring about the performance of a
  person who did some site work on
  Mises.org last year. I was able to
  tell him about a remarkable young man
  who swung into action during a crisis,
  and how he worked three 19-hour days,
  three days in a row, how he learned
  new software with diligence, how he
  kept his cool, how he navigated his
  way with grace and expertise amidst
  some 80 different third-party plug-ins
  and databases, how he saw his way
  around the inevitable problems, how he
  assumed responsibility for the
  results, and much more.

What I didn't tell the interviewer was
  that this person did all this without
  asking for any payment. Did that fact
  influence my report on his
  performance? I'm not entirely sure,
  but the interviewer probably sensed in
  my voice my sense of awe toward what
  this person had done for the Mises
  Institute. The interviewer told me
  that he had written down 15 different
  questions to ask me but that I had
  answered them all already in the
  course of my monologue, and that he
  was thrilled to hear all these
  specifics.

The person was offered the job. He had
  done a very wise thing; he had earned
  a devotee for life.

The harder the economic times, the
  more employers need to know what they
  are getting when they hire someone.
  The job applications pour in by the
  buckets, all padded with degrees and
  made to look as impressive as
  possible. It's all just paper. What
  matters today is what a person can do
  for a firm. The resume becomes pro
  forma but not decisive under these
  conditions. But for a former boss or
  manager to rave about you to a
  potential employer? That's worth
  everything.

What do you think? Has anyone here worked for free? If so, has it benefited you in any way? Why should(nt) you work for free (presuming you have the money from other means to keep you going)? Can you share your experience?

Me, I am taking a year out of college and haven't gotten a degree yet so that's probably why most of my job applications are getting ignored. So im thinking about working for free for the experience?

答:
Every time programmers with no experience say they think working for free is reasonable, I tell them it's not worth it unless they're really desperate to have something on their resume and have no financial problems above all.

An inexperienced person would probably feel pressured to produce something for the company to prove they are worth something. However, they should face the fact that whenever someone hires someone for anything, they expect results really soon. This might not be enough time to learn about a certain framework or technology, how things really work, etc and both parties end up frustrated.
Of course, it might work out alright, but why risk it and end up ruining your reputation? It's always a good idea to take the time to try to produce something for yourself first. That's what I did and it's going well.

ContentLicense: CC BY-SA 2.5

Title: Working for free?


问:
Does OOP fulfill the promise of code reuse? What alternatives are there to achieve code reuse?
Perhaps the greatest promise of using object-oriented paradigm is the code reuse. Some dispute that this was achieved. Why was it (not) achieved?

Does code reuse as OOP defines it, make projects more productive?

Or more manageable? Or easier to maintain? Or with more quality?

Probably we all agree that code reuse is a good thing, but there are several ways to achieve this goal. The question is about the method of code reuse offered by OOP. Was it a good thing? Are there better methods to achieved code reuse than object orientation, sub-classing, polymorphism, etc.? What ways are better? Why?

Tell us your experience with OOP reuse or other paradigms reuse.

答:
Reading the above posts, a few remarks:

Many think that code reuse in OOP implies inheritance. I do not agree. Interfaces and contracts are the core to code reuse in OOP systems. OOP is a gray box attempt in creating a component technology.

The difference between domain specific and generic "frameworks" as subject of re-use deem me too abstract. In my view on things, a component (a concise, minimal and re-usable interface contract and the implementation behind) can only be done, if the problem it addresses is well understood. A domain specific component, which allows non-domain experts to do their job with less knowledge about the domain is a (re-)useful component. Users need to understand the interface, less so the intricacies of the problem domain.

Levels of re-use often forgotten: Idea re-use, Specification re-use, Architecture/Design re-use, Interface re-use, Test-case re-use. Code re-use is not always favorable. But it is a big time saver often to stick to a specific architecture to tackle a new, similar product.

The OOP Design patterns (Gamma et. al) in my eyes elaborated on tactical implementation techniques rather than being meaningful in the context of code re-use on a larger scale. They help write an application with OOP elements, yet I would not see them as a solution to the "code re-use" question beyond a single application.

Maybe it is not fair: 20 years of C/C++/C# experience and 6 months functional programming (F#). One major element of enabling re-use is: People need to easily find "the interface", study it, understand it, then use it. Pure functional programming does not make it easy for me to see structure, candidates for reuse or where it all starts and where it all ends. The so praised "syntactic sugar" often is salt in my eyes, preventing me from easily seeing what happens. Thusly I would less likely try to re-use a functional (what is it - bunch of functions?), which may have hidden side-effects I cannot even see (lazy evaluation, monads,...). Don't get me wrong, functional programming has very cool sides, but all the strengths proclaimed I see with a good measure of doubt. I am very curious what the post-functional future brings and hope to see it before I retire ;)

Specification, Design, Implementation are coupled, yet not easily traversable views on the "same thing". Much more vital for increased future productivity than a new programming paradigm is, to close the gap, to increase (automated reasoning, traceability) the mutual benefits between those views. Formalized specification languages, standardized test notations (e.g. ttcn3) and programming languages supporting verification of interfaces and contracts against specifications without comment-littering might be what we need most urgently.

ContentLicense: CC BY-SA 3.0


问:
When to use interfaces (unit testing, IoC?)
I suspect I've made a schoolboy error here, and am looking for clarification. A lot of the classes in my solution (C#) - dare I say the majority - I've ended up writing a corresponding interface for. E.g. an "ICalculator" interface and a "Calculator" class that implements it, even though I'm never likely to replace that calculator with a different implementation. Also, most of these classes reside in the same project as their dependencies - they really only need to be internal, but have ended up being public as a side-effect of implementing their respective interfaces.

I think this practice of creating interfaces for everything stemmed from a few falsehoods:-

1) I originally thought that an interface was necessary to create unit test mocks (I'm using Moq), but I've since discovered that a class can be mocked if its members are virtual, and it has a parameterless constructor (correct me if I'm wrong).

2) I originally thought an interface was necessary to register a class with the IoC framework (Castle Windsor), e.g.

```<code>Container.Register(Component.For<ICalculator>().ImplementedBy<Calculator>()...
</code>```

when in fact I could just register the concrete type against itself:

```<code>Container.Register(Component.For<Calculator>().ImplementedBy<Calculator>()...
</code>```

3) Using interfaces, e.g. constructor parameters for dependency injection, results in "loose coupling".

So have I gone mad with interfaces?! I'm aware of the scenarios where you would "normally" use an interface, e.g. exposing a public API, or for things like "pluggable" functionality. My solution has a small number of classes that fit such use cases, but I wonder if all the other interfaces are unnecessary, and should be removed? Regarding point 3) above, won't I be violating "loose coupling" if I was to do this?

Edit:- I'm just having a play with Moq, and it seems to require methods to be public and virtual, and have a public parameterless constructor, in order to be able to mock them. So it looks like I can't have internal classes then?

答:
In general, if you make an interface which only has one implementor, you're just writing things twice and wasting your time. Interfaces alone do not provide loose coupling if they're tightly coupled to one implementation... That said, if you want to mock these things in unit tests, that's usually a great sign that you'll inevitably need more than one implementor in real code.

I would consider it a bit of a code smell if nearly all your classes have interfaces though. That means they're almost all working with one another in one way or another. I would suspect that the classes are doing too much (since there's no helper classes) or you've abstracted too much (oh, I want a provider interface for gravity since that might change!).


问:
Advantage of 2-way merge sort against n-way
It's known 2-way Merge sort takes N*logN time.

I wonder, what would be the running time if we split an array of the size N into N subarrays and then do the same thing as we would do for 2-way Merge?

答:
Well, the recurrence will be:

where f(n) is the merge function.

Of course in 2-way merge sort we can do this in linear time, hence f(n)=O(n) for the k=2 case. But in general, the best time this can be done is O(nlogk), using Priority Queues.

Now, according to the Master Theorem you can solve this recurrence and see that T(n)=O(n log n).

So in asymptotic notation it looks like both k-way and the original merge-sort are equal. however note that in practice, implementing the original merge-sort is simpler and might require less effort to implement and maintain.


答:
The term you are looking for has been recently coined by Nassim Nicholas Taleb: Antifragility. His book Antifragile is definitely recommended. It barely mentions IT, but the unspoken, obvious parallels are most inspiring.
His idea is to extend the scale of fragile <-> robust to fragile <-> robust <-> antifragile. Fragile breaks with random events, robust manages with random events and anti-fragile gains with random events. </p>

Title: Should we design programs to randomly kill themselves?

Body:
In a nutshell, should we design death into our programs, processes, and threads at a low level, for the good of the overall system?

Failures happen. Processes die. We plan for disaster and occasionally recover from it. But we rarely design and implement unpredictable program death. We hope that our services' uptimes are as long as we care to keep them running.

A macro-example of this concept is Netflix's Chaos Monkey, which randomly terminates AWS instances in some scenarios. They claim that this has helped them discover problems and build more redundant systems.

What I'm talking about is lower level. The idea is for traditionally long-running processes to randomly exit. This should force redundancy into the design and ultimately produce more resilient systems.

Does this concept already have a name? Is it already being used in the industry?

EDIT

Based on the comments and answers, I'm afraid I wasn't clear in my question. For clarity:

yes, I do mean randomly,

yes, I do mean in production, and

no, not just for testing.

To explain, I'd like to draw an analogy to multicellular organisms.

In nature, organisms consist of many cells. The cells fork themselves to create redundancy, and they eventually die. But there should always be enough cells of the right kinds for the organism to function. This highly redundant system also facilitates healing when injured. The cells die so the organism lives.

Incorporating random death into a program would force the greater system to adopt redundancy strategies to remain viable. Would these same strategies help the system remain stable in the face of other kinds of unpredictable failure?

And, if anyone has tried this, what is it called? I'd like to read more about it if it already exists.


问:
I have only two languages on my resume - how bad is this?
I have a question that can be best answered here, given the vast experience some of you guys have!

I am going to finish my bachelor's degree in CS and let's face it, I am just comfortable with C++ and Python. C++ - I have no experience to show for and I can't quote the C++ standard like some of the guys on SO do but yet I am comfortable with the language basics and the stuff that mostly matters. With Python, I have demonstrated work experience with a good company, so I can safely put that.

I have never touched C, though I have been meaning to do it now. So I cannot write C on my resume because I have not done it ever. Sure I can finish K & R and get a sense of the language in a month, but I don't feel like writing it cause that would be being unfaithful to myself.

So the big question is, are two languages on a a resume considered OK or that is usually a bad sign? Most resumes I have seen mention lots of languages and hence my question. Under the language section of my resume, I just mention: C++ and Python and that kinda looks empty!

What are your views on this and what do you feel about such a situation?

PS: I really don't want to write every single library or API I am familiar with. Or should I?

答:
It's not that bad if you're applying for a job that's exclusively C++ or Python. Some employers might take the knowledge of multiple languages as a sign that you can be trusted to learn new ones quickly, but since you're just graduating a reasonable employer will probably take that into consideration. It'd be a different story if you had 20 years of job experience but knew only 2 languages.

You might consider starting to get familiar with a new language that you're interested in and mention that your resume. It'd show that you're dedicated to broaden your language selection and to develop your skills.


问:
Reaching Intermediate Programming Status
I am a software engineer that's had positions programming in VBA (though I dare not consider that 'real' experience, as it was trial and error!), Perl w/ CGI, C#, and ASP.NET.  The latter two are post-undergraduate, with my entrance into the 'real world'.  I'm 2 years out of college, and have had 5 years of experience (total) across the languages I've mentioned.  However, when it comes to my resume, I can only put 2 years down for C#, and less than a year down for ASP.NET.

I feel like I know C#, but I still have to spend time going 'What does this method do?', whereas some of the more senior level engineers can immediately say, "Oh, Method X does this, without ever having looked at that method before."  So I know empirically that there's a gulf there, but I'm not exactly sure how to bridge it.  I've started programming in Project Euler, and I picked up a book on design patterns, but I still feel like I spend each day treading water, instead of moving forward.

That isn't to say that I don't feel like I've made progress, it just means that as far as I come each day, I still see the mountain top way off in the distance.

My question is this:  How did you overcome this plateau?  How long did it take you?  What methods can you suggest to assist me in this?

I've read through Code Complete, The Mythical Man Month, and CLR via C#, 2nd edition -- my question is: What do I do now?

Edit: I just found this question on projects for an intermediate level programmer. I think it adds to the discussion (though it does not supplant my question).  As such, I'm adding it to the question as a "For More Information".

答:
To excel as a C# developer read the following two. Note that the focus of these books is more on the language (C#) not the framework (.NET)..

Essential C#: link is for the latest edition. I actually read the previous one (C# 4.0) but i am assuming the newer the better. This book has some basic things as well but be patient read that book cover to cover.

C# in Depth: link is again for the latest edition which will be released in 10-15 days. I have only skimmed though the book but my colleagues who have read it have high regard for this.

You have already read CLR via C#, otherwise that is probably third suggestion by anyone for C# developers.

These should also make you a better developer: Framework Design Guidelines and Working Effectively with Legacy Code.

OwnerDisplayName: George Stocker


问:
Are there algorithims for polling optimization?
I have a web-application with an async HTTP backend, which gets called by the client by AJAX requests. The client has to start a job and then polls for the result.

I started with a simple 150ms polling interval, which was fine for small jobs, but big jobs, which could take several minutes, threw many failed requests to the server.

Currently, I just add 1000ms to the delay after every poll, so the polling gets slower over time for longer requests, but never longer than 10 seconds.

Are there some formulas, statistics, or algorithms that I could use to dynamically optimize the polling time?

答:
This really depends on how much time it takes on average to perform the job and the standard deviation of this time.

Once you know this, you have a good idea about what your minimum and maximum waiting times are for 95% of jobs (2 standard deviations).  So I would plan for a minimum polling time somewhere in the vicinity of 2 standard deviation (so that statistically, only 5% of jobs have finished at this point).

From there, it largely depends on you, but ideally you would poll with higher frequency as you approach the norm and then fall off afterwards.  I can't tell you at what rate you should poll the server, since you are the one which ultimately determines how much traffic you can support.  Have you also considered web sockets?


答:
If the server can give a rough estimate of how long a job will take, then I would return that estimate in the first response (the one indicating that the job was received/accepted). The client can then wait at least that time before it starts polling for results.

To avoid flooding a server with unsuccessful polling requests, you might also use a scheme that is often used to send retries over an unreliable protocol: After sending a request, wait a time T before sending a retry. After sending a retry, double the waiting time, until a maximum T2. After success, the waiting time gets reset to its default (minimum) value T1. You could, for example, use the values T1 = 250ms and T2 = 16s

As an example, here is what the polling would look like for a job that is estimated at 2 minutes and runs a little late (network latency ignored):

```<code>Time             Action/Reply
----             ------------
0:00.000         Start job. Server responds with a duration of 2:00 minutes
2:00.000         Polling starts. Server responds job still running
2:00.250         First retry. Job still running
2:00.750         Second retry. Job still running
2:01.429             Job finishes
2:01.750         Third retry. Job reported as done.
</code>```

As you can see, there is some latency in reporting that the job is done, but what is a delay of a few hundred milliseconds if you were already waiting 2 minutes for the job to complete?

Title: Are there algorithims for polling optimization?

Body:
I have a web-application with an async HTTP backend, which gets called by the client by AJAX requests. The client has to start a job and then polls for the result.

I started with a simple 150ms polling interval, which was fine for small jobs, but big jobs, which could take several minutes, threw many failed requests to the server.

Currently, I just add 1000ms to the delay after every poll, so the polling gets slower over time for longer requests, but never longer than 10 seconds.

Are there some formulas, statistics, or algorithms that I could use to dynamically optimize the polling time?

Body:
If the server can give a rough estimate of how long a job will take, then I would return that estimate in the first response (the one indicating that the job was received/accepted). The client can then wait at least that time before it starts polling for results.

To avoid flooding a server with unsuccessful polling requests, you might also use a scheme that is often used to send retries over an unreliable protocol: After sending a request, wait a time T before sending a retry. After sending a retry, double the waiting time, until a maximum T2. After success, the waiting time gets reset to its default (minimum) value T1. You could, for example, use the values T1 = 250ms and T2 = 16s

As an example, here is what the polling would look like for a job that is estimated at 2 minutes and runs a little late (network latency ignored):

Time             Action/Reply
----             ------------
0:00.000         Start job. Server responds with a duration of 2:00 minutes
2:00.000         Polling starts. Server responds job still running
2:00.250         First retry. Job still running
2:00.750         Second retry. Job still running
2:01.429             Job finishes
2:01.750         Third retry. Job reported as done.

As you can see, there is some latency in reporting that the job is done, but what is a delay of a few hundred milliseconds if you were already waiting 2 minutes for the job to complete?


问:
Protect Images in a Webpage
I want to build a website that will contain a lot of images. I don't want users who visit the website to be able to save the images.

I have blocked the right click option, but is there any other way to keep users from saving the images?

答: There is nothing you can do. If the browser can download an image, other non-browser tools can download it too. If somebody wants to save one of your images to their computer, they can find a way.</p>

Title: Protect Images in a Webpage


问:
What are some standard design methods to add GUI to a command line app?
I have an embedded Linux C application that runs with a simple CLI. I am now tasked with creating a GUI that accomplishes the same functionality as the command line program. I am not an accomplished GUI designer and the majority if my experience is in deeply embedded C  coding.

My initial thought is to use qtcreator to create the GUI, but there are several issues I'm ruminating over.

Moving forward I want to maintain both the CL program and the GUI program, and preferably even have them be the exact same executable that can be launched in either mode. Unless this is a bad idea?

My code is in C so far, and qt is natively c++

I would like a direct correlation where button presses in the GUI call the same functions that I call from the CLI

How do I best do this cleanly and efficiently? Is there some other thecnology or library that simplifies this? I don't have to use qt if there is something better.

答:
I could give you some rough guidelines as to how to create the equivalent GUI for a CLI app, design-wise. How you would actually make the calls is out of the scope of this answer.

switches like -p -v etc are checkboxes

mutually exclusive options are a group of radio buttons

parameters that are a filename are a textbox with a "choose" button that shows a choose file dialog box when pressed

string parameters in general are textboxes

number parameters can be textboxes, combo-boxes, or spin boxes, depending on the values being known, being restricted in a range or free-form.

totally divergent usages are separated into tab pages ( for example adding the meta-switch "commit" to git, changes the whole set of expected/allowed switches and parameters )

Once the parameters are entered, a button executes the action

Note: input validation must be proactive, ie, you must prevent the user from executing the action when mandatory parameters have not been entered, by greying out the execute button and, generally, greying out or activating GUI elements in order to convey proper usage. In CLI apps, the user just runs the command and gets an error message, ie, validation is reactive.


问:
Adding correct documentation for a method
I have method like this:

```<code>methodA(someParams)
{
  do some initializations,etc;
  call methodB(someParams);
}

methodB(someParams)
{
  do work;
  if blah then raise exception::FileNotFound
  if blahblah then raise exception::ResourceNotFound
}
</code>```

When I am adding documentation for methodB, I am also documenting the exceptions it can raise.

But how about documentation of methodA ? It IS consuming methodB that may raise exceptions, so should I still document those exceptions for methodA as well? Right? wrong?

答:
Yes, you should document all the exceptions that a method can throw method's clients are expected to handle. Where exactly the exceptions originate is irrelevant - even if they come from some methodC() which happens to be called by methodB().

Code calling methodA() shouldn't care what other methods it calls in order to get the job done, but it does need know about the things that might go wrong.

In your example, since methodA() doesn't take responsibility for handling the FileNotFound or ResourceNotFound exceptions, any code calling methodA() needs to know that it has to deal with those scenarios.

Now, if methodA() can take some sensible action in the case of a FileNotFound or ResourceNotFound exception, then it should do that and it doesn't need to report those exceptions - it can hide them from its clients.

A simple example, in Java: (For the sake of argument, let's agree that a non-existent file is 0 bytes long)

```<code>int getFileSize(String filename) {
    try {
        return getFileBytes(filename).length;
    } catch (FileNotFoundException e) {
        return 0;
    }
}

byte[] getFileBytes(String filename) throws FileNotFoundException {
    // ...
}
</code>```

Edit

As Illustrated by Bobson's comment, I've feel I've misrepresented a very important point - see the change in bold above!

There are generally 3 cases where an exception/error should thrown:

Things you can reasonably expect to go wrong. e.g. Trying to print something but you can't get access to a printer, or you're trying to open a file which doesn't exist.

Programming errors - i.e. bugs. e.g. Dividing by 0, NullPointerExceptions. These shouldn't be making it into released code so you generally shouldn't be writing code to deal with them.

Unrecoverable errors. e.g. StackOverflowError. These tend to be thrown by the underlying system (virtual machine, OS, etc.) and generally there isn't anything you can do about them.

The ones you should be declaring are those in category 1. Java tries to force you to do this, but it does have some problems.

Body:
Yes, you should document all the exceptions that a method can throw method's clients are expected to handle. Where exactly the exceptions originate is irrelevant - even if they come from some methodC() which happens to be called by methodB().

Code calling methodA() shouldn't care what other methods it calls in order to get the job done, but it does need know about the things that might go wrong.

In your example, since methodA() doesn't take responsibility for handling the FileNotFound or ResourceNotFound exceptions, any code calling methodA() needs to know that it has to deal with those scenarios.

Now, if methodA() can take some sensible action in the case of a FileNotFound or ResourceNotFound exception, then it should do that and it doesn't need to report those exceptions - it can hide them from its clients.

A simple example, in Java: (For the sake of argument, let's agree that a non-existent file is 0 bytes long)

int getFileSize(String filename) {
    try {
        return getFileBytes(filename).length;
    } catch (FileNotFoundException e) {
        return 0;
    }
}

byte[] getFileBytes(String filename) throws FileNotFoundException {
    // ...
}

Edit

As Illustrated by Bobson's comment, I've feel I've misrepresented a very important point - see the change in bold above!

There are generally 3 cases where an exception/error should thrown:

Things you can reasonably expect to go wrong. e.g. Trying to print something but you can't get access to a printer, or you're trying to open a file which doesn't exist.

Programming errors - i.e. bugs. e.g. Dividing by 0, NullPointerExceptions. These shouldn't be making it into released code so you generally shouldn't be writing code to deal with them.

Unrecoverable errors. e.g. StackOverflowError. These tend to be thrown by the underlying system (virtual machine, OS, etc.) and generally there isn't anything you can do about them.

The ones you should be declaring are those in category 1. Java tries to force you to do this, but it does have some problems.


答:
See Wikipedia's Analog Hole to confirm this implausibility. Best quote to summarize:

It is simply not possible to simultaneously display and conceal a
  signal.

(Especially when you have zero chance of controlling the hardware people will use to view this content)

However, in the chance that this is an XY problem, you can often provide tiny imperceptible watermarks in images that don't affect their visual quality. If the images appear in a newspaper later, uncredited, you can likely take the newspaper to court and point to your website's faded URL in the corner.

(Responding to edit): Blocking the right-click sounds like a decent idea to provide a minimal level of protection. Many users will have Javascript disabled, even without intending to hack your site, so they will still likely have no problem.

It may be worth clarifying if you just think that the right-click menu is an annoying part of your user experience (ie, right-clicking has a clear and logical effect on the UI, and the menu annoys users trying to do so). Even then, I think that many UI designers would disagree with you. I've been to well over 1,000 websites; even the ones overriding the right-click menu simply brought up a different one.

Title: Protect Images in a Webpage

Body:
I want to build a website that will contain a lot of images. I don't want users who visit the website to be able to save the images.

I have blocked the right click option, but is there any other way to keep users from saving the images?


答:
Two problems with knowing only two languages:

There are a number of programming models that can help improve how you think about problem design. A lack of knowledge around these other models limits your ability.

Your skills aren't as portable to other languages, and you're out of practice in learning new languages.

As for what goes on your resumé, that's a different question: some employers will be very happy to find someone focused on only a few things.  I don't believe this to be a good mark for a programmer, but there are many different needs and businesses.

I suggest learning at least one language a year, outside of what your employer requires.  It's good for the brain, your design mojo, and for your future resumé.

Title: I have only two languages on my resume - how bad is this?

Body:
I have a question that can be best answered here, given the vast experience some of you guys have!

I am going to finish my bachelor's degree in CS and let's face it, I am just comfortable with C++ and Python. C++ - I have no experience to show for and I can't quote the C++ standard like some of the guys on SO do but yet I am comfortable with the language basics and the stuff that mostly matters. With Python, I have demonstrated work experience with a good company, so I can safely put that.

I have never touched C, though I have been meaning to do it now. So I cannot write C on my resume because I have not done it ever. Sure I can finish K & R and get a sense of the language in a month, but I don't feel like writing it cause that would be being unfaithful to myself.

So the big question is, are two languages on a a resume considered OK or that is usually a bad sign? Most resumes I have seen mention lots of languages and hence my question. Under the language section of my resume, I just mention: C++ and Python and that kinda looks empty!

What are your views on this and what do you feel about such a situation?

PS: I really don't want to write every single library or API I am familiar with. Or should I?


答:
A common solution to this sort of problem is watermarking images.  Stock photo sites which require membership or payment in order to download photos show sample photos with watermarks.  In order to see the larger photo, you must already have access.  You'll notice that you will never be able to see the large photo without the watermark without access because of this simple fact that once a user is seeing the photo, it is already on their hard drive and hence can be used (or misused) however they wish.  At least a watermark guarantees they cannot have the untampered version.

Short of this, preventing right-clicking will stop a reasonable percentage of users, but it is no security measure, hence nothing can be done.

Title: Protect Images in a Webpage


问:
How can I secure a request handler so I only respond to the correct clients?
Here's the scenario...

I have a web site that has a generic handler written in asp.net (.ashx file) that accepts http requests, gets relevant data, converts the result into xml and then passes that back via the response.

This will eventually be used so that a windows application can make data requests to this web site.

My concern is that anyone who knows how to put together the request can then access potentially personal data.  The data isn't anything as sensitive as financial information, but it will have names and addresses so I obviously need to think about securing it.

My initial thought was to encrypt the information before responding, and maybe even encrypt the request as well, and I'm happy to do this, but I just wanted to ask some other boffins for their opinion on the matter.

Is this something that has a "standard" way of doing it, or is it simply a case of thinking of something suitable and implementing it.

Incidentally, the windows app will be distributed all over the country so the requests will come from many places.  Using the IP address is not only a laborious way of doing it, but it also doesn't help as you could obviously send the message from an IP without using the application.

TL;DR

How do I make sure that it was my windows app that asked my web app for information?

答: If the web site is only to be accessed by your app then I think the best way is to use a token encrypted with keys known only to the two parties (website and app), the web site checks the token using the keys and only responds if the token is valid. And yes you should also encrypt the response.</p>


问:
Using a Proxy as an ACL
I am building an MVC application in PHP, using Zend Framework.

My model includes Domain Model and Mapper layers.  I am trying to keep the domain model in pristine condition and have managed to keep it free from persistence-related code.  Now I am trying to find a solution for ACL.

I have 'general' ACL rules that can be easily enforced in a service layer, but I also have some very fine grained rules.  The fine grained rules apply at the property level and affect whether the current user can alter a field, and if so, what the range of allowable values is.

Currently I am thinking of using the proxy pattern, and that the proxy should extend the real object (to save me having to redirect 100% of calls).  Does this sound reasonable?  Is there a better option?

答:
If you extend your ACL class from the original class, you're not following the Proxy pattern. A Proxy controlls the access to a given subject, implementing the same interface as the subject.

Using traits in PHP, you can build a generic Decorator, which you can use for all Proxies and Decorators.

```<code>interface MyModel {...}

class ConcreteModel implements MyModel
{
    // Your properties and methods as usual
}

trait Decorator
{
    private $subject;

    public function __call($method, $args)
    {
        return call_user_func_array($method, $args);
    }

    // You might want to implement __callStatic, __get, and __set, too
}

class AclProxy implements MyModel
{
    use Decorator;

    public function __construct(MyModel $model)
    {
        $this->subject = $model;
    }

    // Your specific overrides go here
}
</code>```

Title: Using a Proxy as an ACL

Body:
If you extend your ACL class from the original class, you're not following the Proxy pattern. A Proxy controlls the access to a given subject, implementing the same interface as the subject.

Using traits in PHP, you can build a generic Decorator, which you can use for all Proxies and Decorators.

interface MyModel {...}

class ConcreteModel implements MyModel
{
    // Your properties and methods as usual
}

trait Decorator
{
    private $subject;

    public function __call($method, $args)
    {
        return call_user_func_array($method, $args);
    }

    // You might want to implement __callStatic, __get, and __set, too
}

class AclProxy implements MyModel
{
    use Decorator;

    public function __construct(MyModel $model)
    {
        $this->subject = $model;
    }

    // Your specific overrides go here
}


答: An alternative option is to use something like long polling or websockets. This way you can replace slamming the server with multiple "is it done yet?" requests with a single "tell me when your done" request</p>


问:
Career advice: stay with PHP or start a new career in something else ( .Net?)
I'm planning on moving to NY in 6-12 months tops, so I'm forced to find a new job. When I'm planing to start my life in another city it's also probably a good time to think about career changes.

I've found a lot of different opinions about PHP vs .Net vs Java and this is not the topic here. I don't want to start a new fight about which language is better. Knowing a programming language is not the most important thing for being a software developer. To be a really good developer you need to know OOP, design patterns, testing... and a language is just a tool to make things happen.

So back to my question. I have mixed experience in IT - 1 year as an IT support guy (Windows administration and support), around 2 years of experience in embedded programming (VB.Net 2005) and for the last 2 years I'm working with PHP/MySQL. I have worked with Magento web shop, assisted in some projects in Symfony, modified few Drupal sites.

My main concerns are the following:

Do I continue to improve my skills in PHP e.g. to start learning some major PHP framework like Zend, Symfony maybe get some PHP certification.

Or do I start learning .NET or Java. I'm more familiar to .NET so I'll probably choose it if choice falls between .NET and Java ( or you could convince me to choose Java :).

Career-wise, I don't know what is the best choice. Learning a new framework and language is more time consuming then improving my existing skills in PHP. But with .NET you have a lot of possibilities (Windows 7 Phone development, Silverlight, WPF) and possibly bigger chances to find better jobs.

PHP jobs are less well payed then .NET, at least, according to my research (correct me if I'm wrong). But if I start now with .NET I'm just a beginner and my salary will be low. I need at least 2+ years of experience in some language to even try to find some job that is paying higher than $50-60k in NY. My main goal in the next 2-3 years is to try to find a job in the $60-80k category. Don't get me wrong, I'm not just chasing money, but money is an important factor when you're trying to start a family.

I'm 27 years old and I feel that there isn't a lot of room for wrong decisions regarding my career, so any advice will be very welcome.

Update

Thank you all for spending time to help me with my problem. All of the answers and comments have been very helpful. I have decided to stick with PHP but also to learn C# and Silverlight 4. We'll see where the life will take me.

答:
Language and platform are not that important. Learn solid people and comp sci skills. A lot of people have said this but haven't given specifics so let me do that. Here are some things to learn

algorithms and data structures.

concurrency

machine learning

systems level programming

information retrieval and search engines


答:
Off the top of my head, I see two possibilities to authenticate your client app:

Use a standard (HTTP) authentication mechanism, possibly with a username/password that are hard-coded in the client.

Use an SSL connection and require the client to provide a client certificate when establishing the connection.

Title: How can I secure a request handler so I only respond to the correct clients?

Body:
Here's the scenario...

I have a web site that has a generic handler written in asp.net (.ashx file) that accepts http requests, gets relevant data, converts the result into xml and then passes that back via the response.

This will eventually be used so that a windows application can make data requests to this web site.

My concern is that anyone who knows how to put together the request can then access potentially personal data.  The data isn't anything as sensitive as financial information, but it will have names and addresses so I obviously need to think about securing it.

My initial thought was to encrypt the information before responding, and maybe even encrypt the request as well, and I'm happy to do this, but I just wanted to ask some other boffins for their opinion on the matter.

Is this something that has a "standard" way of doing it, or is it simply a case of thinking of something suitable and implementing it.

Incidentally, the windows app will be distributed all over the country so the requests will come from many places.  Using the IP address is not only a laborious way of doing it, but it also doesn't help as you could obviously send the message from an IP without using the application.

TL;DR

How do I make sure that it was my windows app that asked my web app for information?


问:
How can I return generated HTML and a response too?
My web application will use AJAX calls often and so I have set up some JavaScript to handle "messages" or "responses". These responses are returned (from my ASP.NET application) as JSON objects that act as feedback once a function is complete.

Suppose my responses have three basic elements.

Type (error, warning, info, success)

Title

Message

For example

Save unsuccessful

Your data was not saved because of XYZ.

Sometimes, however, I want my function to generate and return some HTML. That's easy enough, but what if I still want to return a message to the user (or some other JSON)?

Should I return the HTML as part of the JSON?

Should I only return one or the other?

Should I return HTML, then make another AJAX call for the response?

Should I return HTML and store the response in data- tags?

Can someone point me in the right direction?

答:
Should I return HTML, then make another AJAX call for the response?

Unless you have some compelling reason not to (there aren't any I can think of), you should definitely favor minimizing the number of calls. Each call has the overhead of URL resolution/etc. and if you're just getting the same data you'd send anyway in the single call, there's no reason for that waste.

Should I return the HTML as part of the JSON?

Returning HTML in JSON is fine, if you're using jQuery (or even naked DOM access), it's easy to update the HTML of an element. If you don't need the HTML message, that property can be null or omitted entirely, so it wouldn't be wasteful to include it only in the cases where you need it.

Should I only return one or the other?

From the ASP.NET function? I think it's probably best to include the HTML property as part of a standard protocol. For example, I have 3 standard properties from all AJAX calls: Success, ErrorMessage, ErrorTitle. This keeps it easier for someone to work with as well since they can rely on those being there all the time and act accordingly.

Should I return HTML and store the response in data- tags?

You might have a use case where this makes sense, but I think in general, it makes more sense to have JS functions for responding to the standard message protocol instead. This way it allows the caller more control over how, when, where, etc. the messages display. You can also come up with sensible defaults that can be overridden if there's a need.


答:
1) Even if concrete classes are mockable, it still requires that you make members virtual and provide a parameterless constructor, which may be obtrusive and unwanted. You (or new team members) will soon find yourself systematically adding virtual's and parameterless constructors in every new class without a second thought, just because "that's the way stuff works".

An interface is IMO a much better idea when you need to mock a dependency, because it allows you to defer implementation until when you really need it, and makes for a nice clear contract of the dependency.

3) How's that a falsehood ?

I believe interfaces are great for defining messaging protocols between collaborating objects. There might be cases when the need for them is debatable, as with domain entities for instance. However, wherever you have a stable partner (i.e., an injected dependency as opposed to a transient reference) you need to communicate with, you should generally consider using an interface.

Title: When to use interfaces (unit testing, IoC?)

Body:
I suspect I've made a schoolboy error here, and am looking for clarification. A lot of the classes in my solution (C#) - dare I say the majority - I've ended up writing a corresponding interface for. E.g. an "ICalculator" interface and a "Calculator" class that implements it, even though I'm never likely to replace that calculator with a different implementation. Also, most of these classes reside in the same project as their dependencies - they really only need to be internal, but have ended up being public as a side-effect of implementing their respective interfaces.

I think this practice of creating interfaces for everything stemmed from a few falsehoods:-

1) I originally thought that an interface was necessary to create unit test mocks (I'm using Moq), but I've since discovered that a class can be mocked if its members are virtual, and it has a parameterless constructor (correct me if I'm wrong).

2) I originally thought an interface was necessary to register a class with the IoC framework (Castle Windsor), e.g.

```<code>Container.Register(Component.For<ICalculator>().ImplementedBy<Calculator>()...
</code>```

when in fact I could just register the concrete type against itself:

```<code>Container.Register(Component.For<Calculator>().ImplementedBy<Calculator>()...
</code>```

3) Using interfaces, e.g. constructor parameters for dependency injection, results in "loose coupling".

So have I gone mad with interfaces?! I'm aware of the scenarios where you would "normally" use an interface, e.g. exposing a public API, or for things like "pluggable" functionality. My solution has a small number of classes that fit such use cases, but I wonder if all the other interfaces are unnecessary, and should be removed? Regarding point 3) above, won't I be violating "loose coupling" if I was to do this?

Edit:- I'm just having a play with Moq, and it seems to require methods to be public and virtual, and have a public parameterless constructor, in order to be able to mock them. So it looks like I can't have internal classes then?


答:
A best practice is to keep the reply consistent, meaning you should always have JSON offering a structure which is consistent and provides enough information to infer whether or not the call was a success.

First check the ajax status that the command was properly handled.  Once you've determined that the command was properly handled, you then proceed to check your json, in particular some sort of indicator which implies whether or not your internal program could handle that particular request.

If both are correct, then you search for an additional property which you must guarantee to always be there which contains the HTML string.  If something goes wrong, then you search for an additional property which you must guarantee in case of failure which contains the error message.

What is important is that you always have an indicator of success to let you know what to expect from the response.  This is of course completely arbitrary, but best practice dictates that if the ajax command went well, that you should provide enough information such that your javascript program knows what to do next.

Title: How can I return generated HTML and a response too?

Body:
My web application will use AJAX calls often and so I have set up some JavaScript to handle "messages" or "responses". These responses are returned (from my ASP.NET application) as JSON objects that act as feedback once a function is complete.

Suppose my responses have three basic elements.

Type (error, warning, info, success)

Title

Message

For example

Save unsuccessful

Your data was not saved because of XYZ.

Sometimes, however, I want my function to generate and return some HTML. That's easy enough, but what if I still want to return a message to the user (or some other JSON)?

Should I return the HTML as part of the JSON?

Should I only return one or the other?

Should I return HTML, then make another AJAX call for the response?

Should I return HTML and store the response in data- tags?

Can someone point me in the right direction?


问:
Will high reputation in Stack Overflow help to get a good job?
In a post, Joel Spolsky mentioned that 5 digit Stack Overflow reputation can help you to earn a job paying $100k+. How much of that is real?

Would anyone like to share their success in getting a high paid job by virtue of their reputations on Stack Exchange sites?

I read somewhere that, a person got an interview offer from Google because a recruiter found his Stack Overflow reputation to be impressive. Anyone else with similar stories?

答:
My current job pays me about $54k a year for 25h a week, most of which I work from home. Plus working as a game developer was kind of a childhood dream, that has now come true (although I sometimes think of moving on to something more "meaningful"). So I suppose my job is arguably equivalent to or even better than the average $100k+ jobs you get as a developer.

On my application I added a section "participation in online communities", wherein I listed SO (and a few smaller german forums). I don't have a superbly high score, but among ActionScript 3 developers I am very well placed.

The references I had were not really outstanding. Mostly the stupid kind of stuff you do as a Flash Developer to get money for sites you'd never visit yourself. But upon arrival to the interview I immediatly sensed, that I had a very high standing from the start. I have personally accounted this to my SO activity.

Getting a high rep on SO means, that you are eager to exchange thoughts, that you are knowledgeable enough to solve the problems your peers pose you (real problems from they actually encounter in every day life), and that you are able to communicate your ideas. These are key abilities for good developers. Thus one can say, people who have a high rep on SO have those abilities. The reputation is given to you by independent developers, not by some comittees or someone vaguely in touch with the subject. I think a high rep on SO is a much better measure than good grades (which appearently are still consider a criterium by some employers).

That being said, I'd never hire someone just because they have a high SO rep. But let's say a person with a high rep will have a head start while trying to convince me they're good. Appearently my current employer reasons similarly.


问:
Do these specific tables need surrogate keys?

Background

I have this tables

```<code>+-------------------------+  +------------------------+
|Airport                  |  |Country                 |
|-------------------------|  |------------------------|
|airport_code string (PK) |  |country_code string (PK)|
|address string           |  |name string             |
|name  string             |  +------------------------+
+-------------------------+

+-------------------------+
|Currency                 |
|-------------------------|
|currency_code string (PK)|
|name string              |
+-------------------------+
</code>```

airport_code is the IATA (International Air Transport Association ) airport code, you can see them in your luggage tags when you travel by plane.

country_code is the ISO 3166-1 A3 standard country code, you can see them in the olympics.

currency_code is the IS0 417 standard 3-chars currency code, you can see them in international currency exchange display boards.

Questions

Are these natural PKs good enough ?

Is using world respected standards, which are accepted by whole industries good enough for PKs ?

Do this tables need surrogates no matter what ?

答:
No, they don't.  Those keys are definitely good enough!

They're unique, <s>not</s> rarely going to change, and meaningful, which is a step up over a surrogate key.  That's pretty much the definition of a good PK.

The restrictions about PKs being immutable and numeric-integer are not part of the Relational Model (Codd's) or any SQL standard (ANSI or other).


问:
How does the Microsoft Operations Framework define the role of Architects and architecture in the SDLC
I have been trying to get some architecture documentation passed at work. I've spoken to my CIO and he has said to me that if I prove to him that if we stay within MOF then we can implement it. I am not an architect, I am a software developer trying to become an architect. </p>

<p>I downloaded the MOF documentation and did some searches for "architect" or "architecture" and really only found 3 very minor references. So I'm trying to find out more about the role of "Architecture" in MOF. </p>

答:
Welcome to architecture.

Defining an architect's role is a notoriously difficult task.  Essentially, each shop has their own approach and set of expectations around the role.

MaxS pointed out the MOF's definition of Architecture Manager which is probably one of the "very minor references" you mentioned in your question.

An Architects role is to gather together and keep together all the odds and sods that are within the application and supporting systems.  Sounds like your first real task as an architect for your employer is to understand the MOF, how it applies to your application, and how the architecture artifacts that you want fit into the overall scheme.

The CIO is essentially saying "show me the value, with respect to this operations framework, that your suggested documents bring to our environment."  IMO, that's a good, measured approach.  He gave you the rules within which to justify your request and he hasn't outright rejected your request.  Now you need to demonstrate the value they bring and how it keeps you on the path you're already on.  He's looking for enhancements, not course or directional change.

So go read the MOF.  Go understand the artifacts that MOF suggests using.  Then understand how the artifacts you want align with the suggested artifacts from the MOF.  Hint: there's not all that much new under the sun so it shouldn't be too hard to show how your preferred document formats align with an MOF suggestion.  But you need to put the up-front effort in so you can have a knowledgeable conversation with the CIO.


问:
Choosing the language to build an app in based on hiring market vs performance and maintainability
I'm facing a choice of whether to start building Haskell components for a certain production app that is all done in Ruby.

I'm leaning toward Haskell for several reasons, primarily speed (compiled Haskell is like 4-8x faster), greater transparency (via Haskell type system), and safer refactorability (type system).  I've written a few open source and production programs in Haskell already and enjoy writing it very much.

Feasibility is not an issue. I've played around with the Haskell Snap web framework and database libraries like PostgreSQL.Simple and am satisfied that rewriting a Rails app and various backend programs with Haskell is feasible.

The real issue is hiring programmers when we need to scale the dev team, or eventually handing off the programming responsibilities altogether. It's a lot easier to find programmers in Ruby than in Haskell. On the other hand, the Haskell community seems to be growing, and it's not too hard to train programmers to modify parts of a Haskell program if you approach it as a DSL (much like Ruby on Rails). The Haskell type system also seems to promise much safer collaboration than dynamic Ruby does.

In his essay "Beating the Averages" (http://www.paulgraham.com/avg.html), Paul Graham argues that using a superior language can be a decisive advantage. But when does it make sense to forgo using a superior language in order to make it easier to add programmers to your team?

答:
If the speed, transparency, and refactorability benefits of Haskell are more important to the success of your app then the risks of having to train developers then you should stick with Haskell.

A reasonably intelligent programmer with mentoring should be able to contribute to your development without too much pain.

Just make sure you can afford (in time and cost) to do that mentoring.


答:
I think need is a very strong word, and in a strict sense, the tables probably do not need surrogate keys.

However, if it were my database, I would probably add surrogate keys anyway. I may not necessarily want my database design to depend on a bunch of third parties (IATA, ISO), regardless of how stable their standards are. Or, I may not want to depend on a particular standard at all (are there other currency code standards? I don't know). I would probably model my tables with surrogate keys like so:

```<code>+-------------------------+  +------------------------+
|Airport                  |  |Country                 |
|-------------------------|  |------------------------|
|airport_id       int (PK)|  |country_id     int (PK) |
|iata_airport_code string |  |iso_country_code string |
|icao_airport_code string |  +------------------------+
|faa_identifier    string |
|address           string |
|name              string |
+-------------------------+

+-------------------------+
|Currency                 |
|-------------------------|
|currency_id int (PK)     |
|iso_currency_code string |
|name string              |
+-------------------------+
</code>```

In other words, unless those industry standard codes are inherently important to my application, I wouldn't use them as the PK of my tables. They're just labels. Most of my other tables will probably have surrogate keys anyway, and this setup would add consistency to my data model. The cost of 'adding' the surrogate keys is minimal.

Update based on some of the comments:

Without knowing the context of the example tables, it's impossible to know how important things like IATA Airport Codes are to the application using the database. Obviously, if IATA codes are centrally important to and used pervasively throughout the application, it might be the correct decision, after proper analysis, to use the codes as the PK of the table.

However, if the table is just a lookup table that's used in a few corners of the app, the relative importance of the IATA codes may not justify such an prominent spot in the database infrastructure. Sure, you may have to make an additional join in a few queries here and there, but that effort might be trivial in comparison to the effort it would take to do the research to ensure that you fully understand the implications of making the IATA codes the primary key field. In some cases, not only do I not care, but I don't want to have to care about the IATA codes. @James Snell's comment below is a perfect example of something I might not want to have to worry about affecting the PK of my tables.

Also, consistency in design is important. If you have a database with dozens of tables that all have consistently designed surrogate keys, and then a few lookup tables that are using 3rd party codes as PK, that introduces an inconsistency. That's not altogether bad, but it requires extra attention in documentation and such that may not be warranted. They're lookup tables for goodness sake, just using a surrogate key for consistency is perfectly fine.

Update based on further research:

Ok, curiosity bit me and I decided to do some research on IATA airport codes for fun, starting with the links provided in the question.

As it turns out, the IATA codes are not as universal and authoritative as the question makes them out to be. According to this page:

Most countries use four-character ICAO codes, not IATA codes, in their
  official aeronautical publications.

In addition, IATA codes and ICAO codes are distinct from FAA Identifier codes, which are yet another way to identify airfields.

My point in bringing these up is not to begin a debate about which codes are better or more universal or more authoritative or more comprehensive, but to show exactly why designing your database structure around an arbitrary 3rd party identifier is not something I would choose to do, unless there were a specific business reason to do so.

In this case, I feel my database would be better structured, more stable, and more flexible, by forgoing the IATA codes (or any 3rd party, potentially changeable code) as a primary key candidate and use a surrogate key. By doing so, I can forgo any potential pitfalls that might crop up due to the primary key selection.

Title: Do these specific tables need surrogate keys?

Body:
Background

I have this tables

```<code>+-------------------------+  +------------------------+
|Airport                  |  |Country                 |
|-------------------------|  |------------------------|
|airport_code string (PK) |  |country_code string (PK)|
|address string           |  |name string             |
|name  string             |  +------------------------+
+-------------------------+

+-------------------------+
|Currency                 |
|-------------------------|
|currency_code string (PK)|
|name string              |
+-------------------------+
</code>```

airport_code is the IATA (International Air Transport Association ) airport code, you can see them in your luggage tags when you travel by plane.

country_code is the ISO 3166-1 A3 standard country code, you can see them in the olympics.

currency_code is the IS0 417 standard 3-chars currency code, you can see them in international currency exchange display boards.

Questions

Are these natural PKs good enough ?

Is using world respected standards, which are accepted by whole industries good enough for PKs ?

Do this tables need surrogates no matter what ?

Body:
I think need is a very strong word, and in a strict sense, the tables probably do not need surrogate keys.

However, if it were my database, I would probably add surrogate keys anyway. I may not necessarily want my database design to depend on a bunch of third parties (IATA, ISO), regardless of how stable their standards are. Or, I may not want to depend on a particular standard at all (are there other currency code standards? I don't know). I would probably model my tables with surrogate keys like so:

+-------------------------+  +------------------------+
|Airport                  |  |Country                 |
|-------------------------|  |------------------------|
|airport_id       int (PK)|  |country_id     int (PK) |
|iata_airport_code string |  |iso_country_code string |
|icao_airport_code string |  +------------------------+
|faa_identifier    string |
|address           string |
|name              string |
+-------------------------+

+-------------------------+
|Currency                 |
|-------------------------|
|currency_id int (PK)     |
|iso_currency_code string |
|name string              |
+-------------------------+

In other words, unless those industry standard codes are inherently important to my application, I wouldn't use them as the PK of my tables. They're just labels. Most of my other tables will probably have surrogate keys anyway, and this setup would add consistency to my data model. The cost of 'adding' the surrogate keys is minimal.

Update based on some of the comments:

Without knowing the context of the example tables, it's impossible to know how important things like IATA Airport Codes are to the application using the database. Obviously, if IATA codes are centrally important to and used pervasively throughout the application, it might be the correct decision, after proper analysis, to use the codes as the PK of the table.

However, if the table is just a lookup table that's used in a few corners of the app, the relative importance of the IATA codes may not justify such an prominent spot in the database infrastructure. Sure, you may have to make an additional join in a few queries here and there, but that effort might be trivial in comparison to the effort it would take to do the research to ensure that you fully understand the implications of making the IATA codes the primary key field. In some cases, not only do I not care, but I don't want to have to care about the IATA codes. @James Snell's comment below is a perfect example of something I might not want to have to worry about affecting the PK of my tables.

Also, consistency in design is important. If you have a database with dozens of tables that all have consistently designed surrogate keys, and then a few lookup tables that are using 3rd party codes as PK, that introduces an inconsistency. That's not altogether bad, but it requires extra attention in documentation and such that may not be warranted. They're lookup tables for goodness sake, just using a surrogate key for consistency is perfectly fine.

Update based on further research:

Ok, curiosity bit me and I decided to do some research on IATA airport codes for fun, starting with the links provided in the question.

As it turns out, the IATA codes are not as universal and authoritative as the question makes them out to be. According to this page:

Most countries use four-character ICAO codes, not IATA codes, in their
  official aeronautical publications.

In addition, IATA codes and ICAO codes are distinct from FAA Identifier codes, which are yet another way to identify airfields.

My point in bringing these up is not to begin a debate about which codes are better or more universal or more authoritative or more comprehensive, but to show exactly why designing your database structure around an arbitrary 3rd party identifier is not something I would choose to do, unless there were a specific business reason to do so.

In this case, I feel my database would be better structured, more stable, and more flexible, by forgoing the IATA codes (or any 3rd party, potentially changeable code) as a primary key candidate and use a surrogate key. By doing so, I can forgo any potential pitfalls that might crop up due to the primary key selection.


答:
How many days would you save using Haskell as opposed to Ruby?  Would it be more or less than the number of days required to find Haskell programmers or train non-Haskell programmers?  Are you already prepared to teach non-Haskell programmers how to use Haskell?  Are you willing to hire programmers knowing full and well that they will not be able to demonstrate their capacity to use Haskell until long after their initial hiring?

These are difficult questions to answer.  I think the deciding factor here should be whether or not you intend to continue using Haskell in the future or if this is going to be for one project only.  If you plan on continuing to use Haskell in the future, then while the program will take longer, it could also be thought of as an investment.  However in my humble opinion, language is not as important as architecture.  If you use the right framework and the right program structure, you could easily outperform the same program in another "superior" language with the wrong framework or the wrong program structure.

In other words, if time is to be invested in properly doing a program, I think this time would be better spent analyzing an approach before writing the first line of code, which has been proven to cut down on programming times significantly if done right.

Title: Choosing the language to build an app in based on hiring market vs performance and maintainability

Body:
I'm facing a choice of whether to start building Haskell components for a certain production app that is all done in Ruby.

I'm leaning toward Haskell for several reasons, primarily speed (compiled Haskell is like 4-8x faster), greater transparency (via Haskell type system), and safer refactorability (type system).  I've written a few open source and production programs in Haskell already and enjoy writing it very much.

Feasibility is not an issue. I've played around with the Haskell Snap web framework and database libraries like PostgreSQL.Simple and am satisfied that rewriting a Rails app and various backend programs with Haskell is feasible.

The real issue is hiring programmers when we need to scale the dev team, or eventually handing off the programming responsibilities altogether. It's a lot easier to find programmers in Ruby than in Haskell. On the other hand, the Haskell community seems to be growing, and it's not too hard to train programmers to modify parts of a Haskell program if you approach it as a DSL (much like Ruby on Rails). The Haskell type system also seems to promise much safer collaboration than dynamic Ruby does.

In his essay "Beating the Averages" (http://www.paulgraham.com/avg.html), Paul Graham argues that using a superior language can be a decisive advantage. But when does it make sense to forgo using a superior language in order to make it easier to add programmers to your team?


问:
What are some good assignments for an introductory course, to reach today's students?
I periodically teach an introduction to programming course using Java. I want to give my students some exciting assignments that they can relate to or find interesting. At the very least, I want assignments that make sense and have an internal cohesion (for example, some very bad programming exercises seem contrived just so that you have to use the most recent programming construct covered).

To give you an idea of scope, here's what's being covered:

The assignments must be in Java, using some external library can be done, but it would need to be a simple API and not a full framework

Variables, Primitives and Strings

Console input and output

if, for, while

Arithmetic and logical operators

Simple graphics with line and shape drawing

Static methods

One-dimensional arrays

The students will not go into advanced topics (e.g., no recursion, no emphasis on inheritance). Thus, I'm not looking for complex projects: "Have them write a C compiler. I did it when I was 5 and it was the only way I learned!"

If you have ideas that are more advanced than the scope, please post them on the "Challenging" question linked below, and not this one.

Instead, what I'm looking for are interesting ideas that can be accomplished in a short program. For example:

Students can write a console version of the "Star Wars Name" Generator. This is effectively reading Strings and using substring, but I think it's fun. A similar variation would be a "Mad Libs" program. I used this one five years ago, and perhaps it's already "stale."

Using some trig supplied to them, students can draw regular polygons, and create interesting spiral shapes.

It's also not out of the question to use some simple animation class with most of the code supplied to them. And if you know a Twitter or Facebook service that can be accessed with a simple API, I would be very interested to know.

Please note that this question is different from the "Challenging Java questions for beginners" Question. I'm not looking for challenging per se, just interesting. I think if students work on something where they can easily answer "why would anyone ever want to program that?" then they will learn better.

Even simple problems like computing Miles per Gallon can be good. Although, if there's a way to update it to be more relevant, all the better. If you have an exercise from somewhere else (a book or a website), please cite the source.

To help you think about the typical freshman today, check out the Beloit Mindset list, for many examples that will surely make you feel old.

答:
The most important assignments I've seen force people to think about something they would have not otherwise considered. Something entirely outside of the simple course material, something that seems impossible. Something that has multiple valid solutions.

A few that have impressed me:

Roshambo AIs (used in the AI course at UOA).  A simple function that returns -1, 0, 1 for rock, paper, scissors.  The AIs are pit against each other, and stats are collected by an aggregate utility program.  This assignment constantly surprises people in how many approaches are viable (and how many perform so poorly).

Simple sorting problems with impossible characteristics.  Sort a file of infinite length with finite memory.  This problem shook my foundation of thinking in algorithms.  There are many related problems: windowed averages over infinite-length data, etc., each forces a solution to something apparently impossible.

Simulation problems that appear trivial. Traffic simulations (vehicle, network), race car simulations (left, right, faster, slower), grocery store simulations.

Networking problems (a great weakness in the graduates I've worked with over the last few yearrs).  Peer networking problems with handhelds, for example, proving complexity of n-sync issues, peer updates, peer trust, etc.

Little languages (another weakness in recent grads).  Develop a little language for a simple game AI (checkers, roshambo, tanks, CSS mojo, Twitter bots).  Thinking about concepts of language design, interpretation, and actions is fundimental.


问:
Software Design Stability , YAGNI and Agile
I've met the criterion of good system desing as its stability relative to requirements change.

Small req. changes should raise small changes in design.

Yet I have gut feeling that almost for any somewhat complex software system it's possible to state the set of small changes in requirements which causes unacceptable amount of changes in software.

This feeling is based on personal experience though not very great and the fact that schedules are often broken.

Community can argue against this statement in case of strong disagreement.

But the question only has meaning if you agree.

YAGNI principle works well against overengineering and Agile methodology brings it to the whole process of software development: system evolves incrementally and this perfectly conforms to stability concept which I started this post from.

But... If we however agree that there are some instability points shouldn't we localize this cases to understand the implications from the very beginning? And how is it possible if we designs system in agile incremetnal manner?!

P.S. Itneresting part of the dialog with my colleague:

Nothing is wrong with incremental software development.

Do you imagine the costs of changing the architecture of Curiosity's firmware after it landed Mars?

Hey, but the can and changed the firmware!

Yes, but before that, they had carefully designed this feature. And if not...that would be the point of no return.

答:
I think the key is to encapsulate the sources of likely change within your application.

In a way, change is good as it indicates the software is growing (new requirements) or getting better (bug fixes).

With an understanding of where the change is likely to occur (AKA. "know your business domain") then you can structure the application to encapsulate those areas of change.  And I think that's what you're considering when you say localize this cases to understand the implications from the very beginning.

You are still at risk to a catastrophic change (eg. a requirements change that causes a disproportionate amount of code change), but that's always a risk within software development.

Wisdom gained from experience with design and programming is how we know to encapsulate the areas of change.  A solid understanding of the current requirements as well as the broader vision of the project is crucial as well.  Locking your application vision into a single sprint at a time will increase your risk of catastrophic change.  (Good) Agile promotes focusing on the sprint but also understanding the overall direction.


问:
Building a tool to fix compiler errors automagically
When a program doesn't compile, error messages are sometimes esoteric. Often a simple Google search leading to a site like stack exchange solves the problem. Now why can't we automate this?

How about a Siri for coding? By Siri, I mean an intelligent personal assistant. Not talking about speech recognition here.

I wonder if there is anybody out there (startups/ research labs) building a cool product like this. It will cut down debugging time drastically.

答:
Compilers cannot divine your intent, that's why.

Have you ever gotten some obscure error like

Cannot infer the type of x

only to find out you were missing a semicolon or comma?  That's because the compiler doesn't have something it needs (a critical token), but it doesn't know why.  If it can't figure that out, how's it supposed to figure out that you really do need that cast?

Naturally, we can write better compilers.  But it's an ongoing work in progress, and I suspect that the quality of the language design has a lot to do with it.  Static typing and compile-time assertions are probably the most promising ways to give the compiler the ability to check for errors.

See Also

https://stackoverflow.com/questions/3787960/what-makes-haskells-type-system-more-powerful-than-other-languages-type-syst


问:
Is abusing Application.UnhandledException for login redirection okay?
I'm programming a windows phone 7 app which needs authentication for news-like read access.
I use Application.UnhandledException to handle (my) AuthFailedException, which can be thrown from any page, and navigate to a login page.

To mimic a modal dialog, I do the following:

I attach a BackKeyPress event handler to clear the back stack, effectively causing the app to exit.

On login, I invoke the actual go-back behavior to get back to the previous page, which
threw the AuthFailedException (all in the view model via proper dependency injection).

This feels dirty, but at least a little better than what hacks might be neccessary otherwise... Any advice on how to improve the situation?

答:
The guideline that you shouldn't use exceptions for flow control exists, in part, because exceptions can be orders of magnitude slower than a simpleif statement.  But you can handle an exception, especially a lone one, and that's exactly what you're doing here.

Revel in the mosh pit.  It's OK.

OwnerDisplayName: Sebastian


问:
Choosing between performance vs readable/cleaner code?
If you have to pay the price of performance to make code more readable would you prefer that or you would always prefer performance over it?</p>

答: The general idea is to make the code as readable as possible first, and then only look at optimizing where there's a proven performance problem.  In most cases a response time of, e.g. 5 ms instead of 1 ms isn't going to make a difference.  50 seconds instead of 10 seconds is a different matter.</p>


答:
In layman's words:

Making the code ugly does not make it fast.

Making the code clean does not make it slow (or fast).

Making the code ugly does make the maintainer's work slower.

Clean code usually means the code was made by someone who cares.

One who cares to make his code clean, usually cares to make it efficient.

Hardware becomes cheaper with time.

Programmers don't get cheaper over time.

CPU time is cheaper than programmer's time.

Some performance problems can be solved by throwing money at them.

Very few code maintainability problems can be solved by throwing money at them.

Title: Choosing between performance vs readable/cleaner code?

Body: If you have to pay the price of performance to make code more readable would you prefer that or you would always prefer performance over it?</p>


问:
Mono is frequently used to say "Yes, .NET is cross-platform". How valid is that claim?
In What would you choose for your project between .NET and Java at this point in time? I say that I would consider the "Will you always deploy to Windows?" the single most important technical decision to make up front in a new web project, and if the answer is "no", I would recommend Java instead of .NET.

A very common counter-argument is that "If we ever want to run on Linux/OS X/Whatever, we'll just run Mono"1, which is a very compelling argument on the surface, but I don't agree for several reasons.

OpenJDK and all the vendor supplied JVM's have passed the official Sun TCK ensuring things work correctly.  I am not aware of Mono passing a Microsoft TCK.

Mono trails the .NET releases.  What .NET-level is currently fully supported?

Does all GUI elements (WinForms?) work correctly in Mono?

Businesses may not want to depend on Open Source frameworks as the official plan B.

I am aware that with the new governance of Java by Oracle, the future is unsafe, but e.g. IBM provides JDK's for many platforms, including Linux.  They are just not open sourced.

So, under which circumstances is Mono a valid business strategy for .NET-applications?

1Mark H summarized it as: "If the claim is that "I have a windows application written in .NET, it should run on mono", then not, it's not a valid claim - but Mono has made efforts to make porting such applications simpler."

答:
Sparkie's answer got it, let me complement a little.

".NET is cross platform" is too much of an ambiguous statement as both the framework and the world it was originally created for have changed and evolved.

The short answer is:

The underlying engine that powers .NET and its derivatives, the Common Language Infrastructure Standard, is cross-platform and as if you want to make your code go to multiple platforms, you need to plan on using the right APIs on the right platform to deliver the best experience on each platform.

The CLI family has not tried the "Write Once, Run Anywhere" approach, as the differences from a phone to a mainframe are too big.   Instead a universe of API and runtime features that are platform-specific has emerged to give developers the right tools to create great experiences in each platform.

Think of it: programmers no longer target Windows PCs or Unix Servers.   The world, now more than ever is surrounded by fascinating platforms from PCs, to gaming consoles, to powerful phones, to set-top boxes, to big servers and distributed clusters of machines.  A one-size fits on all platform would merely feel bloated on tiny devices, and feel underpowered on large systems.

The Microsoft's .NET Framework product is not cross platform, it only runs on Windows.  There are variations of the .NET Framework from Microsoft that run on other systems like the Windows Phone 7, the XBox360 and browsers through Silverlight, but they are all slightly different profiles.

Today you can target every major mainstream OS, phone, mobile device, embedded system and server with .NET-based technologies.   Here is a list that shows which CLI implementation you would use in each case (this list is not comprehensive, but should cover 99% of the cases):

x86 and x86-64 based PC computers:

running Windows -> Typically you run .NET or Silverlight but you can also use full Mono here.

running Linux, BSD or Solaris -> You run full Mono or Silverlight

running MacOS X -> You run full Mono or Silverlight

running Android -> You run Mono/Android subset

ARM computers:

Running Windows Phone 7: you run Compact Framework 2010

Running Windows 6.5 and older: you run the old Compact Framework

Android devices: you run Mono/Android

PowerPC computers:

You run full Mono for full Linux, BSD or Unix operating systems

You run embedded Mono for PS3, Wii or other embedded systems.

On XBox360, you run CompactFramework

S390, S390x, Itanium, SPARC computers:

You run full Mono

Other embedded operating systems:

You run .NET MicroFramework or Mono with the mobile profile.

Depending on your needs the above might be enough or not.   You will hardly get the same source code to run everywhere.   For example, XNA code wont run on every desktop, while .NET Desktop software wont run on XNA or the phone.   You typically need to make changes to your code to run in other profiles of the .NET Framework.   Here are some of the profiles I am aware of:

.NET 4.0 Profile

Silverlight Profile

Windows Phone 7 Profile

XBox360 Profile

Mono core Profile - follows the .NET profile and is available on Linux, MacOS X, Solaris, Windows and BSD.

.NET Micro Framework

Mono on iPhone profile

Mono on Android Profile

Mono on PS3 Profile

Mono on Wii Profile

Moonlight profile (compatible with Silverlight)

Moonlight extended profile (Silverlight + full .NET 4 API access)

So each one of those profiles is actually slightly different, and this is not a bad thing.   Each profile is designed to fit on its host platform and expose the APIs that make sense, and remove the ones that do not make sense.

For instance, Silverlight's APIs to control the host browser do not make sense on the phone.   And shaders in XNA make no sense on PC hardware that lacks the equivalent support for it.

The sooner you realize that .NET is not a solution to isolating the developer from the underlying capabilities of the hardware and the native platform, the better off you will be.

That begin said, some APIs and stacks are available in multiple platforms, for example ASP.NET can be used on Windows, on Linux, on Solaris, on MacOS X because those APIs exist both on .NET and Mono.   ASP.NET is not available on some of Microsoft's supported platforms like XBox or Windows Phone 7 and is not supported either on other platforms that Mono supports like the Wii or the iPhone.

The following information is only correct as of November 21st, and many things in the Mono world will likely change.

The same principles can be applied to other stacks, a full list would require a proper table, which I have no idea of how to present here, but here is a list of technologies that might not be present on a particular platform.   You can assume that anything not listed here is available (feel free to send me edits for things I missed):

Core Runtime Engine [everywhere]

Reflection.Emit Support [everywhere, except WP7, CF, Xbox, MonoTouch, PS3]

CPU SIMD support [Linux, BSD, Solaris, MacOS X; Soon PS3,  MonoTouch and MonoDroid]

Continuations - Mono.Tasklets [Linux, BSD, Solaris, MacOS, PS3, Wii]

Assembly Unloading [Windows only]

VM Injection [Linux, BSD, MacOS X, Solaris]

DLR [Windows, Linux, MacOS X, Solaris, MonoDroid]

Generics [some limitations on PS3 and iPhone].

Languages

C# 4 [everywhere]

C# Compiler as a Service (Linux, MacOS, Solaris, BSD, Android)

IronRuby [everywhere, execpt WP7, CF, Xbox, MonoTouch, PS3]

IronPython [everywhere, execpt WP7, CF, Xbox, MonoTouch, PS3]

F# [everywhere, execpt WP7, CF, Xbox, MonoTouch, PS3]

Server Stacks

ASP.NET [Windows, Linux, MacOS, BSD, Solaris]

ADO.NET [everywhere]

LINQ to SQL [everywhere]

Entity Framework [everywhere]

Core XML stack [everywhere]

XML serialization [everywhere, except WP7, CF, Xbox)

LINQ to XML (everywhere)

System.Json [Silverlight, Linux, MacOS, MonoTouch, MonoDroid]

System.Messaging [Windows; on Linux, MacOS and Solaris requires RabbitMQ]

.NET 1 Enterprise Services [Windows only]

WCF [complete on Windows; small subset on Silverlight, Solaris, MacOS, Linux, MonoTouch, MonoDroid]

Windows Workflow [Windows only]

Cardspace identity [Windows only]

GUI stacks

Silverlight (Windows, Mac, Linux - with Moonlight)

WPF (Windows only)

Gtk# (Windows, Mac, Linux, BSD)

Windows.Forms (Windows, Mac, Linux, BSD)

MonoMac - Native Mac Integration (Mac only)

MonoTouch - Native iPhone Integration (iPhone/iPad only)

MonoDroid - Native Android Integration (Android only)

Media Center APIs - Windows only

Clutter (Windows and Linux)

Graphic Libraries

GDI+ (Windows, Linux, BSD, MacOS)

Quartz (MacOS X, iPhone, iPad)

Cairo (Windows, Linux, BSD, MacOS, iPhone, iPad, MacOS X, PS3, Wii)

Mono Libraries - Cross Platform, can be used in .NET but require manually building

C# 4 Compiler as a Service

Cecil - CIL Manipulation, workflow, instrumentation of CIL, Linkers

RelaxNG libraries

Mono.Data.* database providers

Full System.Xaml (for use in setups where .NET does not offer the stack)

MonoTouch means Mono running on iPhone;   MonoDroid means Mono running on Android;   PS3 and Wii ports only available to Sony and Nintendo qualified developers.

I apologize for the lack of formality.


答:
Prefer meeting your customer's requirements.

If the customer has imposed a performance requirement, and that requirement dictates that you change the code to make it less readable but more performant, then you change the code to make it less readable but more performant.

But ugly fast code is a false dichotomy.  Sometimes you can make code perform better without making it significantly more ugly.

If the code already performs adequately, then prefer readability over more performance.

Measure first, then optimize the slow bits only if you need to do so to meet the requirements.


答:
You should always choose clean code first as it reduces the cost of maintenance and it likely to be less complex.  You shouldn't address a performance problem that you haven't identified; that's probably a premature optimisation.

See When is Optimization Premature?


问:
Why is binary search,which needs sorted data, considered better than linear search?
I have always heard that linear search is a naive approach and binary search is better than it in performance due to better asymptotic complexity. But I never understood why is it better than linear search when sorting is required before binary search?

Linear search is O(n) and binary search is O(log n). That seems to be the basis of saying that binary search is better. But binary search requires sorting which is O(n log n) for the best algorithms. So binary search shouldn't be actually faster as it requires sorting.

I am reading CLRS in which the author implies that in insertion sort instead of using the naive linear search approach it is better to use binary search for finding the place where item has to be inserted.  In this case this seems to be justified as at each loop iteration there is a sorted list over which the binary search can be applied. But in the general case where there is no guarantee about the data set in which we need to search isn't using binary search actually worse than linear search due to sorting requirements?

Are there any practical considerations that I am overlooking which make binary search better than linear search? Or is binary search considered better than linear search without considering the computation time required for sorting?

答:
In layman's words:

If you have an unordered list with ten billion items, and the item you happen to be looking for is the last one, you will end up reading the ten billion items.

In the case of the binary search, the indexing can be done just once. Later insertions can be made in the right place to maintain order.


答: I think that the value of binary search over linear search is contextual. If you start with an enormous unordered data set and only plan to pluck a small number of items from it, then sorting and performing a binary search will be slow. If, however, you maintain an ordered list throughout the lifetime of your application and access it regularly, then binary search is a far better way to go.</p>

Title: Why is binary search,which needs sorted data, considered better than linear search?

Body:
I have always heard that linear search is a naive approach and binary search is better than it in performance due to better asymptotic complexity. But I never understood why is it better than linear search when sorting is required before binary search?

Linear search is O(n) and binary search is O(log n). That seems to be the basis of saying that binary search is better. But binary search requires sorting which is O(n log n) for the best algorithms. So binary search shouldn't be actually faster as it requires sorting.

I am reading CLRS in which the author implies that in insertion sort instead of using the naive linear search approach it is better to use binary search for finding the place where item has to be inserted.  In this case this seems to be justified as at each loop iteration there is a sorted list over which the binary search can be applied. But in the general case where there is no guarantee about the data set in which we need to search isn't using binary search actually worse than linear search due to sorting requirements?

Are there any practical considerations that I am overlooking which make binary search better than linear search? Or is binary search considered better than linear search without considering the computation time required for sorting?


答: If you're going to be creating a windows app, then you should be able to store the encryption key in the registry.  Then simply use that key to encrypt all or some part of the message (possibly a custom field in the header).  You write the key to the registry at installation time, so it's never transmitted and therefore can't be intercepted.  Depending on how your app will be distributed, you could even generate separate keys for each of your users.  If users download the app, you can encrypt it and e-mail or text them the decryption key, so even though the app's key (inside the installer) is interceptable, it's still reasonably secure.</p>


问:
What is the most inspiring speech from a developer you ever watched?
Please put a direct link to it.

Required:

Still available online (please put a direct link to it)

Must be a speech from a current or former developer

Speaker's popularity doesn't matter

Target audience should be other developers

It is not required that the topic is programming (the task). I'm more looking for subject generally developing here within P.SE rather than SO.

Explain why it was inspiring

(please, native english speaker, edit my question)

答: I like Guy Steele's Growing a Language.  I find it thought-provoking on a number of levels -- not least of which is that I get to know what a computer feels like while it is being programmed by a master :)</p>